// https://tools.ietf.org/html/rfc7239#section-6
        private void AppendNode(IPAddress ipAddress, int port, NodeFormat format, StringBuilder builder)
        {
            // "It is important to note that an IPv6 address and any nodename with
            // node-port specified MUST be quoted, since ":" is not an allowed
            // character in "token"."
            var addPort = port != 0 && (format == NodeFormat.IpAndPort || format == NodeFormat.UnknownAndPort || format == NodeFormat.RandomAndPort);
            var ipv6    = (format == NodeFormat.Ip || format == NodeFormat.IpAndPort) &&
                          ipAddress != null && ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6;
            var quote = addPort || ipv6;

            if (quote)
            {
                builder.Append("\"");
            }

            switch (format)
            {
            case NodeFormat.Ip:
            case NodeFormat.IpAndPort:
                if (ipAddress != null)
                {
                    if (ipv6)
                    {
                        builder.Append("[");
                    }
                    builder.Append(ipAddress.ToString());
                    if (ipv6)
                    {
                        builder.Append("]");
                    }
                    break;
                }
                // This primarily happens in test environments that don't use real connections.
                goto case NodeFormat.Unknown;

            case NodeFormat.Unknown:
            case NodeFormat.UnknownAndPort:
                builder.Append("unknown");
                break;

            case NodeFormat.Random:
            case NodeFormat.RandomAndPort:
                AppendRandom(builder);
                break;

            default:
                throw new NotImplementedException(format.ToString());
            }

            if (addPort)
            {
                builder.Append(":");
                builder.Append(port);
            }

            if (quote)
            {
                builder.Append("\"");
            }
        }
        public async Task By_Added(string startValue, string ip, int port, NodeFormat format, ForwardedTransformActions action, string expected)
        {
            var randomFactory = new TestRandomFactory();

            randomFactory.Instance = new TestRandom()
            {
                Sequence = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 }
            };
            var httpContext = new DefaultHttpContext();

            httpContext.Connection.LocalIpAddress = string.IsNullOrEmpty(ip) ? null : IPAddress.Parse(ip);
            httpContext.Connection.LocalPort      = port;
            var proxyRequest = new HttpRequestMessage();

            proxyRequest.Headers.Add("Forwarded", startValue.Split("|", StringSplitOptions.RemoveEmptyEntries));
            var transform = new RequestHeaderForwardedTransform(randomFactory, forFormat: NodeFormat.None,
                                                                byFormat: format, host: false, proto: false, action);
            await transform.ApplyAsync(new RequestTransformContext()
            {
                HttpContext   = httpContext,
                ProxyRequest  = proxyRequest,
                HeadersCopied = true,
            });

            Assert.Equal(expected.Split("|", StringSplitOptions.RemoveEmptyEntries), proxyRequest.Headers.GetValues("Forwarded"));
        }
예제 #3
0
        public void AddForwarded(NodeFormat forFormat, bool useHost, bool useProto, NodeFormat byFormat, bool append)
        {
            var builderContext = CreateBuilderContext(services: CreateServices());

            builderContext.AddForwarded(useHost, useProto, forFormat, byFormat, append);

            ValidateForwarded(builderContext, useHost, useProto, forFormat, byFormat, append);
        }
예제 #4
0
 public RequestHeaderForwardedTransform(IRandomFactory randomFactory, NodeFormat forFormat, NodeFormat byFormat, bool host, bool proto, bool append)
 {
     _randomFactory = randomFactory ?? throw new ArgumentNullException(nameof(randomFactory));
     ForFormat      = forFormat;
     ByFormat       = byFormat;
     HostEnabled    = host;
     ProtoEnabled   = proto;
     Append         = append;
 }
 public RequestHeaderForwardedTransform(IRandomFactory randomFactory, NodeFormat forFormat, NodeFormat byFormat, bool host, bool proto, bool append)
 {
     _randomFactory = randomFactory;
     ForFormat      = forFormat;
     ByFormat       = byFormat;
     HostEnabled    = host;
     ProtoEnabled   = proto;
     Append         = append;
 }
예제 #6
0
        public void WithTransformForwarded(NodeFormat forFormat, bool useHost, bool useProto, NodeFormat byFormat, bool append)
        {
            var proxyRoute = new ProxyRoute();

            proxyRoute = proxyRoute.WithTransformForwarded(useHost, useProto, forFormat, byFormat, append);

            var builderContext = ValidateAndBuild(proxyRoute, _factory, CreateServices());

            ValidateForwarded(builderContext, useHost, useProto, forFormat, byFormat, append);
        }
 public RequestHeaderForwardedTransform(IRandomFactory randomFactory, NodeFormat forFormat, NodeFormat byFormat, bool host, bool proto, ForwardedTransformActions action)
 {
     _randomFactory = randomFactory ?? throw new ArgumentNullException(nameof(randomFactory));
     ForFormat      = forFormat;
     ByFormat       = byFormat;
     HostEnabled    = host;
     ProtoEnabled   = proto;
     Debug.Assert(action != ForwardedTransformActions.Off);
     TransformAction = action;
 }
예제 #8
0
        internal static string ConvertNodes(IEnumerable <Loader.NodeInfo> nodes, NodeFormat format)
        {
            switch (format)
            {
            case NodeFormat.Text:
                return(ConvertNodesToYarnText(nodes));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
예제 #9
0
 /// <summary>
 /// Adds the transform which will add the Forwarded header as defined by [RFC 7239](https://tools.ietf.org/html/rfc7239).
 /// </summary>
 public static TransformBuilderContext AddForwarded(this TransformBuilderContext context,
                                                    bool useHost        = true, bool useProto = true, NodeFormat forFormat = NodeFormat.Random,
                                                    NodeFormat byFormat = NodeFormat.Random, bool append = true)
 {
     context.UseDefaultForwarders = false;
     if (byFormat != NodeFormat.None || forFormat != NodeFormat.None || useHost || useProto)
     {
         var random = context.Services.GetRequiredService <IRandomFactory>();
         context.RequestTransforms.Add(new RequestHeaderForwardedTransform(random,
                                                                           forFormat, byFormat, useHost, useProto, append));
     }
     return(context);
 }
        internal static string ConvertNodes(IEnumerable <Loader.NodeInfo> nodes, NodeFormat format)
        {
            switch (format)
            {
            case NodeFormat.JSON:
                return(JsonConvert.SerializeObject(nodes, Formatting.Indented));

            case NodeFormat.Text:
                return(ConvertNodesToYarnText(nodes));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
예제 #11
0
        public void DeserializeFormat(XmlNode xmlNode, MapTree tree)
        {
            XmlAttribute att;

            Color backColor = (att = xmlNode.Attributes["BACKGROUND_COLOR"]) != null?Convert.ToColor(att.Value) : NodeFormat.DefaultBackColor;

            bool bold = (att = xmlNode.Attributes["BOLD"]) != null?Convert.ToBool(att.Value) : false;

            Color color = (att = xmlNode.Attributes["COLOR"]) != null?Convert.ToColor(att.Value) : NodeFormat.DefaultColor;

            string fontName = (att = xmlNode.Attributes["FONTNAME"]) != null ? att.Value : NodeFormat.DefaultFontName;
            float  fontSize = (att = xmlNode.Attributes["FONTSIZE"]) != null?float.Parse(att.Value) : NodeFormat.DefaultFontSize;

            bool italic = (att = xmlNode.Attributes["ITALIC"]) != null?Convert.ToBool(att.Value) : false;

            Color lineColor = (att = xmlNode.Attributes["LINECOLOR"]) != null?Convert.ToColor(att.Value) : NodeFormat.DefaultLineColor;

            DashStyle linePattern = (att = xmlNode.Attributes["PATTERN"]) != null?Convert.ToDashStyle(att.Value) : NodeFormat.DefaultLinePattern;

            int lineWidth = (att = xmlNode.Attributes["LINEWIDTH"]) != null?int.Parse(att.Value) : NodeFormat.DefaultLineWidth;

            NodeShape shape = (att = xmlNode.Attributes["STYPE"]) != null?Convert.ToNodeStyle(att.Value) : NodeFormat.DefaultNodeShape;

            bool strikeout = (att = xmlNode.Attributes["STRIKEOUT"]) != null?Convert.ToBool(att.Value) : false;

            if ((att = xmlNode.Attributes["CANVASCOLOR"]) != null)
            {
                tree.CanvasBackColor = Convert.ToColor(att.Value);
            }
            if ((att = xmlNode.Attributes["NOTEBACKCOLOR"]) != null)
            {
                tree.NoteBackColor = Convert.ToColor(att.Value);
            }
            if ((att = xmlNode.Attributes["NOTETEXTCOLOR"]) != null)
            {
                tree.NoteForeColor = Convert.ToColor(att.Value);
            }
            if ((att = xmlNode.Attributes["HIGHLIGHTCOLOR"]) != null)
            {
                tree.SelectedOutlineColor = Convert.ToColor(att.Value);
            }
            if ((att = xmlNode.Attributes["DROPHINTCOLOR"]) != null)
            {
                tree.DropHintColor = Convert.ToColor(att.Value);
            }

            var format = new NodeFormat(backColor, bold, color, fontName, fontSize, italic, strikeout, lineColor, linePattern, lineWidth, shape);

            tree.DefaultFormat = format;
        }
예제 #12
0
        private static void ValidateForwarded(TransformBuilderContext builderContext, bool useHost, bool useProto,
                                              NodeFormat forFormat, NodeFormat byFormat, bool append)
        {
            Assert.False(builderContext.UseDefaultForwarders);

            if (byFormat != NodeFormat.None || forFormat != NodeFormat.None || useHost || useProto)
            {
                var transform = Assert.Single(builderContext.RequestTransforms);
                var requestHeaderForwardedTransform = Assert.IsType <RequestHeaderForwardedTransform>(transform);
                Assert.Equal(append, requestHeaderForwardedTransform.Append);
                Assert.Equal(useHost, requestHeaderForwardedTransform.HostEnabled);
                Assert.Equal(useProto, requestHeaderForwardedTransform.ProtoEnabled);
                Assert.Equal(byFormat, requestHeaderForwardedTransform.ByFormat);
                Assert.Equal(forFormat, requestHeaderForwardedTransform.ForFormat);
            }
            else
            {
                Assert.Empty(builderContext.RequestTransforms);
            }
        }
예제 #13
0
        /// <summary>
        /// Clones the route and adds the transform which will add the Forwarded header as defined by [RFC 7239](https://tools.ietf.org/html/rfc7239).
        /// </summary>
        public static ProxyRoute WithTransformForwarded(this ProxyRoute proxyRoute, bool useHost = true, bool useProto = true,
                                                        NodeFormat forFormat = NodeFormat.Random, NodeFormat byFormat  = NodeFormat.Random, bool append = true)
        {
            var headers = new List <string>();

            if (forFormat != NodeFormat.None)
            {
                headers.Add(ForwardedTransformFactory.ForKey);
            }

            if (byFormat != NodeFormat.None)
            {
                headers.Add(ForwardedTransformFactory.ByKey);
            }

            if (useHost)
            {
                headers.Add(ForwardedTransformFactory.HostKey);
            }

            if (useProto)
            {
                headers.Add(ForwardedTransformFactory.ProtoKey);
            }

            return(proxyRoute.WithTransform(transform =>
            {
                transform[ForwardedTransformFactory.ForwardedKey] = string.Join(',', headers);
                transform[ForwardedTransformFactory.AppendKey] = append.ToString();

                if (forFormat != NodeFormat.None)
                {
                    transform.Add(ForwardedTransformFactory.ForFormatKey, forFormat.ToString());
                }

                if (byFormat != NodeFormat.None)
                {
                    transform.Add(ForwardedTransformFactory.ByFormatKey, byFormat.ToString());
                }
            }));
        }
예제 #14
0
        /// <summary>
        /// Clones the route and adds the transform which will add the Forwarded header as defined by [RFC 7239](https://tools.ietf.org/html/rfc7239).
        /// </summary>
        public static RouteConfig WithTransformForwarded(this RouteConfig route, bool useHost = true, bool useProto    = true,
                                                         NodeFormat forFormat = NodeFormat.Random, NodeFormat byFormat = NodeFormat.Random, ForwardedTransformActions action = ForwardedTransformActions.Set)
        {
            var headers = new List <string>();

            if (forFormat != NodeFormat.None)
            {
                headers.Add(ForwardedTransformFactory.ForKey);
            }

            if (byFormat != NodeFormat.None)
            {
                headers.Add(ForwardedTransformFactory.ByKey);
            }

            if (useHost)
            {
                headers.Add(ForwardedTransformFactory.HostKey);
            }

            if (useProto)
            {
                headers.Add(ForwardedTransformFactory.ProtoKey);
            }

            return(route.WithTransform(transform =>
            {
                transform[ForwardedTransformFactory.ForwardedKey] = string.Join(',', headers);
                transform[ForwardedTransformFactory.ActionKey] = action.ToString();

                if (forFormat != NodeFormat.None)
                {
                    transform.Add(ForwardedTransformFactory.ForFormatKey, forFormat.ToString());
                }

                if (byFormat != NodeFormat.None)
                {
                    transform.Add(ForwardedTransformFactory.ByFormatKey, byFormat.ToString());
                }
            }));
        }
예제 #15
0
        /// <summary>
        /// Adds the transform which will add the Forwarded header as defined by [RFC 7239](https://tools.ietf.org/html/rfc7239).
        /// </summary>
        public static TransformBuilderContext AddForwarded(this TransformBuilderContext context,
                                                           bool useHost        = true, bool useProto = true, NodeFormat forFormat = NodeFormat.Random,
                                                           NodeFormat byFormat = NodeFormat.Random, ForwardedTransformActions action = ForwardedTransformActions.Set)
        {
            context.UseDefaultForwarders = false;

            if (action == ForwardedTransformActions.Off)
            {
                return(context);
            }

            if (byFormat != NodeFormat.None || forFormat != NodeFormat.None || useHost || useProto)
            {
                var random = context.Services.GetRequiredService <IRandomFactory>();
                context.RequestTransforms.Add(new RequestHeaderForwardedTransform(random,
                                                                                  forFormat, byFormat, useHost, useProto, action));

                // Remove the X-Forwarded headers when an Forwarded transform is enabled
                TransformHelpers.RemoveAllXForwardedHeaders(context, ForwardedTransformFactory.DefaultXForwardedPrefix);
            }
            return(context);
        }
예제 #16
0
        public static void StartService()
        {
            string sharedFilePathFile = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\AreaParty\sharedFilePathInfor.audio";

            transferinformation.Action.readSharedFileAndParse(ref sharedFilePathFile, ref sharedFileList);


            System.Threading.Thread thread = new System.Threading.Thread(MonitoringSys);
            thread.IsBackground = true;
            thread.Start();

            System.Threading.Thread thread1 = new System.Threading.Thread(MonitoringProcesses);
            thread1.IsBackground = true;
            thread1.Start();

            System.Threading.Thread thread2 = new System.Threading.Thread(TransferMonitorData);
            thread2.IsBackground = true;
            thread2.Start();

            //bool run = false;
            //while (!run)
            //{
            //    System.Threading.Thread thread2 = new System.Threading.Thread(TransferMonitorData);
            //    thread2.IsBackground = true;
            //    try
            //    {
            //        thread2.Start();
            //        run = true;
            //    }
            //    catch (SocketException e)
            //    {
            //        thread2.Abort();
            //        AreaParty.function.pcapp.PCApp.Close("127.0.0.1", 7777);
            //        //thread2.Start();
            //    }
            //}



            IPEndPoint  localIP  = new IPEndPoint(IPAddress.Any, ConfigResource.PCINFO_PORT);
            TcpListener listener = new TcpListener(localIP);

            //try
            //{
            listener.Start();
            //}
            //catch (SocketException)
            //{
            //    //listener.
            //    //localIP = new IPEndPoint(IPAddress.Any, ConfigResource.PCINFO_PORT);
            //    //listener = new TcpListener(localIP);
            //    //listener.
            //}



            Console.WriteLine("Action Server is listening...");
            while (isRun)
            {
                TcpClient remoteClient = listener.AcceptTcpClient();
                Console.WriteLine("Action Server is connected...");

                int    RecvBytes  = 0;
                byte[] RecvBuf    = new byte[1024];
                string messageGet = null;
                try
                {
                    RecvBytes = remoteClient.Client.Receive(RecvBuf);
                    if (RecvBytes <= 0)
                    {
                        Console.WriteLine("Action socket 被动关闭");
                        continue;
                    }
                    messageGet = Encoding.UTF8.GetString(RecvBuf, 0, RecvBytes);
                    Console.WriteLine("Action Message: {0}", messageGet);

                    RequestMessageFormat request       = JsonHelper.DeserializeJsonToObject <RequestMessageFormat>(messageGet);
                    ReturnMessageFormat  returnMessage = new ReturnMessageFormat();
                    switch (request.name)
                    {
                    case Order.get_areaparty_path:
                        returnMessage.data    = null;
                        returnMessage.message = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\AreaParty\\";
                        returnMessage.status  = 200;
                        break;

                    case Order.ownProgressAction_name:
                        if (request.command == Order.ownProgressAction_Close)
                        {
                            StopService();
                        }
                        //transferinformation.Action.CloseProcess(System.Diagnostics.Process.GetCurrentProcess().Id);
                        break;

                    case Order.processAction_name:
                        if (request.command == Order.processAction_command)
                        {
                            returnMessage = transferinformation.Action.CloseProcess(int.Parse(request.param));
                        }
                        break;

                    case Order.computerAction_name:
                        if (request.command == Order.computerAction_command_reboot)
                        {
                            transferinformation.Action.RebootComputer();
                        }
                        else if (request.command == Order.computerAction_command_shutdown)
                        {
                            transferinformation.Action.shutdownComputer();
                        }
                        break;

                    case Order.fileAction_name:
                        switch (request.command)
                        {
                        case Order.fileAction_share_command:
                            SharedFilePathFormat sharedFile = JsonHelper.DeserializeJsonToObject <SharedFilePathFormat>(request.param);
                            returnMessage = transferinformation.Action.AddSharedFile(ref sharedFile, ref sharedFileList, ref sharedFilePathFile);
                            break;

                        case Order.fileAction_open_command:
                        {
                            // 此处是打开文件代码
                        }
                        break;

                        case Order.fileOrFolderAction_delete_command:
                        {
                            // 此处是删除文件的代码
                            returnMessage = transferinformation.Action.DeleteFile(request.param);
                        }
                        break;

                        case Order.fileOrFolderAction_rename_command:
                        {
                            // 此处是重命名文件的代码
                            string[] temp = System.Text.RegularExpressions.Regex.Split(request.param, "-PATH-",
                                                                                       System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            returnMessage = transferinformation.Action.RenameFile(temp[1], temp[2]);
                        }
                        break;

                        case Order.fileOrFolderAction_copy_command:
                        {
                            string[] temp = System.Text.RegularExpressions.Regex.Split(request.param, "-PATH-",
                                                                                       System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            returnMessage = transferinformation.Action.CopyFile(temp[2], temp[1]);
                        }
                        break;

                        case Order.fileOrFolderAction_cut_command:
                        {
                            string[] temp = System.Text.RegularExpressions.Regex.Split(request.param, "-PATH-",
                                                                                       System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            returnMessage = transferinformation.Action.CutFile(temp[2] + @"\", temp[1]);
                        }
                        break;
                        }
                        break;

                    case Order.folderAction_name:
                        switch (request.command)
                        {
                        case Order.nasAction_add:
                            returnMessage = NasFunction.addNasFolder(request.param);
                            break;

                        case Order.nasAction_delete:
                            returnMessage = NasFunction.deleteNasFolder(request.param);
                            break;

                        case Order.folderAction_addtohttp_command:
                            ReturnMessageFormat message = new ReturnMessageFormat();
                            string method = request.param.Substring(0, 5);   //request.param = "VIDIO/AUDIO/IMAGE" + uri
                            string path   = request.param.Remove(0, 5);      //request.param = uri
                            //FileInfo Info = new FileInfo(path);
                            try
                            {
                                switch (method)
                                {
                                case AreaParty.pages.ListName.VIDIO:
                                    MediaConfig.AddMyVideoLibrary(path);
                                    //MediaPage.videoList.Add(new MediaPage.ListBoxMediaItem { Name = Info.Name, ImagePath = "/styles/skin/item/item_video.png" });
                                    //MediaPage.dictVideo.Add(Info.Name, path);
                                    //MediaPage..Add(new ListBoxMediaItem { Name = Info.Name, ImagePath = "/styles/skin/item/item_video.png" });
                                    break;

                                case AreaParty.pages.ListName.AUDIO:
                                    MediaConfig.AddMyAudioLibrary(path);
                                    break;

                                case AreaParty.pages.ListName.IMAGE:
                                    MediaConfig.AddMyImageLibrary(path);
                                    break;
                                }
                                new AreaParty.function.media.MediaFunction().GetThumbnail(path);
                                AreaParty.util.JAVAUtil.AddAlltoHttp(path);
                                message.status  = Order.success;
                                message.message = "";
                                message.data    = null;
                            }
                            catch (Exception e)
                            {
                                message.status  = Order.failure;
                                message.message = e.Message;
                                message.data    = null;
                            }
                            returnMessage = message;
                            break;

                        case Order.folderAction_open_command:
                        {
                            // 此处是打开文件夹代码
                            if (request.param != Order.folderAction_open_more_param)
                            {
                                NodeFormat root = new NodeFormat();
                                root.path     = request.param;
                                folderContent = transferinformation.Action.OpenFolder(root);
                            }
                            returnMessage = folderContent[0];
                            folderContent.RemoveAt(0);
                        }
                        break;

                        case Order.fileOrFolderAction_delete_command:
                        {
                            // 此处是删除文件夹的代码
                            returnMessage = transferinformation.Action.DeleteFolder(request.param);
                        }
                        break;

                        case Order.fileOrFolderAction_rename_command:
                        {
                            // 此处是重命名文件夹的代码
                            string[] temp = System.Text.RegularExpressions.Regex.Split(request.param, "-PATH-",
                                                                                       System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            returnMessage = transferinformation.Action.RenameFolder(temp[1], temp[2]);
                        }
                        break;

                        case Order.folderAction_add_command:
                        {
                            returnMessage = transferinformation.Action.CreateFolder(request.param);
                        }
                        break;

                        case Order.fileOrFolderAction_copy_command:
                        {
                            string[] temp = System.Text.RegularExpressions.Regex.Split(request.param, "-PATH-",
                                                                                       System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            returnMessage = transferinformation.Action.CopyFolder(temp[1], temp[2]);
                        }
                        break;

                        case Order.fileOrFolderAction_cut_command:
                        {
                            string[] temp = System.Text.RegularExpressions.Regex.Split(request.param, "-PATH-",
                                                                                       System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            returnMessage = transferinformation.Action.CutFolder(temp[2], temp[1]);
                        }
                        break;
                        }
                        break;

                    case Order.diskAction_name:
                        switch (request.command)
                        {
                        case Order.diskAction_get_command:
                            returnMessage = transferinformation.Action.GetDiskList();
                            break;
                        }
                        break;

                    case Order.appAction_name:
                        switch (request.command)
                        {
                        case Order.appAction_get_command:
                            if (request.param != Order.appAction_get_more_param)
                            {
                                exeContent = transferinformation.Action.GetApplicationList();
                            }
                            returnMessage = exeContent[0];
                            exeContent.RemoveAt(0);
                            break;
                        }
                        break;
                    }

                    byte[] messageToSend = Encoding.UTF8.GetBytes(JsonHelper.SerializeObject(returnMessage));
                    int    i             = remoteClient.Client.Send(messageToSend);
                    Console.WriteLine("send Message: {0} ", JsonHelper.SerializeObject(returnMessage));
                }
                catch (Exception e)
                {
                    Console.WriteLine("Action socket 被动关闭" + e.Message);
                }
                remoteClient.Close();
            }

            Console.ReadLine();
        }
예제 #17
0
 public void CreateDefaultFormat_SameDefaultObject()
 {
     Assert.AreEqual(NodeFormat.CreateDefaultFormat(), NodeFormat.CreateDefaultFormat());
 }
예제 #18
0
        public void CreateNodeFormat()
        {
            var n = new MapNode(new MapTree(), "");

            Assert.IsNotNull(NodeFormat.CreateNodeFormat(n));
        }
예제 #19
0
        public void CreateNodeFormat_NoFormating_ReturnsDefault()
        {
            var n = new MapNode(new MapTree(), "");

            Assert.AreEqual(NodeFormat.CreateNodeFormat(n), NodeFormat.CreateDefaultFormat());
        }
예제 #20
0
        // Given a bunch of raw text, load all nodes that were inside it.
        // You can call this multiple times to append to the collection of nodes,
        // but note that new nodes will replace older ones with the same name.
        // Returns the number of nodes that were loaded.
        public Program Load(string text, Library library, string fileName, Program includeProgram, bool showTokens, bool showParseTree, string onlyConsiderNode, NodeFormat format)
        {
            if (format == NodeFormat.Unknown)
            {
                format = GetFormatFromFileName(fileName);
            }

            // currently experimental node can only be used on yarn.txt yarn files and single nodes
            if (format != NodeFormat.Text && format != NodeFormat.SingleNodeText)
            {
                throw new InvalidDataException($"Invalid node format {format}");
            }
            // this isn't the greatest...
            if (format == NodeFormat.SingleNodeText)
            {
                // it is just the body
                // need to add a dummy header and body delimiters
                StringBuilder builder = new StringBuilder();
                builder.Append("title:Start\n");
                builder.Append("---\n");
                builder.Append(text);
                builder.Append("\n===\n");
                text = builder.ToString();
            }

            string      inputString = preprocessor(text);
            ICharStream input       = CharStreams.fromstring(inputString);

            YarnSpinnerLexer  lexer  = new YarnSpinnerLexer(input);
            CommonTokenStream tokens = new CommonTokenStream(lexer);

            YarnSpinnerParser parser = new YarnSpinnerParser(tokens);

            // turning off the normal error listener and using ours
            parser.RemoveErrorListeners();
            parser.AddErrorListener(ErrorListener.Instance);

            IParseTree tree     = parser.dialogue();
            Compiler   compiler = new Compiler(library);

            compiler.Compile(tree);

            // merging in the other program if requested
            if (includeProgram != null)
            {
                compiler.program.Include(includeProgram);
            }

            return(compiler.program);
        }
예제 #21
0
        public void ApplyTheme(string theme, MapTree tree)
        {
            switch (theme)
            {
            case "Default (Light)":
                tree.DefaultFormat        = NodeFormat.CreateDefaultFormat();
                tree.CanvasBackColor      = TreeFormat.DefaultCanvasBackColor;
                tree.NoteBackColor        = TreeFormat.DefaultNoteEditorBackColor;
                tree.NoteForeColor        = TreeFormat.DefaultNoteEditorForeColor;
                tree.SelectedOutlineColor = TreeFormat.DefaultSelectedNodeOutlineColor;
                tree.DropHintColor        = TreeFormat.DefaultDropTargetHintColor;
                break;

            case "Default (Dark)":
                tree.DefaultFormat = new NodeFormat(Color.Empty, false, Color.White, NodeFormat.DefaultFontName,
                                                    NodeFormat.DefaultFontSize, false, false, NodeFormat.DefaultLineColor, NodeFormat.DefaultLinePattern,
                                                    NodeFormat.DefaultLineWidth, NodeFormat.DefaultNodeShape);
                var backColor = Color.FromArgb(40, 44, 52);
                tree.CanvasBackColor      = backColor;
                tree.NoteBackColor        = backColor;
                tree.NoteForeColor        = Color.White;
                tree.SelectedOutlineColor = Color.Red;
                tree.DropHintColor        = Color.FromArgb(255, 128, 64);
                break;

            case "Pitch Black":
                tree.DefaultFormat = new NodeFormat(Color.Empty, false, Color.White, NodeFormat.DefaultFontName,
                                                    NodeFormat.DefaultFontSize, false, false, NodeFormat.DefaultLineColor, NodeFormat.DefaultLinePattern,
                                                    NodeFormat.DefaultLineWidth, NodeFormat.DefaultNodeShape);
                tree.CanvasBackColor      = Color.Black;
                tree.NoteBackColor        = Color.Black;
                tree.NoteForeColor        = Color.White;
                tree.SelectedOutlineColor = Color.Red;
                tree.DropHintColor        = Color.FromArgb(255, 128, 64);
                break;

            case "Fun (Light)":
                tree.DefaultFormat = new NodeFormat(Color.FromArgb(253, 246, 227), false, Color.Black, "Comic Sans MS",
                                                    11, false, false, Color.Green, NodeFormat.DefaultLinePattern,
                                                    2, NodeShape.Bullet);
                backColor                 = Color.WhiteSmoke;
                tree.CanvasBackColor      = backColor;
                tree.NoteBackColor        = backColor;
                tree.NoteForeColor        = Color.Black;
                tree.SelectedOutlineColor = Color.Green;
                tree.DropHintColor        = Color.Red;
                break;

            case "Fun (Dark)":
                tree.DefaultFormat = new NodeFormat(Color.FromArgb(123, 109, 141), false, Color.White, "Comic Sans MS",
                                                    11, false, false, Color.FromArgb(147, 79, 28), NodeFormat.DefaultLinePattern,
                                                    4, NodeShape.Bullet);
                backColor                 = Color.FromArgb(64, 57, 73);
                tree.CanvasBackColor      = backColor;
                tree.NoteBackColor        = backColor;
                tree.NoteForeColor        = Color.White;
                tree.SelectedOutlineColor = Color.Yellow;
                tree.DropHintColor        = Color.Lime;
                break;

            case "Solarized Blue":
                var textColor = Color.FromArgb(60, 151, 174);
                tree.DefaultFormat = new NodeFormat(Color.Empty, false, textColor, NodeFormat.DefaultFontName,
                                                    10, false, false, Color.FromArgb(255, 128, 64), NodeFormat.DefaultLinePattern,
                                                    1, NodeShape.Fork);
                backColor                 = Color.FromArgb(253, 246, 227);
                tree.CanvasBackColor      = backColor;
                tree.NoteBackColor        = backColor;
                tree.NoteForeColor        = textColor;
                tree.SelectedOutlineColor = Color.FromArgb(64, 0, 0);
                tree.DropHintColor        = Color.Black;
                break;

            case "Solarized Orange":
                textColor          = Color.FromArgb(255, 128, 64);
                tree.DefaultFormat = new NodeFormat(Color.Empty, false, textColor, NodeFormat.DefaultFontName,
                                                    10, false, false, Color.FromArgb(60, 151, 174), NodeFormat.DefaultLinePattern,
                                                    1, NodeShape.Bullet);
                backColor                 = Color.FromArgb(253, 246, 227);
                tree.CanvasBackColor      = backColor;
                tree.NoteBackColor        = backColor;
                tree.NoteForeColor        = textColor;
                tree.SelectedOutlineColor = Color.FromArgb(64, 0, 0);
                tree.DropHintColor        = Color.Black;
                break;

            case "Solarized Dark":
                textColor          = Color.FromArgb(253, 246, 227);
                tree.DefaultFormat = new NodeFormat(Color.Empty, false, textColor, NodeFormat.DefaultFontName,
                                                    10, false, false, Color.FromArgb(60, 151, 174), NodeFormat.DefaultLinePattern,
                                                    1, NodeShape.Fork);
                backColor                 = Color.FromArgb(0, 43, 54);
                tree.CanvasBackColor      = backColor;
                tree.NoteBackColor        = backColor;
                tree.NoteForeColor        = textColor;
                tree.SelectedOutlineColor = Color.FromArgb(255, 128, 64);
                tree.DropHintColor        = Color.Red;
                break;

            case "Red":
                tree.DefaultFormat = new NodeFormat(Color.FromArgb(77, 0, 0), false, Color.White, NodeFormat.DefaultFontName,
                                                    NodeFormat.DefaultFontSize, false, false, Color.FromArgb(97, 0, 0), NodeFormat.DefaultLinePattern,
                                                    NodeFormat.DefaultLineWidth, NodeFormat.DefaultNodeShape);
                backColor                 = Color.FromArgb(57, 0, 0);
                tree.CanvasBackColor      = backColor;
                tree.NoteBackColor        = backColor;
                tree.NoteForeColor        = Color.White;
                tree.SelectedOutlineColor = Color.Red;
                tree.DropHintColor        = Color.FromArgb(0, 128, 255);
                break;

            case "Dim":
                textColor          = Color.FromArgb(203, 105, 89);
                tree.DefaultFormat = new NodeFormat(Color.Empty, false, textColor, NodeFormat.DefaultFontName,
                                                    NodeFormat.DefaultFontSize, false, false, Color.FromArgb(103, 159, 115), NodeFormat.DefaultLinePattern,
                                                    NodeFormat.DefaultLineWidth, NodeFormat.DefaultNodeShape);
                backColor                 = Color.FromArgb(41, 40, 40);
                tree.CanvasBackColor      = backColor;
                tree.NoteBackColor        = backColor;
                tree.NoteForeColor        = textColor;
                tree.SelectedOutlineColor = Color.Red;
                tree.DropHintColor        = Color.FromArgb(255, 128, 64);
                break;

            case "Twine":
                textColor          = Color.FromArgb(210, 141, 37);
                tree.DefaultFormat = new NodeFormat(Color.Empty, false, textColor, NodeFormat.DefaultFontName,
                                                    NodeFormat.DefaultFontSize, false, false, Color.FromArgb(189, 153, 86), NodeFormat.DefaultLinePattern,
                                                    NodeFormat.DefaultLineWidth, NodeFormat.DefaultNodeShape);
                backColor                 = Color.FromArgb(34, 26, 15);
                tree.CanvasBackColor      = backColor;
                tree.NoteBackColor        = backColor;
                tree.NoteForeColor        = textColor;
                tree.SelectedOutlineColor = Color.FromArgb(198, 53, 52);
                tree.DropHintColor        = Color.FromArgb(255, 128, 64);
                break;
            }
        }
예제 #22
0
        // Given either Twine, JSON or XML input, return an array
        // containing info about the nodes in that file
        public static NodeInfo[] GetNodesFromText(string text, NodeFormat format)
        {
            // All the nodes we found in this file
            var nodes = new List <NodeInfo> ();

            switch (format)
            {
            case NodeFormat.SingleNodeText:
                // If it starts with a comment, treat it as a single-node file
                var nodeInfo = new NodeInfo();
                nodeInfo.title = "Start";
                nodeInfo.body  = text;
                nodes.Add(nodeInfo);
                break;

            case NodeFormat.JSON:
                // Parse it as JSON
                try
                {
                    nodes = JsonConvert.DeserializeObject <List <NodeInfo> >(text);
                }
                catch (JsonReaderException e)
                {
//					dialogue.LogErrorMessage("Error parsing Yarn input: " + e.Message);
                    Debug.Log("Error parsing Yarn input: " + e.Message);
                }

                break;

            case NodeFormat.Text:

                // check for the existence of at least one "---"+newline sentinel, which divides
                // the headers from the body

                // we use a regex to match either \r\n or \n line endings
                if (System.Text.RegularExpressions.Regex.IsMatch(text, "---.?\n") == false)
                {
//					dialogue.LogErrorMessage("Error parsing input: text appears corrupt (no header sentinel)");
                    Debug.Log("Error parsing input: text appears corrupt (no header sentinel)");
                    break;
                }

                var headerRegex = new System.Text.RegularExpressions.Regex("(?<field>.*): *(?<value>.*)");

                var nodeProperties = typeof(NodeInfo).GetProperties();

                int lineNumber = 0;

                using (var reader = new System.IO.StringReader(text))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        // Create a new node
                        NodeInfo node = new NodeInfo();

                        // Read header lines
                        do
                        {
                            lineNumber++;

                            // skip empty lines
                            if (line.Length == 0)
                            {
                                continue;
                            }

                            // Attempt to parse the header
                            var headerMatches = headerRegex.Match(line);

                            if (headerMatches == null)
                            {
//								dialogue.LogErrorMessage(string.Format("Line {0}: Can't parse header '{1}'", lineNumber, line));
                                Debug.Log(string.Format("Line {0}: Can't parse header '{1}'", lineNumber, line));
                                continue;
                            }

                            var field = headerMatches.Groups["field"].Value;
                            var value = headerMatches.Groups["value"].Value;

                            // Attempt to set the appropriate property using this field
                            foreach (var property in nodeProperties)
                            {
                                if (property.Name != field)
                                {
                                    continue;
                                }

                                // skip properties that can't be written to
                                if (property.CanWrite == false)
                                {
                                    continue;
                                }
                                try
                                {
                                    var    propertyType = property.PropertyType;
                                    object convertedValue;
                                    if (propertyType.IsAssignableFrom(typeof(string)))
                                    {
                                        convertedValue = value;
                                    }
                                    else if (propertyType.IsAssignableFrom(typeof(int)))
                                    {
                                        convertedValue = int.Parse(value);
                                    }
                                    else if (propertyType.IsAssignableFrom(typeof(NodeInfo.Position)))
                                    {
                                        var components = value.Split(',');

                                        // we expect 2 components: x and y
                                        if (components.Length != 2)
                                        {
                                            throw new FormatException();
                                        }

                                        var position = new NodeInfo.Position();
                                        position.x = int.Parse(components[0]);
                                        position.y = int.Parse(components[1]);

                                        convertedValue = position;
                                    }
                                    else
                                    {
                                        throw new NotSupportedException();
                                    }
                                    // we need to box this because structs are value types,
                                    // so calling SetValue using 'node' would just modify a copy of 'node'
                                    object box = node;
                                    property.SetValue(box, convertedValue, null);
                                    node = (NodeInfo)box;
                                    break;
                                }
                                catch (FormatException)
                                {
//									dialogue.LogErrorMessage(string.Format("{0}: Error setting '{1}': invalid value '{2}'", lineNumber, field, value));
                                    Debug.Log(string.Format("{0}: Error setting '{1}': invalid value '{2}'", lineNumber, field, value));
                                }
                                catch (NotSupportedException)
                                {
                                    //								dialogue.LogErrorMessage(string.Format("{0}: Error setting '{1}': This property cannot be set", lineNumber, field));
                                    Debug.Log(string.Format("{0}: Error setting '{1}': This property cannot be set", lineNumber, field));
                                }
                            }
                        } while ((line = reader.ReadLine()) != "---");

                        lineNumber++;

                        // We're past the header; read the body

                        var lines = new List <string>();

                        // Read header lines until we hit the end of node sentinel or the end of the file
                        while ((line = reader.ReadLine()) != "===" && line != null)
                        {
                            lineNumber++;
                            lines.Add(line);
                        }
                        // We're done reading the lines! Zip 'em up into a string and
                        // store it in the body
                        node.body = string.Join("\n", lines.ToArray());

                        // And add this node to the list
                        nodes.Add(node);

                        // And now we're ready to move on to the next line!
                    }
                }
                break;

            default:
                throw new InvalidOperationException("Unknown format " + format.ToString());
            }

            // hooray we're done
            return(nodes.ToArray());
        }
예제 #23
0
 public DefaultTreeFormatChange(MapTree tree, NodeFormat oldValue)
 {
     this.tree     = tree;
     this.oldValue = oldValue;
 }
예제 #24
0
        // Given a bunch of raw text, load all nodes that were inside it.
        // You can call this multiple times to append to the collection of nodes,
        // but note that new nodes will replace older ones with the same name.
        // Returns the number of nodes that were loaded.
        public Program Load(string text, Library library, string fileName, Program includeProgram, bool showTokens, bool showParseTree, string onlyConsiderNode, NodeFormat format, bool experimentalMode = false)
        {
            if (format == NodeFormat.Unknown)
            {
                format = GetFormatFromFileName(fileName);
            }

            // currently experimental node can only be used on yarn.txt yarn files and single nodes
            if (experimentalMode && (format == NodeFormat.Text || format == NodeFormat.SingleNodeText))
            {
                // this isn't the greatest...
                if (format == NodeFormat.SingleNodeText)
                {
                    // it is just the body
                    // need to add a dummy header and body delimiters
                    StringBuilder builder = new StringBuilder();
                    builder.Append("title:Start\n");
                    builder.Append("---\n");
                    builder.Append(text);
                    builder.Append("\n===\n");
                    text = builder.ToString();
                }

                string      inputString = preprocessor(text);
                ICharStream input       = CharStreams.fromstring(inputString);

                YarnSpinnerLexer  lexer  = new YarnSpinnerLexer(input);
                CommonTokenStream tokens = new CommonTokenStream(lexer);

                YarnSpinnerParser parser = new YarnSpinnerParser(tokens);
                // turning off the normal error listener and using ours
                parser.RemoveErrorListeners();
                parser.AddErrorListener(ErrorListener.Instance);

                IParseTree    tree          = parser.dialogue();
                AntlrCompiler antlrcompiler = new AntlrCompiler(library);
                antlrcompiler.Compile(tree);

                // merging in the other program if requested
                if (includeProgram != null)
                {
                    antlrcompiler.program.Include(includeProgram);
                }

                return(antlrcompiler.program);
            }
            else
            {
                // The final parsed nodes that were in the file we were given
                Dictionary <string, Yarn.Parser.Node> nodes = new Dictionary <string, Parser.Node>();

                // Load the raw data and get the array of node title-text pairs

                var nodeInfos = GetNodesFromText(text, format);

                int nodesLoaded = 0;

                foreach (NodeInfo nodeInfo in nodeInfos)
                {
                    if (onlyConsiderNode != null && nodeInfo.title != onlyConsiderNode)
                    {
                        continue;
                    }

                    // Attempt to parse every node; log if we encounter any errors
#if CATCH_EXCEPTIONS
                    try
                    {
#endif

                    if (nodeInfo.title == null)
                    {
                        throw new InvalidOperationException("Tried to load a node with no title.");
                    }
                    if (nodes.ContainsKey(nodeInfo.title))
                    {
                        throw new InvalidOperationException("Attempted to load a node called " +
                                                            nodeInfo.title + ", but a node with that name has already been loaded!");
                    }

                    var lexer  = new Lexer();
                    var tokens = lexer.Tokenise(nodeInfo.title, nodeInfo.body);

                    if (showTokens)
                    {
                        PrintTokenList(tokens);
                    }

                    var node = new Parser(tokens, library).Parse();

                    // If this node is tagged "rawText", then preserve its source
                    if (string.IsNullOrEmpty(nodeInfo.tags) == false &&
                        nodeInfo.tags.Contains("rawText"))
                    {
                        node.source = nodeInfo.body;
                    }

                    node.name = nodeInfo.title;

                    node.nodeTags = nodeInfo.tagsList;

                    if (showParseTree)
                    {
                        PrintParseTree(node);
                    }

                    nodes[nodeInfo.title] = node;

                    nodesLoaded++;

#if CATCH_EXCEPTIONS
                }
                catch (Yarn.TokeniserException t)
                {
                    // Add file information
                    var message = string.Format("In file {0}: Error reading node {1}: {2}", fileName, nodeInfo.title, t.Message);
                    throw new Yarn.TokeniserException(message);
                }
                catch (Yarn.ParseException p)
                {
                    var message = string.Format("In file {0}: Error parsing node {1}: {2}", fileName, nodeInfo.title, p.Message);
                    throw new Yarn.ParseException(message);
                }
                catch (InvalidOperationException e)
                {
                    var message = string.Format("In file {0}: Error reading node {1}: {2}", fileName, nodeInfo.title, e.Message);
                    throw new InvalidOperationException(message);
                }
#endif
                }

                var compiler = new Yarn.Compiler(fileName);

                foreach (var node in nodes)
                {
                    compiler.CompileNode(node.Value);
                }

                if (includeProgram != null)
                {
                    compiler.program.Include(includeProgram);
                }

                return(compiler.program);
            }
        }
예제 #25
0
 private void CreateNodeFormat()
 {
     nodeFomat = NodeFormat.CreateNodeFormat(node);
 }
예제 #26
0
 public void CreateDefaultFormat_FontNotNull()
 {
     Assert.IsNotNull(NodeFormat.CreateDefaultFormat().Font);
 }