Exemplo n.º 1
0
        public SimpleTransition GetTransition(List <Instruction> inst, DrawableObject select, Dictionary <int, DrawableObject> list)
        {
            Point[] pts = new Point[4] {
                inst[1].Point(0),
                inst[2].Point(0),
                inst[3].Point(0),
                inst[4].Point(0)
            };
            SimpleTransition trans = new SimpleTransition(Owner.OwnerDraw, pts, null);

            trans.Name = Owner.OwnerDraw.OwnerSheet.NextObjectName(trans.GetFormName());
            Owner.OwnerDraw.AddObject(trans);
            trans.StartObject = select;
            Point point = trans.StartPoint;

            trans.StartObject.Intersect(trans.StartPoint, ref point, ref trans.StartAngle);
            trans.EndObject = list[StateId];
            point           = trans.EndPoint;
            trans.EndObject.Intersect(trans.EndPoint, ref point, ref trans.EndAngle);
            trans.Condition = Text[1];
            trans.OutputsList.AddRange(Text[3].Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
            Point textPoint = Util.Center(new Point[] { Point(0), Point(3) });

            trans.SetTextPoint(textPoint);
            return(trans);
        }
Exemplo n.º 2
0
		public State (int id, string name, SimpleTransition[] ts)
		{
			if (id < 0 || id >= 255)
				throw new ArgumentOutOfRangeException ();

			Id = id;
			Name = name;
			Delta = ts;
		}
Exemplo n.º 3
0
        private IImageTransition getTransition()
        {
            switch (settings.BlendImages)
            {
            case BlendImagesMode.CustomImage:
            {
                Image image;
                try
                {
                    image = ImageHelper.FromFile(settings.CustomImagePath);
                }
                catch (Exception ex)
                {
                    image = ImageHelper.FromFile(settings.DefaultImageName);
                    Logger.Debug(string.Format("Cannot open custom image {0} : {1}",
                                               settings.CustomImagePath, ex.Message));
                }
                CustomImageTransition transition = _imageTransition as CustomImageTransition;
                if (transition == null)
                {
                    _imageTransition = new CustomImageTransition(image);
                }
            }
            break;

            case BlendImagesMode.InAndOut:
            {
                SmoothTransition smooth = _imageTransition as SmoothTransition;
                if (smooth == null)
                {
                    _imageTransition = new SmoothTransition();
                }
            }
            break;

            case BlendImagesMode.OutThenIn:
            {
                OutThenInTransition outThenIn = _imageTransition as OutThenInTransition;
                if (outThenIn == null)
                {
                    _imageTransition = new OutThenInTransition();
                }
            }
            break;

            case BlendImagesMode.None:
            {
                SimpleTransition simple = _imageTransition as SimpleTransition;
                if (simple == null)
                {
                    _imageTransition = new SimpleTransition();
                }
            }
            break;
            }
            return(_imageTransition);
        }
Exemplo n.º 4
0
        public void Equals_DifferentTypes_ReturnsFalse()
        {
            var comparer = this.GetComparer();

            var transitionA = new SimpleTransition();
            var transitionB = new SetTransition();

            var result = comparer.Equals(transitionA, transitionB);

            Assert.IsFalse(result);
        }
Exemplo n.º 5
0
        public void Equals_DifferentSimpleTransitions_ReturnsTrue()
        {
            var comparer = this.GetComparer();

            var transitionA = new SimpleTransition {
                GlyphId = 2
            };
            var transitionB = new SimpleTransition {
                GlyphId = 1
            };

            var result = comparer.Equals(transitionA, transitionB);

            Assert.IsFalse(result);
        }
Exemplo n.º 6
0
        protected SimpleTransition CreateMissingTransitionBranches(byte read)
        {
            SimpleTransition trans = null;

            var nTransitions = _Definition.Q.Values.Sum(q => q.Delta == null ? 0 : q.Delta.Count(t => t != null));

            if (nTransitions == _Definition.Q.Count * 2 - 3)
            {
                // Last transition is always the halting state
                trans = new SimpleTransition(Q, read, _Definition.Qa ?? _Definition.Qr, 1, 1);
            }
            else
            {
                var from = _Definition.Q.Values.Where(q => q.Delta != null);
                var qs   = from.Take(1).ToList();
                qs.AddRange(from.Skip(1).TakeWhile(q => q.Sources.Any()));
                qs.AddRange(from.Skip(1).SkipWhile(q => q.Sources.Any()).Take(1));

                var Directions = new short[] { 1, -1 };
                foreach (var q in qs)
                {
                    foreach (var o in _Definition.Gamma.Keys)
                    {
                        foreach (var d in Directions)
                        {
                            var t = new SimpleTransition(Q, read, q, o, d);

                            if (trans == null)
                            {
                                trans = t;
                            }
                            else
                            {
                                var branch = _Definition.GetShortDefinitionString(null, t);
                                Branches.Add(branch);
                            }
                        }
                    }
                }
            }

            _Definition.UpdateTransition(trans);
            return(trans);
        }
Exemplo n.º 7
0
		public string GetShortDefinitionString (int? changeSuggestedMacroSize, SimpleTransition additionalTransition)
		{
			var s = "";

			foreach (var q in Q.OrderBy (x => x.Key).Select (x => x.Value)) {
				if (s.Length > 0) {
					s += ",";
				}

				var ts = new List<SimpleTransition> ();
				if (q.Delta != null) {
					ts.AddRange (q.Delta);
				}
				if (additionalTransition != null && q == additionalTransition.Source) {
					if (ts.Any ()) {
						if (ts[additionalTransition.Read] != null) {
							throw new InvalidOperationException ("Tried to replace an existing transition in delta table.");
						}
						ts[additionalTransition.Read] = additionalTransition;
					}
					else {
						throw new Exception ("ist das so ok?");
						ts.Add (additionalTransition);
					}
				}

				foreach (var t in ts) {
					if (s.Length > 0) {
						s += " ";
					}
					if (t == null) {
						s += "---";
					}
					else {
						s += t.Write;
						s += t.Direction == 1 ? "R" : "L";
						s += t.Next.Name;
					}
				}
			}

			var k = changeSuggestedMacroSize ?? SuggestedMacroSize;
			if (k != null) {
				s += " K=" + k.Value;
			}

			return s;
		}
Exemplo n.º 8
0
		public void UpdateTransition (SimpleTransition t)
		{
			if (t == null)
				throw new ArgumentNullException ();

			t.Source.Delta[t.Read] = t;
			FullDefinitionString += " " + t.ToString (this) + ";";
			UpdateShortDefinitionString ();
		}
Exemplo n.º 9
0
		public TmDefinition (JsonTmDefinition def)
		{
			if (def == null)
				throw new ArgumentNullException ();

			Gamma = MapSymbols (def.Gamma, 0);
			Sigma = new Dictionary<byte, string> ();
			foreach (var sig in def.Sigma) {
				Sigma.Add (Gamma.Where (p => p.Value == sig).First ().Key, sig);
			}

			Func<string, State> createState = name => {
				var halting = false
					|| def.AcceptingState == name
					|| def.RefusingState == name;
				var ts = halting ? null : new SimpleTransition[Gamma.Count];
				var q = new State (Q.Count, name, ts);
				Q.Add (name, q);
				return q;
			};

			Q0 = createState (def.InitialState);

			foreach (var qs in def.NonfinalStates) {
				if (qs == def.InitialState) {
					continue;
				}
				createState (qs);
			}

			if (def.AcceptingState != null) {
				createState (def.AcceptingState);
			}
			if (def.RefusingState != null) {
				createState (def.RefusingState);
			}

			foreach (var t in def.Delta) {
				var qin = Q[t.From];
				byte gin = Gamma.First (p => p.Value == t.Read).Key;
				var qout = Q[t.To];
				byte gout = Gamma.First (p => p.Value == t.Write).Key;
				short dir;
				switch (t.Dir) {
					case "R":
						dir = 1;
						break;

					case "L":
						dir = -1;
						break;

					case "S":
						dir = 0;
						break;

					default:
						throw new Exception ();
				}

				var st = new SimpleTransition (qin, gin, qout, gout, dir);
				qin.Delta[gin] = st;
				qout.Sources.Add (st);
			}

			SuggestedMacroSize = def.SuggestedMacroSize;

			UpdateShortDefinitionString ();
		}
Exemplo n.º 10
0
		/// <summary>
		/// </summary>
		/// <param name="s">
		/// Format:
		/// q0,q1,...; Q
		/// s0,s1,...; Sigma
		/// g0,g1,...; Gamma without Sigma
		/// q,i -> q',o,d; Single Delta transition, repeatable
		/// K=n; Suggested macro width, optional
		/// /* anywhere: comments in old C style allowed */
		/// </param>
		public TmDefinition (string s)
		{
			if (s == null)
				throw new ArgumentNullException ();

			if (s.Count (c => c == ';') <= 1) { // todo: bug when ';' in comments
				s = DefinitionLibrary.CreateBeaverFromNote (s);
			}
			FullDefinitionString = s;

			s = StripComments (s);

			var split = s.Split (';').Select (x => x.Trim ()).ToList ();

			var sStates = split[0];
			split.RemoveAt (0);
			var sHalting = split[0];
			split.RemoveAt (0);
			var sSigma = split[0];
			split.RemoveAt (0);
			var sGamma = split[0];
			split.RemoveAt (0);

			/*
			 * Sigma/Gamma
			 */
			var sigmasplit = sSigma.Split (',');
			var gammasplit = sGamma.Split (',');
			Sigma = MapSymbols (sigmasplit, 1);
			Gamma = MapSymbols (gammasplit.Skip (1), 1 + Sigma.Count);
			Gamma.Add (0, gammasplit[0]);
			foreach (var sig in Sigma) {
				Gamma.Add (sig.Key, sig.Value);
			}

			/*
			 * Q
			 * (can only be constructed once Gamma is known)
			 */
			var statessplit = sStates.Split (',');
			foreach (var p in statessplit.Select (x => x.Trim ())) {
				if (p == "") {
					continue;
				}

				if (Q.Count >= 255) {
					throw new Exception ();
				}

				var q = new State ((byte) Q.Count, p, new SimpleTransition[Gamma.Count]);
				Q.Add (p, q);

				if (Q0 == null) {
					Q0 = q;
				}
			}
			foreach (var p in sHalting.Split (',').Select (x => x.Trim ())) {
				if (p == "") {
					continue;
				}

				if (Q.Count >= 255) {
					throw new Exception ();
				}

				var q = new State ((byte) Q.Count, p, null);
				Q.Add (p, q);

				if (Q0 == null) {
					Q0 = q;
				}
			}

			var haltingStates = Q.Values.Where (q => q.Delta == null).ToArray ();
			if (haltingStates.Length == 0) {
				var nonhaltingStates = Q.OrderBy (x => x.Key).Select (x => x.Value).ToArray ();
				Qa = nonhaltingStates[nonhaltingStates.Length - 2];
				Qr = nonhaltingStates[nonhaltingStates.Length - 1];
			}
			else if (haltingStates.Length == 1) {
				Qa = haltingStates[0];
				Qr = null;
			}
			else {
				Qa = haltingStates[0];
				Qr = haltingStates[1];
			}

			// Here be dragons

			/*
			 * Delta
			 */
			while (split.Any ()) {
				var d = split[0];
				d = d.TrimStart (' ', '\t');
				split.RemoveAt (0);

				if (d == "") {
					continue;
				}

				if (d.StartsWith ("K=")) {
					d = d.Substring (2);
					SuggestedMacroSize = Unlog.Util.StringCutting.CutInt (ref d);
					split.Insert (0, d);
					continue;
				}

				var parts = d.Split (new[] { "->" }, 2, StringSplitOptions.None);
				var input = parts[0].Split (',').Select (x => x.Trim ()).ToArray ();
				var output = parts[1].Split (',').Select (x => x.Trim ()).ToArray ();

				var sqin = input[0];
				var stin = input[1];
				var sqout = output[0];
				var stout = output[1];
				var sd = output[2].ToUpperInvariant ();

				// Check different notation
				if (sd != "L" && sd != "R") {
					if (stout == "L" || stout == "R") {
						var tmp = sd;
						sd = stout;
						stout = sqout;
						sqout = tmp;
					}
				}

				var qin = Q[sqin];
				byte gin = Gamma.First (p => p.Value == stin).Key;
				var qout = Q[sqout];
				byte gout = Gamma.First (p => p.Value == stout).Key;
				short dir;
				switch (sd) {
					case "R":
						dir = 1;
						break;

					case "L":
						dir = -1;
						break;

					case "S":
						dir = 0;
						break;

					default:
						throw new Exception ();
				}

				var t = new SimpleTransition (qin, gin, qout, gout, dir);
				qin.Delta[gin] = t;
				qout.Sources.Add (t);
			}

			UpdateShortDefinitionString ();
		}
        public void GetStateMachine_ForkingPath_CollectsAllStatesAndTransitions()
        {
            SimpleTransition commonTransition, forkedTransition1, forkedTransition2;

            var paths = new[]
            {
                new[]
                {
                    commonTransition = new SimpleTransition
                    {
                        GlyphId   = 1,
                        HeadShift = 1,
                        Action    = new SubstitutionAction
                        {
                            ReplacedGlyphCount  = 1,
                            ReplacementGlyphIds = new ushort[] { 1 }
                        }
                    },
                    forkedTransition1 = new SimpleTransition
                    {
                        GlyphId   = 2,
                        HeadShift = 2,
                        Action    = new SubstitutionAction
                        {
                            ReplacedGlyphCount  = 2,
                            ReplacementGlyphIds = new ushort[] { 2 }
                        }
                    }
                },
                new[]
                {
                    new SimpleTransition
                    {
                        GlyphId   = 1,
                        HeadShift = 1,
                        Action    = new SubstitutionAction
                        {
                            ReplacedGlyphCount  = 1,
                            ReplacementGlyphIds = new ushort[] { 1 }
                        }
                    },
                    forkedTransition2 = new SimpleTransition {
                        GlyphId   = 3,
                        HeadShift = 3,
                        Action    = new SubstitutionAction
                        {
                            ReplacedGlyphCount  = 3,
                            ReplacementGlyphIds = new ushort[] { 3 }
                        }
                    }
                }
            };

            var builder = new StateMachineBuilder();

            foreach (var path in paths)
            {
                builder.AddPath(path);
            }

            var result = builder.GetStateMachine();

            Assert.AreEqual(result.States.Count, 4);
            Assert.IsTrue(
                new[] { commonTransition, forkedTransition1, forkedTransition2 }.ValuesEqual(result.Transitions, new TransitionNonrecursiveEqualityComparer()));
        }
Exemplo n.º 12
0
        /// <inheritdoc />
        public override void CompileTransformation(IGlyphTransformationTable transformation, IStateMachineBuilder builder)
        {
            if (transformation is SimpleReplacementSubstitutionTable)
            {
                var table = transformation as SimpleReplacementSubstitutionTable;

                var paths = table.Coverage.CoveredGlyphIds.Zip(
                    table.ReplacementGlyphIds,
                    (coveragePair, replacementGlyphId) => new[]
                {
                    new SimpleTransition {
                        GlyphId     = coveragePair.Value,
                        HeadShift   = 1,
                        LookupFlags = table.LookupFlags,
                        Action      = new SubstitutionAction
                        {
                            ReplacementGlyphIds = new[] { replacementGlyphId },
                            ReplacedGlyphCount  = 1
                        }
                    }
                });

                foreach (var path in paths)
                {
                    builder.AddPath(path);
                }
            }
            else if (transformation is DeltaSubstitutionTable)
            {
                var table = transformation as DeltaSubstitutionTable;

                var paths =
                    from coveragePair in table.Coverage.CoveredGlyphIds
                    select
                    new[]
                {
                    new SimpleTransition
                    {
                        GlyphId     = coveragePair.Value,
                        HeadShift   = 1,
                        LookupFlags = table.LookupFlags,
                        Action      = new SubstitutionAction
                        {
                            ReplacementGlyphIds = new[] { (ushort)(coveragePair.Value + table.GlyphIdDelta) },
                            ReplacedGlyphCount  = 1
                        }
                    }
                };

                foreach (var path in paths)
                {
                    builder.AddPath(path);
                }
            }
            else if (transformation is LigatureSubstitutionTable)
            {
                var table = transformation as LigatureSubstitutionTable;

                var ligatureSetInfos = table.Coverage.CoveredGlyphIds.Zip(
                    table.LigatureSets,
                    (coveragePair, ligatureSet) => new { CoveredGlyphId = coveragePair.Value, LigatureSet = ligatureSet });

                var paths =
                    from ligatureSetInfo in ligatureSetInfos
                    from ligature in ligatureSetInfo.LigatureSet
                    select this.ConvertLigatureToPath(ligatureSetInfo.CoveredGlyphId, ligature, table.LookupFlags).ToList();

                foreach (var path in paths)
                {
                    builder.AddPath(path);
                }
            }
            else if (transformation is MultipleSubstitutionTable)
            {
                var table = transformation as MultipleSubstitutionTable;

                var paths = table.Coverage.CoveredGlyphIds.Zip(
                    table.ReplacementSequences,
                    (coveragePair, replacementSequence) =>
                {
                    var list = replacementSequence.ToList();
                    return(new[]
                    {
                        new SimpleTransition
                        {
                            GlyphId = coveragePair.Value,
                            HeadShift = 1,
                            LookupFlags = table.LookupFlags,
                            Action = new SubstitutionAction
                            {
                                ReplacementGlyphIds = list,
                                ReplacedGlyphCount = 1
                            }
                        }
                    });
                });

                foreach (var path in paths)
                {
                    builder.AddPath(path);
                }
            }
            else if (transformation is ReverseChainingContextSubstitutionTable)
            {
                var table = transformation as ReverseChainingContextSubstitutionTable;

                builder.SetProcessingDirection(ProcessingDirection.EndToStart);

                // The entire machine is executed from the end of the string towards its start
                var lookbackCoveragesList = table.LookbackCoverages.ToList();
                var completeContext       = (((IEnumerable <ICoverageTable>)lookbackCoveragesList)
                                             .Reverse()
                                             .Append(table.Coverage)
                                             .Append(table.LookaheadCoverages)
                                             ).Reverse().ToList();

                var contextCheckPathSeqment = completeContext
                                              .Take(completeContext.Count - 1)
                                              .Select(coverage => (ITransition) new SetTransition
                {
                    GlyphIdSet  = new HashSet <ushort>(coverage.CoveredGlyphIds.Select(p => p.Value)),
                    HeadShift   = -1,
                    LookupFlags = table.LookupFlags
                })
                                              .Append(new SetTransition
                {
                    GlyphIdSet  = new HashSet <ushort>(completeContext.Last().CoveredGlyphIds.Select(p => p.Value)),
                    HeadShift   = lookbackCoveragesList.Count,
                    LookupFlags = table.LookupFlags
                }).ToList();

                int i = 0;
                var replacementGlyphIds = table.SubstituteGlyphIds.ToList();
                foreach (var coveredGlyphId in table.Coverage.CoveredGlyphIds.Values)
                {
                    var transition = new SimpleTransition
                    {
                        GlyphId     = coveredGlyphId,
                        HeadShift   = lookbackCoveragesList.Count,
                        LookupFlags = table.LookupFlags,
                        Action      = new SubstitutionAction
                        {
                            ReplacedGlyphCount  = 1,
                            ReplacementGlyphIds = new [] { replacementGlyphIds[i] }
                        }
                    };

                    builder.AddPath(contextCheckPathSeqment.Append(transition));

                    i++;
                }

                builder.AddPath(contextCheckPathSeqment.Append(new AlwaysTransition
                {
                    HeadShift   = lookbackCoveragesList.Count,
                    LookupFlags = table.LookupFlags
                }));
            }
            else
            {
                base.CompileTransformation(transformation, builder);
            }
        }