Exemple #1
0
        /// <summary>
        /// Adds menu items for all panels or toolbars, except the doc panel, to a menu.
        /// On menu item click will show that panel.
        /// </summary>
        public void ZAddShowPanelsToMenu(ToolStripDropDown m, bool toolbars, bool clear = false)
        {
            m.SuspendLayout();
            if (clear)
            {
                m.Items.Clear();
            }

            var a = _aPanel.FindAll(v => !v.HasDocument && (toolbars == v.HasToolbar));

            a.Sort((v1, v2) => v1.Name.CompareTo(v2.Name));
            foreach (var v in a)
            {
                var s = v.Text;
                if (!v.Visible)
                {
                    s += "  (hidden)";
                }
                m.Items.Add(s, v.Image, (unu, sed) => { v.Show(true); });
            }
            //add Reset...
            m.Items.Add(new ToolStripSeparator());
            (m.Items.Add("Reset...", null, (unu, sed) => {
                if (ZResetLayoutAfterRestart)
                {
                    ZResetLayoutAfterRestart = false;
                }
                else
                {
                    ZResetLayoutAfterRestart = ADialog.ShowOkCancel("Reset panel/toolbar layout", "After restarting this application.");
                }
            }) as ToolStripMenuItem).Checked = ZResetLayoutAfterRestart;

            m.ResumeLayout();
        }
Exemple #2
0
    private void readFile(string filename)
    {
        Dialogs.Clear();
        TextAsset textFile = Resources.Load <TextAsset>("Story/" + filename);

        if (textFile == null)
        {
            Debug.Log("OpenFileError");
            return;
        }

        string text = textFile.text;

        string[] textArr = text.Split('#');
        foreach (string paragraph in textArr)
        {
            ADialog aDialog = new ADialog();
            aDialog.choice = new string[] { "", "", "" };
            aDialog.love   = new int[] { 0, 0, 0 };

            string[] lineArr = paragraph.Split('\n');
            aDialog.question = lineArr[0];
            aDialog.audioID  = int.Parse(lineArr[1]);
            for (int i = 2; i < lineArr.Length; i += 2)
            {
                aDialog.choice[(i / 2) - 1] = lineArr[i];
                aDialog.love[(i / 2) - 1]   = int.Parse(lineArr[i + 1]);
            }
            Dialogs.Add(aDialog);
            //Debug.Log(aDialog.question + " " + aDialog.choice[0] + " " + aDialog.choice[1] + " " + aDialog.choice[2] + " " + aDialog.love[2]);
        }
    }
Exemple #3
0
    private void _bAddNet_Click(object button, EventArgs e)
    {
        using var d = new System.Windows.Forms.OpenFileDialog { InitialDirectory = AFolders.ThisApp, Filter = "Dll|*.dll|All files|*.*", Multiselect = true };
        if (d.ShowDialog(this) != DialogResult.OK)
        {
            return;
        }

        var a = d.FileNames;

        foreach (var v in a)
        {
            if (MetaReferences.IsDotnetAssembly(v))
            {
                continue;
            }
            ADialog.ShowError("Not a .NET assembly.", v, owner: this);
            return;
        }

        //remove path and ext if need
        var thisApp = AFolders.ThisAppBS;

        if (a[0].Starts(thisApp, true))
        {
            for (int i = 0; i < a.Length; i++)
            {
                a[i] = a[i].Substring(thisApp.Length);
            }
        }

        _meta.r.AddRange(a);
        _Added(button, _meta.r);
    }
Exemple #4
0
	//protected override void OnGotFocus(EventArgs e) { _c.Focus(); }

	/// <summary>
	/// Loads existing or new workspace.
	/// If fails, shows a task dialog with several choices - retry, load another, create new, cancel. If then fails, ends process.
	/// Sets Model and Text properties of the main form. Updates recent files.
	/// By default runs startup script.
	/// </summary>
	/// <param name="wsDir">
	/// Workspace's directory. The directory should contain file "files.xml" and subdirectory "files".
	/// If null, loads the last used workspace (its path is in settings).
	/// If the setting does not exist, uses AFolders.ThisAppDocuments + @"Main".
	/// If the file does not exist, copies from AFolders.ThisApp + @"Default\Workspace".
	/// </param>
	public FilesModel ZLoadWorkspace(string wsDir = null)
	{
		wsDir ??= Program.Settings.workspace;
		if(wsDir.NE()) wsDir = AFolders.ThisAppDocuments + "Main";
		var xmlFile = wsDir + @"\files.xml";
		var oldModel = _model;
		FilesModel m = null;
		_isNewWorkspace = false;
		g1:
		try {
			//SHOULDDO: if editor runs as admin, the workspace directory should be write-protected from non-admin processes.

			if(_isNewWorkspace = !AFile.ExistsAsFile(xmlFile)) {
				AFile.Copy(AFolders.ThisAppBS + @"Default\Workspace", wsDir);
			}

			_model?.UnloadingWorkspace(); //saves all, closes documents, sets current file = null

			m = new FilesModel(_c, xmlFile);
			_c.Model = m;
		}
		catch(Exception ex) {
			m?.Dispose();
			m = null;
			//AOutput.Write($"Failed to load '{wsDir}'. {ex.Message}");
			switch(ADialog.ShowError("Failed to load workspace", wsDir,
				"1 Retry|2 Load another|3 Create new|0 Cancel",
				owner: this, expandedText: ex.ToString())) {
			case 1: goto g1;
			case 2: m = ZLoadAnotherWorkspace(); break;
			case 3: m = ZLoadNewWorkspace(); break;
			}
			if(m != null) return m;
			if(_model != null) return _model;
			Environment.Exit(1);
		}

		oldModel?.Dispose();
		Program.Model = _model = m;

		//CONSIDER: unexpand path
		if(wsDir != Program.Settings.workspace) {
			if(Program.Settings.workspace != null) {
				var ar = Program.Settings.recentWS ?? Array.Empty<string>();
				int i = Array.IndexOf(ar, wsDir); if(i >= 0) ar = ar.RemoveAt(i);
				Program.Settings.recentWS = ar.InsertAt(0, Program.Settings.workspace);
			}
			Program.Settings.workspace = wsDir;
		}

		Program.MainForm.ZSetTitle();
		if(Program.Loaded >= EProgramState.LoadedWorkspace) {
			ZOpenDocuments();
			ZModel.RunStartupScripts();
		}

		return _model;
	}
Exemple #5
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));
	}
Exemple #6
0
 /// <summary>
 /// Used only by the Save class.
 /// </summary>
 bool _SaveWorkspaceNow()
 {
     try {
         //AOutput.Write("saving");
         Root.Save(WorkspaceFile);
         return(true);
     }
     catch (Exception ex) {        //XElement.Save exceptions are undocumented
         ADialog.ShowError("Failed to save", WorkspaceFile, expandedText: ex.Message);
         return(false);
     }
 }
Exemple #7
0
partial class Script : AScript { [STAThread] static void Main(string[] a) => new Script(a); Script(string[] args) //;;;
//This is an example script used by ATask.Run examples in files "Hotkey triggers" (Ctrl+Shift+3) and "Common toolbars".
//It runs in separate process. You can edit and run it without restarting the main script process (triggers and toolbars).

                                 {
                                     ADialog.Show("Example");

//Although this script is in the project folder, it is not part of the project (only the first script is).
//Therefore other files of the project folder are not included in the compilation, and their classes/functions are not available.
//But you can explicitly specify class files. Use the Properties dialog. See the "c ..." in the first line.
                                     Class1.Function1();
                                 }
Exemple #8
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;
    }
Exemple #9
0
    /// <summary>
    /// Creates SQLite databases containing design-time assemblies and XML documentation files of a .NET Core runtime. The SDK must be installed.
    /// </summary>
    /// <remarks>
    /// Shows a list dialog.
    ///		If selected All, creates for all runtime versions starting from 3.1, with names ref.version.db (eg ref.3.1.0.db) and doc.version.db, in AFolders.ThisAppBS.
    ///		Else creates only for the selected runtime version, with names ref.db and doc.db, in dataDir, and sets to copy to AFolders.ThisAppBS when opening next time after process restarts.
    /// We ship and at run time load databases of single version, named ref.db and doc.db. In the future should allow to download and use multiple versions.
    /// Also this function allows users to create databases from SDKs installed on their PC, but currently this feature is not exposed. Would need to add UI and exception handling.
    /// ref.db contains dlls from 'dotnet\packs' folder. They contain only metadata of public API, not all code like dlls in the 'dotnet\shared' folder.
    ///		Why need it when we can load PortableExecutableReference from 'dotnet\shared' folder? Because:
    ///			1. They are big and may add 100 MB of process memory. We need to load all, because cannot know which are actually used in various stages of compilation.
    ///			2. When loading from dll files, Windows Defender makes it as slow as 2.5 s or more, unless the files already are in OS file buffers.
    ///			3. Better compatibility. See https://github.com/dotnet/standard/blob/master/docs/history/evolution-of-design-time-assemblies.md
    ///	doc.db contains XML documentation files of .NET Core assemblies. From the same 'dotnet\packs' folder.
    ///		Why need it:
    ///			1. Else users would have to download whole .NET Core SDK. Now need only runtimes.
    ///			2. Parsed XML files can use eg 200 MB of process memory. Now we get doc of a single type/method/etc from database only when need; all other data is not in memory.
    ///
    /// Need to run this after changing Core version of C# projects (<TargetFramework>netcoreapp3.1</TargetFramework>). Also update COREVER2 etc in AppHost.cpp.
    /// </remarks>
    public static void CreateRefAndDoc(string dataDir = @"Q:\app\Au\Other\Data")
    {
        Cursor.Current = Cursors.WaitCursor;
        if (0 == AFolders.NetRuntimeBS.RegexReplace(@"(?i)\\shared\\(Microsoft\.NETCore\.App)\\.+", @"\packs\$1.Ref", out var refDir, 1))
        {
            throw new AuException();
        }
        //AOutput.Write(refDir);
        var a = new List <string>();

        foreach (var f in AFile.EnumDirectory(refDir, FEFlags.UseRawPath))          //for each version
        {
            if (!f.IsDirectory)
            {
                continue;
            }
            var s = f.Name;
            int v1 = s.ToInt(0, out int ne), v2 = s.ToInt(ne + 1); if (v1 < 3 || v2 < 1)
            {
                continue;                                                                                     //must be 3.1 or later
            }
            a.Add(s);
        }
        a.Add("All");
        int i = ADialog.ShowList(a, "Create database", "For runtime") - 1;

        if (i < 0)
        {
            return;
        }
        int n = a.Count - 1;

        if (i < n)
        {
            _CreateRefAndDoc(refDir, a[i], false, dataDir);
        }
        else
        {
            for (i = 0; i < n; i++)
            {
                _CreateRefAndDoc(refDir, a[i], true, dataDir);
            }
        }
        AOutput.Write("CreateRefAndDoc done.");
        Cursor.Current = Cursors.Arrow;
    }
Exemple #10
0
            private void _bClick(object sender, EventArgs e)
            {
                if (!(_lb.SelectedItem is AToolbar tb))
                {
                    return;
                }
                if (tb._c.IsDisposed)
                {
                    ADialog.Show("Closed", owner: this);
                    return;
                }
                var w = tb._c.Hwnd();
                var r = w.Rect;

                if (sender == _bShow)
                {
                    if (AScreen.IsInAnyScreen(r))
                    {
                        r.Inflate(2, 2);
                        var osd = new AOsdRect {
                            Rect = r, Color = 0xff0000
                        };
                        osd.Show();
                        ATimer.After(1000, _ => osd.Dispose());
                    }
                    else
                    {
                        ADialog.Show("Offscreen", "Rectangle: " + r.ToString(), owner: this);
                    }
                }
                else if (sender == _bMove)
                {
                    if (!w.IsVisible && !ADialog.ShowOkCancel("Hidden", "Move this hidden toolbar?", owner: this))
                    {
                        return;
                    }
                    var xy = AMouse.XY;
                    w.MoveLL(xy.x, xy.y);
                    var w2 = this.Hwnd();
                    if (!w.ZorderIsAbove(w2))
                    {
                        w.ZorderAbove(w2);
                    }
                }
            }
Exemple #11
0
        //Use r on Capture. Use image on Open.
        void _SetImage(WICResult r = null, Bitmap image = null)
        {
            if (r != null)              //on Capture
            {
                var wnd = r.wnd.Window; if (wnd.Is0)
                {
                    return;
                }
                _SetWndCon(wnd, r.wnd, true, false);
                if (_isColor = (r.image == null))
                {
                    using (var g = Graphics.FromImage(r.image = new Bitmap(16, 16))) g.Clear((Color)r.color);
                }
                _color = r.color.color & 0xffffff;
                _image = r.image;
                _rect  = r.rect;
            }
            else                 //on Open
            {
                _color = 0;
                _image = image;
                _rect  = new RECT(0, 0, image.Width, image.Height);
            }

            //set _pict
            var oldImage = _pict.Image;

            _pict.Image = _image;
            oldImage?.Dispose();

            //set _code
            _FormatCode();

            _bTest.Enabled = true; _bOK.Enabled = true;

            if (_MultiIsActive && ADialog.ShowYesNo("Add to array?", owner: this))
            {
                _MultiAdd();
            }

            _errorProvider.Clear();
        }
Exemple #12
0
partial class Script : AScript { [STAThread] static void Main(string[] a) => new Script(a); Script(string[] args)   //;;;
//Click the ► button on the toolbar to run the script.

                                 {
                                     AOutput.Write("The programming language is C#.");
                                     if (ADialog.ShowYesNo("Run Notepad?", "The script will add some text and close Notepad after 2 s."))
                                     {
                                         AExec.Run(AFolders.System + @"Notepad.exe");
                                         var w = AWnd.Wait(5, active: true, "*- Notepad"); //to create this code can be used the Code menu
                                         50.ms();
                                         AKeys.Text("some text");
                                         2.s();
                                         AKeys.Key("Ctrl+Z"); //Undo
                                         w.Close();
                                     }

                                     string linkText = "Read about code editor features",
                                            linkUrl  = "https://www.quickmacros.com/au/help/editor/Code editor.html";

                                     AOutput.Write($"<><link \"{linkUrl}\">{linkText}</link>");
                                 }
Exemple #13
0
    public void RegexWindowShow(SciCode doc, string code, int pos16, TextSpan stringSpan, bool replace)
    {
        int j = stringSpan.Start, vi = _StringPrefixLength(code, j);

        if (!replace && (vi == 0 || !(code[j] == '@' || code[j + 1] == '@')))
        {
            ADialog.ShowInfo(null, "Regular expression string should be like @\"text\", not like \"text\". The Regex tool will not escape \\ when inserting text.");
        }

        if (_regexWindow == null)
        {
            _regexWindow             = new RegexWindow();
            _regexWindow.Window.Name = "Ci.Regex";             //prevent hiding when activated
        }

        var r = CiUtil.GetCaretRectFromPos(doc, pos16);
        int i = Au.Util.ADpi.ScaleInt(100);

        r.Width = i;
        r.Inflate(i, 0);
        _regexWindow.Show(doc, r, false, PopupAlignment.TPM_CENTERALIGN | PopupAlignment.TPM_VERTICAL);
        _regexWindow.InsertInControl = doc;
        var s = _regexWindow.CurrentTopic;

        if (s == "replace")
        {
            if (!replace)
            {
                _regexWindow.CurrentTopic = _regexTopic;
            }
        }
        else if (replace)
        {
            _regexTopic = s;
            _regexWindow.CurrentTopic = "replace";
        }
        doc.ZTempRanges_Add(this, stringSpan.Start + vi + 1, stringSpan.End - 1, onLeave: () => _regexWindow.Hide());
    }
Exemple #14
0
    static void _ShowRegexOrKeysWindow(bool regex)
    {
        bool retry = false;

g1:
        if (!CodeInfo.GetDocumentAndFindNode(out var cd, out var node))
        {
            return;
        }
        var pos16 = cd.pos16;

        if (!CiUtil.IsInString(ref node, pos16))
        {
            if (regex || retry)
            {
                ADialog.ShowInfo("The text cursor must be in a string.");
                return;
            }
            InsertCode.Statements("AKeys.Key(\"%\");", goToPercent: true);
            retry = true;
            goto g1;
        }
        var doc        = cd.sciDoc;
        var stringSpan = node.Span;

        var t = CodeInfo._tools;

        if (regex)
        {
            t.RegexWindowShow(doc, cd.code, pos16, stringSpan, replace: false);
        }
        else
        {
            t.KeysWindowShow(doc, cd.code, pos16, stringSpan);
        }
    }
Exemple #15
0
    /// <summary>
    /// Processes command line of this program.
    /// Returns true if this instance must exit: 1. If finds previous program instance; then sends the command line to it if need. 2. If incorrect command line.
    /// </summary>
    public static bool OnProgramStarted(string[] a)
    {
        string s           = null;
        int    cmd         = 0;
        bool   activateWnd = true;

        if (a.Length > 0)
        {
            //AOutput.Write(a);

            for (int i = 0; i < a.Length; i++)
            {
                if (a[i].Starts('-'))
                {
                    a[i] = a[i].ReplaceAt(0, 1, "/");
                }
                if (a[i].Starts('/'))
                {
                    a[i] = a[i].Lower();
                }
            }

            s = a[0];
            if (s.Starts('/'))
            {
                for (int i = 0; i < a.Length; i++)
                {
                    s = a[i];
                    switch (s)
                    {
                    case "/test":
                        if (++i < a.Length)
                        {
                            TestArg = a[i];
                        }
                        break;

                    case "/v":
                        StartVisible = true;
                        break;

                    default:
                        ADialog.ShowError("Unknown command line parameter", s);
                        return(true);
                    }
                    //rejected: /h start hidden. Not useful.
                }
            }
            else                 //one or more files
            {
                if (a.Length == 1 && FilesModel.IsWorkspaceDirectory(s))
                {
                    switch (cmd = ADialog.Show("Workspace", s, "1 Open|2 Import|0 Cancel", footerText: FilesModel.GetSecurityInfo("v|")))
                    {
                    case 1: WorkspaceDirectory = s; break;

                    case 2: _importWorkspace = s; break;
                    }
                }
                else
                {
                    cmd          = 3;
                    _importFiles = a;
                }
            }
        }

        //single instance
        s_mutex = new Mutex(true, "Au.Mutex.1", out bool createdNew);
        if (createdNew)
        {
            return(false);
        }

        var w = AWnd.FindFast(null, "Au.Editor.Msg", true);

        if (!w.Is0)
        {
            if (activateWnd)
            {
                AWnd wMain = (AWnd)w.Send(Api.WM_USER);
                if (!wMain.Is0)
                {
                    try { wMain.Activate(); }
                    catch (Exception ex) { ADebug.Print(ex); }
                }
            }

            switch (cmd)
            {
            case 3:             //import files
                s = string.Join("\0", a);
                break;
            }
            if (cmd != 0)
            {
                AWnd.More.CopyDataStruct.SendString(w, cmd, s);
            }
        }
        return(true);
    }
Exemple #16
0
    //void TestMenu2()
    //{
    //	var m = new AMenu();
    //	m["One"] = o => AOutput.Write(o);
    //	m["Two"] = o => AOutput.Write(o);
    //	m.LazySubmenu("Submenu 1").Fill = _ => {
    //		AOutput.Write("adding items of " + m.CurrentAddMenu.OwnerItem);
    //		m["Three"] = o => AOutput.Write(o);
    //		m["Four"] = o => AOutput.Write(o);
    //		m.LazySubmenu("Submenu 2", _ => {
    //			AOutput.Write("adding items of " + m.CurrentAddMenu.OwnerItem);
    //			m["Five"] = o => AOutput.Write(o);
    //			m["Six"] = o => AOutput.Write(o);
    //		});
    //		m["Seven"] = o => AOutput.Write(o);
    //	};
    //	m["Eight"] = o => AOutput.Write(o);
    //	m.Show();

    //}

    //void TestMenu2()
    //{
    //	var m = new AMenu();
    //	m["One"] = o => AOutput.Write(o);
    //	m["Two"] = o => AOutput.Write(o);
    //	m.LazySubmenu("Submenu 1");
    //	m.LazyFill = _ => {
    //		AOutput.Write("adding items of " + m.CurrentAddMenu.OwnerItem);
    //		m["Three"] = o => AOutput.Write(o);
    //		m["Four"] = o => AOutput.Write(o);
    //		m.LazySubmenu("Submenu 2", _ => {
    //			AOutput.Write("adding items of " + m.CurrentAddMenu.OwnerItem);
    //			m["Five"] = o => AOutput.Write(o);
    //			m["Six"] = o => AOutput.Write(o);
    //		});
    //		m["Seven"] = o => AOutput.Write(o);
    //	};
    //	m["Eight"] = o => AOutput.Write(o);
    //	m.Show();

    //}

#if false
    void TestToolbar()
    {
        for (int i = 0; i < 1; i++)
        {
            var t = new AToolbar("123");
            //t.NoText = true;
            //t.Border= TBBorder.Sizable3;t.Control.Text = "Toolbar";
            //t.Border = TBBorder.SizableWithCaptionX;

            //t["Find", @"Q:\app\find.ico"] = o => AOutput.Write(o);
            //t["Copy", @"Q:\app\copy.ico"] = o => AOutput.Write(o);
            //t.Separator("Tpi group");
            //t["Delete", @"Q:\app\delete.ico"] = o => AOutput.Write(o);
            //t["No image"] = o => AOutput.Write(o);
            //t["TT", tooltip: "WWWWWWWWWWWW WWWWWWWWWWWW WWWWWWWWWWWW WWWWWWWWWWWW WWWWWWWWWWWW WWWWWWWWWWWW WWWWWWWWWWWW WWWWWWWWWWWW WWWWWWWWWWWW WWWWWWWWWWWW WWWWWWWWWWWW WWWWWWWWWWWW WWWWWWWWWWWW WWWWWWWWWWWW WWWWWWWWWWWW "] = o => AOutput.Write(o);
            ////t.LastButton.DisplayStyle = ToolStripItemDisplayStyle.Image;
            ////t.LastButton.AutoToolTip = false;
            ////t.LastButton.ToolTipText = "ggg";
            //t.Separator();
            //t["Run", @"Q:\app\run.ico"] = o => AOutput.Write(o);
            //t.Separator("");
            //t["Paste text", @"Q:\app\paste.ico"] = o => AOutput.Write(o);
            //t.LastButton.ToolTipText = "Toooooltip";

            //t.ExtractIconPathFromCode = true;
            //t["Auto icon"] = o => AOutput.Write("notepad.exe");
            //t["Failed icon", @"Q:\app\-.ico"] = o => AOutput.Write(o);
            ////t.LastButton.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
            ////t.Separator("");
            ////t.Add(new ToolStripTextBox { ToolTipText= "ToolStripTextBox", AutoSize=false, Width=50 });
            ////t.Add(new ToolStripComboBox { ToolTipText= "ToolStripComboBox", AutoSize=false, Width=50 });
            ////t.Add(new ToolStripTextBox());
            ////t.Add(new ToolStripTextBox());
            ////t.Add(new ToolStripTextBox());
            ////t.Add(new ToolStripButton("aaa"));
            ////t.Add(new ToolStripButton("bbb"));
            ////t["Multi\r\nline"] = o => AOutput.Write(o);

            //t["None"] = o => _B(TBBorder.None);
            //t["SWC"] = o => _B(TBBorder.SizableWithCaption);
            //t["Sizable1"] = o => _B(TBBorder.Sizable1);
            //t["Sizable2"] = o => _B(TBBorder.Sizable2);
            //t["Sizable3"] = o => _B(TBBorder.Sizable3);
            //t["Sizable3D"] = o => _B(TBBorder.Sizable3D);
            //t["Sizable"] = o => _B(TBBorder.Sizable);
            //t["FixedWithCaption"] = o => _B(TBBorder.FixedWithCaption);
            //t["SizableWithCaption"] = o => _B(TBBorder.SizableWithCaption);
            //t["Close"] = o => t.Close();

#if false
            var dd = new ToolStripDropDownButton("DD");
            t.Add(dd, @"Q:\app\find.ico");
            dd.DropDownOpening += (unu, sed) => {
                var m = new AMenu(dd);
                m["one"] = o => AOutput.Write(o);
                using (m.Submenu("Sub")) {
                    m["si"] = o => AOutput.Write(o);
                }
            };
            var sb = new ToolStripSplitButton("SB");
            t.Add(sb, @"Q:\app\copy.ico", o => AOutput.Write(o));
#elif true
            //t.Control.Font = new Font("Courier New", 16);
            //t.Control.RightToLeft = RightToLeft.Yes;
            t.MenuButton("DD", m => {
                AOutput.Write("dd");
                //m.MultiShow = false;
                m["one"] = o => AOutput.Write(o);
                using (m.Submenu("Sub")) {
                    m["si"] = o => AOutput.Write(o);
                }
            }, @"Q:\app\find.ico", "MenuButton");
            t.SplitButton("SB", m => {
                m["one"] = o => AOutput.Write(o);
                //var sb = m.Control.OwnerItem as ToolStripSplitButton;
                //AOutput.Write(sb);
                //sb.DefaultItem = m.LastItem;
                using (m.Submenu("Sub")) {
                    m["si"] = o => AOutput.Write(o);
                }
            }, @"Q:\app\copy.ico", "SplitButton", o => AOutput.Write(o));
            t.Separator("");
            t[true, "DD2", @"Q:\app\delete.ico"] = m => {
                AOutput.Write("create menu");
                //m.MultiShow = false;
                m["one"] = o => AOutput.Write(o);
                using (m.Submenu("Sub")) {
                    m["si"] = o => AOutput.Write(o);
                }
            };
            //t.SplitButton("SB", o => {
            //	AOutput.Write(o);
            //}, m => {
            //	m["one"] = o => AOutput.Write(o);
            //	using(m.Submenu("Sub")) {
            //		m["si"] = o => AOutput.Write(o);
            //	}
            //}, @"Q:\app\copy.ico", "SplitButton");
            //Action<AMenu> menu1 = m => {
            //	m["one"] = o => AOutput.Write(o);
            //	using(m.Submenu("Sub")) {
            //		m["si"] = o => AOutput.Write(o);
            //	}
            //};
            //t.MenuButton("DD", menu1, @"Q:\app\find.ico", "MenuButton");
#elif false
            t.MenuButton("DD", @"Q:\app\find.ico");
            t.Menu = m => {
                m["one"] = o => AOutput.Write(o);
                using (m.Submenu("Sub")) {
                    m["si"] = o => AOutput.Write(o);
                }
            };
#else
            t.MenuButton("DD", @"Q:\app\find.ico").Menu = m => {
                AOutput.Write("dd");
                //m.MultiShow = false;
                m["one"] = o => AOutput.Write(o);
                using (m.Submenu("Sub")) {
                    m["two"] = o => AOutput.Write(o);
                }
            };
            t.SplitButton("SB", o => AOutput.Write(o), @"Q:\app\copy.ico").Menu = m => {
                AOutput.Write("dd");
                m["one"] = o => AOutput.Write(o);
                using (m.Submenu("Sub")) {
                    m["two"] = o => AOutput.Write(o);
                }
            };
#endif
            //t.Separator("");
            ////t["GC"] = o => GC.Collect();

            //var dd = new ToolStripSplitButton("SB2", null, (unu,sed)=>AOutput.Write("click"));
            //t.Add(dd, @"Q:\app\delete.ico");
            //dd.DropDownOpening += (unu, sed) => {
            //	var m = new AMenu();
            //	dd.DropDown = m.Control;
            //	m["one"] = o => AOutput.Write(o);
            //};
            //dd.ButtonClick += (unu, sed) => AOutput.Write("button click");
            //dd.DoubleClickEnabled = true;
            //dd.ButtonDoubleClick += (unu, sed) => AOutput.Write("button double click");

            //ATimer.After(3000, _ => {
            //	var c = t.Control.Items[0];
            //	c.Select();
            //});

            //void _B(TBBorder b){
            //	t.Border = b;
            //	//AOutput.Write(AWnd.More.BorderWidth((AWnd)t.Control));
            //}

            //t.Bounds = new Rectangle(i * 300 + 700, 200, 200, 200);
            t.Show();
            //t.Window.ActivateLL();
            ATime.SleepDoEvents(200);

            //for(int j = 1; j <= (int)TBBorder.SizableWithCaptionX; j++) {
            //	ATime.SleepDoEvents(1000);
            //	t.Border = (TBBorder)j;
            //}

            //ATime.SleepDoEvents(1000);
            //t.Border = TBBorder.FixedWithCaption;
            //ATime.SleepDoEvents(3000);
            //t.Border = TBBorder.SizableWithCaption;

            //var m = new AMenu();
            //using(m.Submenu("Sub")) {

            //}
            //m.Show()
        }

        //var c = new System.Windows.Forms.VisualStyles.VisualStyleRenderer(VisualStyleElement.Window.FrameLeft.Inactive).GetColor(ColorProperty.BorderColor);
        //AOutput.Write((uint)c.ToArgb());

        //ATimer.After(500, _ => {
        //	var w = (AWnd)t.Control;
        //	//w.SetStyle(WS.DLGFRAME, SetAddRemove.Add);
        //});

        ADialog.Options.TopmostIfNoOwnerWindow = true;
        ADialog.Show();

        //ATimer.After(10000, _ => Application.Exit());
        //Application.Run();
    }
Exemple #17
0
            internal void SetDockState(_DockState state, bool onStartDrag = false)
            {
                //AOutput.Write(this, Name);
                var gp = this as _Panel;

                if (state == _DockState.LastVisible)
                {
                    if (!this.IsHidden)
                    {
                        if (this.IsTabbedPanel)
                        {
                            gp.ParentTab.SetDockState(_DockState.LastVisible);
                            if (this.IsDocked)
                            {
                                gp.ParentTab.SetActiveItem(gp);
                            }
                        }
                        if (this.ParentControl is _Float gf)
                        {
                            ((AWnd)gf).EnsureInScreen();
                        }
                        return;
                    }
                    state = this.SavedVisibleDockState;
                }

                var prevState = this.DockState;

                if (state == prevState)
                {
                    return;
                }

                if (this.ParentSplit == null && state == _DockState.Docked)                  //new panel
                {
                    ADialog.ShowInfo("How to dock floating panels", "Alt+drag and drop.", owner: _manager);
                    return;
                }

                bool isTab = gp == null;
                _Tab gt = null, gtParent = null;

                if (isTab)
                {
                    gt = this as _Tab;
                }
                else
                {
                    gtParent = gp.ParentTab;
                }

                this.DockState = state;

                //get RECT for floating now, because later this.ParentControl will change and even may be destroyed
                RECT rect = default;

                if (state == _DockState.Floating)
                {
                    if (!onStartDrag && !SavedFloatingBounds.IsEmptyRect())
                    {
                        if (SavedFloatingBounds.X == int.MinValue)                          //specified only width and height
                        {
                            var mp = AMouse.XY;
                            rect = new RECT(mp.x - 15, mp.y - 15, SavedFloatingBounds.Width, SavedFloatingBounds.Height);
                        }
                        else
                        {
                            rect = SavedFloatingBounds;
                        }
                        rect.EnsureInScreen();
                    }
                    else if (this.ParentSplit != null)
                    {
                        rect = this.RectangleInScreen;
                        AWnd.More.WindowRectFromClientRect(ref rect, WS.POPUP | WS.THICKFRAME, WS2.TOOLWINDOW);
                    }
                    else                         //new panel, empty bounds
                    {
                        var mp = AMouse.XY;
                        rect = new RECT(mp.x - 15, mp.y - 15, 300, 150);
                        rect.EnsureInScreen();
                    }
                }

                var panels = isTab ? gt.Items.FindAll(v => v.IsDocked) : new List <_Panel>(1)
                {
                    gp
                };

                //(isTab ? gt.ActiveItem : gp)?.Content.Hide();
                var gtp = isTab ? gt.ActiveItem : gp;

                if (gtp != null)
                {
                    if (state != _DockState.Docked && _manager.ZFocusControlOnUndockEtc != null && gtp.Content.ContainsFocus)
                    {
                        _manager.ZFocusControlOnUndockEtc.Focus();
                    }
                    gtp.Content.Hide();
                }

                Action postAction = null;

                switch (prevState)
                {
                case _DockState.Docked:
                    if (gtParent != null)
                    {
                        gtParent.OnItemUndocked(gp, out postAction);
                    }
                    else
                    {
                        this.ParentSplit.OnChildUndocked(this);
                    }

                    _manager.Invalidate(this.Bounds, true);                     //some controls don't redraw properly, eg ToolStripTextBox
                    break;

                case _DockState.Floating:
                    //case _DockState.AutoHide:
                    var f      = this.ParentControl as _Float;
                    var parent = (gtParent != null) ? gtParent.ParentControl : _manager;
                    _parentControl = parent;
                    foreach (var v in panels)
                    {
                        _ChangeParent(v, parent);
                    }
                    if (prevState == _DockState.Floating)
                    {
                        this.SavedFloatingBounds = f.Bounds;
                    }
                    f.Close();
                    break;
                }

                switch (state)
                {
                case _DockState.Docked:
                    if (gtParent != null)
                    {
                        gtParent.OnItemDocked(gp);
                    }
                    else
                    {
                        this.ParentSplit.OnChildDocked(this);
                    }
                    break;

                case _DockState.Floating:
                    var f = new _Float(_manager, this);
                    this._parentControl = f;
                    foreach (var v in panels)
                    {
                        _ChangeParent(v, f);
                    }

                    f.Bounds = rect;
                    f.Show(_manager.TopLevelControl);
                    break;

                //case _DockState.AutoHide:
                //	break;
                case _DockState.Hidden:
                    this.SavedVisibleDockState = prevState;
                    break;
                }

                if (state != _DockState.Hidden)
                {
                    (isTab ? gt.ActiveItem : gp)?.Content.Show();
                }

                postAction?.Invoke();
                //_manager.Invalidate(true);

                if (prevState != _DockState.Hidden)
                {
                    _manager._OnMouseLeave_Common(this.ParentControl);                                                //calls _UnhiliteTabButton and _HideTooltip
                }
            }
Exemple #18
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);
        }
Exemple #19
0
        /// <summary>
        /// Opens XML file and creates toolbars/menus/submenus from XML tags.
        /// </summary>
        /// <param name="xmlFile">XML file containing menus/toolbars without user customizations.</param>
        /// <param name="xmlFileCustom">XML file containing user customizations. It will be created or updated when saving customizations.</param>
        /// <param name="tsRenderer"></param>
        public void BuildAll(string xmlFile, string xmlFileCustom, ToolStripRenderer tsRenderer = null)
        {
            Debug.Assert(_xStrips == null); if (_xStrips != null)
            {
                throw new InvalidOperationException();
            }

            _xmlFileDefault = xmlFile;
            _xmlFileCustom  = xmlFileCustom;
            try { _xStrips = AExtXml.LoadElem(xmlFile); }
            catch (Exception ex) { ADialog.ShowError("Failed to load file", ex.ToString()); throw; }
            XElement xCustom = null;

            if (AFile.ExistsAsFile(_xmlFileCustom))
            {
                try { xCustom = AExtXml.LoadElem(_xmlFileCustom); }
                catch (Exception e) { AOutput.Write("Failed to load file", _xmlFileCustom, e.Message); }
            }

            Size imageScalingSize = Au.Util.ADpi.SmallIconSize_;             //if high DPI, auto scale images

            //create top-level toolstrips (menu bar and toolbars), and call _AddChildItems to add items and create drop-down menus and submenus
            _inBuildAll = true;
            bool isMenu = true;

            foreach (var xe in _xStrips.Elements().ToArray())              //info: ToArray() because _MergeCustom replaces XML elements of custom toolbars
            {
                string name = xe.Name.LocalName;
                var    x    = xe;
                if (xCustom != null)
                {
                    _MergeCustom(xCustom, ref x, name, isMenu);
                }

                ToolStrip t;
                if (isMenu)
                {
                    t = MenuBar = new Util.AMenuStrip();
                }
                else
                {
                    var cts = new Util.AToolStrip();
                    Toolbars.Add(name, cts);
                    t = cts;
                    switch (name)
                    {
                    case "Custom1": _tsCustom1 = cts; break;

                    case "Custom2": _tsCustom2 = cts; break;
                    }
                }

                t.SuspendLayout();

                t.Tag  = x;
                t.Text = t.Name = name;
                //t.AllowItemReorder = true; //don't use, it's has bugs etc, we know better how to do it
                if (tsRenderer != null)
                {
                    t.Renderer = tsRenderer;
                }
                if (isMenu)
                {
                    t.Padding = new Padding();                     //remove menu bar paddings
                }
                else
                {
                }
                if (imageScalingSize.Height != 16)
                {
                    t.ImageScalingSize = imageScalingSize;                                               //info: all submenus will inherit it from menubar
                }
                _AddChildItems(x, t, isMenu);

                t.ResumeLayout(false);
                isMenu = false;
            }
            _inBuildAll = false;
        }
Exemple #20
0
 /// <summary>
 /// 警告提示
 /// </summary>
 /// <param name="content"></param>
 public void ArtWarning(string content)
 {
     ADialog.WarningDialog(DialogTitle, content);
 }
Exemple #21
0
        public static void Dialog(object text, [CallerFilePath] string cp = null, [CallerLineNumber] int cln = 0, [CallerMemberName] string cmn = null)
        {
            string s = AOutput.ObjectToString_(text);

            ADialog.Show("Debug", s, flags: DFlags.ExpandDown, expandedText: $"{cmn} ({APath.GetFileName(cp)}:{cln})");
        }
Exemple #22
0
    static void _Main()
    {
        bool isConsole = AOutput.IsConsoleProcess;

        if (!isConsole)
        {
            AOutput.QM2.UseQM2 = true;
            AOutput.Clear();
        }

        var docfx   = @"Q:\Programs\DocFx\docfx.exe";
        var objDir  = @"Q:\Temp\Au\DocFX\obj";
        var docDir  = @"Q:\app\Au\Other\DocFX\_doc";
        var siteDir = docDir + @"\_site";
        var apiDir  = docDir + @"\api";

        //ProcessYamlFile(apiDir + @"\Au.AaaDocFX.yml", true); return;
        //ProcessHtmlFiles(siteDir, true); return;
        //ProcessToc(siteDir); return;

        //Compress(docDir); return;
        //Upload(docDir); return;
        //CompressAndUpload(docDir); return;

        foreach (var v in Process.GetProcessesByName("docfx"))
        {
            v.Kill();
        }
        if (isConsole)
        {
            int k = 0;
            foreach (var v in AWnd.FindAll(@"C:\WINDOWS\system32\cmd.exe", "ConsoleWindowClass"))
            {
                if (k++ > 0)
                {
                    v.Close();
                }
            }
        }

        AFile.Delete(siteDir);
        Directory.SetCurrentDirectory(docDir);

        var t1 = ATime.PerfMilliseconds;

        using (var fw = new FileSystemWatcher(apiDir, "*.yml")) {
            fw.Changed += (sen, e) => {
                //AOutput.Write(e.Name);
                if (e.Name.Starts("Au.", true))
                {
                    ProcessYamlFile(e.FullPath, false);
                }
            };
            fw.EnableRaisingEvents = true;
            fw.NotifyFilter        = NotifyFilters.LastWrite;

            bool serving = false;
            try {
                AExec.RunConsole(o => {
                    AOutput.Write(o);
                    if (o.Starts("Serving"))
                    {
                        throw new OperationCanceledException();
                    }
                }, docfx, $@"docfx.json --intermediateFolder ""{objDir}"" --serve");
                // --force
            }
            catch (OperationCanceledException) {
                serving = true;
            }
            //if(!serving) { ADialog.Show("error?"); return; } //need if this process is not hosted
            if (!serving)
            {
                return;
            }
        }

        var t2 = ATime.PerfMilliseconds;

        ProcessHtmlFiles(siteDir, false);

        var t3 = ATime.PerfMilliseconds; AOutput.Write("speed (s):", (t2 - t1) / 1000, (t3 - t2) / 1000);

        //AWnd.Find("* Chrome").Activate();
        //AKeys.Key("F5");

        1.s();
        if (1 == ADialog.Show("Upload?", null, "1 Yes|2 No" /*, secondsTimeout: 5*/))
        {
            CompressAndUpload(docDir);
        }

        //Delete obj folder if big. Each time it grows by 10 MB, and after a day or two can be > 1 GB. After deleting builds slower by ~50%.
        if (AFile.More.CalculateDirectorySize(objDir) / 1024 / 1024 > 500)
        {
            AOutput.Write("Deleting obj folder."); AFile.Delete(objDir);
        }
        //info: if DocFX starts throwing stack overflow exception, delete the obj folder manually. It is likely to happen after many refactorings in the project.
    }
Exemple #23
0
 /// <summary>
 /// 错误提示
 /// </summary>
 /// <param name="content"></param>
 public void ArtError(string content)
 {
     ADialog.ErrorDialog(DialogTitle, content);
 }
Exemple #24
0
 /// <summary>
 /// 成功提示
 /// </summary>
 /// <param name="content"></param>
 public void ArtSuccess(string content)
 {
     ADialog.SuccessDialog(DialogTitle, content);
 }
Exemple #25
0
            /// <summary>
            /// Starts or stops capturing.
            /// Does nothing if already in that state.
            /// </summary>
            public void StartStop(bool start)
            {
                if (start == Capturing)
                {
                    return;
                }
                var wForm = (AWnd)_form;

                if (start)
                {
                    //let other forms stop capturing
                    wForm.Prop.Set(c_propName, 1);
                    AWnd.Find(null, "WindowsForms*", also: o => {
                        if (o != wForm && o.Prop[c_propName] == 1)
                        {
                            o.Send(c_stopMessage);
                        }
                        return(false);
                    });

                    if (!Api.RegisterHotKey(wForm, 1, 0, KKey.F3))
                    {
                        ADialog.ShowError("Failed to register hotkey F3", owner: _form);
                        return;
                    }
                    Capturing = true;

                    //set timer that shows AO rect
                    if (_timer == null)
                    {
                        _osr   = TUtil.CreateOsdRect();
                        _timer = new ATimer(t => {
                            //Don't capture too frequently.
                            //	Eg if the callback is very slow. Or if multiple timer messages are received without time interval (possible in some conditions).
                            long t1 = ATime.PerfMilliseconds, t2 = t1 - _prevTime; _prevTime = t1; if (t2 < 100)
                            {
                                return;
                            }

                            //show rect of UI object from mouse
                            AWnd w = AWnd.FromMouse(WXYFlags.NeedWindow);
                            RECT?r = default;
                            if (!(w.Is0 || w == wForm || w.OwnerWindow == wForm))
                            {
                                r = _cbGetRect();
                            }
                            if (r.HasValue)
                            {
                                var rr = r.GetValueOrDefault();
                                rr.Inflate(2, 2);                                 //2 pixels inside, 2 outside
                                _osr.Rect = rr;
                                _osr.Show();
                            }
                            else
                            {
                                _osr.Visible = false;
                            }
                        });
                    }
                    _timer.Every(250);
                }
                else
                {
                    Capturing = false;
                    Api.UnregisterHotKey(wForm, 1);
                    wForm.Prop.Remove(c_propName);
                    _timer.Stop();
                    _osr.Hide();
                }
            }
Exemple #26
0
 /// <summary>
 /// 提示框
 /// </summary>
 /// <param name="content"></param>
 public void ArtAlert(string content)
 {
     ADialog.Alert(DialogTitle, content);
 }
Exemple #27
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);
    }
Exemple #28
0
        //Loads and parses XML. Creates the _aX lists, _firstSplit and the tree structure.
        void _LoadXmlAndCreateLayout(string xmlFileDefault, string xmlFileCustomized)
        {
            //We have 1 or 2 XML files containing panel/toolbar layout.
            //xmlFileDefault contains default XML. It eg can be in AFolders.ThisApp.
            //xmlFileCustomized contains previously saved XML (user-modified layout).
            //At first try to load xmlFileCustomized. If it does not exist or is invalid, load xmlFileDefault; or get missing data from xmlFileDefault, if possible.
            //Also loads xmlFileDefault when xmlFileCustomized XML does not match panels of new app version and cannot resolve it (eg some panels removed).
            bool   usesDefaultXML = false;
            string xmlFile = xmlFileCustomized, xmlVersion = null, outInfo = null;

            for (int i = 0; i < 2; i++)
            {
                if (i == 0)
                {
                    if (!AFile.ExistsAsFile(xmlFile))
                    {
                        continue;
                    }
                }
                else
                {
                    usesDefaultXML = true;
                    xmlFile        = xmlFileDefault;
                }

                bool fileLoaded = false;
                try {
                    var x = AExtXml.LoadElem(xmlFile);
                    fileLoaded = true;
                    if (!usesDefaultXML)
                    {
                        xmlVersion = x.Attr("version");
                    }
                    x = x.Element("split");

                    //THIS DOES THE MAIN JOB
                    _firstSplit = new _Split(this, null, x);

                    if (_aPanel.Count < _initControls.Count)                      //more panels added in this app version
                    {
                        if (usesDefaultXML)
                        {
                            throw new Exception("debug1");
                        }
                        _GetPanelXmlFromDefaultFile(xmlFileDefault);
                    }

                    break;

                    //speed: xml.Load takes 170 microseconds.
                    //tested: XML can be added to Application Settings, but var xml=Properties.Settings.Default.PanelsXML takes 61 MILLIseconds.
                }
                catch (Exception e) {
                    var sErr = $"Failed to load file '{xmlFile}'.\r\n\t{e.ToStringWithoutStack()}";
                    if (usesDefaultXML)
                    {
                        _xmlFile = null;
                        ADialog.ShowError("Cannot load panel/toolbar layout.", $"{sErr}\r\n\r\nReinstall the application.");
                        Environment.Exit(1);
                    }
                    else
                    {
                        //probably in this version there are less panels, most likely when downgraded. Or the file is corrupt.
                        if (fileLoaded && xmlVersion != _asmVersion)
                        {
                            outInfo = "Info: this application version resets the panel/toolbar layout, sorry.";
                        }
                        else
                        {
                            AWarning.Write(sErr, -1);
                        }
                    }
                    _aSplit.Clear(); _aTab.Clear(); _aPanel.Clear();
                }
            }

            //if(usesDefaultXML || xmlVersion == _asmVersion) return;
            if (outInfo != null)
            {
                AOutput.Write(outInfo);
            }
        }
Exemple #29
0
    async void _ConvertTypeLibrary(object tlDef, object button)
    {
        string comDll = null;

        switch (tlDef)
        {
        case string path:
            comDll = path;
            break;

        case _RegTypelib r:
            //can be several locales
            var aloc  = new List <string>();           //registry keys like "0" or "409"
            var aloc2 = new List <string>();           //locale names for display in the list dialog
            using (var verKey = Registry.ClassesRoot.OpenSubKey($@"TypeLib\{r.guid}\{r.version}")) {
                foreach (var s1 in verKey.GetSubKeyNames())
                {
                    int lcid = s1.ToInt(0, out int iEnd, STIFlags.IsHexWithout0x);
                    if (iEnd != s1.Length)
                    {
                        continue;                                       //"FLAGS" etc; must be hex number without 0x
                    }
                    aloc.Add(s1);
                    var s2 = "Neutral";
                    if (lcid > 0)
                    {
                        try { s2 = new CultureInfo(lcid).DisplayName; } catch { s2 = s1; }
                    }
                    aloc2.Add(s2);
                }
            }
            string locale;
            if (aloc.Count == 1)
            {
                locale = aloc[0];
            }
            else
            {
                int i = ADialog.ShowList(aloc2, "Locale", owner: this);
                if (i == 0)
                {
                    return;
                }
                locale = aloc[i - 1];
            }
            comDll = r.GetPath(locale);
            if (comDll == null || !AFile.ExistsAsFile(comDll))
            {
                ADialog.ShowError(comDll == null ? "Failed to get file path." : "File does not exist.", owner: this);
                return;
            }
            break;
        }

        await Task.Run(() => {
            this.Enabled = false;
            AOutput.Write($"Converting COM type library to .NET assembly.");
            try {
                if (_convertedDir == null)
                {
                    _convertedDir = AFolders.Workspace + @".interop\";
                    AFile.CreateDirectory(_convertedDir);
                }
                List <string> converted  = new List <string>();
                Action <string> callback = s => {
                    AOutput.Write(s);
                    if (s.Starts("Converted: "))
                    {
                        s.RegexMatch(@"""(.+?)"".$", 1, out s);
                        converted.Add(s);
                    }
                };
                int rr = AExec.RunConsole(callback, AFolders.ThisAppBS + "Au.Net45.exe", $"/typelib \"{_convertedDir}|{comDll}\"", encoding: Encoding.UTF8);
                if (rr == 0)
                {
                    foreach (var v in converted)
                    {
                        if (!_meta.com.Contains(v))
                        {
                            _meta.com.Add(v);
                        }
                    }
                    AOutput.Write(@"<>Converted and saved in <link>%AFolders.Workspace%\.interop<>.");
                    _Added(button, _meta.com);
                }
            }
            catch (Exception ex) { ADialog.ShowError("Failed to convert type library", ex.ToStringWithoutStack(), owner: this); }
            this.Enabled = true;
        });
    }
Exemple #30
0
partial class Script : AScript { [STAThread] static void Main(string[] a) => new Script(a); Script(string[] args) { //;;;

/*
The programming language is C#.

In scripts you can use classes/functions of the automation library provided by
this program, as well as of .NET Core and everything that can be used in C#.
Also you can create and use new functions, classes, libraries and .exe programs.

Script properties are saved in /*/ /*/ comments at the very start of script.
You can change them in the Properties dialog.

Like all C# programs, a script starts with standard code: using directives,
class and function Main where the program starts. Click the small [+] box at
the top-left to see and edit that code when need. The //. and //; are used to
fold (hide) code.

To avoid 'static' everywhere, function Main creates a class instance. Your script
code is in the constructor function. The function and the class end with } and }.

To run a script, you can click the ► Run button on the toolbar, or use command line,
or call ATask.Run from another scrit, or in Options set to run at startup.

Triggers such as hotkeys, autotext, mouse and window are used to execute functions
in a running script. Also you can create custom toolbars and menus. To start
using them: menu File -> New -> Examples -> @Triggers and toolbars.
*/

//Examples of automation functions.

AOutput.Write("Main script code.");

ADialog.Show("Message box.");

AExec.Run(AFolders.System + "notepad.exe");
var w = AWnd.Wait(0, true, "*- Notepad");
AKeys.Key("F5 Enter*2");
AKeys.Text(w.Name);
2.s();
w.Close();
var w2 = AWnd.Wait(-3, true, "Notepad", "#32770");
if(!w2.Is0) {
	500.ms();
	var c = +w2.Child(null, "Button", skip: 1); // "Don't Save"
	AMouse.Click(c);
	500.ms();
}

//Examples of .NET functions.

string s = "Example";
var b = new System.Text.StringBuilder();
for(int i = 0; i < s.Length; i++) {
	b.Append(s[i]).AppendLine();
}
MessageBox.Show(b.ToString());

//Example of your function and how functions can share variables.

_sharedVariable = 1;
FunctionExample("Example");
AOutput.Write(_sharedVariable);

} //end of main function