Esempio n. 1
0
        internal async Task Initialize(ProgressMonitor monitor)
        {
            monitor.BeginTask(GettextCatalog.GetString("Initializing Main Window"), 4);
            try {
                monitors = (IdeProgressMonitorManager)await Runtime.GetService <ProgressMonitorManager> ();

                documentManager = await Runtime.GetService <DocumentManager> ();

                await Runtime.GetService <DocumentModelRegistry> ();

                await Runtime.GetService <DocumentControllerService> ();

                Counters.Initialization.Trace("Creating DefaultWorkbench");
                workbench = (DefaultWorkbench)await Runtime.GetService <IShell> ();

                monitor.Step(1);

                Counters.Initialization.Trace("Initializing Workspace");
                workbench.InitializeWorkspace();
                monitor.Step(1);

                Counters.Initialization.Trace("Initializing Layout");
                workbench.InitializeLayout();
                monitor.Step(1);

                ((Gtk.Window)workbench).Visible          = false;
                workbench.WorkbenchTabsChanged          += WorkbenchTabsChanged;
                IdeApp.Workspace.StoringUserPreferences += OnStoringWorkspaceUserPreferences;
                IdeApp.Workspace.LoadingUserPreferences += OnLoadingWorkspaceUserPreferences;

                IdeApp.FocusOut += delegate(object o, EventArgs args) {
                    if (!fileEventsFrozen)
                    {
                        fileEventsFrozen = true;
                        FileService.FreezeEvents();
                    }
                };
                IdeApp.FocusIn += delegate(object o, EventArgs args) {
                    if (fileEventsFrozen)
                    {
                        fileEventsFrozen = false;
                        FileService.ThawEvents();
                    }
                };

                pads = null;                    // Make sure we get an up to date pad list.
                monitor.Step(1);
            } finally {
                monitor.EndTask();
            }
        }
        public void SetProgress(double progress)
        {
            int ns = (int)(progress * 100);

            monitor.Step(ns - step);
            step = ns;
        }
Esempio n. 3
0
        void InstallEntry(ProgressMonitor monitor, DeployContext ctx, SolutionFolderItem entry, ConfigurationSelector configuration)
        {
            foreach (DeployFile df in DeployService.GetDeployFiles(ctx, new SolutionFolderItem[] { entry }, configuration))
            {
                string targetPath = df.ResolvedTargetFile;
                if (targetPath == null)
                {
                    monitor.ReportWarning("Could not copy file '" + df.RelativeTargetPath + "': Unknown target directory.");
                    continue;
                }

                CopyFile(monitor, df.SourcePath, df.ResolvedTargetFile, df.FileAttributes);
            }

            SolutionFolder c = entry as SolutionFolder;

            if (c != null)
            {
                monitor.BeginTask("Installing solution '" + c.Name + "'", c.Items.Count);
                foreach (SolutionFolderItem ce in c.Items)
                {
                    InstallEntry(monitor, ctx, ce, configuration);
                    monitor.Step(1);
                }
                monitor.EndTask();
            }
        }
        protected override void OnReadProject(ProgressMonitor monitor, MonoDevelop.Projects.MSBuild.MSBuildProject msproject)
        {
            base.OnReadProject(monitor, msproject);
            var ext = msproject.GetMonoDevelopProjectExtension("MonoDevelop.Autotools.MakefileInfo");

            if (ext == null)
            {
                return;
            }

            data = MakefileData.Read(ext);
            if (data == null)
            {
                return;
            }

            monitor.BeginTask(GettextCatalog.GetString("Updating project from Makefile"), 1);
            try {
                data.OwnerProject = Project;
                if (data.SupportsIntegration)
                {
                    data.UpdateProject(monitor, false);
                }
                monitor.Step(1);
            } catch (Exception e) {
                monitor.ReportError(GettextCatalog.GetString(
                                        "\tError loading Makefile for project {0}", Project.Name), e);
            } finally {
                monitor.EndTask();
            }
        }
        private void MakeStaticLibrary(Project project,
                                       ProjectFileCollection projectFiles,
                                       CProjectConfiguration configuration,
                                       ProjectPackageCollection packages,
                                       CompilerResults cr,
                                       ProgressMonitor monitor, string outputName)
        {
            if (!NeedsUpdate(projectFiles, configuration, outputName))
            {
                return;
            }

            string objectFiles = string.Join(" ", ObjectFiles(projectFiles, configuration, true));
            string args        = string.Format("rcs \"{0}\" {1}", outputName, objectFiles);

            monitor.BeginTask(GettextCatalog.GetString("Generating static library {0} from object files", Path.GetFileName(outputName)), 1);

            string errorOutput;
            int    exitCode = ExecuteCommand("ar", args, Path.GetDirectoryName(outputName), monitor, out errorOutput);

            if (exitCode == 0)
            {
                monitor.Step(1);
            }
            monitor.EndTask();

            ParseCompilerOutput(errorOutput, cr);
            ParseLinkerOutput(errorOutput, cr);
            CheckReturnCode(exitCode, cr);
        }
        protected async override Task OnExecute(ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration)
        {
            if (data == null || !data.SupportsIntegration || String.IsNullOrEmpty(data.ExecuteTargetName))
            {
                await base.OnExecute(monitor, context, configuration);

                return;
            }

            OperationConsole console = context.ConsoleFactory.CreateConsole();

            monitor.BeginTask(GettextCatalog.GetString("Executing {0}", Project.Name), 1);
            try
            {
                ProcessWrapper process = Runtime.ProcessService.StartProcess("make",
                                                                             data.ExecuteTargetName,
                                                                             Project.BaseDirectory,
                                                                             console.Out,
                                                                             console.Error,
                                                                             null);

                await process.Task;

                monitor.Log.WriteLine(GettextCatalog.GetString("The application exited with code: {0}", process.ExitCode));
                monitor.Step(1);
            } catch (Exception e) {
                monitor.ReportError(GettextCatalog.GetString("Project could not be executed: "), e);
                return;
            } finally {
                monitor.EndTask();
                console.Dispose();
            }
        }
 void Step()
 {
     completedWork++;
     if (monitor != null && completedWork % reportingThinningFactor == 0)
     {
         monitor.Step(reportingThinningFactor);
     }
 }
 void RunActionsWithProgressMonitor(ProgressMonitor monitor, IList <PaketAction> actions)
 {
     foreach (PaketAction action in actions)
     {
         action.Monitor = monitor;
         action.Run();
         monitor.Step(1);
     }
 }
 void RunActionsWithProgressMonitor(ProgressMonitor monitor, IList <IPackageAction> packageActions)
 {
     foreach (IPackageAction action in packageActions)
     {
         action.Execute(monitor.CancellationToken);
         instrumentationService.InstrumentPackageAction(action);
         monitor.Step(1);
     }
 }
 void RunActionsWithProgressMonitor(ProgressMonitor monitor, IList <IPackageAction> packageActions)
 {
     foreach (IPackageAction action in packageActions)
     {
         action.Execute();
         InstrumentPackageAction(action);
         monitor.Step(1);
     }
 }
Esempio n. 11
0
		public async Task SaveAsync (ProgressMonitor monitor)
		{
			monitor.BeginTask (GettextCatalog.GetString ("Saving Workspace..."), Items.Count);
			List<WorkspaceItem> items = new List<WorkspaceItem> (Items);
			foreach (WorkspaceItem it in items) {
				await it.SaveAsync (monitor);
				monitor.Step (1);
			}
			monitor.EndTask ();
		}
Esempio n. 12
0
 public void OnReload()
 {
     using (ProgressMonitor m = IdeApp.Workbench.ProgressMonitors.GetProjectLoadProgressMonitor(true)) {
         m.BeginTask(null, CurrentNodes.Length);
         foreach (ITreeNavigator nav in CurrentNodes)
         {
             Project p = (Project)nav.DataItem;
             p.ParentFolder.ReloadItem(m, p);
             m.Step(1);
         }
         m.EndTask();
     }
 }
Esempio n. 13
0
 public void OnReload()
 {
     using (ProgressMonitor m = IdeApp.Workbench.ProgressMonitors.GetProjectLoadProgressMonitor(true)) {
         m.BeginTask(null, CurrentNodes.Length);
         foreach (ITreeNavigator node in CurrentNodes)
         {
             Solution solution = (Solution)node.DataItem;
             solution.ParentWorkspace.ReloadItem(m, solution);
             m.Step(1);
         }
         m.EndTask();
     }
 }
Esempio n. 14
0
        /// <summary>
        /// Tries to apply the actions passed in <paramref name="actions"/>.
        /// </summary>
        /// <param name="actions">The actions to apply.</param>
        /// <returns>The fixed code actions.</returns>
        public IEnumerable <ActionSummary> TryFixIssues(IEnumerable <ActionSummary> actions)
        {
            if (actions == null)
            {
                throw new ArgumentNullException("actions");
            }

            // enumerate once
            var actionSummaries = actions as IList <ActionSummary> ?? actions.ToList();
            var issueSummaries  = actionSummaries.Select(action => action.IssueSummary).ToList();
            var files           = issueSummaries.Select(issue => issue.File).Distinct().ToList();

            monitor.BeginTask("Applying fixes", files.Count);

            var appliedActions = new List <ActionSummary> (issueSummaries.Count);

            Parallel.ForEach(files, file => {
                monitor.Step(1);

                var fileSummaries = issueSummaries.Where(summary => summary.File == file);
                var inspectorIds  = new HashSet <string> (fileSummaries.Select(summary => summary.InspectorIdString));

                bool isOpen;
                var data = TextFileProvider.Instance.GetTextEditorData(file.FilePath, out isOpen);
                IRefactoringContext refactoringContext;
                var realActions = GetIssues(data, file, inspectorIds, out refactoringContext).SelectMany(issue => issue.Actions).ToList();
                if (realActions.Count == 0 || refactoringContext == null)
                {
                    return;
                }

                var fileActionSummaries = actionSummaries.Where(summary => summary.IssueSummary.File == file).ToList();
                var matches             = matcher.Match(fileActionSummaries, realActions).ToList();

                var appliedFixes = RefactoringService.ApplyFixes(matches.Select(match => match.Action), refactoringContext);
                appliedActions.AddRange(matches.Where(match => appliedFixes.Contains(match.Action)).Select(match => match.Summary));

                if (!isOpen)
                {
                    // If the file is open we leave it to the user to explicitly save the file
                    data.Save();
                }
            });
            return(appliedActions);
        }
Esempio n. 15
0
        static async Task BuildPackages(ICollection packages)
        {
            ProgressMonitor mon = IdeApp.Workbench.ProgressMonitors.GetToolOutputProgressMonitor(true);

            // Run the deploy command in a background thread to avoid
            // deadlocks with the gui thread

            using (mon) {
                mon.BeginTask("Creating packages", packages.Count);
                foreach (Package p in packages)
                {
                    await DeployService.BuildPackage(mon, p);

                    mon.Step(1);
                }
                mon.EndTask();
            }
        }
Esempio n. 16
0
        public void OnUnload()
        {
            HashSet <Solution> solutions = new HashSet <Solution> ();

            using (ProgressMonitor m = IdeApp.Workbench.ProgressMonitors.GetProjectLoadProgressMonitor(true)) {
                m.BeginTask(null, CurrentNodes.Length);
                foreach (ITreeNavigator nav in CurrentNodes)
                {
                    UnknownSolutionItem p = (UnknownSolutionItem)nav.DataItem;
                    solutions.Add(p.ParentSolution);
                    p.Enabled = false;
                    p.ParentFolder.ReloadItem(m, p);
                    m.Step(1);
                }
                m.EndTask();
            }
            IdeApp.ProjectOperations.SaveAsync(solutions);
        }
        private bool PrecompileHeaders(ProjectFileCollection projectFiles,
                                       CProjectConfiguration configuration,
                                       string args,
                                       ProgressMonitor monitor,
                                       CompilerResults cr)
        {
            monitor.BeginTask(GettextCatalog.GetString("Precompiling headers"), 1);
            bool success = true;

            foreach (ProjectFile file in projectFiles)
            {
                if (file.Subtype == Subtype.Code && CProject.IsHeaderFile(file.Name))
                {
                    string precomp = Path.Combine(configuration.IntermediateOutputDirectory, "prec");
                    precomp = Path.Combine(precomp, configuration.Id);
                    precomp = Path.Combine(precomp, Path.GetFileName(file.Name) + ".ghc");
                    if (file.BuildAction == BuildAction.Compile)
                    {
                        if (!File.Exists(precomp) || configuration.UseCcache || File.GetLastWriteTime(file.Name) > File.GetLastWriteTime(precomp))
                        {
                            if (DoPrecompileHeader(file, precomp, args, monitor, cr) == false)
                            {
                                success = false;
                                break;
                            }
                        }
                    }
                    else
                    {
                        //remove old files or they'll interfere with the build
                        if (File.Exists(precomp))
                        {
                            File.Delete(precomp);
                        }
                    }
                }
            }
            if (success)
            {
                monitor.Step(1);
            }
            monitor.EndTask();
            return(success);
        }
Esempio n. 18
0
        void CreateDefaultCatalog(ProgressMonitor monitor)
        {
            IFileScanner[] scanners = TranslationService.GetFileScanners();

            Catalog        catalog  = new Catalog(this);
            List <Project> projects = new List <Project> ();

            foreach (Project p in ParentSolution.GetAllProjects())
            {
                if (IsIncluded(p))
                {
                    projects.Add(p);
                }
            }
            foreach (Project p in projects)
            {
                monitor.Log.WriteLine(GettextCatalog.GetString("Scanning project {0}...", p.Name));
                foreach (ProjectFile file in p.Files)
                {
                    if (!File.Exists(file.FilePath))
                    {
                        continue;
                    }
                    if (file.Subtype == Subtype.Code)
                    {
                        string mimeType = DesktopService.GetMimeTypeForUri(file.FilePath);
                        foreach (IFileScanner fs in scanners)
                        {
                            if (fs.CanScan(this, catalog, file.FilePath, mimeType))
                            {
                                fs.UpdateCatalog(this, catalog, monitor, file.FilePath);
                            }
                        }
                    }
                }
                if (monitor.CancellationToken.IsCancellationRequested)
                {
                    return;
                }
                monitor.Step(1);
            }
            catalog.Save(Path.Combine(this.BaseDirectory, "messages.po"));
        }
        protected async override Task <BuildResult> OnClean(ProgressMonitor monitor, ConfigurationSelector configuration, OperationContext operationContext)
        {
            if (data == null || !data.SupportsIntegration || String.IsNullOrEmpty(data.CleanTargetName))
            {
                return(await base.OnClean(monitor, configuration, operationContext));
            }

            monitor.BeginTask(GettextCatalog.GetString("Cleaning project"), 1);
            try
            {
                string baseDir = Project.BaseDirectory;

                ProcessWrapper process = Runtime.ProcessService.StartProcess("make",
                                                                             data.CleanTargetName,
                                                                             baseDir,
                                                                             monitor.Log,
                                                                             monitor.Log,
                                                                             null);

                await process.Task;

                if (process.ExitCode > 0)
                {
                    throw new Exception(GettextCatalog.GetString("An unspecified error occurred while running '{0}'", "make " + data.CleanTargetName));
                }

                monitor.Step(1);
            }
            catch (Exception e)
            {
                monitor.ReportError(GettextCatalog.GetString("Project could not be cleaned: "), e);
                var res = new BuildResult();
                res.AddError(GettextCatalog.GetString("Project could not be cleaned: ") + e.Message);
                return(res);
            }
            finally
            {
                monitor.EndTask();
            }
            monitor.ReportSuccess(GettextCatalog.GetString("Project successfully cleaned"));
            return(BuildResult.CreateSuccess());
        }
Esempio n. 20
0
        public void OnReload()
        {
            var solutions = new HashSet <Solution> ();

            using (ProgressMonitor m = IdeApp.Workbench.ProgressMonitors.GetProjectLoadProgressMonitor(true)) {
                m.BeginTask(null, CurrentNodes.Length);
                foreach (ITreeNavigator node in CurrentNodes)
                {
                    UnknownSolutionItem entry = (UnknownSolutionItem)node.DataItem;
                    if (!entry.Enabled)
                    {
                        entry.Enabled = true;
                        solutions.Add(entry.ParentSolution);
                    }
                    entry.ParentFolder.ReloadItem(m, entry);
                    m.Step(1);
                }
                m.EndTask();
            }
            IdeApp.ProjectOperations.SaveAsync(solutions);
        }
Esempio n. 21
0
        async Task WriteWorkspaceItem(FilePath actualFile, FilePath outFile, WorkspaceItem item, ProgressMonitor monitor)
        {
            Workspace ws = item as Workspace;

            if (ws != null)
            {
                monitor.BeginTask(null, ws.Items.Count);
                try {
                    foreach (WorkspaceItem it in ws.Items)
                    {
                        await it.SaveAsync(monitor);

                        monitor.Step(1);
                    }
                } finally {
                    monitor.EndTask();
                }
            }

            await Task.Run(delegate {
                StreamWriter sw = new StreamWriter(outFile);
                try {
                    monitor.BeginTask(GettextCatalog.GetString("Saving item: {0}", actualFile), 1);
                    XmlTextWriter tw                         = new XmlTextWriter(sw);
                    tw.Formatting                            = Formatting.Indented;
                    XmlDataSerializer ser                    = new XmlDataSerializer(MD1ProjectService.DataContext);
                    ser.SerializationContext.BaseFile        = actualFile;
                    ser.SerializationContext.ProgressMonitor = monitor;
                    ser.Serialize(sw, item, typeof(WorkspaceItem));
                } catch (Exception ex) {
                    monitor.ReportError(GettextCatalog.GetString("Could not save item: {0}", actualFile), ex);
                    throw;
                } finally {
                    monitor.EndTask();
                    sw.Close();
                }
            });
        }
Esempio n. 22
0
        public static Task WaitForRunningTools(ProgressMonitor monitor)
        {
            TaskInfo[] operations;
            lock (runningTasks) {
                operations = runningTasks.Values.ToArray();
            }

            if (operations.Length == 0)
            {
                return(Task.FromResult(true));
            }

            monitor.BeginTask("Waiting for custom tools...", operations.Length);

            List <Task> tasks = new List <Task> ();

            foreach (var t in operations)
            {
                tasks.Add(t.Task.ContinueWith(ta => {
                    if (!monitor.CancellationToken.IsCancellationRequested)
                    {
                        monitor.Step(1);
                    }
                }));
            }

            var cancelTask = new TaskCompletionSource <bool> ();
            var allDone    = Task.WhenAll(tasks);

            var cancelReg = monitor.CancellationToken.Register(() => {
                cancelTask.SetResult(true);
            });

            return(Task.WhenAny(allDone, cancelTask.Task).ContinueWith(t => {
                monitor.EndTask();
                cancelReg.Dispose();
            }));
        }
Esempio n. 23
0
        public Translation AddNewTranslation(string isoCode, ProgressMonitor monitor)
        {
            try {
                Translation tr = new Translation(this, isoCode);
                translations.Add(tr);
                string templateFile    = Path.Combine(this.BaseDirectory, "messages.po");
                string translationFile = GetFileName(isoCode);
                if (!File.Exists(templateFile))
                {
                    CreateDefaultCatalog(monitor);
                }
                File.Copy(templateFile, translationFile);

                monitor.ReportSuccess(String.Format(GettextCatalog.GetString("Language '{0}' successfully added."), isoCode));
                monitor.Step(1);
                SaveAsync(monitor);
                return(tr);
            } catch (Exception e) {
                monitor.ReportError(String.Format(GettextCatalog.GetString("Language '{0}' could not be added: "), isoCode), e);
                return(null);
            } finally {
                monitor.EndTask();
            }
        }
        public Makefile Deploy(AutotoolsContext ctx, SolutionFolderItem entry, ProgressMonitor monitor)
        {
            generateAutotools = ctx.MakefileType == MakefileType.AutotoolsMakefile;

            monitor.BeginTask(GettextCatalog.GetString(
                                  "Creating {0} for Project {1}",
                                  generateAutotools ? "Makefile.am" : "Makefile", entry.Name), 1);

            Makefile makefile = new Makefile();

            try
            {
                if (!CanDeploy(entry, generateAutotools ? MakefileType.AutotoolsMakefile : MakefileType.SimpleMakefile))
                {
                    throw new Exception(GettextCatalog.GetString("Not a deployable project."));
                }

                Project               project        = entry as Project;
                TemplateEngine        templateEngine = new TemplateEngine();
                ISimpleAutotoolsSetup setup          = FindSetupForProject(project);

                // Handle files to be deployed
                deployDirs            = new Dictionary <string, StringBuilder> ();
                deployFileVars        = new Dictionary <string, string> ();
                builtFiles            = new List <string> ();
                deployFileCopyVars    = new StringBuilder();
                deployFileCopyTargets = new StringBuilder();

                //used only for simple makefile generation
                templateFilesTargets = null;
                installTarget        = null;
                installDeps          = null;
                installDirs          = null;
                uninstallTarget      = null;

                // handle configuration specific variables
                conf_vars = new StringBuilder();

                // grab all project files
                files     = new StringBuilder();
                res_files = new StringBuilder();
                extras    = new StringBuilder();
                datafiles = new StringBuilder();
                Set <string> extraFiles = new Set <string> ();

                string        includes = String.Empty;
                string        references, dllReferences;
                DotNetProject netProject = project as DotNetProject;
                ProcessProjectReferences(netProject, out references, out dllReferences, ctx);

                templateEngine.Variables["REFERENCES"]     = references;
                templateEngine.Variables["DLL_REFERENCES"] = dllReferences;
                templateEngine.Variables["WARNING"]        = "Warning: This is an automatically generated file, do not edit!";

                if (entry is DotNetProject dotnetProject)
                {
                    templateEngine.Variables ["RESGEN"] = "resgen";
                }

                string pfpath = null;
                foreach (ProjectFile projectFile in project.Files)
                {
                    pfpath = FileService.NormalizeRelativePath(projectFile.FilePath.ToRelative(project.BaseDirectory));
                    switch (projectFile.BuildAction)
                    {
                    case BuildAction.Compile:

                        if (projectFile.Subtype != Subtype.Code)
                        {
                            continue;
                        }
                        files.AppendFormat("\\\n\t{0} ", MakefileData.ToMakefilePath(pfpath));
                        break;

                    case BuildAction.Content:
                    case BuildAction.None:

                        extraFiles.Add(MakefileData.ToMakefilePath(pfpath));
                        break;

                    case BuildAction.EmbeddedResource:

                        if (!projectFile.FilePath.IsChildPathOf(ctx.BaseDirectory))
                        {
                            // file is not within directory hierarchy, copy it in
                            string rdir = Path.Combine(Path.GetDirectoryName(project.FileName), resourcedir);
                            if (!Directory.Exists(rdir))
                            {
                                Directory.CreateDirectory(rdir);
                            }
                            string newPath = Path.Combine(rdir, Path.GetFileName(projectFile.FilePath));
                            FileService.CopyFile(projectFile.FilePath, newPath);
                            pfpath = project.GetRelativeChildPath(newPath);
                            pfpath = FileService.NormalizeRelativePath(pfpath);
                        }
                        if (!String.IsNullOrEmpty(projectFile.ResourceId) && projectFile.ResourceId != Path.GetFileName(pfpath))
                        {
                            res_files.AppendFormat("\\\n\t{0},{1} ", MakefileData.ToMakefilePath(pfpath), MakefileData.EscapeString(projectFile.ResourceId));
                        }
                        else
                        {
                            res_files.AppendFormat("\\\n\t{0} ", MakefileData.ToMakefilePath(pfpath));
                        }

                        break;

                    case "FileCopy":

                        datafiles.AppendFormat("\\\n\t{0} ", MakefileData.ToMakefilePath(pfpath));
                        break;
                    }
                }

                if (!generateAutotools)
                {
                    templateFilesTargets = new StringBuilder();
                    installTarget        = new StringBuilder();
                    uninstallTarget      = new StringBuilder();
                    installDeps          = new StringBuilder();
                    installDirs          = new List <string> ();

                    customCommands = new StringBuilder();

                    string programFilesDir = ctx.DeployContext.GetDirectory(TargetDirectory.ProgramFiles);
                    //FIXME:temp
                    programFilesDir = TranslateDir(programFilesDir);
                    installDirs.Add(programFilesDir);
                    installTarget.Append("\tmake pre-install-local-hook prefix=$(prefix)\n");
                    installTarget.Append("\tmake install-satellite-assemblies prefix=$(prefix)\n");
                    installTarget.AppendFormat("\tmkdir -p '$(DESTDIR){0}'\n", programFilesDir);
                    installTarget.AppendFormat("\t$(call cp,$(ASSEMBLY),$(DESTDIR){0})\n", programFilesDir);
                    installTarget.AppendFormat("\t$(call cp,$(ASSEMBLY_MDB),$(DESTDIR){0})\n", programFilesDir);

                    //remove dir?
                    uninstallTarget.Append("\tmake pre-uninstall-local-hook prefix=$(prefix)\n");
                    uninstallTarget.Append("\tmake uninstall-satellite-assemblies prefix=$(prefix)\n");
                    uninstallTarget.AppendFormat("\t$(call rm,$(ASSEMBLY),$(DESTDIR){0})\n", programFilesDir);
                    uninstallTarget.AppendFormat("\t$(call rm,$(ASSEMBLY_MDB),$(DESTDIR){0})\n", programFilesDir);

                    installDeps.Append(" $(ASSEMBLY) $(ASSEMBLY_MDB)");

                    conf_vars.AppendFormat("srcdir=.\n");
                    conf_vars.AppendFormat("top_srcdir={0}\n\n",
                                           FileService.AbsoluteToRelativePath(project.BaseDirectory, ctx.TargetSolution.BaseDirectory));

                    conf_vars.AppendFormat("include $(top_srcdir)/config.make\n\n");

                    // Don't emit for top level project makefile(eg. pdn.make), as it would be
                    // included by top level solution makefile
                    if (ctx.TargetSolution.BaseDirectory != project.BaseDirectory)
                    {
                        string customhooks = Path.Combine(project.BaseDirectory, "custom-hooks.make");
                        bool   include     = File.Exists(customhooks);

                        includes  = "include $(top_srcdir)/Makefile.include\n";
                        includes += String.Format("{0}include $(srcdir)/custom-hooks.make\n\n", include ? "" : "#");
                        if (include)
                        {
                            makefile.SetVariable("EXTRA_DIST", "$(srcdir)/custom-hooks.make");
                        }
                    }
                }

                bool buildEnabled;
                List <ConfigSection> configSections = new List <ConfigSection> ();
                allDeployVars = new Dictionary <string, DeployFileData> ();

                foreach (SolutionConfiguration combineConfig in ctx.TargetSolution.Configurations)
                {
                    DotNetProjectConfiguration config = GetProjectConfig(combineConfig.Id, project, out buildEnabled) as DotNetProjectConfiguration;
                    if (config == null)
                    {
                        continue;
                    }

                    ConfigSection configSection = new ConfigSection(combineConfig.Id);

                    string assembly = MakefileData.GetUnixPath(project.GetRelativeChildPath(config.CompiledOutputName));

                    configSection.BuildVariablesBuilder.AppendFormat("ASSEMBLY_COMPILER_COMMAND = {0}\n",
                                                                     setup.GetCompilerCommand(project, config.Id));
                    configSection.BuildVariablesBuilder.AppendFormat("ASSEMBLY_COMPILER_FLAGS = {0}\n",
                                                                     setup.GetCompilerFlags(project, config.Id));

                    // add check for compiler command in configure.ac
                    ctx.AddCommandCheck(setup.GetCompilerCommand(project, config.Id));

                    configSection.BuildVariablesBuilder.AppendFormat("ASSEMBLY = {0}\n",
                                                                     AutotoolsContext.EscapeStringForAutomake(assembly));
                    configSection.BuildVariablesBuilder.AppendFormat("ASSEMBLY_MDB = {0}\n",
                                                                     config.DebugSymbols ? "$(ASSEMBLY).mdb" : String.Empty);

                    string target;
                    switch (config.CompileTarget)
                    {
                    case CompileTarget.Exe:
                        target = "exe";
                        break;

                    case CompileTarget.Library:
                        target = "library";
                        break;

                    case CompileTarget.WinExe:
                        target = "winexe";
                        break;

                    case CompileTarget.Module:
                        target = "module";
                        break;

                    default:
                        throw new Exception(GettextCatalog.GetString("Unknown target {0}", config.CompileTarget));
                    }
                    configSection.BuildVariablesBuilder.AppendFormat("COMPILE_TARGET = {0}\n", target);

                    // for project references, we need a ref to the dll for the current configuration
                    StringWriter projectReferences = new StringWriter();
                    string       pref = null;
                    foreach (ProjectReference reference in netProject.References)
                    {
                        if (reference.ReferenceType != ReferenceType.Project)
                        {
                            continue;
                        }
                        Project refp = reference.ResolveProject(ctx.TargetSolution);
                        if (refp == null)
                        {
                            throw new Exception(GettextCatalog.GetString("Couldn't find referenced project '{0}'", reference.Reference));
                        }
                        if (!(refp is DotNetProject))
                        {
                            continue;
                        }

                        DotNetProjectConfiguration dnpc = GetProjectConfig(combineConfig.Id, refp, out buildEnabled) as DotNetProjectConfiguration;
                        if (dnpc == null)
                        {
                            throw new Exception(GettextCatalog.GetString
                                                    ("Could not add reference to project '{0}'", refp.Name));
                        }

                        projectReferences.WriteLine(" \\");
                        projectReferences.Write("\t");
                        pref = project.GetRelativeChildPath(dnpc.CompiledOutputName);

                        projectReferences.Write(MakefileData.ToMakefilePath(pref));
                    }
                    configSection.BuildVariablesBuilder.AppendFormat("PROJECT_REFERENCES = {0}\n", projectReferences.ToString());

                    string buildDir = project.GetRelativeChildPath(config.OutputDirectory);
                    configSection.BuildVariablesBuilder.AppendFormat("BUILD_DIR = {0}\n", MakefileData.ToMakefilePath(buildDir));

                    // Register files built by this configuration.
                    // Built files won't be distributed.
                    foreach (string bfile in builtFiles)
                    {
                        ctx.AddBuiltFile(Path.Combine(config.OutputDirectory, bfile));
                    }

                    DeployFileCollection deployFiles = DeployService.GetDeployFiles(
                        ctx.DeployContext, new SolutionFolderItem[] { project }, config.Selector);

                    ProcessDeployFilesForConfig(deployFiles, project, configSection, ctx, config);
                    configSections.Add(configSection);

                    if (!generateAutotools)
                    {
                        EmitCustomCommandTargets(config.CustomCommands, project, customCommands, combineConfig.Id,
                                                 new CustomCommandType [] {
                            CustomCommandType.BeforeBuild,
                            CustomCommandType.AfterBuild,
                            CustomCommandType.BeforeClean,
                            CustomCommandType.AfterClean
                        }, monitor);
                    }
                    else
                    {
                        if (config.CustomCommands.Count > 0)
                        {
                            monitor.ReportWarning(GettextCatalog.GetString("Custom commands are not supported for autotools based makefiles. Ignoring."));
                        }
                    }

                    // Register files generated by the compiler
                    ctx.AddBuiltFile(project.GetOutputFileName(combineConfig.Selector));
                    if (config.DebugSymbols)
                    {
                        ctx.AddBuiltFile(project.GetOutputFileName(combineConfig.Selector) + ".mdb");
                    }

                    if (config.SignAssembly)
                    {
                        string spath = project.GetRelativeChildPath(config.AssemblyKeyFile);
                        spath = FileService.NormalizeRelativePath(spath);
                        extraFiles.Add(MakefileData.ToMakefilePath(spath));
                    }

                    if (buildEnabled && pkgs.Count > 0)
                    {
                        ctx.AddRequiredPackages(combineConfig.Id, pkgs);
                    }
                }


                foreach (string ef in extraFiles)
                {
                    extras.AppendFormat("\\\n\t{0} ", ef);
                }

                Dictionary <string, DeployFileData> commonDeployVars = new Dictionary <string, DeployFileData> (allDeployVars);
                foreach (ConfigSection configSection in configSections)
                {
                    List <string> toRemove = new List <string> ();
                    foreach (KeyValuePair <string, DeployFileData> pair in commonDeployVars)
                    {
                        if (!configSection.DeployFileVars.ContainsKey(pair.Key))
                        {
                            toRemove.Add(pair.Key);
                        }
                    }
                    foreach (string s in toRemove)
                    {
                        commonDeployVars.Remove(s);
                    }
                }

                //emit the config sections here.. to conf_vars
                foreach (ConfigSection configSection in configSections)
                {
                    conf_vars.AppendFormat(generateAutotools ? "if ENABLE_{0}\n" : "ifeq ($(CONFIG),{0})\n",
                                           ctx.EscapeAndUpperConfigName(configSection.Name));

                    conf_vars.Append(configSection.BuildVariablesBuilder.ToString());
                    conf_vars.Append("\n");

                    if (ctx.Switches != null)
                    {
                        foreach (Switch s in ctx.Switches)
                        {
                            conf_vars.AppendLine(string.Format(@"if ENABLE_{0}
ASSEMBLY_COMPILER_FLAGS += -define:{1}
endif", s.SwitchName.Replace('-', '_').ToUpperInvariant(), s.Define));
                        }
                    }

                    foreach (KeyValuePair <string, DeployFileData> pair in allDeployVars)
                    {
                        string targetDeployVar = pair.Key;
                        if (pair.Value.File.ContainsPathReferences)
                        {
                            //Template files are not handled per-config
                            continue;
                        }

                        if (configSection.DeployFileVars.ContainsKey(targetDeployVar))
                        {
                            //use the dfile from the config section
                            DeployFile dfile = configSection.DeployFileVars [targetDeployVar];
                            string     fname = MakefileData.ToMakefilePath(
                                FileService.AbsoluteToRelativePath(
                                    Path.GetFullPath(project.BaseDirectory),
                                    Path.GetFullPath(dfile.SourcePath)));

                            conf_vars.AppendFormat("{0}_SOURCE={1}\n", targetDeployVar, fname);

                            if (!commonDeployVars.ContainsKey(targetDeployVar))
                            {
                                //FOO_DLL=$(BUILD_DIR)/foo.dll
                                conf_vars.AppendFormat("{0}=$(BUILD_DIR)/{1}\n",
                                                       targetDeployVar,
                                                       MakefileData.ToMakefilePath(dfile.RelativeTargetPath));
                            }
                        }
                        else
                        {
                            // not common and not part of @configSection
                            conf_vars.AppendFormat("{0}=\n", pair.Key);
                        }
                    }

                    conf_vars.Append("\nendif\n\n");
                }

                conf_vars.AppendFormat("AL=al\n");
                conf_vars.AppendFormat("SATELLITE_ASSEMBLY_NAME=$(notdir $(basename $(ASSEMBLY))).resources.dll\n");

                foreach (KeyValuePair <string, DeployFileData> pair in allDeployVars)
                {
                    HandleDeployFile(pair.Value, pair.Key, project, ctx);

                    if (commonDeployVars.ContainsKey(pair.Key))
                    {
                        //FOO_DLL=$(BUILD_DIR)/foo.dll
                        deployFileCopyVars.AppendFormat("{0} = $(BUILD_DIR)/{1}\n",
                                                        pair.Key,
                                                        MakefileData.ToMakefilePath(pair.Value.File.RelativeTargetPath));
                    }
                }

                conf_vars.Append('\n');

                StringBuilder vars = new StringBuilder();
                foreach (KeyValuePair <string, StringBuilder> pair in deployDirs)
                {
                    //PROGRAM_FILES= .. etc
                    conf_vars.AppendFormat("{0} = {1} \n\n", pair.Key, pair.Value.ToString());
                    //Build list of deploy dir variables
                    vars.AppendFormat("$({0}) ", pair.Key);
                }

                if (!generateAutotools)
                {
                    installTarget.Insert(0, String.Format("install-local:{0}\n", installDeps.ToString()));
                    installTarget.Append("\tmake post-install-local-hook prefix=$(prefix)\n");

                    uninstallTarget.Insert(0, String.Format("uninstall-local:{0}\n", installDeps.ToString()));
                    uninstallTarget.Append("\tmake post-uninstall-local-hook prefix=$(prefix)\n");
                }

                if (!generateAutotools && customCommands.Length > 0)
                {
                    customCommands.Insert(0, "# Targets for Custom commands\n");
                }

                templateEngine.Variables["CONFIG_VARS"]               = conf_vars.ToString();
                templateEngine.Variables["DEPLOY_FILE_VARS"]          = vars.ToString();
                templateEngine.Variables["COPY_DEPLOY_FILES_VARS"]    = deployFileCopyVars.ToString();
                templateEngine.Variables["COPY_DEPLOY_FILES_TARGETS"] = deployFileCopyTargets.ToString();
                templateEngine.Variables["ALL_TARGET"] = (ctx.TargetSolution.BaseDirectory == project.BaseDirectory) ? "all-local" : "all";
                templateEngine.Variables["INCLUDES"]   = includes;

                templateEngine.Variables["FILES"]      = files.ToString();
                templateEngine.Variables["RESOURCES"]  = res_files.ToString();
                templateEngine.Variables["EXTRAS"]     = extras.ToString();
                templateEngine.Variables["DATA_FILES"] = datafiles.ToString();
                templateEngine.Variables["CLEANFILES"] = vars.ToString();

                if (!generateAutotools)
                {
                    templateEngine.Variables["TEMPLATE_FILES_TARGETS"] = templateFilesTargets.ToString();
                    templateEngine.Variables["INSTALL_TARGET"]         = installTarget.ToString();
                    templateEngine.Variables["UNINSTALL_TARGET"]       = uninstallTarget.ToString();
                    templateEngine.Variables["CUSTOM_COMMAND_TARGETS"] = customCommands.ToString();
                }

                // Create project specific makefile
                Stream stream = ctx.GetTemplateStream(
                    generateAutotools ? "Makefile.am.project.template" : "Makefile.noauto.project.template");

                StreamReader reader = new StreamReader(stream);
                string       txt    = templateEngine.Process(reader);
                reader.Close();

                makefile.Append(txt);
                monitor.Step(1);
            }
            finally { monitor.EndTask(); }
            return(makefile);
        }
Esempio n. 25
0
        internal void LoadSolution(Solution sol, SlnFile sln, ProgressMonitor monitor, SolutionLoadContext ctx)
        {
            var version = sln.FormatVersion;

            //Parse the .sln file
            var folder = sol.RootFolder;

            sol.Version = "0.1";             //FIXME:

            monitor.BeginTask("Loading projects ..", sln.Projects.Count + 1);
            Dictionary <string, SolutionFolderItem> items = new Dictionary <string, SolutionFolderItem> ();
            List <string> sortedList = new List <string> ();

            List <Task> loadTasks = new List <Task> ();

            foreach (SlnProject sec in sln.Projects)
            {
                try {
                    // Valid guid?
                    new Guid(sec.TypeGuid);
                } catch (FormatException) {
                    monitor.Step(1);
                    //Use default guid as projectGuid
                    LoggingService.LogDebug(GettextCatalog.GetString(
                                                "Invalid Project type guid '{0}' on line #{1}. Ignoring.",
                                                sec.Id,
                                                sec.Line));
                    continue;
                }

                string projTypeGuid = sec.TypeGuid.ToUpper();
                string projectName  = sec.Name;
                string projectPath  = sec.FilePath;
                string projectGuid  = sec.Id;

                lock (items)
                    sortedList.Add(projectGuid);

                if (projTypeGuid == MSBuildProjectService.FolderTypeGuid)
                {
                    //Solution folder
                    SolutionFolder sfolder = new SolutionFolder();
                    sfolder.Name   = projectName;
                    sfolder.ItemId = projectGuid;

                    DeserializeSolutionItem(monitor, sol, sfolder, sec);

                    foreach (string f in ReadFolderFiles(sec))
                    {
                        sfolder.Files.Add(MSBuildProjectService.FromMSBuildPath(Path.GetDirectoryName(sol.FileName), f));
                    }

                    lock (items)
                        items.Add(projectGuid, sfolder);

                    monitor.Step(1);
                    continue;
                }

                if (projectPath.StartsWith("http://"))
                {
                    monitor.ReportWarning(GettextCatalog.GetString(
                                              "{0}({1}): Projects with non-local source (http://...) not supported. '{2}'.",
                                              sol.FileName, sec.Line, projectPath));
                    monitor.Step(1);
                    continue;
                }

                string path = MSBuildProjectService.FromMSBuildPath(Path.GetDirectoryName(sol.FileName), projectPath);
                if (String.IsNullOrEmpty(path))
                {
                    monitor.ReportWarning(GettextCatalog.GetString(
                                              "Invalid project path found in {0} : {1}", sol.FileName, projectPath));
                    LoggingService.LogWarning(GettextCatalog.GetString(
                                                  "Invalid project path found in {0} : {1}", sol.FileName, projectPath));
                    monitor.Step(1);
                    continue;
                }

                projectPath = Path.GetFullPath(path);

                SolutionItem        item = null;
                Task <SolutionItem> loadTask;
                DateTime            ti = DateTime.Now;

                if (sol.IsSolutionItemEnabled(projectPath))
                {
                    loadTask = Services.ProjectService.ReadSolutionItem(monitor, projectPath, format, projTypeGuid, projectGuid, ctx);
                }
                else
                {
                    loadTask = Task.FromResult <SolutionItem> (new UnloadedSolutionItem()
                    {
                        FileName = projectPath
                    });
                }

                var ft = loadTask.ContinueWith(ta => {
                    try {
                        item = ta.Result;
                        if (item == null)
                        {
                            throw new UnknownSolutionItemTypeException(projTypeGuid);
                        }
                    } catch (Exception cex) {
                        var e = UnwrapException(cex).First();

                        string unsupportedMessage = e.Message;

                        if (e is UserException)
                        {
                            var ex = (UserException)e;
                            LoggingService.LogError("{0}: {1}", ex.Message, ex.Details);
                            monitor.ReportError(string.Format("{0}{1}{1}{2}", ex.Message, Environment.NewLine, ex.Details), null);
                        }
                        else
                        {
                            LoggingService.LogError(string.Format("Error while trying to load the project {0}", projectPath), e);
                            monitor.ReportWarning(GettextCatalog.GetString(
                                                      "Error while trying to load the project '{0}': {1}", projectPath, e.Message));
                        }

                        SolutionItem uitem;
                        uitem = new UnknownSolutionItem()
                        {
                            FileName  = projectPath,
                            LoadError = unsupportedMessage,
                        };
                        item          = uitem;
                        item.ItemId   = projectGuid;
                        item.TypeGuid = projTypeGuid;
                    }

                    item.UnresolvedProjectDependencies = ReadSolutionItemDependencies(sec);

                    // Deserialize the object
                    DeserializeSolutionItem(monitor, sol, item, sec);

                    lock (items) {
                        if (!items.ContainsKey(projectGuid))
                        {
                            items.Add(projectGuid, item);
                        }
                        else
                        {
                            monitor.ReportError(GettextCatalog.GetString("Invalid solution file. There are two projects with the same GUID. The project {0} will be ignored.", projectPath), null);
                        }
                    }
                    monitor.Step(1);
                });
                loadTasks.Add(ft);
            }

            Task.WaitAll(loadTasks.ToArray());

            sol.LoadedProjects = new HashSet <string> (items.Keys);

            var nested = sln.Sections.GetSection("NestedProjects");

            if (nested != null)
            {
                LoadNestedProjects(nested, items, monitor);
            }

            // Resolve project dependencies
            foreach (var it in items.Values.OfType <SolutionItem> ())
            {
                if (it.UnresolvedProjectDependencies != null)
                {
                    foreach (var id in it.UnresolvedProjectDependencies.ToArray())
                    {
                        SolutionFolderItem dep;
                        if (items.TryGetValue(id, out dep) && dep is SolutionItem)
                        {
                            it.UnresolvedProjectDependencies.Remove(id);
                            it.ItemDependencies.Add((SolutionItem)dep);
                        }
                    }
                    if (it.UnresolvedProjectDependencies.Count == 0)
                    {
                        it.UnresolvedProjectDependencies = null;
                    }
                }
            }

            //Add top level folders and projects to the main folder
            foreach (string id in sortedList)
            {
                SolutionFolderItem ce;
                if (items.TryGetValue(id, out ce) && ce.ParentFolder == null)
                {
                    folder.Items.Add(ce);
                }
            }

            //FIXME: This can be just SolutionConfiguration also!
            LoadSolutionConfigurations(sln.SolutionConfigurationsSection, sol, monitor);

            LoadProjectConfigurationMappings(sln.ProjectConfigurationsSection, sol, items, monitor);

            foreach (var e in sln.Sections)
            {
                string name = e.Id;
                if (name.StartsWith("MonoDevelopProperties."))
                {
                    int i = name.IndexOf('.');
                    LoadMonoDevelopConfigurationProperties(name.Substring(i + 1), e, sol, monitor);
                }
            }

            monitor.EndTask();
        }
Esempio n. 26
0
        public static void Initialize(ProgressMonitor monitor)
        {
            // Already done in IdeSetup, but called again since unit tests don't use IdeSetup.
            DispatchService.Initialize();

            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();

            commandService.CommandTargetScanStarted  += CommandServiceCommandTargetScanStarted;
            commandService.CommandTargetScanFinished += CommandServiceCommandTargetScanFinished;
            commandService.KeyBindingFailed          += KeyBindingFailed;

            KeyBindingService.LoadBindingsFromExtensionPath("/MonoDevelop/Ide/KeyBindingSchemes");
            KeyBindingService.LoadCurrentBindings("MD2");

            commandService.CommandError += delegate(object sender, CommandErrorArgs args) {
                LoggingService.LogInternalError(args.ErrorMessage, args.Exception);
            };

            FileService.ErrorHandler = FileServiceErrorHandler;

            monitor.BeginTask(GettextCatalog.GetString("Loading Workbench"), 6);
            Counters.Initialization.Trace("Loading Commands");

            commandService.LoadCommands("/MonoDevelop/Ide/Commands");
            monitor.Step(1);

            // Before startup commands.
            Counters.Initialization.Trace("Running Pre-Startup Commands");
            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/PreStartupHandlers", OnExtensionChanged);
            monitor.Step(1);

            Counters.Initialization.Trace("Initializing Workbench");
            workbench.Initialize(monitor);
            monitor.Step(1);

            MonoDevelop.Ide.WelcomePage.WelcomePageService.Initialize();
            MonoDevelop.Ide.WelcomePage.WelcomePageService.ShowWelcomePage();

            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;
            Xwt.MessageDialog.RootWindow = Xwt.Toolkit.CurrentEngine.WrapWindow(workbench.RootWindow);

            commandService.EnableIdleUpdate = true;

            if (Customizer != null)
            {
                Customizer.OnIdeInitialized();
            }

            // 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", BuildInfo.Version);
                PropertyService.Set("MonoDevelop.Core.LastRunRevision", 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", BuildInfo.Version);
                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);
                initializedEvent = null;
            }

            //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.EnableInstrumentation.Changed += delegate {
                UpdateInstrumentationIcon();
            };
            AutoTestService.Start(commandService, Preferences.EnableAutomatedTesting);
            AutoTestService.NotifyEvent("MonoDevelop.Ide.IdeStart");

            Gtk.LinkButton.SetUriHook((button, uri) => Xwt.Desktop.OpenUrl(uri));
        }
Esempio n. 27
0
        public object ReadFile(FilePath fileName, bool hasParentSolution, ProgressMonitor monitor)
        {
            FilePath     basePath = fileName.ParentDirectory;
            MonoMakefile mkfile   = new MonoMakefile(fileName);
            string       aname    = mkfile.GetVariable("LIBRARY");

            if (aname == null)
            {
                aname = mkfile.GetVariable("PROGRAM");
            }

            if (!string.IsNullOrEmpty(aname))
            {
                monitor.BeginTask("Loading '" + fileName + "'", 0);
                var project = Services.ProjectService.CreateProject("C#");
                project.FileName = fileName;

                var ext = new MonoMakefileProjectExtension();
                project.AttachExtension(ext);
                ext.Read(mkfile);

                monitor.EndTask();
                return(project);
            }

            string        subdirs;
            StringBuilder subdirsBuilder = new StringBuilder();

            subdirsBuilder.Append(mkfile.GetVariable("common_dirs"));
            if (subdirsBuilder.Length != 0)
            {
                subdirsBuilder.Append("\t");
                subdirsBuilder.Append(mkfile.GetVariable("net_2_0_dirs"));
            }
            if (subdirsBuilder.Length == 0)
            {
                subdirsBuilder.Append(mkfile.GetVariable("SUBDIRS"));
            }

            subdirs = subdirsBuilder.ToString();
            if (subdirs != null && (subdirs = subdirs.Trim(' ', '\t')) != "")
            {
                object         retObject;
                SolutionFolder folder;
                if (!hasParentSolution)
                {
                    Solution sol = new Solution();
                    sol.AttachExtension(new MonoMakefileSolutionExtension());
                    sol.FileName = fileName;
                    folder       = sol.RootFolder;
                    retObject    = sol;

                    foreach (string conf in MonoMakefile.MonoConfigurations)
                    {
                        SolutionConfiguration sc = new SolutionConfiguration(conf);
                        sol.Configurations.Add(sc);
                    }
                }
                else
                {
                    folder      = new SolutionFolder();
                    folder.Name = Path.GetFileName(Path.GetDirectoryName(fileName));
                    retObject   = folder;
                }

                subdirs = subdirs.Replace('\t', ' ');
                string[] dirs = subdirs.Split(' ');

                monitor.BeginTask("Loading '" + fileName + "'", dirs.Length);
                HashSet <string> added = new HashSet <string> ();
                foreach (string dir in dirs)
                {
                    if (!added.Add(dir))
                    {
                        continue;
                    }
                    monitor.Step(1);
                    if (dir == null)
                    {
                        continue;
                    }
                    string tdir = dir.Trim();
                    if (tdir == "")
                    {
                        continue;
                    }
                    string mfile = Path.Combine(Path.Combine(basePath, tdir), "Makefile");
                    if (File.Exists(mfile) && CanRead(mfile, typeof(SolutionItem)))
                    {
                        SolutionFolderItem it = (SolutionFolderItem)ReadFile(mfile, true, monitor);
                        folder.Items.Add(it);
                    }
                }
                monitor.EndTask();
                return(retObject);
            }
            return(null);
        }
Esempio n. 28
0
        public void UpdateTranslations(ProgressMonitor monitor, params Translation[] translations)
        {
            monitor.BeginTask(null, Translations.Count + 1);

            try {
                List <Project> projects = new List <Project> ();
                foreach (Project p in ParentSolution.GetAllProjects())
                {
                    if (IsIncluded(p))
                    {
                        projects.Add(p);
                    }
                }
                monitor.BeginTask(GettextCatalog.GetString("Updating message catalog"), projects.Count);
                CreateDefaultCatalog(monitor);
                monitor.Log.WriteLine(GettextCatalog.GetString("Done"));
            } finally {
                monitor.EndTask();
                monitor.Step(1);
            }
            if (monitor.CancellationToken.IsCancellationRequested)
            {
                monitor.Log.WriteLine(GettextCatalog.GetString("Operation cancelled."));
                return;
            }

            Dictionary <string, bool> isIncluded = new Dictionary <string, bool> ();

            foreach (Translation translation in translations)
            {
                isIncluded[translation.IsoCode] = true;
            }
            foreach (Translation translation in this.Translations)
            {
                if (!isIncluded.ContainsKey(translation.IsoCode))
                {
                    continue;
                }
                string poFileName = translation.PoFile;
                monitor.BeginTask(GettextCatalog.GetString("Updating {0}", translation.PoFile), 1);
                try {
                    var pb = new ProcessArgumentBuilder();
                    pb.Add("-U");
                    pb.AddQuoted(poFileName);
                    pb.Add("-v");
                    pb.AddQuoted(this.BaseDirectory.Combine("messages.po"));

                    var process = Runtime.ProcessService.StartProcess(Translation.GetTool("msgmerge"),
                                                                      pb.ToString(), this.BaseDirectory, monitor.Log, monitor.Log, null);
                    process.WaitForOutput();
                }
                catch (System.ComponentModel.Win32Exception) {
                    var msg = GettextCatalog.GetString("Did not find msgmerge. Please ensure that gettext tools are installed.");
                    monitor.ReportError(msg, null);
                }
                catch (Exception ex) {
                    monitor.ReportError(GettextCatalog.GetString("Could not update file {0}", translation.PoFile), ex);
                }
                finally {
                    monitor.EndTask();
                    monitor.Step(1);
                }
                if (monitor.CancellationToken.IsCancellationRequested)
                {
                    monitor.Log.WriteLine(GettextCatalog.GetString("Operation cancelled."));
                    return;
                }
            }
        }
Esempio n. 29
0
        public static void TransferFiles(
            ProgressMonitor monitor,
            FilePath sourcePath,
            FilePath targetPath,
            bool removeFromSource)
        {
            // When transfering directories, targetPath is the directory where the source
            // directory will be transfered, including the destination directory or file name.
            // For example, if sourcePath is /a1/a2/a3 and targetPath is /b1/b2, the
            // new folder or file will be /b1/b2
            bool sourceIsFolder = Directory.Exists(sourcePath);

            bool movingFolder = removeFromSource && sourceIsFolder;

            // We need to remove all files + directories from the source project
            // but when dealing with the VCS addins we need to process only the
            // files so we do not create a 'file' in the VCS which corresponds
            // to a directory in the project and blow things up.
            var filesToRemove = new List <SystemFile> ();

            try {
                GetAllFilesRecursive(sourcePath, filesToRemove);
            } catch (Exception ex) {
                monitor.ReportError(GettextCatalog.GetString("Could not get any file from '{0}'.", sourcePath), ex);
                return;
            }

            // Strip out all the directories to leave us with just the files.
            List <SystemFile> filesToMove = filesToRemove.Where(f => !Directory.Exists(f.Path)).ToList();

            // Ensure that the destination folder is created, even if no files
            // are copied

            try {
                if (sourceIsFolder && !Directory.Exists(targetPath) && !movingFolder)
                {
                    FileService.CreateDirectory(targetPath);
                }
            } catch (Exception ex) {
                monitor.ReportError(GettextCatalog.GetString("Could not create directory '{0}'.", targetPath), ex);
                return;
            }

            // Transfer files
            // If moving a folder, do it all at once

            if (movingFolder)
            {
                try {
                    FileService.MoveDirectory(sourcePath, targetPath);
                } catch (Exception ex) {
                    monitor.ReportError(GettextCatalog.GetString("Directory '{0}' could not be moved.", sourcePath), ex);
                    return;
                }
            }

            if (removeFromSource)
            {
                monitor.BeginTask(GettextCatalog.GetString("Moving files..."), filesToMove.Count);
            }
            else
            {
                monitor.BeginTask(GettextCatalog.GetString("Copying files..."), filesToMove.Count);
            }

            foreach (SystemFile file in filesToMove)
            {
                var      sourceFile = file.Path;
                FilePath newFile;
                if (sourceIsFolder)
                {
                    newFile = targetPath.Combine(sourceFile.ToRelative(sourcePath));
                }
                else if (sourceFile == sourcePath)
                {
                    newFile = targetPath;
                }
                else if (sourceFile.ParentDirectory != targetPath.ParentDirectory)
                {
                    newFile = targetPath.ParentDirectory.Combine(sourceFile.ToRelative(sourcePath.ParentDirectory));
                }
                else
                {
                    newFile = GetTargetCopyName(sourceFile, false);
                }

                if (!movingFolder)
                {
                    try {
                        FilePath fileDir = newFile.ParentDirectory;
                        if (!Directory.Exists(fileDir))
                        {
                            FileService.CreateDirectory(fileDir);
                        }
                        if (removeFromSource)
                        {
                            // File.Move() does not have an overwrite argument and will fail if the destFile path exists, however, the user
                            // has already chosen to overwrite the destination file.
                            if (File.Exists(newFile))
                            {
                                File.Delete(newFile);
                            }

                            FileService.MoveFile(sourceFile, newFile);
                        }
                        else
                        {
                            FileService.CopyFile(sourceFile, newFile);
                        }
                    } catch (Exception ex) {
                        if (removeFromSource)
                        {
                            monitor.ReportError(GettextCatalog.GetString("File '{0}' could not be moved.", sourceFile), ex);
                        }
                        else
                        {
                            monitor.ReportError(GettextCatalog.GetString("File '{0}' could not be copied.", sourceFile), ex);
                        }
                        monitor.Step(1);
                        continue;
                    }
                }

                monitor.Step(1);
            }

            monitor.EndTask();
        }
        public async Task <string> DownloadSampleAsync(ProgressMonitor progressMonitor = null)
        {
            try
            {
                string projectPath = string.Empty;

                if (!string.IsNullOrEmpty(SelectedSample.DownloadUrl))
                {
                    progressMonitor?.BeginTask("Downloading...", 1);

                    string zipProjectPath = Path.Combine(UserProfile.Current.TempDir, $"{SelectedSample.Name}.zip");
                    projectPath = Path.Combine(UserProfile.Current.TempDir, SelectedSample.Name);

                    if (!File.Exists(zipProjectPath))
                    {
                        await _sampleImporterService.DownloadSampleAsync(new Uri(SelectedSample.DownloadUrl), zipProjectPath);
                    }

                    progressMonitor?.Step();

                    if (!Directory.Exists(projectPath))
                    {
                        Directory.CreateDirectory(projectPath);
                        ZipFile.ExtractToDirectory(zipProjectPath, projectPath);
                    }

                    var solutions = Directory.GetFiles(projectPath, "*.sln", SearchOption.AllDirectories);
                    var solution  = solutions.FirstOrDefault();

                    if (!string.IsNullOrEmpty(solution))
                    {
                        projectPath = solution;
                    }
                }
                else
                {
                    var content = await _sampleImporterService.GetSampleContentAsync(SelectedSample);

                    progressMonitor?.BeginTask("Downloading...", content.Count);

                    var folders = content.Where(c => c.Type == ContentType.Dir);

                    foreach (var folder in folders)
                    {
                        string directoryPath = Path.Combine(_projectsPath, folder.Path);

                        if (!Directory.Exists(directoryPath))
                        {
                            progressMonitor?.Step();
                            progressMonitor?.Log.WriteLine("Creating folder" + ": " + directoryPath);
                            Directory.CreateDirectory(directoryPath);
                        }
                    }

                    var files = content.Where(c => c.Type == ContentType.File);

                    foreach (var file in files)
                    {
                        string filePath = Path.Combine(_projectsPath, file.Path);
                        progressMonitor?.Step();
                        progressMonitor?.Log.WriteLine("Downloading file" + ": " + filePath);
                        await _downloaderService.DownloadFileAsync(file.DownloadUrl, filePath, CancellationToken.None);
                    }

                    var projectFile = files.FirstOrDefault(c => c.Path.EndsWith(".sln", StringComparison.InvariantCultureIgnoreCase));

                    if (projectFile != null)
                    {
                        projectPath = Path.Combine(_projectsPath, projectFile.Path);
                    }
                }

                return(projectPath);
            }
            catch (Exception ex)
            {
                LoggingService.LogError(ex.Message);

                return(string.Empty);
            }
        }