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); }
static bool FileServiceErrorHandler(string message, Exception ex) { MessageService.ShowException(ex, message); return(true); }
//this method is MIT/X11, 2009, Michael Hutchinson / (c) Novell public static void OpenFiles(IEnumerable <FileOpenInformation> files) { if (files.Count() == 0) { return; } if (!IsInitialized) { EventHandler onInit = null; onInit = delegate { Initialized -= onInit; OpenFiles(files); }; Initialized += onInit; return; } var filteredFiles = new List <FileOpenInformation> (); //open the firsts sln/workspace file, and remove the others from the list //FIXME: can we handle multiple slns? bool foundSln = false; foreach (var file in files) { if (Services.ProjectService.IsWorkspaceItemFile(file.FileName) || Services.ProjectService.IsSolutionItemFile(file.FileName)) { if (!foundSln) { try { Workspace.OpenWorkspaceItem(file.FileName); foundSln = true; } catch (Exception ex) { LoggingService.LogError("Unhandled error opening solution/workspace \"" + file.FileName + "\"", ex); MessageService.ShowException(ex, "Could not load solution: " + file.FileName); } } } else { filteredFiles.Add(file); } } foreach (var file in filteredFiles) { try { Workbench.OpenDocument(file.FileName, file.Line, file.Column, file.Options); } catch (Exception ex) { LoggingService.LogError("Unhandled error opening file \"" + file.FileName + "\"", ex); MessageService.ShowException(ex, "Could not open file: " + file.FileName); } } Workbench.Present(); }
public static void Initialize(IProgressMonitor monitor) { Counters.Initialization.Trace("Creating Workbench"); workbench = new Workbench(); Counters.Initialization.Trace("Creating Root Workspace"); workspace = new RootWorkspace(); Counters.Initialization.Trace("Creating Services"); projectOperations = new ProjectOperations(); helpOperations = new HelpOperations(); commandService = new CommandManager(); ideServices = new IdeServices(); CustomToolService.Init(); AutoTestService.Start(commandService, Preferences.EnableAutomatedTesting); commandService.CommandTargetScanStarted += CommandServiceCommandTargetScanStarted; commandService.CommandTargetScanFinished += CommandServiceCommandTargetScanFinished; commandService.KeyBindingFailed += KeyBindingFailed; KeyBindingService.LoadBindingsFromExtensionPath("/MonoDevelop/Ide/KeyBindingSchemes"); KeyBindingService.LoadCurrentBindings("MD2"); commandService.CommandError += delegate(object sender, CommandErrorArgs args) { MessageService.ShowException(args.Exception, args.ErrorMessage); }; FileService.ErrorHandler = FileServiceErrorHandler; monitor.BeginTask(GettextCatalog.GetString("Loading Workbench"), 5); Counters.Initialization.Trace("Loading Commands"); commandService.LoadCommands("/MonoDevelop/Ide/Commands"); monitor.Step(1); Counters.Initialization.Trace("Initializing Workbench"); workbench.Initialize(monitor); monitor.Step(1); InternalLog.EnableErrorNotification(); monitor.Step(1); Counters.Initialization.Trace("Restoring Workbench State"); workbench.Show("SharpDevelop.Workbench.WorkbenchMemento"); monitor.Step(1); Counters.Initialization.Trace("Flushing GUI events"); DispatchService.RunPendingEvents(); Counters.Initialization.Trace("Flushed GUI events"); MessageService.RootWindow = workbench.RootWindow; commandService.EnableIdleUpdate = true; // Default file format MonoDevelop.Projects.Services.ProjectServiceLoaded += delegate(object sender, EventArgs e) { ((ProjectService)sender).DefaultFileFormatId = IdeApp.Preferences.DefaultProjectFileFormat; }; IdeApp.Preferences.DefaultProjectFileFormatChanged += delegate { IdeApp.Services.ProjectService.DefaultFileFormatId = IdeApp.Preferences.DefaultProjectFileFormat; }; // Perser service initialization TypeSystemService.TrackFileChanges = true; TypeSystemService.ParseProgressMonitorFactory = new ParseProgressMonitorFactory(); // Startup commands Counters.Initialization.Trace("Running Startup Commands"); AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/StartupHandlers", OnExtensionChanged); monitor.Step(1); monitor.EndTask(); // Set initial run flags Counters.Initialization.Trace("Upgrading Settings"); if (PropertyService.Get("MonoDevelop.Core.FirstRun", false)) { isInitialRun = true; PropertyService.Set("MonoDevelop.Core.FirstRun", false); PropertyService.Set("MonoDevelop.Core.LastRunVersion", BuildVariables.PackageVersion); PropertyService.Set("MonoDevelop.Core.LastRunVersion", CurrentRevision); PropertyService.SaveProperties(); } string lastVersion = PropertyService.Get("MonoDevelop.Core.LastRunVersion", "1.9.1"); int lastRevision = PropertyService.Get("MonoDevelop.Core.LastRunRevision", 0); if (lastRevision != CurrentRevision && !isInitialRun) { isInitialRunAfterUpgrade = true; if (lastRevision == 0) { switch (lastVersion) { case "1.0": lastRevision = 1; break; case "2.0": lastRevision = 2; break; case "2.2": lastRevision = 3; break; case "2.2.1": lastRevision = 4; break; } } upgradedFromRevision = lastRevision; PropertyService.Set("MonoDevelop.Core.LastRunVersion", BuildVariables.PackageVersion); PropertyService.Set("MonoDevelop.Core.LastRunRevision", CurrentRevision); PropertyService.SaveProperties(); } // The ide is now initialized isInitialized = true; if (isInitialRun) { try { OnInitialRun(); } catch (Exception e) { LoggingService.LogError("Error found while initializing the IDE", e); } } if (isInitialRunAfterUpgrade) { try { OnUpgraded(upgradedFromRevision); } catch (Exception e) { LoggingService.LogError("Error found while initializing the IDE", e); } } if (initializedEvent != null) { initializedEvent(null, EventArgs.Empty); } // load previous combine if ((bool)PropertyService.Get("SharpDevelop.LoadPrevProjectOnStartup", false)) { var proj = DesktopService.RecentFiles.GetProjects().FirstOrDefault(); if (proj != null) { IdeApp.Workspace.OpenWorkspaceItem(proj.FileName).WaitForCompleted(); } } commandService.CommandSelected += OnCommandSelected; commandService.CommandDeselected += OnCommandDeselected; //FIXME: we should really make this on-demand. consumers can display a "loading help cache" message like VS MonoDevelop.Projects.HelpService.AsyncInitialize(); UpdateInstrumentationIcon(); IdeApp.Preferences.EnableInstrumentationChanged += delegate { UpdateInstrumentationIcon(); }; AutoTestService.NotifyEvent("MonoDevelop.Ide.IdeStart"); }
//this method is MIT/X11, 2009, Michael Hutchinson / (c) Novell public static void OpenFiles(IEnumerable <FileOpenInformation> files) { if (files.Count() == 0) { return; } if (!IsInitialized) { EventHandler onInit = null; onInit = delegate { Initialized -= onInit; OpenFiles(files); }; Initialized += onInit; return; } WaitForWorkspaceLoadIfBringingFilesToFront(files); if (Workspace.IsLoading) { EventHandler <WorkspaceItemEventArgs> onLoad = null; onLoad = delegate { Workspace.WorkspaceItemLoaded -= onLoad; OpenFiles(files); }; Workspace.WorkspaceItemLoaded += onLoad; return; } var filteredFiles = files.Where(f => !(Services.ProjectService.IsWorkspaceItemFile(f.FileName) || Services.ProjectService.IsSolutionItemFile(f.FileName))); EventHandler <WorkspaceItemEventArgs> loadFilteredFiles = null; loadFilteredFiles = delegate { WaitForWorkspaceLoadIfBringingFilesToFront(filteredFiles); foreach (var afile in filteredFiles) { try { Workbench.OpenDocument(afile.FileName, afile.Line, afile.Column, afile.Options); } catch (Exception ex) { LoggingService.LogError("Unhandled error opening file \"" + afile.FileName + "\"", ex); MessageService.ShowException(ex, "Could not open file: " + afile.FileName); } Workspace.WorkspaceItemLoaded -= loadFilteredFiles; } }; Workspace.WorkspaceItemLoaded += loadFilteredFiles; //open the firsts sln/workspace file, and remove the others from the list //FIXME: can we handle multiple slns? foreach (var file in files) { if (Services.ProjectService.IsWorkspaceItemFile(file.FileName) || Services.ProjectService.IsSolutionItemFile(file.FileName)) { // Don't reload the currently open solution if (null != Workspace.Items.FirstOrDefault(x => (x.FileName.FullPath.ToString().Equals(file.FileName, StringComparison.OrdinalIgnoreCase) && !x.NeedsReload))) { break; } try { workspaceLoading = Workspace.OpenWorkspaceItem(file.FileName); break; } catch (Exception ex) { LoggingService.LogError("Unhandled error opening solution/workspace \"" + file.FileName + "\"", ex); MessageService.ShowException(ex, "Could not load solution: " + file.FileName); } } } if (!Workspace.IsLoading) { loadFilteredFiles(null, null); } Workbench.Present(); }
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); }