/// <summary> /// Saves the rule. /// </summary> /// <param name = "filename">The filename.</param> /// <param name = "ruleToSave">The rule to save.</param> protected void SaveRule(string filename, grammarRule ruleToSave) { StreamWriter ruleWriter = null; try { ruleToSave.name = Path.GetFileNameWithoutExtension(filename); ruleToSave.L.checkForRepeatNames(); removeNullWhiteSpaceEmptyLabels(ruleToSave.L); ruleToSave.R.checkForRepeatNames(); removeNullWhiteSpaceEmptyLabels(ruleToSave.R); ruleToSave.ReorderNodes(); ruleWriter = new StreamWriter(filename); var s = SerializeRuleToXml(ruleToSave); if (s != null) { ruleWriter.Write(s); } } catch (Exception ioe) { SearchIO.output("***XML Serialization Error***"); SearchIO.output(ioe.ToString()); } finally { if (ruleWriter != null) { ruleWriter.Close(); } } }
private void initGrammarRuleDisplay(grammarRule initRule, string formTitle) { InitializeComponent(); this.MdiParent = Program.main; graphControlLHS.LoadLibraries(); graphControlRHS.LoadLibraries(); if (initRule == null) { rule = new grammarRule(); rule.L = new designGraph(); rule.R = new designGraph(); } else { rule = initRule; } rule.L.displayGraph(graphControlLHS, this.globalLabelsLText); rule.R.displayGraph(graphControlRHS, this.globalLabelsRText); if ((formTitle == null) || (formTitle == "")) { this.Text = rule.name; } else { this.Text = formTitle; } this.rule.updateGraphControl(graphControlLHS, graphControlRHS, globalLabelsLText, globalLabelsRText); }
public void showProperties(Netron.GraphLib.UI.GraphControl GC, grammarRule rule1, object[] props) { graphControl = GC; rule = rule1; if (graphControl.Name == "graphControlLHS") { graph = rule.L; } else { graph = rule.R; } rule.updateFromGraphControl(graphControl); try { this.graphRulePropsTab.Text = "Rule Properties"; if (rule.Bag == null) { rule.initPropertiesBag(); } this.graphRuleProps.SelectedObject = rule.Bag; } catch (Exception exc) { MessageBox.Show("The properties of the rule has thrown an exception and cannot be displayed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); SearchIO.output(exc.Message, 2); } showDisplayProperties(graphControl, (Netron.GraphLib.PropertyBag)props[0]); showRuleNodeArcProperties((Netron.GraphLib.PropertyBag)props[0], graph); }
internal void Update(grammarRule rule, ruleWindow rW) { this.rule = rule; ruleWin = rW; ShapeRulePrpt.rule = rule; Update(); }
private void SaveRule(string filename, grammarRule rule, designGraph graphK) { rule.name = Path.GetFileNameWithoutExtension(filename); if (checkRule(rule)) { // progress is now at 13 var SaveString = BuildXAMLRulePage(rule, graphK); /* A little manipulation is needed to stick the GraphSynth objects within the page. * * The IgnorableSetup string ensures that XAML viewers ignore the following * * GraphSynth specific elements: the canvas data, and the graph data. This eff- * * ectively separates the topology and data of the graph from the graphic elements. */ SaveString = SaveString.Insert(SaveString.IndexOf(">", StringComparison.Ordinal), IgnorableSetup + "Tag=\"Rule\" "); /* remove the ending Page tag but put it back at the end. */ SaveString = SaveString.Replace("</Page>", ""); /* add the graph data. */ SaveString += "\n\n" + AddIgnorablePrefix(SerializeRuleToXml(rule)) + "\n\n"; /* put the closing tag back on. */ SaveString += "</Page>"; try { File.WriteAllText(filename, SaveString); } catch (Exception E) { SearchIO.output("File Access Exception" + E.Message, 10000, "", "Cancel", false); } SearchIO.output("**** Rule successfully saved. ****", 2); } }
public RuleProperties(grammarRule gR) { name = gR.name; spanning = gR.spanning; induced = gR.induced; if (gR.negateLabels.Count > 0) { negateLabels = new List <string>(); foreach (string s in gR.negateLabels) { negateLabels.Add(s); } } containsAllGlobalLabels = gR.containsAllGlobalLabels; OrderedGlobalLabels = gR.OrderedGlobalLabels; if (gR.recognizeFunctions.Count > 0) { recognizeFunctions = new List <string>(); foreach (string s in gR.recognizeFunctions) { recognizeFunctions.Add(s); } } if (gR.applyFunctions.Count > 0) { applyFunctions = new List <string>(); foreach (string s in gR.applyFunctions) { applyFunctions.Add(s); } } if (gR.embeddingRules.Count > 0) { embeddingRules = new List <embeddingRule>(); foreach (embeddingRule e in gR.embeddingRules) { embeddingRules.Add(e); } } UseShapeRestrictions = gR.UseShapeRestrictions; Translate = gR.Translate; Skew = gR.Skew; Scale = gR.Scale; Flip = gR.Flip; Projection = gR.Projection; Rotate = gR.Rotate; TransformNodeShapes = gR.TransformNodeShapes; }
/// <summary> /// Checks the rule with some issues that may have been overlooked. /// </summary> /// <param name="gR">The grammar rule.</param> /// <returns></returns> public static Boolean checkRule(grammarRule gR) { if ((gR.L.checkForRepeatNames()) && !SearchIO.MessageBoxShow("You are not allowed to have repeat names in L. I have changed these " + "names to be unique, which may have disrupted your context graph, K. Do you want to continue?", "Repeat names in L", "Information", "YesNo", "Yes")) { return(false); } if ((gR.R.checkForRepeatNames()) && !SearchIO.MessageBoxShow("You are not allowed to have repeat names in R. I have changed" + " these names to be unique, which may have disrupted your context graph, K. Do you" + " want to continue?", "Repeat names in R", "Information", "YesNo", "Yes")) { return(false); } if ((NotExistElementsinKR(gR)) && !SearchIO.MessageBoxShow("There appears to be common elements between " + "the left and right hand sides of the rule that are indicated as \"Must NOT Exist\"" + " within the left-hand side. This is not allowed. Continue Anyway?", "Improper use of negative elements", "Error", "YesNo", "No")) { return(false); } if ((NumKElements(gR) == 0) && !SearchIO.MessageBoxShow("There appears to be no common elements between " + "the left and right hand sides of the rule. Is this intentional? If so, click yes to continue.", "No Context Graph", "Information", "YesNo", "Yes")) { return(false); } if ((KarcsChangeDirection(gR) != "") && !SearchIO.MessageBoxShow("It appears that arc(s): " + KarcsChangeDirection(gR) + " change direction (to = from or vice-versa). Even though the arc(s) might be undirected," + " this can still lead to problems in the rule application, it is recommended that this is" + " fixed before saving. Save anyway?", "Change in Arc Direction", "Information", "YesNo", "Yes")) { return(false); } if ((!ValidateFreeArcEmbeddingRules(gR)) && !SearchIO.MessageBoxShow("There appears to be invalid references in the free arc embedding rules." + " Node names used in free arc embedding rules do not exist. Continue Anyway?", "Invalid Free-Arc References", "Error", "YesNo", "No")) { return(false); } gR.ReorderNodes(); return(true); }
/// <summary> /// Opens the rule. /// </summary> /// <param name = "filename">The filename.</param> /// <returns></returns> public grammarRule OpenRule(string filename) { grammarRule newGrammarRule = null; XElement xmlRule = null; try { xmlRule = XElement.Load(filename); } catch (FileLoadException fle) { SearchIO.output("File was not found or accessible: " + fle); filename = ""; } if (!string.IsNullOrWhiteSpace(filename)) { if (!xmlRule.Name.LocalName.Contains("grammarRule")) { xmlRule = (from xe in xmlRule.Elements() where xe.Name.LocalName.Contains("grammarRule") select xe).FirstOrDefault(); } if (xmlRule != null) { try { newGrammarRule = DeSerializeRuleFromXML(xmlRule.ToString()); RestoreDisplayShapes(newGrammarRule.L); RestoreDisplayShapes(newGrammarRule.R); removeNullWhiteSpaceEmptyLabels(newGrammarRule.L); removeNullWhiteSpaceEmptyLabels(newGrammarRule.R); if ((string.IsNullOrWhiteSpace(newGrammarRule.name)) || (newGrammarRule.name == "Untitled")) { newGrammarRule.name = Path.GetFileNameWithoutExtension(filename); } } catch (Exception ioe) { SearchIO.output("***XML Serialization Error***"); SearchIO.output(ioe.ToString()); } } } return(newGrammarRule); }
private void CopyRulePropertiesToRule(RuleProperties rP, grammarRule gR) { gR.name = rP.name; gR.spanning = rP.spanning; gR.induced = rP.induced; if (rP.negateLabels != null && rP.negateLabels.Count > 0) { gR.negateLabels = new List <string>(); foreach (string s in rP.negateLabels) { gR.negateLabels.Add(s); } } gR.containsAllGlobalLabels = rP.containsAllGlobalLabels; gR.OrderedGlobalLabels = rP.OrderedGlobalLabels; foreach (string s in rP.recognizeFunctions) { gR.recognizeFunctions.Add(s); } foreach (string s in rP.applyFunctions) { gR.applyFunctions.Add(s); } if (rP.embeddingRules != null && rP.embeddingRules.Count > 0) { gR.embeddingRules = new List <embeddingRule>(); foreach (embeddingRule e in rP.embeddingRules) { gR.embeddingRules.Add(e); } } gR.UseShapeRestrictions = rP.UseShapeRestrictions; gR.Translate = rP.Translate; gR.Skew = rP.Skew; gR.Scale = rP.Scale; gR.Flip = rP.Flip; gR.Projection = rP.Projection; gR.Rotate = rP.Rotate; gR.TransformNodeShapes = rP.TransformNodeShapes; }
private void btnDown_Click(object sender, RoutedEventArgs e) { try { string tempString = null; grammarRule tempRule = null; var numToMoveDown = listBoxOfRules.SelectedItems.Count; var toMoveDown = GetSelectedIndex(); for (var i = numToMoveDown - 1; i >= 0; i--) { if ((toMoveDown[i] != listBoxOfRules.Items.Count - 1) && (!listBoxOfRules.SelectedItems.Contains(listBoxOfRules.Items[toMoveDown[i] + 1]))) { tempString = (string)(listBoxOfRules.Items[toMoveDown[i] + 1] as ListBoxItem).Content; (listBoxOfRules.Items[toMoveDown[i] + 1] as ListBoxItem).Content = (listBoxOfRules.Items[toMoveDown[i]] as ListBoxItem).Content; (listBoxOfRules.Items[toMoveDown[i]] as ListBoxItem).Content = tempString; (listBoxOfRules.Items[toMoveDown[i] + 1] as ListBoxItem).IsSelected = true; (listBoxOfRules.Items[toMoveDown[i]] as ListBoxItem).IsSelected = false; tempRule = Ruleset.rules[toMoveDown[i] + 1]; Ruleset.rules[toMoveDown[i] + 1] = Ruleset.rules[toMoveDown[i]]; Ruleset.rules[toMoveDown[i]] = tempRule; tempString = Ruleset.ruleFileNames[toMoveDown[i] + 1]; Ruleset.ruleFileNames[toMoveDown[i] + 1] = Ruleset.ruleFileNames[toMoveDown[i]]; Ruleset.ruleFileNames[toMoveDown[i]] = tempString; } } /* now re-number the list. */ string itemString; char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; for (var i = 1; i <= listBoxOfRules.Items.Count; i++) { itemString = (string)(listBoxOfRules.Items[(i - 1)] as ListBoxItem).Content; itemString = itemString.TrimStart(digits); (listBoxOfRules.Items[(i - 1)] as ListBoxItem).Content = i + itemString; } } catch (Exception exc) { ErrorLogger.Catch(exc); } }
/// <summary> /// Checks that the K arcs do not change direction. /// </summary> /// <param name="gR">The grammar rule.</param> /// <returns></returns> protected static string KarcsChangeDirection(grammarRule gR) { var badArcNames = ""; foreach (var a in gR.L.arcs) { var b = (ruleArc)gR.R.arcs.FirstOrDefault(c => (c.name.Equals(a.name))); if (b != null) { if (((a.To != null) && (b.From != null) && (a.To.name == b.From.name)) || ((a.From != null) && (b.To != null) && (a.From.name == b.To.name))) { badArcNames += a.name + ", "; } } } return(badArcNames); }
public void showProperties(Netron.GraphLib.UI.GraphControl GC, grammarRule rule, object sender, object[] props) { if (props.GetLength(0) > 0) { if ((propWindow == null) || !propWindow.CanSelect) { propWindow = new PropertiesWindow(); } if (this.ActiveMdiChild.WindowState.Equals(FormWindowState.Maximized)) { propWindow.MdiParent = null; } propWindow.Show(); propWindow.Activate(); propWindow.showProperties(GC, rule, props); } }
internal void Update(grammarRule Rule) { PopulateNodeNames(Rule.L.nodes, cmdLNodeName, "<any>"); PopulateNodeNames(Rule.R.nodes, cmdRNodeName, "<null> (leave dangling)"); if (selectedRule == Rule) { if (Rule.embeddingRules.Count == 0) { DisableProperties(); } else if (Rule.embeddingRules.Contains(selectedEmbeddingRule)) { Update(); } else { eRulesListBox.SelectedIndex = 0; } } else { selectedRule = Rule; BindingOperations.ClearBinding(this, ItemsControl.ItemsSourceProperty); var ItemsBinding = new Binding(); ItemsBinding.Source = Rule.embeddingRules; ItemsBinding.Mode = BindingMode.OneWay; ItemsBinding.Converter = new EmbeddingRuleListConverter(); eRulesListBox.SetBinding(ItemsControl.ItemsSourceProperty, ItemsBinding); listBoxBE = BindingOperations.GetBindingExpression(eRulesListBox, ItemsControl.ItemsSourceProperty); eRulesListBox.DisplayMemberPath = "name"; if (Rule.embeddingRules.Count == 0) { DisableProperties(); } else { eRulesListBox.SelectedIndex = 0; } } }
private void moveCheckedDown_Click(object sender, EventArgs e) { string tempString = null; grammarRule tempRule = null; int numToMoveDown = this.checkedListBox1.CheckedIndices.Count; int[] toMoveDown = new int[numToMoveDown]; this.checkedListBox1.CheckedIndices.CopyTo(toMoveDown, 0); for (int i = numToMoveDown - 1; i >= 0; i--) { if ((toMoveDown[i] != this.checkedListBox1.Items.Count - 1) && (!this.checkedListBox1.GetItemChecked(toMoveDown[i] + 1))) { tempString = (string)this.checkedListBox1.Items[toMoveDown[i] + 1]; this.checkedListBox1.Items[toMoveDown[i] + 1] = this.checkedListBox1.Items[toMoveDown[i]]; this.checkedListBox1.Items[toMoveDown[i]] = tempString; this.checkedListBox1.SetItemChecked(toMoveDown[i] + 1, true); this.checkedListBox1.SetSelected(toMoveDown[i] + 1, true); this.checkedListBox1.SetItemChecked(toMoveDown[i], false); this.checkedListBox1.SetSelected(toMoveDown[i], false); tempRule = ruleset.rules[toMoveDown[i] + 1]; ruleset.rules[toMoveDown[i] + 1] = ruleset.rules[toMoveDown[i]]; ruleset.rules[toMoveDown[i]] = tempRule; tempString = ruleset.ruleFileNames[toMoveDown[i] + 1]; ruleset.ruleFileNames[toMoveDown[i] + 1] = ruleset.ruleFileNames[toMoveDown[i]]; ruleset.ruleFileNames[toMoveDown[i]] = tempString; } } /* now re-number the list. */ string itemString; char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; for (int i = 1; i <= this.checkedListBox1.Items.Count; i++) { itemString = (string)this.checkedListBox1.Items[(i - 1)]; itemString = itemString.TrimStart(digits); this.checkedListBox1.Items[(int)(i - 1)] = i.ToString() + itemString; } }
public ruleWindow(grammarRule gr, CanvasProperty canvasProperties, string filename, string title) { /* the following is common to all GS window types. */ InitializeComponent(); Owner = main; graphCanvasK.ScrollOwner = scrollViewerK; graphCanvasL.ScrollOwner = scrollViewerL; graphCanvasR.ScrollOwner = scrollViewerR; ShowInTaskbar = false; foreach (CommandBinding cb in main.CommandBindings) { CommandBindings.Add(cb); graphCanvasK.CommandBindings.Add(cb); graphCanvasL.CommandBindings.Add(cb); graphCanvasR.CommandBindings.Add(cb); } foreach (InputBinding ib in main.InputBindings) { InputBindings.Add(ib); graphCanvasK.InputBindings.Add(ib); graphCanvasL.InputBindings.Add(ib); graphCanvasR.InputBindings.Add(ib); } /***************************************************/ rule = gr; this.filename = !string.IsNullOrEmpty(filename) ? filename : "Untitled"; Title = !string.IsNullOrEmpty(title) ? title : Path.GetFileNameWithoutExtension(this.filename); canvasProps = canvasProperties; canvasProps.AddGUIToControl(graphCanvasK); canvasProps.AddGUIToControl(graphCanvasL); canvasProps.AddGUIToControl(graphCanvasR); AdoptWindowWideCanvasProperties(); InitDrawRule(); }
/// <summary> /// Validates the free arc embedding rules. /// </summary> /// <param name="gR">The grammar rule.</param> /// <returns></returns> protected static Boolean ValidateFreeArcEmbeddingRules(grammarRule gR) { if (gR.embeddingRules == null) { return(true); } var result = true; for (var i = 0; i < gR.embeddingRules.Count; i++) { var eR = gR.embeddingRules[i]; if ((string.IsNullOrWhiteSpace(eR.LNodeName)) || (eR.LNodeName.Equals("<any>"))) { eR.LNodeName = null; } else if (!gR.L.nodes.Any(nL => nL.name.Equals(eR.LNodeName))) { SearchIO.output("Error in the embedding rules #" + i + ": No L-node named " + eR.LNodeName); result = false; } if ((string.IsNullOrWhiteSpace(eR.RNodeName)) || (eR.RNodeName.Equals("<any>"))) { eR.RNodeName = null; } else if (!gR.R.nodes.Any(nR => nR.name.Equals(eR.RNodeName))) { SearchIO.output("Error in the embedding rules #" + i + ": No R-node named " + eR.RNodeName); result = false; } if (!result) { break; } } return(result); }
public void showProperties(Netron.GraphLib.UI.GraphControl GC, designGraph graph1, object[] props) { graphControl = GC; graph = graph1; rule = null; try { graph.updateFromGraphControl(graphControl); if (graph.Bag == null) { graph.initPropertiesBag(); } this.graphRuleProps.SelectedObject = graph.Bag; this.graphRulePropsTab.Text = "Graph Properties"; } catch (Exception exc) { MessageBox.Show("The properties of the graph has thrown an exception and cannot be displayed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); SearchIO.output(exc.Message, 2); } showDisplayProperties(graphControl, (Netron.GraphLib.PropertyBag)props[0]); showNodeArcProperties((Netron.GraphLib.PropertyBag)props[0], graph); }
/// <summary> /// Serializes the rule to XML. /// </summary> /// <param name = "ruleToSave">The rule to save.</param> /// <returns></returns> protected string SerializeRuleToXml(grammarRule ruleToSave) { try { var settings = new XmlWriterSettings { Indent = true, NewLineOnAttributes = true, CloseOutput = true, OmitXmlDeclaration = true }; var saveString = new StringBuilder(); var saveXML = XmlWriter.Create(saveString, settings); var ruleSerializer = new XmlSerializer(typeof(grammarRule)); ruleSerializer.Serialize(saveXML, ruleToSave); return(saveString.ToString()); } catch (Exception ioe) { SearchIO.output("***XML Serialization Error***"); SearchIO.output(ioe.ToString()); return(null); } }
public grammarRuleDisplay(grammarRule initRule) { initGrammarRuleDisplay(initRule, initRule.name); }
private void SaveRule(string filename, grammarRule rule, designGraph graphK, CanvasProperty canvProp) { if (UserCancelled) { return; } progress = 3; rule.name = Path.GetFileNameWithoutExtension(filename); if (checkRule(rule)) { // progress is now at 13 string SaveString = null; dispatch.Invoke((ThreadStart) delegate { var xamlPage = BuildXAMLRulePage(rule, graphK, canvProp); SaveString = XamlWriter.Save(xamlPage); }); progress = 85; SaveString = MyXamlHelpers.CleanOutxNulls(SaveString); /* A little manipulation is needed to stick the GraphSynth objects within the page. * * The IgnorableSetup string ensures that XAML viewers ignore the following * * GraphSynth specific elements: the canvas data, and the graph data. This eff- * * ectively separates the topology and data of the graph from the graphic elements. */ SaveString = SaveString.Insert(SaveString.IndexOf(">"), IgnorableSetup + "Tag=\"Rule\" "); /* remove the ending Page tag but put it back at the end. */ SaveString = SaveString.Replace("</Page>", ""); /* add the canvas properties. */ if (canvProp != null) { dispatch.Invoke( (ThreadStart) delegate { SaveString += "\n\n" + AddIgnorablePrefix(CanvasProperty.SerializeCanvasToXml(canvProp)); }); } progress = 92; /* add the graph data. */ SaveString += "\n\n" + AddIgnorablePrefix(SerializeRuleToXml(rule)) + "\n\n"; /* put the closing tag back on. */ SaveString += "</Page>"; try { File.WriteAllText(filename, SaveString); } catch (Exception E) { if (!suppressWarnings) { progWindow.QueryUser("File Access Exception" + E.Message, 10000, "", "Cancel", false); } } progress = 100; if ((progWindow != null) && (!suppressWarnings)) { progWindow.QueryUser("\n **** Rule successfully saved. ****", 1000, "OK", "", false); } else { SearchIO.output("**** Rule successfully saved. ****", 2); } } }
public object[] OpenRuleAndCanvas(string filename) { XmlReader xR = null; try { xR = XmlReader.Create(filename); var xeRule = XElement.Load(xR); if (UserCancelled) { return(null); } progress = 5; var shapes = xeRule.Element("{http://schemas.microsoft.com/winfx/2006/xaml/presentation}" + "Border"); shapes = shapes.Elements().FirstOrDefault(); if (UserCancelled) { return(null); } progress = 7; var shapesL = (from s in shapes.Elements() where ((s.Attribute("Tag") != null) && (s.Attribute("Tag").Value == "L")) select s).FirstOrDefault(); if (shapesL != null) { shapesL = shapesL.Elements().First(); } else { SearchIO.output("No Left Canvas of Shapes found."); shapesL = new XElement("dummyL"); } if (UserCancelled) { return(null); } progress = 9; var shapesR = (from s in shapes.Elements() where ((s.Attribute("Tag") != null) && (s.Attribute("Tag").Value == "R")) select s).FirstOrDefault(); if (shapesR != null) { shapesR = shapesR.Elements().First(); } else { SearchIO.output("No Left Canvas of Shapes found."); shapesR = new XElement("dummyL"); } if (UserCancelled) { return(null); } progress = 11; CanvasProperty canvas = null; dispatch.Invoke((ThreadStart) delegate { canvas = LoadCanvasProperty(xeRule); }); if (UserCancelled) { return(null); } progress = 16; var temp = xeRule.Element("{ignorableUri}" + "grammarRule"); var openRule = new grammarRule(); if (temp != null) { openRule = DeSerializeRuleFromXML(RemoveXAMLns(RemoveIgnorablePrefix(temp.ToString()))); } if (UserCancelled) { return(null); } progress = 40; progressEnd = 70; RestoreDisplayShapes(shapesL, openRule.L.nodes, openRule.L.arcs, openRule.L.hyperarcs); progressEnd = 100; RestoreDisplayShapes(shapesR, openRule.R.nodes, openRule.R.arcs, openRule.R.hyperarcs); removeNullWhiteSpaceEmptyLabels(openRule.L); removeNullWhiteSpaceEmptyLabels(openRule.R); xR.Close(); return(new object[] { openRule, canvas, filename }); } catch { xR.Close(); return(OpenRuleAndCanvasesOLD(filename)); } }
private new Boolean checkRule(grammarRule gR) { if (progWindow == null) { return(true); } if ((gR.L.checkForRepeatNames()) && !suppressWarnings && !progWindow.QueryUser("You are not allowed to have repeat names in L. I have changed these " + "names to be unique, which may have disrupted your context graph, K. Do you want to continue" + "saving?", 0, "Yes", "No", false)) { return(false); } if (UserCancelled) { return(false); } progress += 2; if ((gR.R.checkForRepeatNames()) && !suppressWarnings && !progWindow.QueryUser("You are not allowed to have repeat names in R. I have changed" + " these names to be unique, which may have disrupted your context graph, K. Do you" + " want to continue saving?", 0, "Yes", "No", false)) { return(false); } if (UserCancelled) { return(false); } if ((NotExistElementsinKR(gR)) && !suppressWarnings && !progWindow.QueryUser("There appears to be common elements between " + "the left and right hand sides of the rule that are indicated as \"Must NOT Exist\"" + " within the left-hand side. This is not allowed. Continue Anyway?", 0, "Yes", "No", false)) { return(false); } progress += 2; if ((NumKElements(gR) == 0) && !suppressWarnings && !progWindow.QueryUser("No Context Graph: There appears to be no common elements between " + "the left and right hand sides of the rule. Is this intentional? If so, click yes to continue.", 0, "Yes", "No", false)) { return(false); } if (UserCancelled) { return(false); } progress += 2; if ((KarcsChangeDirection(gR) != "") && !suppressWarnings && !progWindow.QueryUser("It appears that arc(s): " + KarcsChangeDirection(gR) + " change direction (to = from or vice-versa). Even though the arc(s) might be undirected," + " this can still lead to problems in the rule application, it is recommended that this is" + " fixed before saving. Save anyway?", 0, "Yes", "No", false)) { return(false); } if (UserCancelled) { return(false); } progress += 2; if ((!ValidateFreeArcEmbeddingRules(gR)) && !suppressWarnings && !progWindow.QueryUser("There appears to be invalid references in the free arc embedding rules." + " Node names used in free arc embedding rules do not exist. Save Anyway?", 0, "Yes", "No", false)) { return(false); } if (UserCancelled) { return(false); } progress += 2; if ((!ValidateFreeArcEmbeddingRules(gR)) && !suppressWarnings && !progWindow.QueryUser("There appears to be invalid references in the free arc embedding rules." + " Node names used in free arc embedding rules do not exist. Save Anyway?", 0, "Yes", "No", false)) { return(false); } if (UserCancelled) { return(false); } progress += 2; gR.ReorderNodes(); return(true); }
private FrameworkElement BuildXAMLRulePage(grammarRule rule, designGraph graphK, CanvasProperty canvProp) { if (canvProp == null) { canvProp = new CanvasProperty(); } var g = new Grid(); g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(canvProp.CanvasWidth.Left) }); g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(6) }); g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(canvProp.CanvasWidth.Top) }); g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(6) }); var rWidth = canvProp.CanvasWidth.Bottom - 12 - canvProp.CanvasWidth.Left - canvProp.CanvasWidth.Top; g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(rWidth) }); var gs1 = new GridSplitter { Width = 6, VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Stretch, ShowsPreview = true }; var gs2 = new GridSplitter { Width = 6, VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Stretch, ShowsPreview = true }; g.Children.Add(gs1); Grid.SetColumn(gs1, 1); g.Children.Add(gs2); Grid.SetColumn(gs2, 3); if (UserCancelled) { return(null); } progress = 20; progressEnd = 40; var svL = new ScrollViewer { Tag = "L", CanContentScroll = false, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Content = BuildGraphGUICanvas(rule.L, canvProp) }; g.Children.Add(svL); Grid.SetColumn(svL, 0); if (UserCancelled) { return(null); } progress += 2; progressEnd = 60; var svK = new ScrollViewer { Tag = "K", CanContentScroll = false, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Auto }; if (graphK != null) { svK.Content = BuildGraphGUICanvas(graphK, canvProp); } else { svK.Content = new TextBlock { Text = "not enough information to display", Margin = new Thickness(3), TextWrapping = TextWrapping.Wrap, HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch } }; g.Children.Add(svK); Grid.SetColumn(svK, 2); if (UserCancelled) { return(null); } progress += 2; progressEnd = 80; var svR = new ScrollViewer { Tag = "R", CanContentScroll = false, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Content = BuildGraphGUICanvas(rule.R, canvProp) }; g.Children.Add(svR); Grid.SetColumn(svR, 4); return(new Page { Background = Brushes.Black, Content = new Border { BorderThickness = new Thickness(1), BorderBrush = Brushes.DarkGray, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Child = g } }); }
/// <summary> /// Checks that the number of K elements is greater than 0. /// </summary> /// <param name="gR">The grammar rule.</param> /// <returns></returns> protected static int NumKElements(grammarRule gR) { return(gR.L.nodes.Count(n => gR.R.nodes.Exists(a => a.name == n.name)) + gR.L.arcs.Count(n => gR.R.arcs.Exists(a => a.name == n.name)) + gR.L.hyperarcs.Count(n => gR.R.hyperarcs.Exists(a => a.name == n.name))); }
public void addAndShowRuleWindow(object obj, string title = null) { var gR = new grammarRule(); var canvas = new CanvasProperty(); string filename = null; if (obj == null) { gR = null; } else if (obj is grammarRule) { gR = (grammarRule)obj; } else if (obj is object[]) { var objArray = (object[])obj; if (objArray.GetLength(0) > 0) { if (objArray[0] is grammarRule) { gR = (grammarRule)objArray[0]; } else if (objArray[0] is CanvasProperty) { canvas = (CanvasProperty)objArray[0]; } else if (objArray[0] is string) { filename = (string)objArray[0]; } } if (objArray.GetLength(0) > 1) { if (objArray[1] is grammarRule) { gR = (grammarRule)objArray[1]; } else if (objArray[1] is CanvasProperty) { canvas = (CanvasProperty)objArray[1]; } else if (objArray[1] is string) { filename = (string)objArray[1]; } } if (objArray.GetLength(0) > 2) { if (objArray[2] is grammarRule) { gR = (grammarRule)objArray[2]; } else if (objArray[2] is CanvasProperty) { canvas = (CanvasProperty)objArray[2]; } else if (objArray[2] is string) { filename = (string)objArray[2]; } } } if (!windowsMgr.FindAndFocusFileInCollection(filename, WindowType.Rule)) { var rW = new ruleWindow(gR, canvas, filename, title); windowsMgr.AddandShowWindow(rW); } }
private object[] OpenRuleAndCanvasesOLD(string filename) { grammarRule openRule = null; var strRuleProperties = ""; var xmlRule = new XmlDocument(); UICanvas Lcanvas = null; UICanvas Rcanvas = null; xmlRule.Load(filename); try { var xmlLGraph = new XmlDocument(); xmlLGraph.AppendChild(xmlLGraph.ImportNode(xmlRule.DocumentElement, false)); //XmlDocument xmlKGraph = new XmlDocument(); //xmlKGraph.AppendChild(xmlKGraph.ImportNode(xmlRule.DocumentElement, false)); var xmlRGraph = new XmlDocument(); xmlRGraph.AppendChild(xmlRGraph.ImportNode(xmlRule.DocumentElement, false)); XmlNode tempNode; var baseGrid = xmlRule.DocumentElement.ChildNodes[0]; var i = 0; while (baseGrid.ChildNodes.Count != 0) { if ((baseGrid.ChildNodes[i].Name == IgnorablePrefix + "Canvas" && baseGrid.ChildNodes[i].Attributes[IgnorablePrefix + "Graph"].Value == "L") || (baseGrid.ChildNodes[i].Name == IgnorablePrefix + "designGraph" && baseGrid.ChildNodes[i].Attributes[IgnorablePrefix + "Graph"].Value == "L") || (baseGrid.ChildNodes[i].Name == "Canvas" && baseGrid.ChildNodes[i].Attributes[IgnorablePrefix + "Graph"].Value == "L")) { baseGrid.ChildNodes[i].Attributes.Remove( baseGrid.ChildNodes[i].Attributes[IgnorablePrefix + "Graph"]); tempNode = baseGrid.RemoveChild(baseGrid.ChildNodes[i]); xmlLGraph.DocumentElement.AppendChild(xmlLGraph.ImportNode(tempNode, true)); } else if ((baseGrid.ChildNodes[i].Name == IgnorablePrefix + "Canvas" && baseGrid.ChildNodes[i].Attributes[IgnorablePrefix + "Graph"].Value == "R") || (baseGrid.ChildNodes[i].Name == IgnorablePrefix + "designGraph" && baseGrid.ChildNodes[i].Attributes[IgnorablePrefix + "Graph"].Value == "R") || (baseGrid.ChildNodes[i].Name == "Canvas" && baseGrid.ChildNodes[i].Attributes[IgnorablePrefix + "Graph"].Value == "R")) { baseGrid.ChildNodes[i].Attributes.Remove( baseGrid.ChildNodes[i].Attributes[IgnorablePrefix + "Graph"]); tempNode = baseGrid.RemoveChild(baseGrid.ChildNodes[i]); xmlRGraph.DocumentElement.AppendChild(xmlRGraph.ImportNode(tempNode, true)); } else if (baseGrid.ChildNodes[i].Name == IgnorablePrefix + "RuleProperties") { tempNode = baseGrid.RemoveChild(baseGrid.ChildNodes[i]); strRuleProperties = tempNode.OuterXml; } else if (baseGrid.ChildNodes[i].Name == "Grid.ColumnDefinitions" || baseGrid.ChildNodes[i].Name == "GridSplitter") { baseGrid.RemoveChild(baseGrid.ChildNodes[i]); // not needed. Used to show rule properly in browser } else { i++; } } if (strRuleProperties.IndexOf("xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"") != -1) { strRuleProperties = strRuleProperties.Replace( "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"", ""); } // get rid of the ignorable prefix if (strRuleProperties.IndexOf(IgnorablePrefix) != -1) { strRuleProperties = strRuleProperties.Remove(strRuleProperties.IndexOf(IgnorablePrefix), IgnorablePrefix.Length); } if (strRuleProperties.IndexOf("xmlns:" + IgnorablePrefix + "=\"ignorableUri\"") != -1) { strRuleProperties = strRuleProperties.Remove( strRuleProperties.IndexOf("xmlns:" + IgnorablePrefix + "=\"ignorableUri\""), "xmlns:".Length + IgnorablePrefix.Length + "=\"ignorableUri\"".Length); } if (strRuleProperties.LastIndexOf(IgnorablePrefix) != -1) { strRuleProperties = strRuleProperties.Remove(strRuleProperties.LastIndexOf(IgnorablePrefix), IgnorablePrefix.Length); } var rP = RuleProperties.DeSerializeFromXML(strRuleProperties); openRule = new grammarRule(); CopyRulePropertiesToRule(rP, openRule); var graphAndCanvas = OpenGraphAndCanvasOLD(xmlLGraph); openRule.L = (designGraph)graphAndCanvas[0]; Lcanvas = (UICanvas)graphAndCanvas[1]; graphAndCanvas = OpenGraphAndCanvasOLD(xmlRGraph); openRule.R = (designGraph)graphAndCanvas[0]; Rcanvas = (UICanvas)graphAndCanvas[1]; if ((string.IsNullOrWhiteSpace(openRule.name)) || (openRule.name == "Untitled")) { openRule.name = Path.GetFileNameWithoutExtension(filename); } } catch { openRule = OpenRule(filename); } if (openRule != null) { if (!suppressWarnings) { progWindow.QueryUser("Rule open in old format. Please re-save soon.", 1500, "OK", "", false); } return(new object[] { openRule, Lcanvas, Rcanvas }); } else { if (!suppressWarnings) { progWindow.QueryUser("Failed to open rule.", 5000, "OK", "", false); } return(null); } }
/// <summary> /// Checks to see that the negative elements are not stored in K and R. /// </summary> /// <param name="gR">The grammar rule.</param> /// <returns></returns> protected static Boolean NotExistElementsinKR(grammarRule gR) { return(gR.L.nodes.Any(a => ((ruleNode)a).NotExist && gR.R.nodes.Exists(b => b.name.Equals(a.name))) || gR.L.arcs.Any(a => ((ruleArc)a).NotExist && gR.R.arcs.Exists(b => b.name.Equals(a.name))) || gR.L.hyperarcs.Any(a => ((ruleHyperarc)a).NotExist && gR.R.hyperarcs.Exists(b => b.name.Equals(a.name)))); }
private string BuildXAMLRulePage(grammarRule rule, designGraph graphK) { return(""); }
public object[] OpenRuleAndCanvas(string filename) { XmlReader xR = null; try { xR = XmlReader.Create(filename); var xeRule = XElement.Load(xR); var shapes = xeRule.Element("{http://schemas.microsoft.com/winfx/2006/xaml/presentation}" + "Border"); shapes = shapes.Elements().FirstOrDefault(); var shapesL = (from s in shapes.Elements() where ((s.Attribute("Tag") != null) && (s.Attribute("Tag").Value == "L")) select s).FirstOrDefault(); if (shapesL != null) { shapesL = shapesL.Elements().First(); } else { SearchIO.output("No Left Canvas of Shapes found."); shapesL = new XElement("dummyL"); } var shapesR = (from s in shapes.Elements() where ((s.Attribute("Tag") != null) && (s.Attribute("Tag").Value == "R")) select s).FirstOrDefault(); if (shapesR != null) { shapesR = shapesR.Elements().First(); } else { SearchIO.output("No Left Canvas of Shapes found."); shapesR = new XElement("dummyL"); } var temp = xeRule.Element("{ignorableUri}" + "grammarRule"); var openRule = new grammarRule(); if (temp != null) { openRule = DeSerializeRuleFromXML(RemoveXAMLns(RemoveIgnorablePrefix(temp.ToString()))); } RestoreDisplayShapes(shapesL, openRule.L.nodes, openRule.L.arcs, openRule.L.hyperarcs); RestoreDisplayShapes(shapesR, openRule.R.nodes, openRule.R.arcs, openRule.R.hyperarcs); return(new object[] { openRule, filename }); } catch { return(null); } finally { xR.Close(); } }
public static void Run(designGraph seed, grammarRule rule, Relaxation RelaxationTemplate = null) { try { if (RelaxationTemplate == null) { RelaxationTemplate = new Relaxation(0); } var rnd = new Random(); int k = 0; var continueTesting = true; SearchIO.output("begin recognizing rule: " + rule.name + "on graph :" + seed.name, 2); var dummyRS = new ruleSet(); dummyRS.Add(rule); if (SearchIO.GetTerminateRequest(Thread.CurrentThread.ManagedThreadId)) { return; } var options = dummyRS.recognize(seed, false, RelaxationTemplate.copy()); if (SearchIO.GetTerminateRequest(Thread.CurrentThread.ManagedThreadId)) { return; } var numOptions = options.Count; if (numOptions == 0) { if (MessageBox.Show("There were no recognized options. Should the rule be relaxed?", "Test Rule Status", MessageBoxButton.YesNo, MessageBoxImage.Asterisk, MessageBoxResult.No) == MessageBoxResult.Yes) { Run(seed, rule, new Relaxation(RelaxationTemplate.NumberAllowable + 1)); } return; } do { var status = "There "; int choice = -1; switch (numOptions) { case 0: throw new Exception("Should not be able to reach here. (Test Rule Chooser, zero options.)"); case 1: status += "was only one recognized option and it applied as shown.\n"; choice = 0; status += options[choice].Relaxations.RelaxationSummary; break; default: status += "were " + numOptions + " recognized locations.\n"; choice = rnd.Next(options.Count); status += options[choice].Relaxations.RelaxationSummary; option.AssignOptionConfluence(options, new candidate(seed, 0), ConfluenceAnalysis.Full); var numberWithConfluence = options.Count(o => (o.confluence.Count > 0)); var maxConfluence = options.Max(o => o.confluence.Count); var withMaxConfluence = options.Count(o => (o.confluence.Count == maxConfluence)); if (numberWithConfluence > 0) { status += "Confluence existed between " + numberWithConfluence + " of them"; if (maxConfluence > 1) { status += "; \nwith " + withMaxConfluence + " options having a confluence with " + maxConfluence + " other options.\n"; } else { status += ".\n"; } } status += "Option #" + choice + " was randomly chosen, and invoked.\n"; break; } if (!continueTesting) { continue; } if (SearchIO.GetTerminateRequest(Thread.CurrentThread.ManagedThreadId)) { return; } var chosenOption = options[choice]; { var seedCopy = seed.copy(); SearchProcess.transferLmappingToChild(seedCopy, seed, chosenOption); seed = seedCopy; } chosenOption.apply(seed, null); SearchIO.output("Rule sucessfully applied", 4); SearchIO.addAndShowGraphWindow(seed, "After calling " + ++k + " rules"); if (SearchIO.GetTerminateRequest(Thread.CurrentThread.ManagedThreadId)) { return; } options = dummyRS.recognize(seed, true, RelaxationTemplate.copy()); if (SearchIO.GetTerminateRequest(Thread.CurrentThread.ManagedThreadId)) { return; } numOptions = options.Count; switch (numOptions) { case 0: status += "There are no recognized locations on the new graph"; continueTesting = false; MessageBox.Show(status, "Test Rule Status", MessageBoxButton.OK, MessageBoxImage.Asterisk); break; case 1: status += "There is one recognized location on the new graph. Would you like to invoke it?"; continueTesting = (MessageBox.Show(status, "Continue Applying?", MessageBoxButton.YesNo, MessageBoxImage.Asterisk, MessageBoxResult.No) == MessageBoxResult.Yes); break; default: status += "There are " + options.Count + " recognized locations on the new graph. Would you " + "like to randomly invoke one?"; continueTesting = (MessageBox.Show(status, "Continue Applying?", MessageBoxButton.YesNo, MessageBoxImage.Asterisk, MessageBoxResult.No) == MessageBoxResult.Yes); break; } } while (continueTesting); } catch (Exception exc) { ErrorLogger.Catch(exc); } }