Example #1
0
        public static Task <IEnumerable <CodeAction> > GetValidActions(Document doc, TextLocation loc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var    editor        = doc.Editor;
            string disabledNodes = editor != null?PropertyService.Get("ContextActions." + editor.MimeType, "") ?? "" : "";

            return(Task.Factory.StartNew(delegate {
                var result = new List <CodeAction> ();
                var timer = InstrumentationService.CreateTimerCounter("Source analysis background task", "Source analysis");
                timer.BeginTiming();
                try {
                    var parsedDocument = doc.ParsedDocument;
                    if (editor != null && parsedDocument != null && parsedDocument.CreateRefactoringContext != null)
                    {
                        var ctx = parsedDocument.CreateRefactoringContext(doc, cancellationToken);
                        if (ctx != null)
                        {
                            foreach (var provider in contextActions.Where(fix => disabledNodes.IndexOf(fix.IdString, StringComparison.Ordinal) < 0))
                            {
                                try {
                                    result.AddRange(provider.GetActions(doc, ctx, loc, cancellationToken));
                                } catch (Exception ex) {
                                    LoggingService.LogError("Error in context action provider " + provider.Title, ex);
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    LoggingService.LogError("Error in analysis service", ex);
                } finally {
                    timer.EndTiming();
                }
                return (IEnumerable <CodeAction>)result;
            }, cancellationToken));
        }
        public NRefactoryIssueProvider(ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssueProvider issue, IssueDescriptionAttribute attr)
        {
            issueProvider    = issue;
            this.attr        = attr;
            providerIdString = issueProvider.GetType().FullName;
            Category         = GettextCatalog.GetString(attr.Category ?? "");
            Title            = GettextCatalog.GetString(attr.Title ?? "");
            Description      = GettextCatalog.GetString(attr.Description ?? "");
            DefaultSeverity  = attr.Severity;
            SetMimeType("text/x-csharp");
            subIssues = issueProvider.SubIssues.Select(subIssue => (BaseCodeIssueProvider) new BaseNRefactoryIssueProvider(this, subIssue)).ToList();

            // Additional source of actions
            var actionProvider = attr.ActionProvider;

            if (actionProvider != null)
            {
                var actionAttr = actionProvider.GetCustomAttributes(typeof(ContextActionAttribute), false);
                if (actionAttr != null && actionAttr.Length == 1)
                {
                    boundActionProvider = (ICSharpCode.NRefactory.CSharp.Refactoring.CodeActionProvider)Activator.CreateInstance(actionProvider);
                }
            }

            counter = InstrumentationService.CreateTimerCounter(IdString, "CodeIssueProvider run times");
        }
Example #3
0
        /// <summary>
        /// Creates a singleton instance or throws if instance is already created
        /// </summary>
        public ZoneGovernorService() : base(null)
        {
            if (!AgniSystem.IsMetabase)
            {
                throw new AZGOVException(StringConsts.METABASE_NOT_AVAILABLE_ERROR.Args(GetType().FullName + ".ctor()"));
            }

            lock (s_InstanceLock)
            {
                if (s_Instance != null)
                {
                    throw new AZGOVException(StringConsts.AZGOV_INSTANCE_ALREADY_ALLOCATED_ERROR);
                }

                m_SubInstr = new InstrumentationService(this);
                m_SubInstrReductionLevels = new Dictionary <string, int>();
                m_SubInstrCallers         = new ConcurrentDictionary <string, DateTime>();

                m_SubLog = new LogService(this);

                m_SubHosts         = new Registry <Contracts.HostInfo>();
                m_DynamicHostSlots = new Registry <Contracts.DynamicHostInfo>();

                m_Locker = new Locking.Server.LockServerService(this);

                s_Instance = this;
            }
        }
Example #4
0
        public void when_latency_headers_off_then_execution_time_is_not_added_to_the_reponse_headers()
        {
            LatencyHeaderOff();

            InstrumentationService.InstrumentResponse(HttpActionExecutedContext);

            HttpActionExecutedContext.Response.Headers.Any(o => o.Key.Contains("X-ExecutionTime")).Should().BeFalse();
        }
Example #5
0
        public async void when_instrumenting_response_latency_message_should_be_sent()
        {
            LatencyHeaderOff();

            InstrumentationService.InstrumentResponse(HttpActionExecutedContext);

            var result = await ListenForTwoStatsDMessages();

            result.Any(o => Regex.IsMatch(o, "^ApplicationName.requests.latency#(.*):(\\d+)|ms$")).Should().BeTrue();
        }
        public BaseNRefactoryIssueProvider(NRefactoryIssueProvider parentIssue, SubIssueAttribute subIssue)
        {
            this.parentIssue = parentIssue;
            this.subIssue    = subIssue;
            this.Title       = subIssue.Title;
            this.Description = subIssue.Description;

            DefaultSeverity = subIssue.HasOwnSeverity ? subIssue.Severity : parentIssue.DefaultSeverity;
            UpdateSeverity();

            counter = InstrumentationService.CreateTimerCounter(IdString, "CodeIssueProvider run times");
        }
        private InstrumentationService CreateInstrumentationService(params dynamic[] listeners)
        {
            dynamic service = new ExpandoObject();

            service.ExecutionListeners = new List <dynamic>(listeners);
            InstrumentationService inst = new InstrumentationService();

            inst.IsAvailable = true;
            inst.ExtractInstrumentationService = _ => new PageInstrumentationServiceAdapter(service);
            inst.CreateContext = CreateExpandoContext;
            return(inst);
        }
Example #8
0
        public async void when_action_name_is_mixed_case_then_it_will_be_changed_to_lowercase_for_the_metric_name()
        {
            LatencyHeaderOff();

            HttpActionExecutedContext.ActionContext.ActionDescriptor.As <FakeActionDescriptor>().SetActionName("AcTiOnNaMe");

            InstrumentationService.InstrumentResponse(HttpActionExecutedContext);

            var result = await ListenForTwoStatsDMessages();

            result.Any(o => Regex.IsMatch(o, "^ApplicationName.requests#(.*)action=actionname(.*):1|c$")).Should().BeTrue();
        }
Example #9
0
        public async void when_controller_name_is_mixed_case_then_it_will_be_changed_to_lowercase_for_the_metric_name()
        {
            LatencyHeaderOff();

            FakeActionDescriptor.ControllerName = "CoNtRoLlErNaMe";

            InstrumentationService.InstrumentResponse(HttpActionExecutedContext);

            var result = await ListenForTwoStatsDMessages();

            result.Any(o => Regex.IsMatch(o, "^ApplicationName.requests#(.*)controller=controllername(.*):1|c$")).Should().BeTrue();
        }
Example #10
0
        public static Task <IEnumerable <CodeAction> > GetValidActions(Document doc, TextLocation loc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var    editor        = doc.Editor;
            string disabledNodes = editor != null?PropertyService.Get("ContextActions." + editor.MimeType, "") ?? "" : "";

            return(Task.Factory.StartNew(delegate {
                var result = new List <CodeAction> ();
                var timer = InstrumentationService.CreateTimerCounter("Source analysis background task", "Source analysis");
                timer.BeginTiming();
                validActionsWatch.Restart();
                var timeTable = new Dictionary <CodeActionProvider, long> ();
                try {
                    var parsedDocument = doc.ParsedDocument;
                    if (editor != null && parsedDocument != null && parsedDocument.CreateRefactoringContext != null)
                    {
                        var ctx = parsedDocument.CreateRefactoringContext(doc, cancellationToken);
                        if (ctx != null)
                        {
                            foreach (var provider in contextActions.Where(fix =>
                                                                          fix.MimeType == editor.MimeType &&
                                                                          disabledNodes.IndexOf(fix.IdString, StringComparison.Ordinal) < 0))
                            {
                                try {
                                    actionWatch.Restart();
                                    result.AddRange(provider.GetActions(doc, ctx, loc, cancellationToken));
                                    actionWatch.Stop();
                                    timeTable[provider] = actionWatch.ElapsedMilliseconds;
                                } catch (Exception ex) {
                                    LoggingService.LogError("Error in context action provider " + provider.Title, ex);
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    LoggingService.LogError("Error in analysis service", ex);
                } finally {
                    timer.EndTiming();
                    validActionsWatch.Stop();
                    if (validActionsWatch.ElapsedMilliseconds > 1000)
                    {
                        LoggingService.LogWarning("Warning slow edit action update.");
                        foreach (var pair in timeTable)
                        {
                            if (pair.Value > 50)
                            {
                                LoggingService.LogInfo("ACTION '" + pair.Key.Title + "' took " + pair.Value + "ms");
                            }
                        }
                    }
                }
                return (IEnumerable <CodeAction>)result;
            }, cancellationToken));
        }
Example #11
0
 public NRefactoryIssueProvider(ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssueProvider issue, IssueDescriptionAttribute attr)
 {
     issueProvider    = issue;
     this.attr        = attr;
     providerIdString = issueProvider.GetType().FullName;
     Category         = GettextCatalog.GetString(attr.Category ?? "");
     Title            = GettextCatalog.GetString(attr.Title ?? "");
     Description      = GettextCatalog.GetString(attr.Description ?? "");
     DefaultSeverity  = attr.Severity;
     SetMimeType("text/x-csharp");
     subIssues = issueProvider.SubIssues.Select(subIssue => (BaseCodeIssueProvider) new BaseNRefactoryIssueProvider(this, subIssue)).ToList();
     counter   = InstrumentationService.CreateTimerCounter(IdString, "CodeIssueProvider run times");
 }
 protected internal void EndContext(TextWriter writer, string virtualPath, int startPosition, int length, bool isLiteral)
 {
     // Double check that the instrumentation service is active because WriteAttribute always calls this
     if (InstrumentationService.IsAvailable)
     {
         InstrumentationService.EndContext(Context,
                                           virtualPath,
                                           writer,
                                           startPosition,
                                           length,
                                           isLiteral);
     }
 }
        public WebPageRazorHost(string virtualPath, string physicalPath)
            : this()
        {
            if (String.IsNullOrEmpty(virtualPath))
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, "virtualPath"), "virtualPath");
            }

            VirtualPath = virtualPath;

            PhysicalPath          = physicalPath;
            DefaultClassName      = GetClassName(VirtualPath);
            CodeLanguage          = GetCodeLanguage();
            EnableInstrumentation = new InstrumentationService().IsAvailable;
        }
Example #14
0
 static void SetupInstrumentation()
 {
     InstrumentationService.Enabled = Runtime.Preferences.EnableInstrumentation;
     if (InstrumentationService.Enabled)
     {
         LoggingService.LogInfo("Instrumentation Service started");
         try {
             int port = InstrumentationService.PublishService();
             LoggingService.LogInfo("Instrumentation available at port " + port);
         } catch (Exception ex) {
             LoggingService.LogError("Instrumentation service could not be published", ex);
         }
     }
     Runtime.Preferences.EnableInstrumentation.Changed += (s, e) => InstrumentationService.Enabled = Runtime.Preferences.EnableInstrumentation;
 }
Example #15
0
 static void SetupInstrumentation()
 {
     InstrumentationService.Enabled = PropertyService.Get("MonoDevelop.EnableInstrumentation", false);
     if (InstrumentationService.Enabled)
     {
         LoggingService.LogInfo("Instrumentation Service started");
         try {
             int port = InstrumentationService.PublishService();
             LoggingService.LogInfo("Instrumentation available at port " + port);
         } catch (Exception ex) {
             LoggingService.LogError("Instrumentation service could not be published", ex);
         }
     }
     PropertyService.AddPropertyHandler("MonoDevelop.EnableInstrumentation", delegate {
         InstrumentationService.Enabled = PropertyService.Get("MonoDevelop.EnableInstrumentation", false);
     });
 }
Example #16
0
 static void UpdateInstrumentationIcon()
 {
     if (IdeApp.Preferences.EnableInstrumentation)
     {
         if (instrumentationStatusIcon == null)
         {
             instrumentationStatusIcon          = IdeApp.Workbench.StatusBar.ShowStatusIcon(ImageService.GetIcon(MonoDevelop.Ide.Gui.Stock.Information));
             instrumentationStatusIcon.ToolTip  = "Instrumentation service enabled";
             instrumentationStatusIcon.Clicked += delegate {
                 InstrumentationService.StartMonitor();
             };
         }
     }
     else if (instrumentationStatusIcon != null)
     {
         instrumentationStatusIcon.Dispose();
     }
 }
Example #17
0
 static void UpdateInstrumentationIcon()
 {
     if (IdeApp.Preferences.EnableInstrumentation)
     {
         if (instrumentationStatusIcon == null)
         {
             instrumentationStatusIcon         = IdeApp.Workbench.StatusBar.ShowStatusIcon(ImageService.GetPixbuf(Gtk.Stock.DialogInfo));
             instrumentationStatusIcon.ToolTip = "Instrumentation service enabled";
             instrumentationStatusIcon.EventBox.ButtonPressEvent += delegate {
                 InstrumentationService.StartMonitor();
             };
         }
     }
     else if (instrumentationStatusIcon != null)
     {
         instrumentationStatusIcon.Dispose();
     }
 }
        public void EndContextDelegatesToRegisteredListeners()
        {
            // Arrange
            dynamic listener1                 = CreateListener();
            dynamic listener2                 = CreateListener();
            InstrumentationService inst       = CreateInstrumentationService(listener1, listener2);
            TextWriter             mockWriter = new StringWriter();

            // Act
            inst.EndContext(null, "Foo.cshtml", mockWriter, 42, 24, isLiteral: false);

            // Assert
            Assert.Equal(1, listener1.EndContextCalls.Count);
            Assert.Equal(0, listener1.BeginContextCalls.Count);
            Assert.Equal(1, listener2.EndContextCalls.Count);
            Assert.Equal(0, listener2.BeginContextCalls.Count);

            AssertContext("Foo.cshtml", mockWriter, 42, 24, false, listener1.EndContextCalls[0]);
            AssertContext("Foo.cshtml", mockWriter, 42, 24, false, listener2.EndContextCalls[0]);
        }
Example #19
0
        public static void Main(string[] args)
        {
            Application.Init();
            if (args.Length == 0)
            {
                ShowHelp();
                return;
            }
            if (args [0] == "-c")
            {
                if (args.Length != 2)
                {
                    ShowHelp();
                    return;
                }
                service = InstrumentationService.GetRemoteService(args[1]);
                try {
                    service.GetCategories();
                } catch (Exception ex) {
                    MessageDialog md = new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, "Could not connect to instrumentation service: " + ex.Message);
                    md.Run();
                    md.Destroy();
                    return;
                }
            }
            else if (args.Length == 1)
            {
                LoadServiceData(args[0]);
            }
            else
            {
                ShowHelp();
                return;
            }

            InstrumentationViewerDialog win = new InstrumentationViewerDialog();

            win.Show();
            Application.Run();
        }
        public static void Main(string[] args)
        {
            AddinManager.Initialize();
            AddinManager.Registry.Update(null);

            try
            {
                // Triggers registration
                InstrumentationService.CreateCounter("allors");
            }
            catch {}
            finally
            {
                InstrumentationService.Enabled = false;
            }

            Application.Init();
            var win = new MainWindow(args);

            win.Show();
            Application.Run();
        }
Example #21
0
 public static void LoadServiceData(string file)
 {
     service  = InstrumentationService.LoadServiceDataFromFile(file);
     FromFile = true;
 }
Example #22
0
        int Run(MonoDevelopOptions options)
        {
            LoggingService.LogInfo("Starting {0} {1}", BrandingService.ApplicationLongName, IdeVersionInfo.MonoDevelopVersion);
            LoggingService.LogInfo("Build Information{0}{1}", Environment.NewLine, SystemInformation.GetBuildInformation());
            LoggingService.LogInfo("Running on {0}", RuntimeVersionInfo.GetRuntimeInfo());

            //ensure native libs initialized before we hit anything that p/invokes
            Platform.Initialize();
            IdeStartupTracker.StartupTracker.MarkSection("PlatformInitialization");

            GettextCatalog.Initialize();
            IdeStartupTracker.StartupTracker.MarkSection("GettextInitialization");

            LoggingService.LogInfo("Operating System: {0}", SystemInformation.GetOperatingSystemDescription());

            // The assembly resolver for MSBuild 15 assemblies needs to be defined early on.
            // Whilst Runtime.Initialize loads the MSBuild 15 assemblies from Mono this seems
            // to be too late to prevent the MEF composition and the static registrar from
            // failing to load the MonoDevelop.Ide assembly which now uses MSBuild 15 assemblies.
            ResolveMSBuildAssemblies();

            Counters.InitializationTracker = Counters.Initialization.BeginTiming();

            if (options.PerfLog)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.perf-log");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            Counters.InitializationTracker.Trace("Initializing GTK");
            if (Platform.IsWindows && !CheckWindowsGtk())
            {
                return(1);
            }
            SetupExceptionManager();

            // explicit GLib type system initialization for GLib < 2.36 before any other type system access
            GLib.GType.Init();

            var args = options.RemainingArgs.ToArray();

            IdeTheme.InitializeGtk(BrandingService.ApplicationName, ref args);

            startupInfo = new StartupInfo(options, args);
            if (startupInfo.HasFiles)
            {
                // If files are present, consider started from the commandline as being the same as file manager.
                // On macOS, we need to wait until the DidFinishLaunching notification to find out we were launched from the Finder
                IdeApp.LaunchReason = IdeApp.LaunchType.LaunchedFromFileManager;
            }
            else if (!Platform.IsMac)
            {
                IdeApp.LaunchReason = IdeApp.LaunchType.Normal;
            }

            IdeApp.Customizer = options.IdeCustomizer ?? new IdeCustomizer();
            try {
                IdeApp.Customizer.Initialize(startupInfo);
            } catch (UnauthorizedAccessException ua) {
                LoggingService.LogError("Unauthorized access: " + ua.Message);
                return(1);
            }

            try {
                GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            IdeStartupTracker.StartupTracker.MarkSection("GtkInitialization");
            LoggingService.LogInfo("Using GTK+ {0}", IdeVersionInfo.GetGtkVersion());

            // XWT initialization
            FilePath p = typeof(IdeStartup).Assembly.Location;

            Runtime.LoadAssemblyFrom(p.ParentDirectory.Combine("Xwt.Gtk.dll"));
            Xwt.Application.InitializeAsGuest(Xwt.ToolkitType.Gtk);
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarWindowBackend, GtkExtendedTitleBarWindowBackend> ();
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarDialogBackend, GtkExtendedTitleBarDialogBackend> ();
            IdeTheme.SetupXwtTheme();

            IdeStartupTracker.StartupTracker.MarkSection("XwtInitialization");

            //default to Windows IME on Windows
            if (Platform.IsWindows && GtkWorkarounds.GtkMinorVersion >= 16)
            {
                var settings = Gtk.Settings.Default;
                var val      = GtkWorkarounds.GetProperty(settings, "gtk-im-module");
                if (string.IsNullOrEmpty(val.Val as string))
                {
                    GtkWorkarounds.SetProperty(settings, "gtk-im-module", new GLib.Value("ime"));
                }
            }

            DispatchService.Initialize();

            // Set a synchronization context for the main gtk thread
            SynchronizationContext.SetSynchronizationContext(DispatchService.SynchronizationContext);
            Runtime.MainSynchronizationContext = SynchronizationContext.Current;

            IdeStartupTracker.StartupTracker.MarkSection("DispatchInitialization");

            // Initialize Roslyn's synchronization context
            RoslynServices.RoslynService.Initialize();

            IdeStartupTracker.StartupTracker.MarkSection("RoslynInitialization");

            AddinManager.AddinLoadError += OnAddinError;

            Counters.InitializationTracker.Trace("Initializing Runtime");
            Runtime.Initialize(true);

            // Register services used by the IDE

            RegisterServices();

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                foreach (var file in startupInfo.RequestedFileList)
                {
                    if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile(file.FileName))
                    {
                        options.NewWindow = true;
                        break;
                    }
                }
            }

            instanceConnection = new IdeInstanceConnection(options.IpcTcp);

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles && instanceConnection.TryConnect(startupInfo))
            {
                return(0);
            }

            IdeStartupTracker.StartupTracker.MarkSection("RuntimeInitialization");

            bool restartRequested = PropertyService.Get("MonoDevelop.Core.RestartRequested", false);

            startupInfo.Restarted = restartRequested;
            PropertyService.Set("MonoDevelop.Core.RestartRequested", false);

            Counters.InitializationTracker.Trace("Initializing theme");

            IdeTheme.SetupGtkTheme();

            IdeApp.Customizer.OnCoreInitialized();

            IdeStartupTracker.StartupTracker.MarkSection("ThemeInitialized");

            IdeApp.IsRunning = true;

            // Load the main menu before running the main loop
            var commandService = Runtime.GetService <CommandManager> ().Result;
            var desktopService = Runtime.GetService <DesktopService> ().Result;

            desktopService.SetGlobalMenu(commandService, DefaultWorkbench.MainMenuPath, DefaultWorkbench.AppMenuPath);

            // Run the main loop
            Gtk.Application.Invoke((s, e) => {
                MainLoop(options, startupInfo).Ignore();
            });
            Gtk.Application.Run();

            IdeApp.IsRunning = false;

            IdeApp.Customizer.OnIdeShutdown();

            instanceConnection.Dispose();

            lockupCheckRunning = false;
            Runtime.Shutdown();

            IdeApp.Customizer.OnCoreShutdown();

            InstrumentationService.Stop();

            MonoDevelop.Components.GtkWorkarounds.Terminate();

            return(0);
        }
Example #23
0
        internal Counter GetCounterByIDOrName(string idOrName)
        {
            Counter c = InstrumentationService.GetCounterByID(idOrName);

            return(c ?? InstrumentationService.GetCounter(idOrName));
        }
Example #24
0
        int Run(MonoDevelopOptions options)
        {
            LoggingService.LogInfo("Starting {0} {1}", BrandingService.ApplicationLongName, IdeVersionInfo.MonoDevelopVersion);
            LoggingService.LogInfo("Build Information{0}{1}", Environment.NewLine, SystemInformation.GetBuildInformation());
            LoggingService.LogInfo("Running on {0}", IdeVersionInfo.GetRuntimeInfo());

            //ensure native libs initialized before we hit anything that p/invokes
            Platform.Initialize();
            GettextCatalog.Initialize();

            LoggingService.LogInfo("Operating System: {0}", SystemInformation.GetOperatingSystemDescription());

            if (!Platform.IsWindows)
            {
                // The assembly resolver for MSBuild 15 assemblies needs to be defined early on.
                // Whilst Runtime.Initialize loads the MSBuild 15 assemblies from Mono this seems
                // to be too late to prevent the MEF composition and the static registrar from
                // failing to load the MonoDevelop.Ide assembly which now uses MSBuild 15 assemblies.
                ResolveMSBuildAssemblies();
            }

            Counters.Initialization.BeginTiming();

            if (options.PerfLog)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.perf-log");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            Counters.Initialization.Trace("Initializing GTK");
            if (Platform.IsWindows && !CheckWindowsGtk())
            {
                return(1);
            }
            SetupExceptionManager();

            // explicit GLib type system initialization for GLib < 2.36 before any other type system access
            GLib.GType.Init();

            IdeApp.Customizer = options.IdeCustomizer ?? new IdeCustomizer();
            try {
                IdeApp.Customizer.Initialize();
            } catch (UnauthorizedAccessException ua) {
                LoggingService.LogError("Unauthorized access: " + ua.Message);
                return(1);
            }

            try {
                GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            var args = options.RemainingArgs.ToArray();

            IdeTheme.InitializeGtk(BrandingService.ApplicationName, ref args);

            LoggingService.LogInfo("Using GTK+ {0}", IdeVersionInfo.GetGtkVersion());

            // XWT initialization
            FilePath p = typeof(IdeStartup).Assembly.Location;

            Runtime.LoadAssemblyFrom(p.ParentDirectory.Combine("Xwt.Gtk.dll"));
            Xwt.Application.InitializeAsGuest(Xwt.ToolkitType.Gtk);
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarWindowBackend, GtkExtendedTitleBarWindowBackend> ();
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarDialogBackend, GtkExtendedTitleBarDialogBackend> ();
            IdeTheme.SetupXwtTheme();

            //default to Windows IME on Windows
            if (Platform.IsWindows && GtkWorkarounds.GtkMinorVersion >= 16)
            {
                var settings = Gtk.Settings.Default;
                var val      = GtkWorkarounds.GetProperty(settings, "gtk-im-module");
                if (string.IsNullOrEmpty(val.Val as string))
                {
                    GtkWorkarounds.SetProperty(settings, "gtk-im-module", new GLib.Value("ime"));
                }
            }

            string   socket_filename = null;
            EndPoint ep = null;

            DispatchService.Initialize();

            // Set a synchronization context for the main gtk thread
            SynchronizationContext.SetSynchronizationContext(DispatchService.SynchronizationContext);
            Runtime.MainSynchronizationContext = SynchronizationContext.Current;

            // Initialize Roslyn's synchronization context
            RoslynServices.RoslynService.Initialize();

            AddinManager.AddinLoadError += OnAddinError;

            var startupInfo = new StartupInfo(args);

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                Counters.Initialization.Trace("Pre-Initializing Runtime to load files in existing window");
                Runtime.Initialize(true);
                foreach (var file in startupInfo.RequestedFileList)
                {
                    if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile(file.FileName))
                    {
                        options.NewWindow = true;
                        break;
                    }
                }
            }

            Counters.Initialization.Trace("Initializing Runtime");
            Runtime.Initialize(true);

            IdeApp.Customizer.OnCoreInitialized();

            Counters.Initialization.Trace("Initializing theme");

            IdeTheme.SetupGtkTheme();

            ProgressMonitor monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor();

            monitor.BeginTask(GettextCatalog.GetString("Starting {0}", BrandingService.ApplicationName), 2);

            //make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
            Counters.Initialization.Trace("Initializing Platform Service");
            DesktopService.Initialize();

            monitor.Step(1);

            if (options.IpcTcp)
            {
                listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ep            = new IPEndPoint(IPAddress.Loopback, ipcBasePort + HashSdbmBounded(Environment.UserName));
            }
            else
            {
                socket_filename = "/tmp/md-" + Environment.GetEnvironmentVariable("USER") + "-socket";
                listen_socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                ep = new UnixEndPoint(socket_filename);
            }

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles)
            {
                try {
                    StringBuilder builder = new StringBuilder();
                    foreach (var file in startupInfo.RequestedFileList)
                    {
                        builder.AppendFormat("{0};{1};{2}\n", file.FileName, file.Line, file.Column);
                    }
                    listen_socket.Connect(ep);
                    listen_socket.Send(Encoding.UTF8.GetBytes(builder.ToString()));
                    return(0);
                } catch {
                    // Reset the socket
                    if (null != socket_filename && File.Exists(socket_filename))
                    {
                        File.Delete(socket_filename);
                    }
                }
            }

            Counters.Initialization.Trace("Checking System");

            CheckFileWatcher();

            Exception error            = null;
            int       reportedFailures = 0;

            try {
                Counters.Initialization.Trace("Loading Icons");
                //force initialisation before the workbench so that it can register stock icons for GTK before they get requested
                ImageService.Initialize();
                LocalizationService.Initialize();

                // If we display an error dialog before the main workbench window on OS X then a second application menu is created
                // which is then replaced with a second empty Apple menu.
                // XBC #33699
                Counters.Initialization.Trace("Initializing IdeApp");
                IdeApp.Initialize(monitor);

                if (errorsList.Count > 0)
                {
                    using (AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), false)) {
                        if (!dlg.Run())
                        {
                            return(1);
                        }
                    }
                    reportedFailures = errorsList.Count;
                }

                if (!CheckSCPlugin())
                {
                    return(1);
                }

                // Load requested files
                Counters.Initialization.Trace("Opening Files");

                // load previous combine
                RecentFile openedProject = null;
                if (IdeApp.Preferences.LoadPrevSolutionOnStartup && !startupInfo.HasSolutionFile && !IdeApp.Workspace.WorkspaceItemIsOpening && !IdeApp.Workspace.IsOpen)
                {
                    openedProject = DesktopService.RecentFiles.MostRecentlyUsedProject;
                    if (openedProject != null)
                    {
                        var metadata = GetOpenWorkspaceOnStartupMetadata();
                        IdeApp.Workspace.OpenWorkspaceItem(openedProject.FileName, true, true, metadata).ContinueWith(t => IdeApp.OpenFiles(startupInfo.RequestedFileList, metadata), TaskScheduler.FromCurrentSynchronizationContext());
                        startupInfo.OpenedRecentProject = true;
                    }
                }
                if (openedProject == null)
                {
                    IdeApp.OpenFiles(startupInfo.RequestedFileList, GetOpenWorkspaceOnStartupMetadata());
                    startupInfo.OpenedFiles = startupInfo.HasFiles;
                }

                monitor.Step(1);
            } catch (Exception e) {
                error = e;
            } finally {
                monitor.Dispose();
            }

            if (error != null)
            {
                string message = BrandingService.BrandApplicationName(GettextCatalog.GetString("MonoDevelop failed to start"));
                MessageService.ShowFatalError(message, null, error);
                return(1);
            }

            if (errorsList.Count > reportedFailures)
            {
                using (AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), true))
                    dlg.Run();
            }

            errorsList = null;
            AddinManager.AddinLoadError -= OnAddinError;

            // FIXME: we should probably track the last 'selected' one
            // and do this more cleanly
            try {
                listen_socket.Bind(ep);
                listen_socket.Listen(5);
                listen_socket.BeginAccept(new AsyncCallback(ListenCallback), listen_socket);
            } catch {
                // Socket already in use
            }

            initialized = true;
            MessageService.RootWindow    = IdeApp.Workbench.RootWindow;
            Xwt.MessageDialog.RootWindow = Xwt.Toolkit.CurrentEngine.WrapWindow(IdeApp.Workbench.RootWindow);
            Thread.CurrentThread.Name    = "GUI Thread";
            Counters.Initialization.Trace("Running IdeApp");
            Counters.Initialization.EndTiming();

            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/InitCompleteHandlers", OnExtensionChanged);
            StartLockupTracker();

            startupTimer.Stop();

            CreateStartupMetadata(startupInfo);

            GLib.Idle.Add(OnIdle);
            IdeApp.Run();

            IdeApp.Customizer.OnIdeShutdown();

            // unloading services
            if (null != socket_filename)
            {
                File.Delete(socket_filename);
            }
            lockupCheckRunning = false;
            Runtime.Shutdown();

            IdeApp.Customizer.OnCoreShutdown();

            InstrumentationService.Stop();

            MonoDevelop.Components.GtkWorkarounds.Terminate();

            return(0);
        }
Example #25
0
        public int Run(string[] args)
        {
            Counters.Initialization.BeginTiming();

            var options    = new MonoDevelopOptions();
            var optionsSet = new Mono.Options.OptionSet()
            {
                { "nologo", "Do not display splash screen.", s => options.NoLogo = true },
                { "ipc-tcp", "Use the Tcp channel for inter-process comunication.", s => options.IpcTcp = true },
                { "newwindow", "Do not open in an existing instance of MonoDevelop", s => options.NewWindow = true },
                { "h|?|help", "Show help", s => options.ShowHelp = true },
                { "clog", "Log internal counter data", s => options.LogCounters = true },
                { "clog-interval=", "Interval between counter logs (in miliseconds)", s => options.LogCountersInterval = int.Parse(s) },
            };
            var remainingArgs = optionsSet.Parse(args);

            if (options.ShowHelp)
            {
                Console.WriteLine("MonoDevelop IDE " + MonoDevelop.Ide.BuildVariables.PackageVersionLabel);
                Console.WriteLine("Options:");
                optionsSet.WriteOptionDescriptions(Console.Out);
                return(0);
            }

            if (options.LogCounters)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.clog");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            Counters.Initialization.Trace("Initializing GTK");
            SetupExceptionManager();

            try {
                MonoDevelop.Ide.Gui.GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            //OSXFIXME
            Gtk.Application.Init("monodevelop", ref args);
            InternalLog.Initialize();
            string   socket_filename = null;
            EndPoint ep = null;

            AddinManager.AddinLoadError += OnAddinError;

            var startupInfo = new StartupInfo(remainingArgs);

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                Counters.Initialization.Trace("Pre-Initializing Runtime to load files in existing window");
                Runtime.Initialize(true);
//				foreach (var file in startupInfo.RequestedFileList) {
//					if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile (file.FileName)) {
//						options.NewWindow = true;
//						break;
//					}
//				}
            }

            DefaultTheme = Gtk.Settings.Default.ThemeName;
            if (!string.IsNullOrEmpty(IdeApp.Preferences.UserInterfaceTheme))
            {
                Gtk.Settings.Default.ThemeName = IdeApp.Preferences.UserInterfaceTheme;
            }

            //don't show the splash screen on the Mac, so instead we get the expected "Dock bounce" effect
            //this also enables the Mac platform service to subscribe to open document events before the GUI loop starts.
            if (PropertyService.IsMac)
            {
                options.NoLogo = true;
            }

            IProgressMonitor monitor;

            if (options.NoLogo)
            {
                monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor();
            }
            else
            {
                monitor = SplashScreenForm.SplashScreen;
                SplashScreenForm.SplashScreen.ShowAll();
            }

            Counters.Initialization.Trace("Initializing Runtime");
            monitor.BeginTask(GettextCatalog.GetString("Starting MonoDevelop"), 2);
            monitor.Step(1);
            Runtime.Initialize(true);

            //make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
            Counters.Initialization.Trace("Initializing Platform Service");
            DesktopService.Initialize();
            monitor.Step(1);
            monitor.EndTask();

            monitor.Step(1);

            if (options.IpcTcp)
            {
                listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ep            = new IPEndPoint(IPAddress.Loopback, ipcBasePort + HashSDBMBounded(Environment.UserName));
            }
            else
            {
                socket_filename = "/tmp/md-unity-" + Environment.GetEnvironmentVariable("USER") + "-socket";
                listen_socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                ep = new UnixEndPoint(socket_filename);
            }

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles)
            {
                try {
                    StringBuilder builder = new StringBuilder();
                    foreach (var file in startupInfo.RequestedFileList)
                    {
                        builder.AppendFormat("{0};{1};{2}\n", file.FileName, file.Line, file.Column);
                    }
                    listen_socket.Connect(ep);
                    listen_socket.Send(Encoding.UTF8.GetBytes(builder.ToString()));
                    listen_socket.Close();
                    return(0);
                } catch {
                    // Reset the socket
                    if (null != socket_filename && File.Exists(socket_filename))
                    {
                        File.Delete(socket_filename);
                    }
                    if (options.IpcTcp)
                    {
                        try {
                            listen_socket.Close();
                            listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                        } catch (Exception exc) {
                            LoggingService.LogError("Error resetting TCP socket", exc);
                        }
                    }
                }
            }

            Counters.Initialization.Trace("Checking System");
            string version = Assembly.GetEntryAssembly().GetName().Version.Major + "." + Assembly.GetEntryAssembly().GetName().Version.Minor;

            if (Assembly.GetEntryAssembly().GetName().Version.Build != 0)
            {
                version += "." + Assembly.GetEntryAssembly().GetName().Version.Build;
            }
            if (Assembly.GetEntryAssembly().GetName().Version.Revision != 0)
            {
                version += "." + Assembly.GetEntryAssembly().GetName().Version.Revision;
            }

            // System checks
            if (!CheckBug77135())
            {
                return(1);
            }

            if (!CheckQtCurve())
            {
                return(1);
            }

            CheckFileWatcher();

            Exception error            = null;
            int       reportedFailures = 0;

            try {
                Counters.Initialization.Trace("Loading Icons");
                //force initialisation before the workbench so that it can register stock icons for GTK before they get requested
                ImageService.Initialize();

                if (errorsList.Count > 0)
                {
                    if (monitor is SplashScreenForm)
                    {
                        SplashScreenForm.SplashScreen.Hide();
                    }
                    AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), false);
                    if (!dlg.Run())
                    {
                        return(1);
                    }
                    if (monitor is SplashScreenForm)
                    {
                        SplashScreenForm.SplashScreen.Show();
                    }
                    reportedFailures = errorsList.Count;
                }

                // no alternative for Application.ThreadException?
                // Application.ThreadException += new ThreadExceptionEventHandler(ShowErrorBox);

                Counters.Initialization.Trace("Initializing IdeApp");
                IdeApp.Initialize(monitor);

                // Load requested files
                Counters.Initialization.Trace("Opening Files");
                IdeApp.OpenFiles(startupInfo.RequestedFileList);

                monitor.Step(1);
            } catch (Exception e) {
                error = e;
            } finally {
                monitor.Dispose();
            }

            if (error != null)
            {
                MessageService.ShowException(error,
                                             GettextCatalog.GetString("MonoDevelop failed to start. The following error has been reported: ") + error.Message);
                return(1);
            }

            if (errorsList.Count > reportedFailures)
            {
                AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), true);
                dlg.Run();
            }

            errorsList = null;

            // FIXME: we should probably track the last 'selected' one
            // and do this more cleanly
            try {
                listen_socket.Bind(ep);
                listen_socket.Listen(5);
                listen_socket.BeginAccept(new AsyncCallback(ListenCallback), listen_socket);
            } catch {
                // Socket already in use
            }

            initialized = true;
            MessageService.RootWindow = IdeApp.Workbench.RootWindow;
            Thread.CurrentThread.Name = "GUI Thread";
            Counters.Initialization.Trace("Running IdeApp");
            Counters.Initialization.EndTiming();
            IdeApp.Run();

            // unloading services
            if (null != socket_filename)
            {
                File.Delete(socket_filename);
            }

            Runtime.Shutdown();
            InstrumentationService.Stop();

            System.Environment.Exit(0);
            return(0);
        }
        int Run(MonoDevelopOptions options)
        {
            LoggingService.LogInfo("Starting {0} {1}", BrandingService.ApplicationName, IdeVersionInfo.MonoDevelopVersion);
            LoggingService.LogInfo("Running on {0}", IdeVersionInfo.GetRuntimeInfo());

            //ensure native libs initialized before we hit anything that p/invokes
            Platform.Initialize();

            IdeApp.Customizer = options.IdeCustomizer ?? new IdeCustomizer();
            IdeApp.Customizer.Initialize();

            Counters.Initialization.BeginTiming();

            if (options.PerfLog)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.perf-log");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            Counters.Initialization.Trace("Initializing GTK");
            if (Platform.IsWindows && !CheckWindowsGtk())
            {
                return(1);
            }
            SetupExceptionManager();

            try {
                GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            SetupTheme();

            var args = options.RemainingArgs.ToArray();

            Gtk.Application.Init(BrandingService.ApplicationName, ref args);

            LoggingService.LogInfo("Using GTK+ {0}", IdeVersionInfo.GetGtkVersion());

            // XWT initialization
            FilePath p = typeof(IdeStartup).Assembly.Location;

            Assembly.LoadFrom(p.ParentDirectory.Combine("Xwt.Gtk.dll"));
            Xwt.Application.InitializeAsGuest(Xwt.ToolkitType.Gtk);
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarWindowBackend, GtkExtendedTitleBarWindowBackend> ();
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarDialogBackend, GtkExtendedTitleBarDialogBackend> ();

            //default to Windows IME on Windows
            if (Platform.IsWindows && Mono.TextEditor.GtkWorkarounds.GtkMinorVersion >= 16)
            {
                var settings = Gtk.Settings.Default;
                var val      = Mono.TextEditor.GtkWorkarounds.GetProperty(settings, "gtk-im-module");
                if (string.IsNullOrEmpty(val.Val as string))
                {
                    Mono.TextEditor.GtkWorkarounds.SetProperty(settings, "gtk-im-module", new GLib.Value("ime"));
                }
            }

            InternalLog.Initialize();
            string   socket_filename = null;
            EndPoint ep = null;

            DispatchService.Initialize();

            // Set a synchronization context for the main gtk thread
            SynchronizationContext.SetSynchronizationContext(new GtkSynchronizationContext());
            Runtime.MainSynchronizationContext = SynchronizationContext.Current;

            AddinManager.AddinLoadError += OnAddinError;

            var startupInfo = new StartupInfo(args);

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                Counters.Initialization.Trace("Pre-Initializing Runtime to load files in existing window");
                Runtime.Initialize(true);
                foreach (var file in startupInfo.RequestedFileList)
                {
                    if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile(file.FileName))
                    {
                        options.NewWindow = true;
                        break;
                    }
                }
            }

            Counters.Initialization.Trace("Initializing Runtime");
            Runtime.Initialize(true);

            IdeApp.Customizer.OnCoreInitialized();

            Counters.Initialization.Trace("Initializing theme");

            DefaultTheme = Gtk.Settings.Default.ThemeName;
            string theme = IdeApp.Preferences.UserInterfaceTheme;

            if (string.IsNullOrEmpty(theme))
            {
                theme = DefaultTheme;
            }
            ValidateGtkTheme(ref theme);
            if (theme != DefaultTheme)
            {
                Gtk.Settings.Default.ThemeName = theme;
            }

            IProgressMonitor monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor();

            monitor.BeginTask(GettextCatalog.GetString("Starting {0}", BrandingService.ApplicationName), 2);

            //make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
            Counters.Initialization.Trace("Initializing Platform Service");
            DesktopService.Initialize();

            monitor.Step(1);

            if (options.IpcTcp)
            {
                listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ep            = new IPEndPoint(IPAddress.Loopback, ipcBasePort + HashSdbmBounded(Environment.UserName));
            }
            else
            {
                socket_filename = "/tmp/md-" + Environment.GetEnvironmentVariable("USER") + "-socket";
                listen_socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                ep = new UnixEndPoint(socket_filename);
            }

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles)
            {
                try {
                    StringBuilder builder = new StringBuilder();
                    foreach (var file in startupInfo.RequestedFileList)
                    {
                        builder.AppendFormat("{0};{1};{2}\n", file.FileName, file.Line, file.Column);
                    }
                    listen_socket.Connect(ep);
                    listen_socket.Send(Encoding.UTF8.GetBytes(builder.ToString()));
                    return(0);
                } catch {
                    // Reset the socket
                    if (null != socket_filename && File.Exists(socket_filename))
                    {
                        File.Delete(socket_filename);
                    }
                }
            }

            Counters.Initialization.Trace("Checking System");
            string version = Assembly.GetEntryAssembly().GetName().Version.Major + "." + Assembly.GetEntryAssembly().GetName().Version.Minor;

            if (Assembly.GetEntryAssembly().GetName().Version.Build != 0)
            {
                version += "." + Assembly.GetEntryAssembly().GetName().Version.Build;
            }
            if (Assembly.GetEntryAssembly().GetName().Version.Revision != 0)
            {
                version += "." + Assembly.GetEntryAssembly().GetName().Version.Revision;
            }

            CheckFileWatcher();

            Exception error            = null;
            int       reportedFailures = 0;

            try {
                Counters.Initialization.Trace("Loading Icons");
                //force initialisation before the workbench so that it can register stock icons for GTK before they get requested
                ImageService.Initialize();

                if (errorsList.Count > 0)
                {
                    AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), false);
                    if (!dlg.Run())
                    {
                        return(1);
                    }
                    reportedFailures = errorsList.Count;
                }

                if (!CheckSCPlugin())
                {
                    return(1);
                }

                // no alternative for Application.ThreadException?
                // Application.ThreadException += new ThreadExceptionEventHandler(ShowErrorBox);

                Counters.Initialization.Trace("Initializing IdeApp");
                IdeApp.Initialize(monitor);

                // Load requested files
                Counters.Initialization.Trace("Opening Files");

                // load previous combine
                if (IdeApp.Preferences.LoadPrevSolutionOnStartup && !startupInfo.HasSolutionFile && !IdeApp.Workspace.WorkspaceItemIsOpening && !IdeApp.Workspace.IsOpen)
                {
                    var proj = DesktopService.RecentFiles.GetProjects().FirstOrDefault();
                    if (proj != null)
                    {
                        IdeApp.Workspace.OpenWorkspaceItem(proj.FileName).WaitForCompleted();
                    }
                }

                IdeApp.OpenFiles(startupInfo.RequestedFileList);

                monitor.Step(1);
            } catch (Exception e) {
                error = e;
            } finally {
                monitor.Dispose();
            }

            if (error != null)
            {
                string message = BrandingService.BrandApplicationName(GettextCatalog.GetString("MonoDevelop failed to start"));
                MessageService.ShowFatalError(message, null, error);
                return(1);
            }

            if (errorsList.Count > reportedFailures)
            {
                AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), true);
                dlg.Run();
            }

            errorsList = null;

            // FIXME: we should probably track the last 'selected' one
            // and do this more cleanly
            try {
                listen_socket.Bind(ep);
                listen_socket.Listen(5);
                listen_socket.BeginAccept(new AsyncCallback(ListenCallback), listen_socket);
            } catch {
                // Socket already in use
            }

            initialized = true;
            MessageService.RootWindow = IdeApp.Workbench.RootWindow;
            Thread.CurrentThread.Name = "GUI Thread";
            Counters.Initialization.Trace("Running IdeApp");
            Counters.Initialization.EndTiming();

            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/InitCompleteHandlers", OnExtensionChanged);
            StartLockupTracker();
            IdeApp.Run();

            IdeApp.Customizer.OnIdeShutdown();

            // unloading services
            if (null != socket_filename)
            {
                File.Delete(socket_filename);
            }
            lockupCheckRunning = false;
            Runtime.Shutdown();

            IdeApp.Customizer.OnCoreShutdown();

            InstrumentationService.Stop();
            AddinManager.AddinLoadError -= OnAddinError;

            return(0);
        }
Example #27
0
 public AgniInstrumentationProvider(InstrumentationService director) : base(director)
 {
 }
Example #28
0
 public TelemetryInstrumentationProvider(InstrumentationService director) : base(director)
 {
 }
Example #29
0
        int Run(MonoDevelopOptions options)
        {
            Counters.Initialization.BeginTiming();

            if (options.LogCounters)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.clog");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            Counters.Initialization.Trace("Initializing GTK");
            SetupExceptionManager();

            try {
                MonoDevelop.Ide.Gui.GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            //OSXFIXME
            var args = options.RemainingArgs.ToArray();

            Gtk.Application.Init("monodevelop", ref args);

            //default to Windows IME on Windows
            if (Platform.IsWindows && Mono.TextEditor.GtkWorkarounds.GtkMinorVersion >= 16)
            {
                var settings = Gtk.Settings.Default;
                var val      = Mono.TextEditor.GtkWorkarounds.GetProperty(settings, "gtk-im-module");
                if (string.IsNullOrEmpty(val.Val as string))
                {
                    Mono.TextEditor.GtkWorkarounds.SetProperty(settings, "gtk-im-module", new GLib.Value("ime"));
                }
            }

            InternalLog.Initialize();
            string   socket_filename = null;
            EndPoint ep = null;

            DispatchService.Initialize();

            // Set a synchronization context for the main gtk thread
            SynchronizationContext.SetSynchronizationContext(new GtkSynchronizationContext());

            AddinManager.AddinLoadError += OnAddinError;

            var startupInfo = new StartupInfo(args);

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                Counters.Initialization.Trace("Pre-Initializing Runtime to load files in existing window");
                Runtime.Initialize(true);
                foreach (var file in startupInfo.RequestedFileList)
                {
                    if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile(file.FileName))
                    {
                        options.NewWindow = true;
                        break;
                    }
                }
            }

            DefaultTheme = Gtk.Settings.Default.ThemeName;
            if (!string.IsNullOrEmpty(IdeApp.Preferences.UserInterfaceTheme))
            {
                Gtk.Settings.Default.ThemeName = IdeApp.Preferences.UserInterfaceTheme;
            }

            //don't show the splash screen on the Mac, so instead we get the expected "Dock bounce" effect
            //this also enables the Mac platform service to subscribe to open document events before the GUI loop starts.
            if (Platform.IsMac)
            {
                options.NoLogo = true;
            }

            IProgressMonitor monitor;

            if (options.NoLogo)
            {
                monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor();
            }
            else
            {
                monitor = SplashScreenForm.SplashScreen;
                SplashScreenForm.SplashScreen.ShowAll();
            }

            Counters.Initialization.Trace("Initializing Runtime");
            monitor.BeginTask(GettextCatalog.GetString("Starting {0}", BrandingService.ApplicationName), 3);
            monitor.Step(1);
            Runtime.Initialize(true);

            //make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
            Counters.Initialization.Trace("Initializing Platform Service");
            DesktopService.Initialize();

            monitor.Step(1);

            if (options.IpcTcp)
            {
                listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ep            = new IPEndPoint(IPAddress.Loopback, ipcBasePort + HashSdbmBounded(Environment.UserName));
            }
            else
            {
                socket_filename = "/tmp/md-" + Environment.GetEnvironmentVariable("USER") + "-socket";
                listen_socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                ep = new UnixEndPoint(socket_filename);
            }

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles)
            {
                try {
                    StringBuilder builder = new StringBuilder();
                    foreach (var file in startupInfo.RequestedFileList)
                    {
                        builder.AppendFormat("{0};{1};{2}\n", file.FileName, file.Line, file.Column);
                    }
                    listen_socket.Connect(ep);
                    listen_socket.Send(Encoding.UTF8.GetBytes(builder.ToString()));
                    return(0);
                } catch {
                    // Reset the socket
                    if (null != socket_filename && File.Exists(socket_filename))
                    {
                        File.Delete(socket_filename);
                    }
                }
            }

            Counters.Initialization.Trace("Checking System");
            string version = Assembly.GetEntryAssembly().GetName().Version.Major + "." + Assembly.GetEntryAssembly().GetName().Version.Minor;

            if (Assembly.GetEntryAssembly().GetName().Version.Build != 0)
            {
                version += "." + Assembly.GetEntryAssembly().GetName().Version.Build;
            }
            if (Assembly.GetEntryAssembly().GetName().Version.Revision != 0)
            {
                version += "." + Assembly.GetEntryAssembly().GetName().Version.Revision;
            }

            // System checks
            if (!CheckBug77135())
            {
                return(1);
            }

            if (!CheckQtCurve())
            {
                return(1);
            }

            CheckFileWatcher();

            Exception error            = null;
            int       reportedFailures = 0;

            try {
                Counters.Initialization.Trace("Loading Icons");
                //force initialisation before the workbench so that it can register stock icons for GTK before they get requested
                ImageService.Initialize();

                if (errorsList.Count > 0)
                {
                    if (monitor is SplashScreenForm)
                    {
                        SplashScreenForm.SplashScreen.Hide();
                    }
                    AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), false);
                    if (!dlg.Run())
                    {
                        return(1);
                    }
                    if (monitor is SplashScreenForm)
                    {
                        SplashScreenForm.SplashScreen.Show();
                    }
                    reportedFailures = errorsList.Count;
                }

                // no alternative for Application.ThreadException?
                // Application.ThreadException += new ThreadExceptionEventHandler(ShowErrorBox);

                Counters.Initialization.Trace("Initializing IdeApp");
                IdeApp.Initialize(monitor);

                // Load requested files
                Counters.Initialization.Trace("Opening Files");
                IdeApp.OpenFiles(startupInfo.RequestedFileList);

                monitor.Step(1);
            } catch (Exception e) {
                error = e;
            } finally {
                monitor.Dispose();
            }

            if (error != null)
            {
                LoggingService.LogFatalError(null, error);
                MessageService.ShowException(error,
                                             GettextCatalog.GetString("MonoDevelop failed to start. The following error has been reported: ") + error.Message);
                return(1);
            }

            if (errorsList.Count > reportedFailures)
            {
                AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), true);
                dlg.Run();
            }

            errorsList = null;

            // FIXME: we should probably track the last 'selected' one
            // and do this more cleanly
            try {
                listen_socket.Bind(ep);
                listen_socket.Listen(5);
                listen_socket.BeginAccept(new AsyncCallback(ListenCallback), listen_socket);
            } catch {
                // Socket already in use
            }

            initialized = true;
            MessageService.RootWindow = IdeApp.Workbench.RootWindow;
            Thread.CurrentThread.Name = "GUI Thread";
            Counters.Initialization.Trace("Running IdeApp");
            Counters.Initialization.EndTiming();

            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/InitCompleteHandlers", OnExtensionChanged);

            IdeApp.Run();

            // unloading services
            if (null != socket_filename)
            {
                File.Delete(socket_filename);
            }

            Runtime.Shutdown();
            InstrumentationService.Stop();

            return(0);
        }
 public TrendingSystemInstrumentationProvider(InstrumentationService director) : base(director)
 {
 }