예제 #1
0
        void CheckFileWatcher()
        {
            string watchesFile = "/proc/sys/fs/inotify/max_user_watches";

            try {
                if (File.Exists(watchesFile))
                {
                    string val = File.ReadAllText(watchesFile);
                    int    n   = int.Parse(val);
                    if (n <= 9000)
                    {
                        string msg = "Inotify watch limit is too low (" + n + ").\n";
                        msg += "MonoDevelop will switch to managed file watching.\n";
                        msg += "See http://monodevelop.com/Inotify_Watches_Limit for more info.";
                        LoggingService.LogWarning(BrandingService.BrandApplicationName(msg));
                        Runtime.ProcessService.EnvironmentVariableOverrides["MONO_MANAGED_WATCHER"] =
                            Environment.GetEnvironmentVariable("MONO_MANAGED_WATCHER");
                        Environment.SetEnvironmentVariable("MONO_MANAGED_WATCHER", "1");
                    }
                }
            } catch (Exception e) {
                LoggingService.LogWarning("There was a problem checking whether to use managed file watching", e);
            }
        }
예제 #2
0
        public ApplyPolicyDialog(IPolicyProvider policyProvider)
        {
            this.policyProvider = policyProvider;

            this.Build();
            tree = new PoliciesListSummaryTree();
            policiesScroll.Add(tree);
            tree.Show();

            foreach (PolicySet pset in PolicyService.GetPolicySets())
            {
                if (pset.Visible)
                {
                    combPolicies.AppendText(pset.Name);
                }
            }

            fileEntry.DefaultPath = ExportProjectPolicyDialog.DefaultFileDialogPolicyDir;
            fileEntry.FileFilters.AddFilter(BrandingService.BrandApplicationName(GettextCatalog.GetString("MonoDevelop policy files")), "*.mdpolicy");
            fileEntry.FileFilters.AddAllFilesFilter();
            combPolicies.Active = 0;
            OnRadioCustomToggled(null, null);
            UpdateContentLabels();
        }
예제 #3
0
        void CheckExternalMonodoc()
        {
            firstCall = false;
            try {
                outWriter = new StringWriter();
                errWriter = new StringWriter();
                pw        = Runtime.ProcessService.StartProcess(
                    "monodoc", "--help", "", outWriter, errWriter,
                    delegate {
                    if (pw.ExitCode != 0)
                    {
                        MessageService.ShowError(
                            String.Format(
                                "MonoDoc exited with exit code {0}. Error : {1}",
                                pw.ExitCode, errWriter.ToString()));
                    }
                    pw = null;
                }, true);

                pw.WaitForOutput();
                if (outWriter.ToString().IndexOf("--about") > 0)
                {
                    useExternalMonodoc = true;
                }
                pw = null;
            } catch (Exception e) {
                MessageService.ShowError(String.Format(
                                             "Could not start monodoc : {0}", e.ToString()));
            }

            if (!useExternalMonodoc)
            {
                MessageService.ShowError(
                    BrandingService.BrandApplicationName(GettextCatalog.GetString("You need a newer monodoc to use it externally from MonoDevelop. Using the integrated help viewer now.")));
            }
        }
예제 #4
0
        Task Load(bool reloading)
        {
            // We actually load initial content at construction time, so this
            // overload only needs to cover reload and autosave scenarios

            if (warnOverwrite)
            {
                warnOverwrite = false;
                DismissInfoBar();
                ShowNotification = false;
            }

            if (reloading)
            {
                TextDocument.Reload();
            }
            else if (AutoSave.AutoSaveExists(FilePath))
            {
                var autosaveContent = AutoSave.LoadAutoSave(FilePath);

                MarkDirty();
                warnOverwrite = true;

                // Set editor read-only until user picks one of the above options.
                var setWritable = !TextView.Options.DoesViewProhibitUserInput();
                if (setWritable)
                {
                    TextView.Options.SetOptionValue(DefaultTextViewOptions.ViewProhibitUserInputId, true);
                }

                var(primaryMessageText, secondaryMessageText) = SplitMessageString(
                    BrandingService.BrandApplicationName(GettextCatalog.GetString(
                                                             "<b>An autosave file has been found for this file.</b>\n" +
                                                             "This could mean that another instance of MonoDevelop is editing this " +
                                                             "file, or that MonoDevelop crashed with unsaved changes.\n\n" +
                                                             "Do you want to use the original file, or load from the autosave file?")));

                PresentInfobar(
                    primaryMessageText,
                    secondaryMessageText,
                    new InfoBarAction(
                        GetButtonString(GettextCatalog.GetString("_Use original file")),
                        UseOriginalFile),
                    new InfoBarAction(
                        GetButtonString(GettextCatalog.GetString("_Load from autosave")),
                        LoadFromAutosave,
                        isDefault: true));

                void OnActionSelected()
                {
                    DismissInfoBar();
                    if (setWritable)
                    {
                        TextView.Options.SetOptionValue(DefaultTextViewOptions.ViewProhibitUserInputId, false);
                    }
                }

                void LoadFromAutosave()
                {
                    try {
                        AutoSave.RemoveAutoSaveFile(FilePath);
                        ReplaceContent(autosaveContent.Text, autosaveContent.Encoding);
                    } catch (Exception e) {
                        LoggingService.LogError("Could not load the autosave file", e);
                    } finally {
                        OnActionSelected();
                    }
                }

                void UseOriginalFile()
                {
                    try {
                        AutoSave.RemoveAutoSaveFile(FilePath);
                    } catch (Exception e) {
                        LoggingService.LogError("Could not remove the autosave file", e);
                    } finally {
                        OnActionSelected();
                    }
                }
            }

            return(Task.CompletedTask);
        }
예제 #5
0
        public async Task <int> Run(string[] arguments)
        {
            DesktopService.Initialize();

            Console.WriteLine(BrandingService.BrandApplicationName("MonoDevelop Gettext Update Tool"));
            foreach (string s in arguments)
            {
                ReadArgument(s);
            }

            if (help)
            {
                Console.WriteLine("gettext-update [options] [project-file]");
                Console.WriteLine("--f --file:FILE   Project or solution file to build.");
                Console.WriteLine("--p --project:PROJECT  Name of the project to build.");
                Console.WriteLine("--sort  Sorts the output po file");
                Console.WriteLine();
                return(0);
            }

            if (file == null)
            {
                var files = Directory.EnumerateFiles(".");
                foreach (string f in files)
                {
                    if (Services.ProjectService.IsWorkspaceItemFile(f))
                    {
                        file = f;
                        break;
                    }
                }
                if (file == null)
                {
                    Console.WriteLine("Solution file not found.");
                    return(1);
                }
            }
            else if (!Services.ProjectService.IsWorkspaceItemFile(file))
            {
                Console.WriteLine("File '{0}' is not a project or solution.", file);
                return(1);
            }

            ConsoleProgressMonitor monitor = new ConsoleProgressMonitor();

            monitor.IgnoreLogMessages = true;

            WorkspaceItem centry = await Services.ProjectService.ReadWorkspaceItem(monitor, file);

            monitor.IgnoreLogMessages = false;

            Solution solution = centry as Solution;

            if (solution == null)
            {
                Console.WriteLine("File is not a solution: " + file);
                return(1);
            }

            if (project != null)
            {
                SolutionItem item = solution.FindProjectByName(project);

                if (item == null)
                {
                    Console.WriteLine("The project '" + project + "' could not be found in " + file);
                    return(1);
                }
                TranslationProject tp = item as TranslationProject;
                if (tp == null)
                {
                    Console.WriteLine("The project '" + item.FileName + "' is not a translation project");
                    return(1);
                }
                tp.UpdateTranslations(monitor, sort);
            }
            else
            {
                foreach (TranslationProject p in solution.GetAllItems <TranslationProject>())
                {
                    p.UpdateTranslations(monitor, sort);
                }
            }

            return(0);
        }
예제 #6
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);
        }
예제 #7
0
 bool CheckSCPlugin()
 {
     if (Platform.IsMac && Directory.Exists("/Library/Contextual Menu Items/SCFinderPlugin.plugin"))
     {
         string message = "SCPlugin not supported";
         string detail  = "MonoDevelop has detected that SCPlugin (scplugin.tigris.org) is installed. " +
                          "SCPlugin is a Subversion extension for Finder that is known to cause crashes in MonoDevelop and" +
                          "other applications running on Mac OSX 10.9 (Mavericks) or upper. Please uninstall SCPlugin " +
                          "before proceeding.";
         var close = new AlertButton(BrandingService.BrandApplicationName(GettextCatalog.GetString("Close MonoDevelop")));
         var info  = new AlertButton(GettextCatalog.GetString("More Information"));
         var cont  = new AlertButton(GettextCatalog.GetString("Continue Anyway"));
         while (true)
         {
             var res = MessageService.GenericAlert(Gtk.Stock.DialogWarning, message, BrandingService.BrandApplicationName(detail), info, cont, close);
             if (res == close)
             {
                 LoggingService.LogInternalError("SCPlugin detected", new Exception("SCPlugin detected. Closing."));
                 return(false);
             }
             if (res == info)
             {
                 DesktopService.ShowUrl("https://bugzilla.xamarin.com/show_bug.cgi?id=21755");
             }
             if (res == cont)
             {
                 bool exists = Directory.Exists("/Library/Contextual Menu Items/SCFinderPlugin.plugin");
                 LoggingService.LogInternalError("SCPlugin detected", new Exception("SCPlugin detected. Continuing " + (exists ? "Installed." : "Uninstalled.")));
                 return(true);
             }
         }
     }
     return(true);
 }
        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);
        }
예제 #9
0
        async Task <int> MainLoop(MonoDevelopOptions options, StartupInfo startupInfo)
        {
            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.InitializationTracker.Trace("Initializing Platform Service");

            var desktopService = await Runtime.GetService <DesktopService> ();

            var commandService = await Runtime.GetService <CommandManager> ();

            // load the global menu for the welcome window to avoid unresponsive menus on Mac
            desktopService.SetGlobalMenu(commandService, DefaultWorkbench.MainMenuPath, DefaultWorkbench.AppMenuPath);

            IdeStartupTracker.StartupTracker.MarkSection("PlatformInitialization");

            monitor.Step(1);

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

            CheckFileWatcher();

            IdeStartupTracker.StartupTracker.MarkSection("FileWatcherInitialization");

            Exception error            = null;
            int       reportedFailures = 0;

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

                IdeStartupTracker.StartupTracker.MarkSection("ImageInitialization");

                // 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.InitializationTracker.Trace("Initializing IdeApp");

                hideWelcomePage = options.NoStartWindow || startupInfo.HasFiles || IdeApp.Preferences.StartupBehaviour.Value != OnStartupBehaviour.ShowStartWindow;
                await IdeApp.Initialize(monitor, hideWelcomePage);

                IdeStartupTracker.StartupTracker.MarkSection("AppInitialization");

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

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

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

                // load previous combine
                RecentFile openedProject = null;
                if (IdeApp.Preferences.StartupBehaviour.Value == OnStartupBehaviour.LoadPreviousSolution && !startupInfo.HasSolutionFile && !IdeApp.Workspace.WorkspaceItemIsOpening && !IdeApp.Workspace.IsOpen)
                {
                    openedProject = IdeServices.DesktopService.RecentFiles.MostRecentlyUsedProject;
                    if (openedProject != null)
                    {
                        var metadata = GetOpenWorkspaceOnStartupMetadata();
                        IdeApp.Workspace.OpenWorkspaceItem(openedProject.FileName, true, true, metadata).ContinueWith(t => IdeApp.OpenFilesAsync(startupInfo.RequestedFileList, metadata), TaskScheduler.FromCurrentSynchronizationContext()).Ignore();
                        startupInfo.OpenedRecentProject = true;
                    }
                }
                if (openedProject == null)
                {
                    IdeApp.OpenFilesAsync(startupInfo.RequestedFileList, GetOpenWorkspaceOnStartupMetadata()).Ignore();
                    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"));
                message = message + "\n\n" + error.Message;
                MessageService.ShowFatalError(message, null, error);

                return(1);
            }

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

            errorsList = null;
            AddinManager.AddinLoadError -= OnAddinError;

            IdeStartupTracker.StartupTracker.MarkSection("BasicInitializationCompleted");

            instanceConnection.FileOpenRequested += (sender, a) => {
                foreach (var e in a)
                {
                    OpenFile(e.FileName);
                }
            };

            instanceConnection.StartListening();

            IdeStartupTracker.StartupTracker.MarkSection("SocketInitialization");

            initialized = true;
            MessageService.RootWindow    = IdeApp.Workbench.RootWindow;
            Xwt.MessageDialog.RootWindow = Xwt.Toolkit.CurrentEngine.WrapWindow(IdeApp.Workbench.RootWindow);

            IdeStartupTracker.StartupTracker.MarkSection("WindowOpened");

            Thread.CurrentThread.Name = "GUI Thread";
            Counters.InitializationTracker.Trace("Running IdeApp");
            Counters.InitializationTracker.End();
            Counters.InitializationTracker = new NullTimeTracker();

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

            // This call is important so the current event loop is run before we run the main loop.
            // On Mac, the OpenDocuments event gets handled here, so we need to get the timeout
            // it queues before the OnIdle event so we can start opening a solution before
            // we show the main window.
            await Task.Yield();

            IdeStartupTracker.StartupTracker.MarkSection("PumpEventLoop");
            IdeStartupTracker.StartupTracker.Stop(startupInfo);

            GLib.Idle.Add(OnIdle);

            return(0);
        }
예제 #10
0
        public override object CreateInstance()
        {
            ActionType ct       = ActionType.Normal;
            bool       isArray  = false;
            bool       custom   = false;
            bool       isAction = false;

            foreach (string p in type.Split('|'))
            {
                switch (p)
                {
                case "check":
                    ct = ActionType.Check;
                    if (isAction)
                    {
                        throw new InvalidOperationException("Action type specified twice.");
                    }
                    isAction = true;
                    break;

                case "radio":
                    ct = ActionType.Radio;
                    if (isAction)
                    {
                        throw new InvalidOperationException("Action type specified twice.");
                    }
                    isAction = true;
                    break;

                case "normal":
                    ct = ActionType.Normal;
                    if (isAction)
                    {
                        throw new InvalidOperationException("Action type specified twice.");
                    }
                    isAction = true;
                    break;

                case "custom":
                    if (widget == null)
                    {
                        throw new InvalidOperationException("Widget type not specified in custom command.");
                    }
                    custom = true;
                    break;

                case "array":
                    isArray = true;
                    break;

                default:
                    throw new InvalidOperationException("Unknown command type: " + p);
                }
            }

            if (isAction && custom)
            {
                throw new InvalidOperationException("Invalid command type combination: " + type);
            }

            Command cmd;

            if (custom)
            {
                if (isArray)
                {
                    throw new InvalidOperationException("Array custom commands are not allowed.");
                }

                CustomCommand ccmd = new CustomCommand();
                ccmd.Text       = label;
                ccmd.WidgetType = Addin.GetType(widget);
                if (ccmd.WidgetType == null)
                {
                    throw new InvalidOperationException("Could not find command type '" + widget + "'.");
                }
                cmd = ccmd;
            }
            else
            {
                if (widget != null)
                {
                    throw new InvalidOperationException("Widget type can only be specified for custom commands.");
                }

                ActionCommand acmd = new ActionCommand();
                acmd.ActionType   = ct;
                acmd.CommandArray = isArray;

                if (defaultHandler != null)
                {
                    acmd.SetDefaultHandlerTypeInfo(Addin, defaultHandler);
                }

                cmd = acmd;
            }

            cmd.Id   = ParseCommandId(this);
            cmd.Text = StringParserService.Parse(BrandingService.BrandApplicationName(label));
            if (!String.IsNullOrWhiteSpace(_displayName))
            {
                cmd.DisplayName = StringParserService.Parse(BrandingService.BrandApplicationName(_displayName));
            }
            if ((_description != null) && (_description.Length > 0))
            {
                cmd.Description = BrandingService.BrandApplicationName(_description);
            }
            cmd.Description = cmd.Description;

            if (icon != null)
            {
                cmd.Icon = GetStockId(Addin, icon);
            }

            var keyBinding = Platform.IsMac ? macShortcut : shortcut;

            if (Platform.IsWindows && !string.IsNullOrEmpty(winShortcut))
            {
                keyBinding = winShortcut;
            }
            string[] splittedKeys = (keyBinding ?? "").Split(' ');

            cmd.AccelKey = KeyBindingManager.FixChordSeparators(KeyBindingManager.CanonicalizeBinding(splittedKeys[0]));
            if (splittedKeys.Length > 1)
            {
                cmd.AlternateAccelKeys = splittedKeys.Skip(1).Select(key => KeyBindingManager.FixChordSeparators(key)).ToArray();
            }

            cmd.DisabledVisible = disabledVisible;

            // Assign the category of the command
            CommandCategoryCodon cat = Parent as CommandCategoryCodon;

            if (cat != null)
            {
                cmd.Category = cat.Name;
            }

            return(cmd);
        }
예제 #11
0
        public int Run(string[] arguments)
        {
            Console.WriteLine(BrandingService.BrandApplicationName("MonoDevelop Build Tool"));
            foreach (string s in arguments)
            {
                ReadArgument(s);
            }

            if (help)
            {
                Console.WriteLine("build [options] [build-file]");
                Console.WriteLine("-p --project:PROJECT  Name of the project to build.");
                Console.WriteLine("-t --target:TARGET    Name of the target: Build or Clean.");
                Console.WriteLine("-c --configuration:CONFIGURATION  Name of the solution configuration to build.");
                Console.WriteLine("-r --runtime:PREFIX   Prefix of the Mono runtime to build against.");
                Console.WriteLine();
                Console.WriteLine("Supported targets:");
                Console.WriteLine("  {0}: build the project (the default target).", ProjectService.BuildTarget);
                Console.WriteLine("  {0}: clean the project.", ProjectService.CleanTarget);
                Console.WriteLine();
                return(0);
            }

            string solFile  = null;
            string itemFile = null;

            if (file == null)
            {
                string[] files = Directory.GetFiles(".");
                foreach (string f in files)
                {
                    if (Services.ProjectService.IsWorkspaceItemFile(f))
                    {
                        solFile = f;
                        break;
                    }
                    else if (itemFile == null && Services.ProjectService.IsSolutionItemFile(f))
                    {
                        itemFile = f;
                    }
                }
                if (solFile == null && itemFile == null)
                {
                    Console.WriteLine("Project file not found.");
                    return(1);
                }
            }
            else
            {
                if (Services.ProjectService.IsWorkspaceItemFile(file))
                {
                    solFile = file;
                }
                else if (Services.ProjectService.IsSolutionItemFile(file))
                {
                    itemFile = file;
                }
                else
                {
                    Console.WriteLine("File '{0}' is not a project or solution.", file);
                    return(1);
                }
            }

            IProgressMonitor monitor = new ConsoleProjectLoadProgressMonitor(new ConsoleProgressMonitor());

            TargetRuntime targetRuntime  = null;
            TargetRuntime defaultRuntime = Runtime.SystemAssemblyService.DefaultRuntime;

            if (runtime != null)
            {
                targetRuntime = MonoTargetRuntimeFactory.RegisterRuntime(new MonoRuntimeInfo(runtime));
                if (targetRuntime != null)
                {
                    Runtime.SystemAssemblyService.DefaultRuntime = targetRuntime;
                }
            }

            IBuildTarget item;

            if (solFile != null)
            {
                item = Services.ProjectService.ReadWorkspaceItem(monitor, solFile);
            }
            else
            {
                item = Services.ProjectService.ReadSolutionItem(monitor, itemFile);
            }

            using (var readItem = item) {
                if (project != null)
                {
                    Solution solution = item as Solution;
                    item = null;

                    if (solution != null)
                    {
                        item = solution.FindProjectByName(project);
                    }
                    if (item == null)
                    {
                        Console.WriteLine("The project '" + project + "' could not be found in " + file);
                        return(1);
                    }
                }

                IConfigurationTarget configTarget = item as IConfigurationTarget;
                if (config == null && configTarget != null)
                {
                    config = configTarget.DefaultConfigurationId;
                }

                monitor = new ConsoleProgressMonitor();
                BuildResult res = null;
                if (item is SolutionEntityItem && ((SolutionEntityItem)item).ParentSolution == null)
                {
                    ConfigurationSelector configuration = new ItemConfigurationSelector(config);
                    res = item.RunTarget(monitor, command, configuration);
                }
                else
                {
                    ConfigurationSelector configuration      = new SolutionConfigurationSelector(config);
                    SolutionEntityItem    solutionEntityItem = item as SolutionEntityItem;
                    if (solutionEntityItem != null)
                    {
                        if (command == ProjectService.BuildTarget)
                        {
                            res = solutionEntityItem.Build(monitor, configuration, true);
                        }
                        else if (command == ProjectService.CleanTarget)
                        {
                            solutionEntityItem.Clean(monitor, configuration);
                        }
                        else
                        {
                            res = item.RunTarget(monitor, command, configuration);
                        }
                    }
                    else
                    {
                        res = item.RunTarget(monitor, command, configuration);
                    }
                }


                if (targetRuntime != null)
                {
                    Runtime.SystemAssemblyService.DefaultRuntime = defaultRuntime;
                    MonoTargetRuntimeFactory.UnregisterRuntime((MonoTargetRuntime)targetRuntime);
                }

                if (res != null)
                {
                    foreach (var err in res.Errors)
                    {
                        Console.Error.WriteLine(err);
                    }
                }

                return((res == null || res.ErrorCount == 0) ? 0 : 1);
            }
        }
예제 #12
0
        private Command CreateCommand()
        {
            ActionType actionType = ActionType.Normal;
            bool       flag1      = false;
            bool       flag2      = false;
            bool       flag3      = false;
            string     type       = this.type;

            char[] chArray = new char[1] {
                '|'
            };
            foreach (string str in type.Split(chArray))
            {
                switch (str)
                {
                case "check":
                    actionType = ActionType.Check;
                    if (flag3)
                    {
                        throw new InvalidOperationException("Action type specified twice.");
                    }
                    flag3 = true;
                    break;

                case "radio":
                    actionType = ActionType.Radio;
                    if (flag3)
                    {
                        throw new InvalidOperationException("Action type specified twice.");
                    }
                    flag3 = true;
                    break;

                case "normal":
                    actionType = ActionType.Normal;
                    if (flag3)
                    {
                        throw new InvalidOperationException("Action type specified twice.");
                    }
                    flag3 = true;
                    break;

                case "custom":
                    if (this.widget == null)
                    {
                        throw new InvalidOperationException("Widget type not specified in custom command.");
                    }
                    flag2 = true;
                    break;

                case "array":
                    flag1 = true;
                    break;

                default:
                    throw new InvalidOperationException("Unknown command type: " + str);
                }
            }
            if (flag3 && flag2)
            {
                throw new InvalidOperationException("Invalid command type combination: " + this.type);
            }
            Command command;

            if (flag2)
            {
                if (flag1)
                {
                    throw new InvalidOperationException("Array custom commands are not allowed.");
                }
                CustomCommand customCommand = new CustomCommand();
                customCommand.Text       = this.label;
                customCommand.WidgetType = this.Addin.GetType(this.widget);
                if (customCommand.WidgetType == (Type)null)
                {
                    throw new InvalidOperationException("Could not find command type '" + this.widget + "'.");
                }
                command = (Command)customCommand;
            }
            else
            {
                if (this.widget != null)
                {
                    throw new InvalidOperationException("Widget type can only be specified for custom commands.");
                }
                ActionCommand actionCommand = new ActionCommand();
                actionCommand.ActionType   = actionType;
                actionCommand.CommandArray = flag1;
                if (this.handler != null)
                {
                    try
                    {
                        MenuHandler instance = (MenuHandler)Activator.CreateInstance(this.Addin.GetType(this.handler, true));
                        if (instance != null)
                        {
                            actionCommand.DefaultHandler     = (CommandHandler) new CcsCmdHandler(instance);
                            actionCommand.DefaultHandlerType = actionCommand.DefaultHandler.GetType();
                        }
                    }
                    catch
                    {
                        LogConfig.Output.Error((object)string.Format("Failed to create MenuHandler: {0}", (object)this.handler));
                    }
                }
                command = (Command)actionCommand;
            }
            command.Id   = CmdEntryCodon.ParseCommandId((ExtensionNode)this);
            command.Text = this.label;
            if (this.description != null && this.description.Length > 0)
            {
                command.Description = BrandingService.BrandApplicationName(this.description);
            }
            command.Description = command.Description;
            if (this.icon != null)
            {
                command.Icon = (IconId)CmdEntryCodon.GetStockId(this.Addin, this.icon);
            }
            string str1 = Platform.IsMac ? this.macShortcut : this.shortcut;

            if (Platform.IsWindows && !string.IsNullOrEmpty(this.winShortcut))
            {
                str1 = this.winShortcut;
            }
            string[] strArray = (str1 ?? "").Split(' ');
            command.AccelKey = KeyBindingManager.CanonicalizeBinding(strArray[0]);
            if (strArray.Length > 1)
            {
                command.AlternateAccelKeys = ((IEnumerable <string>)strArray).Skip <string>(1).ToArray <string>();
            }
            command.DisabledVisible = this.disabledVisible;
            CommandCategoryCodon parent = this.Parent as CommandCategoryCodon;

            if (parent != null)
            {
                command.Category = parent.Name;
            }
            return(command);
        }