示例#1
0
        public static void OnCurrentFileChanged()
        {
            string file     = Npp.Editor.GetCurrentFilePath();
            var    document = Npp.GetCurrentDocument();

            string dbg = CSScriptHelper.GetDbgInfoFile(file);

            if (File.Exists(dbg))
            {
                PlaceBreakPointsForCurrentTab();
            }

            if (!IsRunning)
            {
                OnNextFileOpenComplete = null;
                document.ClearIndicator(INDICATOR_DEBUGSTEP, 0, -1); //clear all document
            }
            else
            {
                if (OnNextFileOpenComplete != null)
                {
                    OnNextFileOpenComplete();
                    OnNextFileOpenComplete = null;
                }
            }

            if (OnBreakpointChanged != null)
            {
                OnBreakpointChanged();
            }
        }
示例#2
0
        private void ConfigForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            panel.OnClosing();

            data.CheckUpdatesOnStartup  = checkUpdates.Checked;
            data.UseEmbeddedEngine      = embeddedEngine.Checked;
            data.RestorePanelsAtStartup = restorePanels.Checked;
            data.ScriptsDir             = scriptsDir.Text;
            //data.UseRoslynProvider = useCS6.Checked;
            //all Roslyn individual config values are merged into RoslynIntellisense;
            data.UseRoslynProvider = CSScriptIntellisense.Config.Instance.RoslynIntellisense;
            data.VbSupportEnabled  = CSScriptIntellisense.Config.Instance.VbSupportEnabled;

            if (customEngine.Checked)
            {
                data.UseCustomEngine = customEngineLocation.Text;
            }
            else
            {
                data.UseCustomEngine = "";
                CSScriptHelper.SynchAutoclssDecorationSettings(useCS6.Checked);
            }

            Config.Instance.Save();
        }
示例#3
0
        static public void SaveBreakPointsFor(string file)
        {
            string expectedkeyPrefix = file + "|";

            string[] fileBreakpoints = breakpoints.Keys.Where(x => x.StartsWith(expectedkeyPrefix, StringComparison.OrdinalIgnoreCase)).ToArray();

            if (fileBreakpoints.Any())
            {
                try
                {
                    string   dbg    = CSScriptHelper.GetDbgInfoFile(file, true);
                    string[] header = new[] { "#script: " + file };
                    File.WriteAllLines(dbg, header.Concat(fileBreakpoints).ToArray());
                }
                catch { }
            }
            else
            {
                string dbg = CSScriptHelper.GetDbgInfoFile(file);
                if (File.Exists(dbg))
                {
                    try
                    {
                        File.Delete(dbg);
                    }
                    catch { }
                }
            }
        }
示例#4
0
        static public void RemoveAllBreakpoints()
        {
            var document = Npp.GetCurrentDocument();

            foreach (var key in breakpoints.Keys)
            {
                document.DeleteMarker(breakpoints[key]);
                if (IsRunning)
                {
                    DebuggerServer.RemoveBreakpoint(key);
                }
            }
            breakpoints.Clear();

            foreach (string file in Npp.Editor.GetOpenFilesSafe())
            {
                string dbgInfo = CSScriptHelper.GetDbgInfoFile(file, false);
                if (File.Exists(dbgInfo))
                {
                    File.Delete(dbgInfo);
                }
            }

            if (OnBreakpointChanged != null)
            {
                OnBreakpointChanged();
            }
        }
示例#5
0
 public static void LoadRoslynResources()
 {
     Task.Factory.StartNew(() =>
     {
         //must be a separate method to allow assembly probing
         InitSyntaxer(pluginDir);
         CSScriptHelper.InitRoslyn();
     });
 }
示例#6
0
        static public void OnCurrentFileChanged()
        {
            if (CodeMapPanel != null)
            {
                CodeMapPanel.RefreshContent();
            }

            if (Npp.Editor.IsCurrentDocScriptFile() && Config.Instance.UseRoslynProvider && Config.Instance.StartRoslynServerAtNppStartup)
            {
                CSScriptHelper.InitRoslyn();
            }
        }
示例#7
0
        public void Build()
        {
            lock (this)
            {
                if (currentScript == null)
                {
                    loadBtn.PerformClick();
                }

                if (currentScript == null)
                {
                    MessageBox.Show("Please load some script file first.", "CS-Script");
                }
                else
                {
                    OutputPanel outputPanel = Plugin.ShowOutputPanel();

                    outputPanel.ShowBuildOutput();
                    outputPanel.BuildOutput.Clear();
                    outputPanel.BuildOutput.WriteLine("------ Build started: Script: " + Path.GetFileNameWithoutExtension(currentScript) + " ------");

                    try
                    {
                        if (!CurrentDocumentBelongsToProject())
                        {
                            EditItem(currentScript);
                        }

                        npp.SaveDocuments(GetProjectDocuments());

                        CSScriptHelper.Build(currentScript,
                                             line => outputPanel.BuildOutput.WriteLine(line));

                        outputPanel.BuildOutput.WriteLine(null)
                        .WriteLine("========== Build: succeeded ==========")
                        .SetCaretAtStart();
                    }
                    catch (Exception ex)
                    {
                        outputPanel.ShowBuildOutput()
                        .WriteLine(null)
                        .WriteLine(ex.Message)
                        .WriteLine("========== Build: Failed ==========")
                        .SetCaretAtStart();
                    }
                }
            }
        }
示例#8
0
        void CheckForUpdates()
        {
            Distro distro = CSScriptHelper.GetLatestAvailableVersion();

            Invoke((Action) delegate
            {
                SetUpdateStatus();
                Cursor = Cursors.Default;
            });

            if (distro == null)
            {
                MessageBox.Show("Cannot check for updates. The latest release Web page will be opened instead.", "CS-Script");
                try
                {
                    Process.Start(Plugin.HomeUrl);
                }
                catch { }
            }
            else
            {
                var latestVersion = new Version(distro.Version);
                var nppVersion    = Assembly.GetExecutingAssembly().GetName().Version;

                if (nppVersion == latestVersion)
                {
                    MessageBox.Show("You are already running the latest version - v" + distro.Version, "CS-Script");
                }
                else if (nppVersion > latestVersion)
                {
                    MessageBox.Show("Wow... your version is even newer than the latest one - v" + distro.Version + ".", "CS-Script");
                }
                else if (nppVersion < latestVersion)
                {
                    PostCloseAction = //Task.Factory.StartNew(
                                      () =>
                    {
                        using (var dialog = new UpdateOptionsPanel(distro))
                            dialog.ShowModal();
                    };    //);

                    Invoke((Action) delegate
                    {
                        Close();
                    });
                }
            }
        }
示例#9
0
        private void ConfigForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            panel.OnClosing();

            data.CheckUpdatesOnStartup  = checkUpdates.Checked;
            data.UseEmbeddedEngine      = embeddedEngine.Checked;
            data.RestorePanelsAtStartup = restorePanels.Checked;
            data.ScriptsDir             = scriptsDir.Text;
            //data.UseRoslynProvider = useCS6.Checked;
            //all Roslyn individual config values are merged into RoslynIntellisense;
            data.UseRoslynProvider = CSScriptIntellisense.Config.Instance.RoslynIntellisense;
            data.VbSupportEnabled  = CSScriptIntellisense.Config.Instance.VbSupportEnabled;

            if (customEngine.Checked)
            {
                data.UseCustomEngine = customEngineLocation.Text;
            }
            else
            {
                data.UseCustomEngine = "";
                CSScriptHelper.SynchAutoclssDecorationSettings(useCS6.Checked);
            }

            data.CustomSyntaxer    = customSyntaxer.Checked;
            data.CustomSyntaxerExe = customSyntaxerExe.Text;
            if (int.TryParse(syntaxerPort.Text, out int port))
            {
                data.SyntaxerPort = port;
            }

            Bootstrapper.DeploySyntaxer();
            CSScriptIntellisense.Syntaxer.RestartServer();

            if (this.useCustomLauncher.Checked)
            {
                data.UseCustomLauncher = useCustomLauncherCmd.Text;
            }
            else
            {
                data.UseCustomLauncher = "";
            }

            if (!skipSavingConfig)
            {
                Config.Instance.Save();
            }
        }
示例#10
0
        static void CheckForUpdates()
        {
            Thread.Sleep(2000); //let Notepad++ to complete all initialization

            Distro distro = CSScriptHelper.GetLatestAvailableVersion();

            if (distro != null && distro.Version != Config.Instance.SkipUpdateVersion)
            {
                var latestVersion = new Version(distro.Version);
                var nppVersion    = Assembly.GetExecutingAssembly().GetName().Version;

                if (nppVersion < latestVersion)
                {
                    using (var dialog = new UpdateOptionsPanel(distro))
                        dialog.ShowDialog();
                }
            }
        }
示例#11
0
        public void Debug(bool breakOnFirstStep)
        {
            if (currentScript == null || (Config.Instance.ReloadActiveScriptOnRun && currentScript != Npp.Editor.GetCurrentFilePath()))
            {
                loadBtn.PerformClick();
            }

            if (currentScript == null)
            {
                MessageBox.Show("Please load some script file first.", "CS-Script");
            }
            else
            {
                try
                {
                    if (!CurrentDocumentBelongsToProject())
                    {
                        EditItem(currentScript);
                    }

                    npp.SaveDocuments(GetProjectDocuments());

                    try
                    {
                        CSScriptHelper.Debug(currentScript);
                    }
                    catch (Exception e)
                    {
                        Plugin.ShowOutputPanel()
                        .ShowBuildOutput()
                        .WriteLine(e.Message)
                        .SetCaretAtStart();
                    }
                }
                catch (Exception ex)
                {
                    Plugin.ShowOutputPanel()
                    .ShowBuildOutput()
                    .WriteLine(ex.Message)
                    .SetCaretAtStart();
                }
            }
        }
示例#12
0
        public void OpenInVS()
        {
            Cursor = Cursors.WaitCursor;

            PluginBase.Editor.SaveCurrentFile();

            try
            {
                var currFile = Npp.Editor.GetCurrentFilePath();

                CSScriptHelper.OpenAsVSProjectFor(currentScript ?? currFile);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            Cursor = Cursors.Default;
        }
示例#13
0
        void deployBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (currentScript == null)
                {
                    LoadCurrentDoc();
                }

                if (currentScript != null) //may not necessarily be loaded successfully

                {
                    using (var dialog = new DeploymentInput())
                        if (DialogResult.OK == dialog.ShowModal())
                        {
                            EditItem(currentScript);

                            npp.SaveDocuments(GetProjectDocuments());

                            string selectedTargetVersion = dialog.SelectedVersion.Version;
                            string path = CSScriptHelper.Isolate(currentScript, dialog.AsScript, selectedTargetVersion, dialog.AsWindowApp, dialog.AsDll);

                            if (path != null)
                            {
                                if (!CSScriptHelper.IsUsingCSScriptCore)
                                {
                                    string pluginClrVersion = "v" + Environment.Version.ToString();

                                    if (dialog.AsScript && !pluginClrVersion.StartsWith(selectedTargetVersion)) //selectedTargetVersion may not include the build number
                                    {
                                        MessageBox.Show("Distribution package targets CLR version, which is different from the default version.\r\nPlease verify that the script is compatible with the selected CLR version.", "CS-Script");
                                    }
                                }
                                Process.Start("explorer.exe", path);
                            }
                        }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "CS-Script");
            }
        }
示例#14
0
        void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string file = CSScriptHelper.GetProjectTemplate();

            Task.Factory.StartNew(() =>
            {
                try
                {
                    Thread.Sleep(500);
                    Process.Start(file);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: \n" + ex.ToString(), "Notepad++");
                }
            });

            Close();
        }
示例#15
0
 public void OpenInVS()
 {
     Cursor = Cursors.WaitCursor;
     if (currentScript == null)
     {
         MessageBox.Show("Please load some script file first.", "CS-Script");
     }
     else
     {
         Win32.SendMessage(Npp.NppHandle, NppMsg.NPPM_SAVECURRENTFILE, 0, 0);
         try
         {
             CSScriptHelper.OpenAsVSProjectFor(currentScript);
         }
         catch (Exception e)
         {
             MessageBox.Show(e.Message);
         }
     }
     Cursor = Cursors.Default;
 }
示例#16
0
        public void OpenInVS()
        {
            Cursor = Cursors.WaitCursor;
            if (currentScript == null)
            {
                MessageBox.Show("Please load some script file first.", "CS-Script");
            }
            else
            {
                PluginBase.Editor.SaveCurrentFile();

                try
                {
                    CSScriptHelper.OpenAsVSProjectFor(currentScript);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
            Cursor = Cursors.Default;
        }
示例#17
0
        static public void LoadBreakPointsFor(string file)
        {
            string expectedkeyPrefix = file + "|";

            string[] fileBreakpoints = breakpoints.Keys.Where(x => x.StartsWith(expectedkeyPrefix, StringComparison.OrdinalIgnoreCase)).ToArray();

            foreach (var key in fileBreakpoints)
            {
                breakpoints.Remove(key); //clear old if any
            }
            try
            {
                string dbg = CSScriptHelper.GetDbgInfoFile(file);
                if (File.Exists(dbg))
                {
                    string[] lines = File.ReadAllLines(dbg);
                    foreach (var key in lines.Skip(1))
                    {
                        breakpoints.Add(key, IntPtr.Zero);
                    }
                }
            }
            catch { }
        }
示例#18
0
        void deployBtn_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            try
            {
                if (currentScript == null)
                {
                    LoadCurrentDoc();
                }

                if (currentScript != null) //may not necessarily be loaded successfully

                {
                    using (var dialog = new DeploymentInput())
                        if (DialogResult.OK == dialog.ShowModal())
                        {
                            EditItem(currentScript);

                            npp.SaveDocuments(GetProjectDocuments());

                            var result = CSScriptHelper.Isolate(currentScript, dialog.AsScript, dialog.AsWindowApp, dialog.AsDll);
                            if (result != null)
                            {
                                Process.Start("explorer.exe", $"\"{result}\"");
                            }
                        }
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show(ex.ToString(), "CS-Script");
            }
            Cursor.Current = Cursors.Default;
        }
示例#19
0
 private void button1_Click(object sender, EventArgs e)
 {
     CSScriptHelper.LoadRoslyn();
 }
示例#20
0
        private static void HandleNotification(string notification)
        {
            //process=>7924:STARTED
            //source=>c:\Users\osh\Documents\Visual Studio 2012\Projects\ConsoleApplication12\ConsoleApplication12\Program.cs|12:9|12:10

            string message = notification;

            Debug.WriteLine("Received: " + message);

            Task.Factory.StartNew(() =>
            {
                try
                {
                    if (OnNotification != null)
                    {
                        OnNotification(message);
                    }
                }
                catch { }
            });

            HandleErrors(() =>
            {
                if (message.StartsWith(NppCategory.Process))
                {
                    ClearDebuggingMarkers();

                    if (message.EndsWith(":STARTED"))
                    {
                        stepsCount     = 0;
                        DecorationInfo = CSScriptHelper.GetDecorationInfo(Debugger.ScriptFile);

                        foreach (string info in breakpoints.Keys)
                        {
                            DebuggerServer.AddBreakpoint(TranslateSourceBreakpoint(info));
                        }

                        if (Debugger.EntryBreakpointFile != null)
                        {
                            //line num is 0; debugger is smart enough to move the breakpoint to the very next appropriate line
                            string key = BuildBreakpointKey(Debugger.EntryBreakpointFile, 0);

                            if (DecorationInfo != null && DecorationInfo.AutoGenFile == Debugger.EntryBreakpointFile)
                            {
                                key = BuildBreakpointKey(DecorationInfo.AutoGenFile, DecorationInfo.InjectedLineNumber + 1);
                            }

                            DebuggerServer.AddBreakpoint(key);
                        }

                        //By default Mdbg always enters break mode at start/attach completed
                        //however we should only resume after mdbg finished the initialization (first break is reported).
                        resumeOnNextBreakPoint = true;
                    }
                    else if (message.EndsWith(":ENDED"))
                    {
                        NotifyOnDebugStepChanges();
                    }
                }
                else if (message.StartsWith(NppCategory.BreakEntered))
                {
                    if (resumeOnNextBreakPoint)
                    {
                        resumeOnNextBreakPoint = false;
                        Go();
                    }
                }
                else if (message.StartsWith(NppCategory.Exception))
                {
                    OnException(message.Substring(NppCategory.Exception.Length));
                }
                else if (message.StartsWith(NppCategory.DbgCommandError))
                {
                    OnDebuggerFailure(message.Substring(NppCategory.DbgCommandError.Length));
                }
                else if (message.StartsWith(NppCategory.Invoke))
                {
                    OnInvokeComplete(message.Substring(NppCategory.Invoke.Length));
                }
                else if (message.StartsWith(NppCategory.Watch))
                {
                    OnWatchData(message.Substring(NppCategory.Watch.Length));
                }
                else if (message.StartsWith(NppCategory.Trace))
                {
                    Plugin.OutputPanel.DebugOutput.Write(message.Substring(NppCategory.Trace.Length));
                }
                else if (message.StartsWith(NppCategory.State))
                {
                    if (message.Substring(NppCategory.State.Length) == "NOSOURCEBREAK")
                    {
                        Task.Factory.StartNew(() =>
                        {
                            //The break can be caused by 'Debugger.Break();'
                            //Trigger user break to force source code entry if available as a small usability improvement.
                            if ((Environment.TickCount - lastNOSOURCEBREAK) > 1500) //Just in case, prevent infinite loop.
                            {
                                lastNOSOURCEBREAK = Environment.TickCount;
                                Thread.Sleep(200); //even 80 is enough
                                Debugger.Break();
                            }
                        });
                    }
                }
                else if (message.StartsWith(NppCategory.CallStack))
                {
                    Plugin.GetDebugPanel().UpdateCallstack(message.Substring(NppCategory.CallStack.Length));
                }
                else if (message.StartsWith(NppCategory.Threads))
                {
                    Plugin.GetDebugPanel().UpdateThreads(message.Substring(NppCategory.Threads.Length));
                }
                else if (message.StartsWith(NppCategory.Modules))
                {
                    Plugin.GetDebugPanel().UpdateModules(message.Substring(NppCategory.Modules.Length));
                }
                else if (message.StartsWith(NppCategory.Locals))
                {
                    Plugin.GetDebugPanel().UpdateLocals(message.Substring(NppCategory.Locals.Length));
                    NotifyOnDebugStepChanges(); // !!! remove
                }
                else if (message.StartsWith(NppCategory.SourceCode))
                {
                    stepsCount++;

                    var sourceLocation = message.Substring(NppCategory.SourceCode.Length);

                    if (stepsCount == 1 && sourceLocation.Contains("css_dbg.cs|"))
                    {
                        //ignore the first source code break as it is inside of the CSScript.Npp debug launcher
                    }
                    else
                    {
                        NavigateToFileLocation(sourceLocation);
                    }
                }
            });
        }
示例#21
0
        public void Debug(bool breakOnFirstStep)
        {
            Plugin.InitDebugPanel();

            if (currentScript == null)
            {
                loadBtn.PerformClick();
            }

            if (currentScript == null)
            {
                MessageBox.Show("Please load some script file first.", "CS-Script");
            }
            else
            {
                Win32.SendMessage(Npp.NppHandle, NppMsg.NPPM_SAVECURRENTFILE, 0, 0);

                bool canCompile = CSScriptHelper.Verify(currentScript);

                if (!canCompile)
                {
                    Build();
                }
                else
                {
                    Plugin.ShowOutputPanel().ShowDebugOutput().Clear();

                    Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            string entryFile    = CSScriptHelper.GetEntryFileName(currentScript);
                            Debugger.ScriptFile = currentScript;

                            bool isX86           = false;
                            bool isSurrogateHost = CSScriptHelper.IsSurrogateHosted(currentScript, ref isX86);
                            if (isSurrogateHost)
                            {
                                var scriptAsm     = CSScript.GetCachedScriptPath(currentScript);
                                var debuggingHost = scriptAsm + ".host.exe";
                                Debugger.Start(debuggingHost, scriptAsm, isX86 ? Debugger.CpuType.x86 : Debugger.CpuType.x64);
                            }
                            else
                            {
                                string targetType    = Debugger.DebugAsConsole ? CSScriptHelper.cscs_exe : CSScriptHelper.csws_exe;
                                string debuggingHost = Path.Combine(Plugin.PluginDir, "css_dbg.exe");
                                Debugger.Start(debuggingHost, string.Format("\"{0}\" /d /l {2} \"{1}\"", targetType, currentScript, CSScriptHelper.GenerateDefaultArgs(currentScript)), Debugger.CpuType.Any);
                            }

                            if (breakOnFirstStep)
                            {
                                Debugger.EntryBreakpointFile = entryFile ?? currentScript;
                            }

                            RefreshControls();
                        }
                        catch (Exception e)
                        {
                            Plugin.OutputPanel.DebugOutput.WriteLine(e.Message);
                        }
                    });
                }
            }
        }
示例#22
0
        public void LoadScript(string scriptFile)
        {
            if (!string.IsNullOrWhiteSpace(scriptFile) && File.Exists(scriptFile))
            {
                if (!scriptFile.IsScriptFile())
                {
                    MessageBox.Show("The file type '" + Path.GetExtension(scriptFile) + "' is not supported.", "CS-Script");
                }
                else
                {
                    try
                    {
                        Npp.Editor.OpenFile(scriptFile, true);

                        Project project = CSScriptHelper.GenerateProjectFor(scriptFile);

                        /*
                         * root
                         * references
                         * assembly_1
                         * assembly_2
                         * assembly_n
                         * script_1
                         * script_2
                         * script_N
                         */

                        treeView1.BeginUpdate();
                        treeView1.Nodes.Clear();

                        TreeNode root       = treeView1.Nodes.Add("Script '" + Path.GetFileNameWithoutExtension(scriptFile) + "'");
                        TreeNode references = root.Nodes.Add("References");

                        root.SelectedImageIndex       =
                            root.ImageIndex           = scriptFile.IsVbFile() ? scriptVbImage : scriptImage;
                        references.SelectedImageIndex =
                            references.ImageIndex     = assemblyImage;

                        root.ContextMenuStrip = solutionContextMenu;
                        root.ToolTipText      = "Script: " + scriptFile;

                        Action <TreeNode, string[]> populateNode =
                            (node, files) =>
                        {
                            foreach (var file in files)
                            {
                                int imageIndex = includeImage;
                                var info       = new ProjectItem(file)
                                {
                                    IsPrimary = (file == project.PrimaryScript)
                                };
                                if (info.IsPrimary)
                                {
                                    imageIndex = file.IsVbFile() ? scriptVbImage : scriptImage;
                                }
                                if (info.IsAssembly)
                                {
                                    imageIndex = assemblyImage;
                                }
                                node.Nodes.Add(new TreeNode(info.Name)
                                {
                                    ImageIndex = imageIndex, SelectedImageIndex = imageIndex, Tag = info, ToolTipText = file, ContextMenuStrip = itemContextMenu
                                });
                            }
                            ;
                        };

                        populateNode(references, project.Assemblies);
                        populateNode(root, project.SourceFiles);
                        root.Expand();

                        treeView1.EndUpdate();

                        currentScript = scriptFile;

                        var history = Config.Instance.ScriptHistory.Split('|').ToList();
                        history.Remove(scriptFile);
                        history.Insert(0, scriptFile);

                        Config.Instance.ScriptHistory = string.Join("|", history.Take(Config.Instance.SciptHistoryMaxCount).ToArray());
                        Config.Instance.Save();
                        ReloadScriptHistory();
                    }
                    catch (Exception e)
                    {
                        //it is not a major use-case so doesn't matter why we failed
                        MessageBox.Show("Cannot load script.\nError: " + e.Message, "CS-Script");
                        e.LogAsError();
                    }
                }
            }
            else
            {
                MessageBox.Show("Script '" + scriptFile + "' does not exist.", "CS-Script");
            }
            RefreshControls();
        }
示例#23
0
        public void RefreshProjectStructure()
        {
            this.InUiThread(() =>
            {
                if (Npp.Editor.GetCurrentFilePath() == currentScript)
                {
                    try
                    {
                        Project project = CSScriptHelper.GenerateProjectFor(currentScript);

                        treeView1.BeginUpdate();

                        /*
                         * root
                         * references
                         *  assembly_1
                         *  assembly_2
                         *  assembly_n
                         * script_1
                         * script_2
                         * script_N
                         */

                        TreeNode root       = treeView1.Nodes[0];
                        TreeNode references = root.Nodes[0];

                        Action <TreeNode, string[]> updateNode =
                            (node, files) =>
                        {
                            string[] currentFiles = node.Nodes
                                                    .Cast <TreeNode>()
                                                    .Where(x => x.Tag is ProjectItem)
                                                    .Select(x => (x.Tag as ProjectItem).File)
                                                    .ToArray();

                            string[] newItems = files.Except(currentFiles).ToArray();

                            var orphantItems = node.Nodes
                                               .Cast <TreeNode>()
                                               .Where(x => x.Tag is ProjectItem)
                                               .Where(x => !files.Contains((x.Tag as ProjectItem).File))
                                               .Where(x => x != root && x != references)
                                               .ToArray();

                            orphantItems.ForEach(x => node.Nodes.Remove(x));
                            newItems.ForEach(file =>
                            {
                                int imageIndex = includeImage;
                                var info       = new ProjectItem(file)
                                {
                                    IsPrimary = (file == project.PrimaryScript)
                                };
                                if (info.IsAssembly)
                                {
                                    imageIndex = assemblyImage;
                                }
                                node.Nodes.Add(new TreeNode(info.Name)
                                {
                                    ImageIndex = imageIndex, SelectedImageIndex = imageIndex, Tag = info, ToolTipText = file, ContextMenuStrip = itemContextMenu
                                });
                            });
                        };

                        updateNode(references, project.Assemblies);
                        updateNode(root, project.SourceFiles);
                        root.Expand();

                        treeView1.EndUpdate();
                    }
                    catch (Exception e)
                    {
                        e.LogAsError();
                    }
                }
            });
        }
示例#24
0
        void Run(bool asExternal)
        {
            if (currentScript == null || (Config.Instance.ReloadActiveScriptOnRun && currentScript != Npp.Editor.GetCurrentFilePath()))
            {
                loadBtn.PerformClick();
            }

            if (currentScript == null)
            {
                MessageBox.Show("Please load some script file first.", "CS-Script");
            }
            else
            {
                try
                {
                    if (!CurrentDocumentBelongsToProject())
                    {
                        EditItem(currentScript);
                    }

                    npp.SaveDocuments(GetProjectDocuments());

                    if (asExternal)
                    {
                        try
                        {
                            CSScriptHelper.ExecuteAsynch(currentScript);
                        }
                        catch (Exception e)
                        {
                            Plugin.ShowOutputPanel()
                            .ShowBuildOutput()
                            .WriteLine(e.Message)
                            .SetCaretAtStart();
                        }
                    }
                    else
                    {
                        OutputPanel outputPanel = Plugin.ShowOutputPanel();

                        if (Config.Instance.StartDebugMonitorOnScriptExecution)
                        {
                            outputPanel.AttachDebgMonitor();
                        }

                        outputPanel.ClearAllDefaultOutputs();

                        Task.Factory.StartNew(() =>
                        {
                            try
                            {
                                if (Config.Instance.InterceptConsole)
                                {
                                    CSScriptHelper.ExecuteScript(currentScript, OnRunStart, OnConsoleObjectOut);
                                }
                                else
                                {
                                    CSScriptHelper.ExecuteScript(currentScript, OnRunStart);
                                }
                            }
                            catch (Exception e)
                            {
                                this.InUiThread(() =>
                                {
                                    outputPanel.ShowBuildOutput()
                                    .WriteLine(e.Message)
                                    .SetCaretAtStart();
                                });
                            }
                            finally
                            {
                                this.InUiThread(() =>
                                {
                                    Plugin.RunningScript = null;
                                    RefreshControls();
                                    Npp.GetCurrentDocument().GrabFocus();
                                });
                            }
                        });
                    }
                }
                catch (Exception ex)
                {
                    Plugin.ShowOutputPanel()
                    .ShowBuildOutput()
                    .WriteLine(ex.Message)
                    .SetCaretAtStart();
                }
            }
        }