Exemplo n.º 1
0
        /// <summary>
        /// gets the path
        /// </summary>
        /// <returns></returns>
        private BehaviorReturnCode getCurrentPath()
        {
            APath path = (APath)f_PathMapper.get(f_ThisEntity);


            s_currentPath = path.FoundPath;

            return(BehaviorReturnCode.Success);


            //s_currentPath = findPath.getPath();

            //GameMap map = (GameMap)s_GameMapMapper.get(s_Map);

            /*
             * f_MapDebug = s_EcsInstance.TagManager.getEntityByTag("MAP_DEBUG");
             * s_Debug = (MapDebug)f_MapDebugMapper.get(f_MapDebug);
             *
             * s_Debug.ClosedSet = findPath.getClosedSet();
             * s_Debug.OpenSet = findPath.getOpenSet();
             * s_Debug.Blocking = findPath.getBlockingSet();
             * s_Debug.Path = s_currentPath;
             *
             * return BehaviorReturnCode.Success;
             */
        }
Exemplo n.º 2
0
 public void OnPathFound(Vector3[] waypoints, bool pathSuccessful)
 {
     if (pathSuccessful)
     {
         path = new APath(waypoints, transform.position, turnDist, stoppingDist);
         StopCoroutine("FollowPath");
         StartCoroutine("FollowPath");
     }
 }
Exemplo n.º 3
0
        private APath CreateAPath()
        {
            var aPath = new APath {
                gridScript = GameManager.Instance.UGrid, gridI = _gridIndex
            };

            aPath.InitializeGrid();
            return(aPath);
        }
Exemplo n.º 4
0
	/// <summary>
	/// Shows "Open" dialog to select an existing workspace.
	/// On OK loads the selected workspace and returns FilesModel. On Cancel return null.
	/// </summary>
	public FilesModel ZLoadAnotherWorkspace()
	{
		var d = new OpenFileDialog { Title = "Open workspace", Filter = "files.xml|files.xml" };
		if(d.ShowDialog(this) != DialogResult.OK) return null;
		var filesXml = d.FileName;
		if(!APath.GetFileName(filesXml).Eqi("files.xml")) {
			ADialog.ShowError("Must be files.xml");
			return null;
		}
		return ZLoadWorkspace(APath.GetDirectoryPath(filesXml));
	}
Exemplo n.º 5
0
        /// <summary>
        /// Loads XML file and creates tree of nodes from it.
        /// Returns the root node.
        /// </summary>
        /// <param name="file">XML file. Must be full path. Can contain environment variables etc, see <see cref="APath.ExpandEnvVar"/>.</param>
        /// <param name="nodeReader">Callback function that reads current XML element and creates/returns new node. See example.</param>
        /// <exception cref="ArgumentException">Not full path.</exception>
        /// <exception cref="Exception">Exceptions of <see cref="XmlReader.Create(string)"/>.</exception>
        /// <exception cref="XmlException">An error occurred while parsing the XML.</exception>
        /// <example><see cref="ATreeBase{T}"/></example>
        protected static T XmlLoad(string file, XmlNodeReader nodeReader)
        {
            file = APath.NormalizeForNET_(file);
            var xs = new XmlReaderSettings()
            {
                IgnoreComments = true, IgnoreProcessingInstructions = true, IgnoreWhitespace = true
            };

            using var r = AFile.WaitIfLocked(() => XmlReader.Create(file, xs));
            return(XmlLoad(r, nodeReader));
        }
Exemplo n.º 6
0
 /// <summary>
 /// Saves tree of nodes (this and descendants) to an XML file.
 /// </summary>
 /// <param name="file">XML file. Must be full path. Can contain environment variables etc, see <see cref="APath.ExpandEnvVar"/>.</param>
 /// <param name="nodeWriter">Callback function that writes node's XML start element (see <see cref="XmlWriter.WriteStartElement(string)"/>) and attributes (see <see cref="XmlWriter.WriteAttributeString(string, string)"/>). Must not write children and end element. Also should not write value, unless your reader knows how to read it.</param>
 /// <param name="sett">XML formatting settings. Optional.</param>
 /// <param name="children">If not null, writes these nodes as if they were children of this node.</param>
 /// <exception cref="ArgumentException">Not full path.</exception>
 /// <exception cref="Exception">Exceptions of <see cref="XmlWriter.Create(string)"/> and other <b>XmlWriter</b> methods.</exception>
 /// <remarks>
 /// Uses <see cref="AFile.Save"/>. It ensures that existing file data is not damaged on exception etc.
 /// </remarks>
 /// <example><see cref="ATreeBase{T}"/></example>
 protected void XmlSave(string file, XmlNodeWriter nodeWriter, XmlWriterSettings sett = null, IEnumerable <T> children = null)
 {
     file = APath.NormalizeForNET_(file);
     sett ??= new XmlWriterSettings()
     {
         OmitXmlDeclaration = true, Indent = true, IndentChars = "  "
     };
     AFile.Save(file, temp => {
         using var x = XmlWriter.Create(temp, sett);
         XmlSave(x, nodeWriter, children);
     });
 }
Exemplo n.º 7
0
 /// <summary>
 /// Loads cursor from file.
 /// Returns null if fails.
 /// </summary>
 /// <param name="file">.cur or .ani file. If not full path, uses <see cref="AFolders.ThisAppImages"/>.</param>
 /// <param name="size">Width and height. If 0, uses system default size, which depends on DPI (the "text size" system setting).</param>
 /// <remarks>
 /// This function exists because <see cref="Forms.Cursor"/> constructors don't support colors, ani cursors and custom size.
 /// </remarks>
 public static Forms.Cursor LoadCursorFromFile(string file, int size = 0)
 {
     file = APath.Normalize(file, AFolders.ThisAppImages);
     if (file == null)
     {
         return(null);
     }
     uint fl = Api.LR_LOADFROMFILE; if (size == 0)
     {
         fl |= Api.LR_DEFAULTSIZE;
     }
     var hCur = Api.LoadImage(default, file, Api.IMAGE_CURSOR, size, size, fl);
Exemplo n.º 8
0
        string                 _exe; //for errors only

        /// <summary>
        /// Prepares parameters for API <msdn>CreateProcess</msdn> and similar.
        /// </summary>
        /// <param name="exe">
        /// Full path of program file. If not full path, uses <see cref="AFolders.ThisApp"/>. Uses <see cref="APath.Normalize"/>.
        /// If <i>rawExe</i> true, does not use <b>Normalize</b>/<b>ThisApp</b>.
        /// </param>
        /// <param name="args">null or command line arguments.</param>
        /// <param name="curDir">
        /// Initial current directory of the new process.
        /// - If null, uses <c>Directory.GetCurrentDirectory()</c>.
        /// - Else if <i>rawCurDir</i>==true, uses raw <i>curDir</i> value.
        /// - Else if "", calls <c>APath.GetDirectoryPath(exe)</c>.
        /// - Else calls <see cref="APath.ExpandEnvVar"/>.
        /// </param>
        /// <param name="envVar">null or environment variables to pass to the new process together with variables of this process. Format: "var1=value1\0var2=value2\0". If ends with "\0\0", will pass only these variables.</param>
        /// <param name="rawExe">Don't normalize <i>exe</i>.</param>
        /// <param name="rawCurDir">Don't normalize <i>curDir</i>.</param>
        public ProcessStarter_(string exe, string args = null, string curDir = null, string envVar = null, bool rawExe = false, bool rawCurDir = false) : this()
        {
            if (!rawExe)
            {
                exe = APath.Normalize(exe, AFolders.ThisApp, PNFlags.DontExpandDosPath | PNFlags.DontPrefixLongPath);
            }
            _exe = exe;
            cl   = (args == null ? ("\"" + exe + "\"" + "\0") : ("\"" + exe + "\" " + args + "\0")).ToCharArray();
            if (curDir == null)
            {
                this.curDir = Directory.GetCurrentDirectory();                            //if null passed to CreateProcessWithTokenW, the new process does not inherit current directory of this process
            }
            else
            {
                this.curDir = rawCurDir ? curDir : (curDir.Length == 0 ? APath.GetDirectoryPath(exe) : APath.ExpandEnvVar(curDir));
            }

            si.cb      = Api.SizeOf <Api.STARTUPINFO>();
            si.dwFlags = Api.STARTF_FORCEOFFFEEDBACK;

            flags = Api.CREATE_UNICODE_ENVIRONMENT;

            if (envVar != null && !envVar.Ends("\0\0"))
            {
                var es = Api.GetEnvironmentStrings();
                int len1; for (var k = es; ; k++)
                {
                    if (k[0] == 0 && k[1] == 0)
                    {
                        len1 = (int)(k - es) + 2; break;
                    }
                }
                int len2 = envVar.Length;
                var t    = new string('\0', len1 + len2);
                fixed(char *p = t)
                {
                    Api.memcpy(p, es, --len1 * 2);
                    for (int i = 0; i < envVar.Length; i++)
                    {
                        p[len1 + i] = envVar[i];
                    }
                }

                this.envVar = t;
                Api.FreeEnvironmentStrings(es);
            }
            else
            {
                this.envVar = null;
            }
        }
Exemplo n.º 9
0
        private BehaviorReturnCode initializePathfinder()
        {
            Position start  = (Position)f_PositionMapper.get(f_ThisEntity);
            Position finish = (Position)f_PositionMapper.get(f_Target);

            f_Map = s_EcsInstance.tag_manager.get_entity_by_tag("MAP");
            GameMap map = (GameMap)f_GameMapMapper.get(f_Map);

            f_Camera = s_EcsInstance.tag_manager.get_entity_by_tag("CAMERA");
            ViewPort viewport = (ViewPort)f_ViewPortMapper.get(f_Camera);

            f_Spatial = s_EcsInstance.tag_manager.get_entity_by_tag("SPATIAL");
            SpatialPartition spatial = (SpatialPartition)f_SpatialMapper.get(f_Spatial);

            spatial.QuadTree.setContentAtLocation(f_ThisEntity, start.Pos);
            s_LastNode = spatial.QuadTree.locateNode(start.Pos);

            Vector2 sVec, fVec;

            //s_Center = viewport.getDimensions() / 2;

            sVec = (start.Pos) / f_TileSize;
            fVec = (finish.Pos + finish.Offset) / f_TileSize;

            /*
             * sVec = (start.Pos + s_Center) / s_TileSize;
             * fVec = (finish.Pos + s_Center) / s_TileSize;
             */

            s_TargetCell.Position  = fVec;
            s_CurrentCell.Position = sVec;

            //findPath = new FindPathAction(s_EcsInstance,sVec,fVec, map);
            APath path = (APath)f_PathMapper.get(f_ThisEntity);

            path.Start     = sVec;
            path.Finish    = fVec;
            path.Map       = map;
            path.PathState = PathState.Idle;

            s_TargetCurrentPosition = finish.Pos + s_Offset;

            //convert to map position
            s_TargetCurrentPosition  = new Vector2((int)s_TargetCurrentPosition.X / f_TileSize, (int)s_TargetCurrentPosition.Y / f_TileSize);
            s_TargetPreviousPosition = s_TargetCurrentPosition;

            f_BeginPathingAndMovement = true;

            return(BehaviorReturnCode.Success);
        }
Exemplo n.º 10
0
    private void _TextChanged(object sender, EventArgs e)
    {
        var    location = textLocation.Text.Trim();
        var    name     = textName.Text.Trim();
        string path     = null;

        if (location.Length > 0 && name.Length > 0)
        {
            name = APath.CorrectFileName(name);
            path = APath.Combine(location, name);
            try { path = APath.Normalize(path); } catch { path = null; }
        }
        textPath.Text    = path;
        buttonOK.Enabled = path != null;
    }
Exemplo n.º 11
0
    private void _ButtonOK_Click(object sender, EventArgs e)
    {
        var ok   = true;
        var path = textPath.Text;

        if (!APath.IsFullPath(path))
        {
            ok = false;
        }
        else if (AFile.ExistsAsAny(path))
        {
            ADialog.ShowError("Already exists", path, owner: this);
            ok = false;
        }
        this.DialogResult = ok ? DialogResult.OK : DialogResult.None;
    }
Exemplo n.º 12
0
 void Start()
 {
     //pathList = new UPath[amountOfThreads];
     targetList        = new List <Vector3>();
     startList         = new List <Vector3>();
     indexList         = new List <int>();
     returnList        = new List <GameObject>();
     _finishActionList = new List <PathFoundEvent>();
     apath             = new APath[amountOfThreads];
     for (int x = 0; x < apath.Length; x++)
     {
         apath[x] = new APath {
             gridScript = GameManager.Instance.UGrid
         };
     }
     startedThreads = new bool[amountOfThreads];
 }
Exemplo n.º 13
0
    void Start()
    {
        pathList   = new UPath[amountOfThreads];
        targetList = new List <Vector3>();
        startList  = new List <Vector3>();
        indexList  = new List <int>();
        returnList = new List <GameObject>();
        apath      = new APath[amountOfThreads];
        UGrid gridScript = GameObject.Find("UGrid").GetComponent <UGrid>();

        for (int x = 0; x < apath.Length; x++)
        {
            apath[x]            = new APath();
            apath[x].gridScript = gridScript;
        }
        startedThreads = new bool[amountOfThreads];
    }
Exemplo n.º 14
0
        /// <summary>
        /// Extracts meta comments from a single C# file.
        /// </summary>
        /// <param name="f"></param>
        /// <param name="isMain">If false, it is a file added through meta option 'c'.</param>
        void _ParseFile(FileNode f, bool isMain)
        {
            //var p1 = APerf.Create();
            string code = f.GetText(cache: true);
            //p1.Next();
            bool isScript = f.IsScript;

            if (_isMain = isMain)
            {
                Name     = APath.GetFileName(f.Name, true);
                IsScript = isScript;

                Optimize     = DefaultOptimize;
                WarningLevel = DefaultWarningLevel;
                NoWarnings   = DefaultNoWarnings != null ? new List <string>(DefaultNoWarnings) : new List <string>();
                Defines      = new List <string>();
                Role         = DefaultRole(isScript);

                CodeFiles  = new List <MetaCodeFile>();
                References = new MetaReferences();
            }

            CodeFiles.Add(new MetaCodeFile(f, code));

            _fn   = f;
            _code = code;

            int endOf = FindMetaComments(code);

            if (endOf > 0)
            {
                if (isMain)
                {
                    EndOfMeta = endOf;
                }

                foreach (var t in EnumOptions(code, endOf))
                {
                    //var p1 = APerf.Create();
                    _ParseOption(t.Name(), t.Value(), t.nameStart, t.valueStart);
                    //p1.Next(); var t1 = p1.TimeTotal; if(t1 > 5) AOutput.Write(t1, t.Name(), t.Value());
                }
            }
            //p1.NW();
        }
Exemplo n.º 15
0
        /// <summary>
        /// calculates a path
        /// </summary>
        /// <returns></returns>
        private BehaviorReturnCode calculatePath()
        {
            f_newPath = true;
            APath path = (APath)f_PathMapper.get(f_ThisEntity);

            switch (path.PathState)
            {
            case PathState.PathFound:
                return(BehaviorReturnCode.Success);

            case PathState.PathFailed:
                return(BehaviorReturnCode.Failure);

            default:
                path.PathState = PathState.DoPathing;
                return(BehaviorReturnCode.Running);
            }
        }
Exemplo n.º 16
0
    // Start is called before the first frame update
    void Start()
    {
        List <ANode> nodes = new List <ANode>();
        List <APath> paths = new List <APath>();

        ANode a = new ANode(new Vector2(0, 0));
        ANode b = new ANode(new Vector2(1, 0));
        ANode c = new ANode(new Vector2(0.5f, -0.5f));
        ANode d = new ANode(new Vector2(0, -1));
        ANode e = new ANode(new Vector2(-1, -1));

        nodes.Add(a);
        nodes.Add(b);
        nodes.Add(c);
        nodes.Add(d);
        nodes.Add(e);

        APath ab = new APath(a, b, 2);
        APath ad = new APath(a, d, 1);
        APath bc = new APath(b, c, 1);
        APath ce = new APath(c, e, 1);
        APath de = new APath(d, e, 5);
        APath be = new APath(b, e, 3);

        paths.Add(ab);
        paths.Add(ad);
        paths.Add(bc);
        paths.Add(ce);
        paths.Add(de);
        paths.Add(be);

        AStar test = new AStar(nodes, paths);

        test.PrintState();

        if (test.FindPath(a, e))
        {
            test.PrintPath();
        }

        test.PrintState();
    }
Exemplo n.º 17
0
        static int _IsSystem64PathIn32BitProcess(string path)
        {
            if (!AVersion.Is32BitProcessAnd64BitOS)
            {
                return(0);
            }
            string sysDir = AFolders.System;

            if (!path.Starts(sysDir, true))
            {
                return(0);
            }
            int len = sysDir.Length;

            if (path.Length > len && !APath.IsSepChar_(path[len]))
            {
                return(0);
            }
            return(len);
        }
Exemplo n.º 18
0
    public void OnClick()
    {
        if (type == 0)
        {
            CubeTerrain.Instance.StartBuildWorld();
        }

        if (type == 1)
        {
            flags = 2;
            obj.GetComponent<Rigidbody>().useGravity = true;
        }

        if (type == 2)
        {
            APath apath = new APath();

            apath.FindPath(10, 10, 10, 100, 100, 100);
        }

        type += 1;
    }
Exemplo n.º 19
0
        private BehaviorReturnCode resetPathfinder()
        {
            Position start    = (Position)f_PositionMapper.get(f_ThisEntity);
            Position finish   = (Position)f_PositionMapper.get(f_Target);
            GameMap  map      = (GameMap)f_GameMapMapper.get(f_Map);
            ViewPort viewport = (ViewPort)f_ViewPortMapper.get(f_Camera);

            Vector2 sVec, fVec;

            //s_Center = viewport.getDimensions() / 2;

            sVec = (start.Pos) / f_TileSize;
            fVec = (finish.Pos + finish.Offset) / f_TileSize;

            /*
             * sVec = (start.Pos + s_Center) / s_TileSize;
             * fVec = (finish.Pos + s_Center) / s_TileSize;
             */
            s_TargetCell.Position  = fVec;
            s_CurrentCell.Position = sVec;

            APath path = (APath)f_PathMapper.get(f_ThisEntity);

            path.Map       = map;
            path.Start     = sVec;
            path.Finish    = fVec;
            path.Failed    = false;
            path.HasRun    = false;
            path.PathState = PathState.Idle;
            //findPath.reset(sVec, fVec, map);

            s_currentPath.Clear();
            f_newPath = true;

            return(BehaviorReturnCode.Success);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Loads image and returns its data in .bmp file format.
        /// Returns null if fails, for example file not found or invalid Base64 string.
        /// </summary>
        /// <param name="s">Depends on t. File path or resource name without prefix or Base64 image data without prefix.</param>
        /// <param name="t">Image type and string format.</param>
        /// <param name="searchPath">Use <see cref="AFile.SearchPath"/></param>
        /// <remarks>Supports environment variables etc. If not full path, searches in <see cref="AFolders.ThisAppImages"/>.</remarks>
        public static byte[] BmpFileDataFromString(string s, ImageType t, bool searchPath = false)
        {
            //AOutput.Write(t, s);
            try {
                switch (t)
                {
                case ImageType.Bmp:
                case ImageType.PngGifJpg:
                case ImageType.Cur:
                    if (searchPath)
                    {
                        s = AFile.SearchPath(s, AFolders.ThisAppImages);
                        if (s == null)
                        {
                            return(null);
                        }
                    }
                    else
                    {
                        if (!APath.IsFullPathExpandEnvVar(ref s))
                        {
                            return(null);
                        }
                        s = APath.Normalize(s, AFolders.ThisAppImages);
                        if (!AFile.ExistsAsFile(s))
                        {
                            return(null);
                        }
                    }
                    break;
                }

                switch (t)
                {
                case ImageType.Base64CompressedBmp:
                    return(AConvert.Decompress(Convert.FromBase64String(s)));

                case ImageType.Base64PngGifJpg:
                    using (var stream = new MemoryStream(Convert.FromBase64String(s), false)) {
                        return(_ImageToBytes(Image.FromStream(stream)));
                    }

                case ImageType.Resource:
                    return(_ImageToBytes(AResources.GetAppResource(s) as Image));

                case ImageType.Bmp:
                    return(File.ReadAllBytes(s));

                case ImageType.PngGifJpg:
                    return(_ImageToBytes(Image.FromFile(s)));

                case ImageType.Ico:
                case ImageType.IconLib:
                case ImageType.ShellIcon:
                case ImageType.Cur:
                    return(_IconToBytes(s, t == ImageType.Cur, searchPath));
                }
            }
            catch (Exception ex) { ADebug.Print(ex.Message + "    " + s); }
            return(null);
        }
Exemplo n.º 21
0
    bool _GetGrid()
    {
        var g = _grid;

        //test script
        FileNode fts = null;

        if (g.ZGetValue("testScript", out var sts, true, true))
        {
            fts = _f.FindRelative(sts, false);
            if (fts == null)
            {
                ADialog.ShowInfo("testScript file not found", "Must be path relative to this file or path in worspace like \\file or \\folder\\file.", owner: this); return(false);
            }
        }
        _f.TestScript = fts;

        //info: _Get returns null if hidden

        _meta.runMode     = _Get("runMode");
        _meta.ifRunning   = _Get("ifRunning");
        _meta.ifRunning2  = _Get("ifRunning2");
        _meta.uac         = _Get("uac");
        _meta.prefer32bit = _Get("prefer32bit");

        _meta.optimize     = _Get("optimize");
        _meta.warningLevel = _Get("warningLevel");
        _meta.noWarnings   = _Get("noWarnings");
        _meta.define       = _Get("define");
        _meta.preBuild     = _Get("preBuild");
        _meta.postBuild    = _Get("postBuild");

        _meta.outputPath = _Get("outputPath");
        _meta.console    = _Get("console");
        _meta.icon       = _Get("icon");
        _meta.manifest   = _Get("manifest");
        _meta.resFile    = _Get("resFile");
        _meta.sign       = _Get("sign");
        _meta.xmlDoc     = _Get("xmlDoc");

        _meta.role = null;
        if (_role != ERole.classFile)
        {
            if (_isClass || _role != ERole.miniProgram)
            {
                _meta.role = _role.ToString();
            }
            switch (_role)
            {
            case ERole.exeProgram:
            case ERole.classLibrary:
                if (_meta.outputPath.NE())
                {
                    _meta.outputPath = _role == ERole.exeProgram ? @"%AFolders.Workspace%\bin" : @"%AFolders.ThisApp%\Libraries";
                }
                break;
            }
            var name = APath.GetFileName(_f.Name, true);
            if (_meta.xmlDoc == "")
            {
                _meta.xmlDoc = name + ".xml";
            }
            if (_meta.manifest == "")
            {
                _meta.manifest = name + ".exe.manifest";
            }
        }

        return(true);
    }
Exemplo n.º 22
0
        /// <summary>
        /// pathing failed
        /// </summary>
        /// <returns></returns>
        private bool hasPathFailed()
        {
            APath path = (APath)f_PathMapper.get(f_ThisEntity);

            return(path.PathState == PathState.PathFailed ? true : false);
        }
Exemplo n.º 23
0
 void Start()
 {
     pathList = new UPath[amountOfThreads];
       		targetList = new List<Vector3>();
     startList = new List<Vector3>();
     indexList = new List<int>();
     returnList = new List<GameObject>();
     apath = new APath[amountOfThreads];
     UGrid gridScript = GameObject.Find("UGrid").GetComponent<UGrid>();
     for(int x = 0; x < apath.Length; x++){
         apath[x] = new APath();
         apath[x].gridScript = gridScript;
     }
     startedThreads = new bool[amountOfThreads];
 }
Exemplo n.º 24
0
        /// <summary>
        /// a path was found
        /// </summary>
        /// <returns></returns>
        private bool hasPathBeenFound()
        {
            APath path = (APath)f_PathMapper.get(f_ThisEntity);

            return((path.PathState == PathState.PathFound ? true : false) && (path.FoundPath != null));
        }
Exemplo n.º 25
0
        static bool _Compile(bool forRun, FileNode f, out CompResults r, FileNode projFolder)
        {
            var p1 = APerf.Create();

            r = new CompResults();

            var m = new MetaComments();

            if (!m.Parse(f, projFolder, EMPFlags.PrintErrors))
            {
                return(false);
            }
            var err = m.Errors;

            p1.Next('m');

            bool needOutputFiles = m.Role != ERole.classFile;

            //if for run, don't compile if f role is classFile
            if (forRun && !needOutputFiles)
            {
                r.role = ERole.classFile;
                return(false);
            }

            XCompiled cache = XCompiled.OfCollection(f.Model);
            string    outPath = null, outFile = null, fileName = null;

            if (needOutputFiles)
            {
                if (m.OutputPath != null)
                {
                    outPath  = m.OutputPath;
                    fileName = m.Name + ".dll";
                }
                else
                {
                    outPath  = cache.CacheDirectory;
                    fileName = f.IdString;
                }
                outFile = outPath + "\\" + fileName;
                AFile.CreateDirectory(outPath);
            }

            if (m.PreBuild.f != null && !_RunPrePostBuildScript(false, m, outFile))
            {
                return(false);
            }

            var po    = m.CreateParseOptions();
            var trees = new CSharpSyntaxTree[m.CodeFiles.Count];

            for (int i = 0; i < trees.Length; i++)
            {
                var f1 = m.CodeFiles[i];
                trees[i] = CSharpSyntaxTree.ParseText(f1.code, po, f1.f.FilePath, Encoding.UTF8) as CSharpSyntaxTree;
                //info: file path is used later in several places: in compilation error messages, run time stack traces (from PDB), Visual Studio debugger, etc.
                //	Our AOutputServer.SetNotifications callback will convert file/line info to links. It supports compilation errors and run time stack traces.
            }
            //p1.Next('t');

            string asmName = m.Name;

            if (m.Role == ERole.editorExtension)
            {
                asmName = asmName + "|" + (++c_versionCounter).ToString();                                             //AssemblyLoadContext.Default cannot load multiple assemblies with same name
            }
            var compilation = CSharpCompilation.Create(asmName, trees, m.References.Refs, m.CreateCompilationOptions());

            //p1.Next('c');

#if PDB
            string pdbFile = null;
#endif
            MemoryStream          pdbStream = null;
            string                xdFile    = null;
            Stream                xdStream  = null;
            Stream                resNat    = null;
            ResourceDescription[] resMan    = null;
            EmitOptions           eOpt      = null;

            if (needOutputFiles)
            {
                _AddAttributes(ref compilation, needVersionEtc: m.Role == ERole.miniProgram || m.Role == ERole.exeProgram);

                //create debug info always. It is used for run-time error links.
#if PDB
                pdbStream = new MemoryStream();
                if (m.OutputPath != null)
                {
                    pdbFile = Path.ChangeExtension(outFile, "pdb");
                    eOpt    = new EmitOptions(debugInformationFormat: DebugInformationFormat.Pdb, pdbFilePath: pdbFile);
                    //eOpt = new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb, pdbFilePath: pdbFile); //smaller, but not all tools support it
                }
                else
                {
                    //eOpt = new EmitOptions(debugInformationFormat: DebugInformationFormat.Embedded); //no, it is difficult to extract, because we load assembly from byte[] to avoid locking. We instead append portable PDB stream to the assembly stream.
                    eOpt = new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb);
                    //adds < 1 KB; almost the same compiling speed. Separate pdb file is 14 KB; 2 times slower compiling, slower loading.
                }
#else
                if (m.OutputPath != null)
                {
                    //we don't use classic pdb file becouse of this error after switching to .NET Core:
                    //	Unexpected error writing debug information -- 'The version of Windows PDB writer is older than required: 'diasymreader.dll''
                    eOpt = new EmitOptions(debugInformationFormat: DebugInformationFormat.Embedded);
                }
                else
                {
                    pdbStream = new MemoryStream();
                    //eOpt = new EmitOptions(debugInformationFormat: DebugInformationFormat.Embedded); //no, it is difficult to extract, because we load assembly from byte[] to avoid locking. We instead append portable PDB stream to the assembly stream.
                    eOpt = new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb);
                    //adds < 1 KB; almost the same compiling speed. Separate pdb file is 14 KB; 2 times slower compiling, slower loading.
                }
#endif

                if (m.XmlDocFile != null)
                {
                    xdStream = AFile.WaitIfLocked(() => File.Create(xdFile = APath.Normalize(m.XmlDocFile, outPath)));
                }

                resMan = _CreateManagedResources(m);
                if (err.ErrorCount != 0)
                {
                    err.PrintAll(); return(false);
                }

                if (m.Role == ERole.exeProgram || m.Role == ERole.classLibrary)
                {
                    resNat = _CreateNativeResources(m, compilation);
                }
                if (err.ErrorCount != 0)
                {
                    err.PrintAll(); return(false);
                }

                //EmbeddedText.FromX //it seems we can embed source code in PDB. Not tested.
            }

            //p1.Next();
            var asmStream  = new MemoryStream(8000);
            var emitResult = compilation.Emit(asmStream, pdbStream, xdStream, resNat, resMan, eOpt);

            if (needOutputFiles)
            {
                xdStream?.Dispose();
                resNat?.Dispose();                 //info: compiler disposes resMan
            }
            //p1.Next('e');

            var diag = emitResult.Diagnostics;
            if (!diag.IsEmpty)
            {
                foreach (var d in diag)
                {
                    if (d.Severity == DiagnosticSeverity.Hidden)
                    {
                        continue;
                    }
                    err.AddErrorOrWarning(d, f);
                    if (d.Severity == DiagnosticSeverity.Error && d.Id == "CS0009")
                    {
                        MetaReferences.RemoveBadReference(d.GetMessage());
                    }
                }
                err.PrintAll();
            }
            if (!emitResult.Success)
            {
                if (needOutputFiles)
                {
                    AFile.Delete(outFile);
#if PDB
                    if (pdbFile != null)
                    {
                        AFile.Delete(pdbFile);
                    }
#endif
                    if (xdFile != null)
                    {
                        AFile.Delete(xdFile);
                    }
                }
                return(false);
            }

            if (needOutputFiles)
            {
                //If there is no [STAThread], will need MTA thread.
                if (m.Role == ERole.miniProgram || m.Role == ERole.exeProgram)
                {
                    bool hasSTAThread = compilation.GetEntryPoint(default)?.GetAttributes().Any(o => o.ToString() == "System.STAThreadAttribute") ?? false;
Exemplo n.º 26
0
        /// <summary>
        /// Toolbar button MouseUp handler. Implements context menu that allows to customize.
        /// </summary>
        private void _OnMouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Right)
            {
                return;
            }
            var  item        = sender as ToolStripItem;
            var  ts          = item.Owner;
            var  dd          = ts as ToolStripDropDownMenu;
            bool isMenu      = dd != null;
            bool isCustom    = ts == _tsCustom1 || ts == _tsCustom2;
            bool isSeparator = item is ToolStripSeparator;
            bool isHidden    = item.Overflow == ToolStripItemOverflow.Always;
            var  x           = item.Tag as XElement;

            var m = new AMenu();

            m["Properties..."] = o => {
                using (var f = new FSMProperties(this, item.Tag as XElement, isMenu)) {
                    if (f.ShowDialog(_form) == DialogResult.OK)
                    {
                        _Strips_Customize(6, item, null, f);
                    }
                }
            };
            if (!isMenu)
            {
                if (!isSeparator)
                {
                    m["Hide"] = o => _Strips_Customize(5, item); if (isHidden)
                    {
                        m.LastMenuItem.Checked = true;
                    }
                }
                if (isCustom || isSeparator)
                {
                    m["Remove"] = o => _Strips_Customize(3, item);
                }
                if (!isHidden)
                {
                    m["Add separator"] = o => _Strips_Customize(4, item, ts);
                }
            }
            if (isCustom)
            {
                if (_tsCustom1 != null && _tsCustom2 != null)
                {
                    if (ts == _tsCustom1)
                    {
                        m["Move to toolbar Custom2"] = o => _Strips_Customize(2, item, _tsCustom2);
                    }
                    else
                    {
                        m["Move to toolbar Custom1"] = o => _Strips_Customize(2, item, _tsCustom1);
                    }
                }
            }
            else
            {
                if (_tsCustom1 != null)
                {
                    m["Copy to toolbar Custom1"] = o => _Strips_Customize(1, item, _tsCustom1);
                }
                if (_tsCustom2 != null)
                {
                    m["Copy to toolbar Custom2"] = o => _Strips_Customize(1, item, _tsCustom2);
                }
            }
            if (!isMenu)
            {
                m.Separator();
                m["How to customize..."] = o => ADialog.ShowInfo("Customizing toolbars and menus",
                                                                 @"There are several standard toolbars and two custom toolbars (initially empty). Standard toolbar buttons cannot be added and removed, but can be hidden and reordered. Menu items cannot be added, removed, hidden and reordered.

You can find most customization options in two context menus. Right-clicking a button or menu item shows its context menu. Right-clicking before the first button shows toolbar's context menu. You can Alt+drag toolbar buttons to reorder them on the same toolbar. You can Alt+drag toolbars to dock them somewhere else. Use splitters to resize. Right click a splitter to change its thickness."
                                                                 );
                string folder = APath.GetDirectoryPath(_xmlFileCustom), link = $"<a href=\"{folder}\">{folder}</a>";
                m["How to backup, restore, reset..."] = o => {
                    ADialog.Show("How to backup, restore or reset customizations",
                                 $@"All customizations are saved in XML files in folder
{link}

To backup:  copy the file.
To restore:  exit this application and replace the file with the backup file.
To reset:  exit this application and delete the file."
                                 , icon: DIcon.Info, onLinkClick: h => { AExec.Run(h.LinkHref); });
                };
            }

            m.Show(ts);
        }
Exemplo n.º 27
0
 public void AddPaths(APath path)
 {
     this.paths.Add(path);
 }
Exemplo n.º 28
0
Arquivo: Run.cs Projeto: alexfordc/Au
    static void _SciLink_RunClassFile(string s)
    {
        int action = s.ToInt();         //1 add meta role miniProgram, 2 create Script project, 3 create new test script and set "run" attribute
        var f      = Program.Model.Find(s.Substring(2), null); if (f == null)
        {
            return;
        }
        FileNode f2 = null;

        if (action == 1)          //add meta role exeProgram
        {
            if (!Program.Model.SetCurrentFile(f))
            {
                return;
            }
            Program.Model.Properties();
        }
        else
        {
            if (action == 2)              //create project
            {
                if (!_NewItem(out f2, @"New Project\@Script"))
                {
                    return;
                }
                f.FileMove(f2, Aga.Controls.Tree.NodePosition.After);
            }
            else                 //create test script
            {
                s = "test " + APath.GetFileName(f.Name, true);
                if (!_NewItem(out f2, "Script.cs", s))
                {
                    return;
                }
                f.TestScript = f2;
            }

            //Creates new item above f or f's project folder.
            bool _NewItem(out FileNode ni, string template, string name = null)
            {
                bool isProject = f.FindProject(out var target, out _);

                if (!isProject)
                {
                    target = f;
                }

                var text = new EdNewFileText();

                if (action == 2)
                {
                    text.text = "Class1.Function1();\r\n";
                }
                else
                {
                    text.meta = $"/*/ {(isProject ? "pr" : "c")} {f.ItemPath} /*/ ";
                    text.text = $"{(isProject ? "Library." : "")}Class1.Function1();\r\n";
                }

                ni = Program.Model.NewItem(target, Aga.Controls.Tree.NodePosition.Before, template, name, text: text);
                return(ni != null);
            }
        }
    }