Esempio n. 1
0
 public static IEnumerable<MissingDepInfo> GetMissingDependencies(Addin addin)
 {
     IEnumerable<Addin> allAddins = AddinManager.Registry.GetAddins ().Union (AddinManager.Registry.GetAddinRoots ());
     foreach (var dep in addin.Description.MainModule.Dependencies) {
         AddinDependency adep = dep as AddinDependency;
         if (adep != null) {
             if (!allAddins.Any (a => Addin.GetIdName (a.Id) == Addin.GetIdName (adep.FullAddinId) &&  a.SupportsVersion (adep.Version))) {
                 Addin found = allAddins.FirstOrDefault (a => Addin.GetIdName (a.Id) == Addin.GetIdName (adep.FullAddinId));
                 yield return new MissingDepInfo () { Addin = Addin.GetIdName (adep.FullAddinId), Required = adep.Version, Found = found != null ? found.Version : null };
             }
         }
     }
 }
Esempio n. 2
0
		public void InitForUninstall (Addin[] info)
		{
			this.uninstallIds = info.Select (a => a.Id);
			buttonOk.Label = Catalog.GetString ("Uninstall");
			
			HashSet<Addin> sinfos = new HashSet<Addin> ();
			
			StringBuilder sb = new StringBuilder ();
			sb.Append ("<b>").Append (Catalog.GetString ("The following packages will be uninstalled:")).Append ("</b>\n\n");
			foreach (var a in info) {
				sb.Append (a.Name + "\n\n");
				sinfos.UnionWith (service.GetDependentAddins (a.Id, true));
			}
			
			if (sinfos.Count > 0) {
				sb.Append ("<b>").Append (Catalog.GetString ("There are other add-ins that depend on the previous ones which will also be uninstalled:")).Append ("</b>\n\n");
				foreach (Addin si in sinfos)
					sb.Append (si.Description.Name + "\n");
			}
			
			ShowMessage (sb.ToString ());
			Services.PlaceDialog (this, TransientFor);
		}
Esempio n. 3
0
 public ITextEditorResolverProvider CreateResolver()
 {
     return((ITextEditorResolverProvider)Addin.CreateInstance(className, true));
 }
Esempio n. 4
0
 public AddinResourceDomain(string domainName)
     : base(domainName)
 {
     m_addin = Addin.LoadFrom(domainName);
 }
Esempio n. 5
0
        string BuildPackageInternal(IProgressStatus monitor, bool debugSymbols, string targetDirectory, string filePath, PackageFormat format)
        {
            AddinDescription conf = registry.GetAddinDescription(monitor, filePath);

            if (conf == null)
            {
                monitor.ReportError("Could not read add-in file: " + filePath, null);
                return(null);
            }

            string basePath = Path.GetDirectoryName(Path.GetFullPath(filePath));

            if (targetDirectory == null)
            {
                targetDirectory = basePath;
            }

            // Generate the file name

            string name;

            if (conf.LocalId.Length == 0)
            {
                name = Path.GetFileNameWithoutExtension(filePath);
            }
            else
            {
                name = conf.LocalId;
            }
            name = Addin.GetFullId(conf.Namespace, name, conf.Version);
            name = name.Replace(',', '_').Replace(".__", ".");

            string outFilePath = Path.Combine(targetDirectory, name);

            switch (format)
            {
            case PackageFormat.Mpack:
                outFilePath += ".mpack";
                break;

            case PackageFormat.Vsix:
                outFilePath += ".vsix";
                break;

            default:
                throw new NotSupportedException(format.ToString());
            }

            ZipOutputStream s = new ZipOutputStream(File.Create(outFilePath));

            s.SetLevel(5);

            if (format == PackageFormat.Vsix)
            {
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = false;
                doc.LoadXml(conf.SaveToVsixXml().OuterXml);
                MemoryStream  ms = new MemoryStream();
                XmlTextWriter tw = new XmlTextWriter(ms, System.Text.Encoding.UTF8);
                tw.Formatting = Formatting.Indented;
                doc.WriteTo(tw);
                tw.Flush();
                byte [] data = ms.ToArray();

                var infoEntry = new ZipEntry("extension.vsixmanifest")
                {
                    Size = data.Length
                };
                s.PutNextEntry(infoEntry);
                s.Write(data, 0, data.Length);
                s.CloseEntry();
            }

            // Generate a stripped down description of the add-in in a file, since the complete
            // description may be declared as assembly attributes

            if (format == PackageFormat.Mpack || format == PackageFormat.Vsix)
            {
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = false;
                doc.LoadXml(conf.SaveToXml().OuterXml);
                CleanDescription(doc.DocumentElement);
                MemoryStream  ms = new MemoryStream();
                XmlTextWriter tw = new XmlTextWriter(ms, System.Text.Encoding.UTF8);
                tw.Formatting = Formatting.Indented;
                doc.WriteTo(tw);
                tw.Flush();
                byte [] data = ms.ToArray();

                var infoEntry = new ZipEntry("addin.info")
                {
                    Size = data.Length
                };
                s.PutNextEntry(infoEntry);
                s.Write(data, 0, data.Length);
                s.CloseEntry();
            }

            // Now add the add-in files

            var files = new HashSet <string> ();

            files.Add(Path.GetFileName(Util.NormalizePath(filePath)));

            foreach (string f in conf.AllFiles)
            {
                var file = Util.NormalizePath(f);
                files.Add(file);
                if (debugSymbols)
                {
                    if (File.Exists(Path.ChangeExtension(file, ".pdb")))
                    {
                        files.Add(Path.ChangeExtension(file, ".pdb"));
                    }
                    else if (File.Exists(file + ".mdb"))
                    {
                        files.Add(file + ".mdb");
                    }
                }
            }

            foreach (var prop in conf.Properties)
            {
                try {
                    var file = Util.NormalizePath(prop.Value);
                    if (File.Exists(Path.Combine(basePath, file)))
                    {
                        files.Add(file);
                    }
                } catch {
                    // Ignore errors
                }
            }

            //add satellite assemblies for assemblies in the list
            var satelliteFinder = new SatelliteAssemblyFinder();

            foreach (var f in files.ToList())
            {
                foreach (var satellite in satelliteFinder.FindSatellites(Path.Combine(basePath, f)))
                {
                    var relativeSatellite = satellite.Substring(basePath.Length + 1);
                    files.Add(relativeSatellite);
                }
            }

            monitor.Log("Creating package " + Path.GetFileName(outFilePath));

            foreach (string file in files)
            {
                string fp = Path.Combine(basePath, file);
                using (FileStream fs = File.OpenRead(fp)) {
                    byte[] buffer = new byte [fs.Length];
                    fs.Read(buffer, 0, buffer.Length);

                    var fileName = Path.DirectorySeparatorChar == '\\' ? file.Replace('\\', '/') : file;
                    var entry    = new ZipEntry(fileName)
                    {
                        Size = fs.Length
                    };
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                    s.CloseEntry();
                }
            }

            if (format == PackageFormat.Vsix)
            {
                files.Add("addin.info");
                files.Add("extension.vsixmanifest");
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = false;
                XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
                XmlElement     root           = doc.DocumentElement;
                doc.InsertBefore(xmlDeclaration, root);
                HashSet <string> alreadyAddedExtensions = new HashSet <string> ();
                var typesEl = doc.CreateElement("Types");
                typesEl.SetAttribute("xmlns", "http://schemas.openxmlformats.org/package/2006/content-types");
                foreach (var file in files)
                {
                    var extension = Path.GetExtension(file);
                    if (string.IsNullOrEmpty(extension))
                    {
                        continue;
                    }
                    if (extension.StartsWith(".", StringComparison.Ordinal))
                    {
                        extension = extension.Substring(1);
                    }
                    if (alreadyAddedExtensions.Contains(extension))
                    {
                        continue;
                    }
                    alreadyAddedExtensions.Add(extension);
                    var typeEl = doc.CreateElement("Default");
                    typeEl.SetAttribute("Extension", extension);
                    typeEl.SetAttribute("ContentType", GetContentType(extension));
                    typesEl.AppendChild(typeEl);
                }
                doc.AppendChild(typesEl);
                MemoryStream  ms = new MemoryStream();
                XmlTextWriter tw = new XmlTextWriter(ms, System.Text.Encoding.UTF8);
                tw.Formatting = Formatting.Indented;
                doc.WriteTo(tw);
                tw.Flush();
                byte [] data = ms.ToArray();

                var infoEntry = new ZipEntry("[Content_Types].xml")
                {
                    Size = data.Length
                };
                s.PutNextEntry(infoEntry);
                s.Write(data, 0, data.Length);
                s.CloseEntry();
            }

            s.Finish();
            s.Close();
            return(outFilePath);
        }
Esempio n. 6
0
                #pragma warning restore 649

        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(KeyBindingManager.FixChordSeparators).ToArray();
            }

            cmd.DisabledVisible = disabledVisible;

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

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

            return(cmd);
        }
        public AddinRepositoryEntry GetUpdate(Addin a)
        {
            AddinRepositoryEntry[] updates = service.Repositories.GetAvailableAddinUpdates(Addin.GetIdName(a.Id));
            AddinRepositoryEntry   best    = null;
            string bestVersion             = a.Version;

            foreach (AddinRepositoryEntry e in updates)
            {
                if (Addin.CompareVersions(bestVersion, e.Addin.Version) > 0)
                {
                    best        = e;
                    bestVersion = e.Addin.Version;
                }
            }
            return(best);
        }
        public static IEnumerable <MissingDepInfo> GetMissingDependencies(Addin addin)
        {
            IEnumerable <Addin> allAddins = AddinManager.Registry.GetAddins().Union(AddinManager.Registry.GetAddinRoots());

            foreach (var dep in addin.Description.MainModule.Dependencies)
            {
                AddinDependency adep = dep as AddinDependency;
                if (adep != null)
                {
                    if (!allAddins.Any(a => Addin.GetIdName(a.Id) == Addin.GetIdName(adep.FullAddinId) && a.SupportsVersion(adep.Version)))
                    {
                        Addin found = allAddins.FirstOrDefault(a => Addin.GetIdName(a.Id) == Addin.GetIdName(adep.FullAddinId));
                        yield return(new MissingDepInfo()
                        {
                            Addin = Addin.GetIdName(adep.FullAddinId), Required = adep.Version, Found = found != null ? found.Version : null
                        });
                    }
                }
            }
        }
Esempio n. 9
0
 bool IsHidden(Addin ainfo)
 {
     return(service.ApplicationNamespace != null && !(ainfo.Namespace + ".").StartsWith(service.ApplicationNamespace + ".") || ainfo.Description.IsHidden);
 }
		public Addin GetAddinForHostAssembly (string assemblyLocation)
		{
			InternalCheck ();
			Addin ainfo = null;
			
			object ob = cachedAddinSetupInfos [assemblyLocation];
			if (ob != null) {
				ainfo = ob as Addin;
				if (ainfo != null)
					return ainfo;
				else
					return null;
			}

			AddinHostIndex index = GetAddinHostIndex ();
			string addin, addinFile;
			if (index.GetAddinForAssembly (assemblyLocation, out addin, out addinFile)) {
				ainfo = new Addin (this, addin, addinFile);
				cachedAddinSetupInfos [assemblyLocation] = ainfo;
			}
			
			return ainfo;
		}
 internal bool SupportsVersion(string ver)
 {
     return(Addin.CompareVersions(ver, Version) >= 0 &&
            (CompatVersion.Length == 0 || Addin.CompareVersions(ver, CompatVersion) <= 0));
 }
Esempio n. 12
0
        void LoadGallery()
        {
            object s = galleryTree.SaveStatus();

            galleryTree.Clear();

            string rep = GetRepoSelection();

            AddinRepositoryEntry[] reps;
            if (rep == AllRepoMarker)
            {
                reps = service.Repositories.GetAvailableAddins(RepositorySearchFlags.LatestVersionsOnly);
            }
            else
            {
                reps = service.Repositories.GetAvailableAddins(rep, RepositorySearchFlags.LatestVersionsOnly);
            }

            int count = 0;

            foreach (AddinRepositoryEntry arep in reps)
            {
                if (!Services.InApplicationNamespace(service, arep.Addin.Id))
                {
                    continue;
                }

                if (IsFiltered(arep.Addin))
                {
                    continue;
                }

                AddinStatus status = AddinStatus.NotInstalled;

                // Find whatever version is installed
                Addin sinfo = AddinManager.Registry.GetAddin(Addin.GetIdName(arep.Addin.Id));

                if (sinfo != null)
                {
                    status |= AddinStatus.Installed;
                    if (!sinfo.Enabled || Services.GetMissingDependencies(sinfo).Any())
                    {
                        status |= AddinStatus.Disabled;
                    }
                    if (Addin.CompareVersions(sinfo.Version, arep.Addin.Version) > 0)
                    {
                        status |= AddinStatus.HasUpdate;
                    }
                }
                galleryTree.AddAddin(arep.Addin, arep, status);
                count++;
            }

            if (count > 0)
            {
                galleryTree.RestoreStatus(s);
            }
            else
            {
                galleryTree.ShowEmptyMessage();
            }

            galleryTabLabel.Text = Catalog.GetString("Gallery");

            if (filterEntry.Text.Length != 0 && count > 0)
            {
                galleryTabLabel.Text += " (" + count + ")";
            }
        }
Esempio n. 13
0
 public void Initialize()
 {
     service = Addin.CreateInstance(class_name) as IService;
 }
Esempio n. 14
0
        internal bool ResolveDependencies(IProgressMonitor monitor, PackageCollection packages, out PackageCollection toUninstall, out DependencyCollection unresolved)
        {
            PackageCollection requested = new PackageCollection();

            requested.AddRange(packages);

            unresolved  = new DependencyCollection();
            toUninstall = new PackageCollection();
            PackageCollection installedRequired = new PackageCollection();

            for (int n = 0; n < packages.Count; n++)
            {
                Package p = packages [n];
                p.Resolve(monitor, this, packages, toUninstall, installedRequired, unresolved);
            }

            if (unresolved.Count != 0)
            {
                foreach (Dependency dep in unresolved)
                {
                    monitor.ReportError(string.Format("The package '{0}' could not be found in any repository", dep.Name), null);
                }
                return(false);
            }

            // Check that we are not uninstalling packages that are required
            // by packages being installed.

            foreach (Package p in installedRequired)
            {
                if (toUninstall.Contains(p))
                {
                    // Only accept to uninstall this package if we are
                    // going to install a newer version.
                    bool foundUpgrade = false;
                    foreach (Package tbi in packages)
                    {
                        if (tbi.Equals(p) || tbi.IsUpgradeOf(p))
                        {
                            foundUpgrade = true;
                            break;
                        }
                    }
                    if (!foundUpgrade)
                    {
                        return(false);
                    }
                }
            }

            // Check that we are not trying to uninstall from a directory from
            // which we don't have write permissions

            foreach (Package p in toUninstall)
            {
                AddinPackage ap = p as AddinPackage;
                if (ap != null)
                {
                    Addin ia = service.Registry.GetAddin(ap.Addin.Id);
                    if (File.Exists(ia.AddinFile) && !HasWriteAccess(ia.AddinFile) && IsUserAddin(ia.AddinFile))
                    {
                        monitor.ReportError(GetUninstallErrorNoRoot(ap.Addin), null);
                        return(false);
                    }
                }
            }

            // Check that we are not installing two versions of the same addin

            PackageCollection resolved = new PackageCollection();

            resolved.AddRange(packages);

            bool error = false;

            for (int n = 0; n < packages.Count; n++)
            {
                AddinPackage ap = packages [n] as AddinPackage;
                if (ap == null)
                {
                    continue;
                }

                for (int k = n + 1; k < packages.Count; k++)
                {
                    AddinPackage otherap = packages [k] as AddinPackage;
                    if (otherap == null)
                    {
                        continue;
                    }

                    if (ap.Addin.Id == otherap.Addin.Id)
                    {
                        if (ap.IsUpgradeOf(otherap))
                        {
                            if (requested.Contains(otherap))
                            {
                                monitor.ReportError("Can't install two versions of the same add-in: '" + ap.Addin.Name + "'.", null);
                                error = true;
                            }
                            else
                            {
                                packages.RemoveAt(k);
                            }
                        }
                        else if (otherap.IsUpgradeOf(ap))
                        {
                            if (requested.Contains(ap))
                            {
                                monitor.ReportError("Can't install two versions of the same add-in: '" + ap.Addin.Name + "'.", null);
                                error = true;
                            }
                            else
                            {
                                packages.RemoveAt(n);
                                n--;
                            }
                        }
                        else
                        {
                            error = true;
                            monitor.ReportError("Can't install two versions of the same add-in: '" + ap.Addin.Name + "'.", null);
                        }
                        break;
                    }
                }
            }

            // Don't allow installing add-ins which are scheduled for uninstall

            foreach (Package p in packages)
            {
                AddinPackage ap = p as AddinPackage;
                if (ap != null && Registry.IsRegisteredForUninstall(ap.Addin.Id))
                {
                    error = true;
                    monitor.ReportError("The addin " + ap.Addin.Name + " v" + ap.Addin.Version + " is scheduled for uninstallation. Please restart the application before trying to re-install it.", null);
                }
            }

            return(!error);
        }
Esempio n. 15
0
        public void Uninstall(IProgressStatus statusMonitor, IEnumerable <string> ids)
        {
            IProgressMonitor monitor = ProgressStatusMonitor.GetProgressMonitor(statusMonitor);

            monitor.BeginTask("Uninstalling add-ins", ids.Count());

            foreach (string id in ids)
            {
                bool      rollback          = false;
                ArrayList toUninstall       = new ArrayList();
                ArrayList uninstallPrepared = new ArrayList();

                Addin ia = service.Registry.GetAddin(id);
                if (ia == null)
                {
                    throw new InstallException("The add-in '" + id + "' is not installed.");
                }

                toUninstall.Add(AddinPackage.FromInstalledAddin(ia));

                Addin[] deps = GetDependentAddins(id, true);
                foreach (Addin dep in deps)
                {
                    toUninstall.Add(AddinPackage.FromInstalledAddin(dep));
                }

                monitor.BeginTask("Deleting files", toUninstall.Count * 2 + uninstallPrepared.Count + 1);

                // Prepare install

                foreach (Package mpack in toUninstall)
                {
                    try {
                        mpack.PrepareUninstall(monitor, this);
                        monitor.Step(1);
                        uninstallPrepared.Add(mpack);
                    } catch (Exception ex) {
                        ReportException(monitor, ex);
                        rollback = true;
                        break;
                    }
                }

                // Commit install

                if (!rollback)
                {
                    foreach (Package mpack in toUninstall)
                    {
                        try {
                            mpack.CommitUninstall(monitor, this);
                            monitor.Step(1);
                        } catch (Exception ex) {
                            ReportException(monitor, ex);
                            rollback = true;
                            break;
                        }
                    }
                }

                // Rollback if failed

                if (rollback)
                {
                    monitor.BeginTask("Rolling back uninstall", uninstallPrepared.Count);
                    foreach (Package mpack in uninstallPrepared)
                    {
                        try {
                            mpack.RollbackUninstall(monitor, this);
                        } catch (Exception ex) {
                            ReportException(monitor, ex);
                        }
                    }
                    monitor.EndTask();
                }
                monitor.Step(1);

                // Cleanup

                foreach (Package mpack in uninstallPrepared)
                {
                    try {
                        mpack.EndUninstall(monitor, this);
                        monitor.Step(1);
                    } catch (Exception ex) {
                        monitor.Log.WriteLine(ex);
                    }
                }

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

            // Update the extension maps
            service.Registry.Update(statusMonitor);

            monitor.EndTask();

            service.SaveConfiguration();
            ResetCachedData();
        }
Esempio n. 16
0
 public ImageContainer(Addin addin, string fileName)
     : this()
 {
     string path = System.IO.Path.Combine (addin.Description.BasePath, fileName);
     LoadImage (File.OpenRead (path));
 }
Esempio n. 17
0
        void PrintAddinInfo(string[] args)
        {
            bool generateXml    = false;
            bool generateAll    = false;
            bool pickNamespace  = false;
            bool extensionModel = true;

            ArrayList addins     = new ArrayList();
            ArrayList namespaces = new ArrayList();

            foreach (string a in args)
            {
                if (pickNamespace)
                {
                    namespaces.Add(a);
                    pickNamespace = false;
                    continue;
                }
                if (a == "--xml")
                {
                    generateXml = true;
                    continue;
                }
                if (a == "--namespace" || a == "-n")
                {
                    pickNamespace = true;
                    continue;
                }
                if (a == "--all")
                {
                    generateAll = true;
                    continue;
                }
                if (a == "--full")
                {
                    extensionModel = false;
                    continue;
                }
                AddinDescription desc = null;
                if (File.Exists(args[0]))
                {
                    desc = registry.GetAddinDescription(new Mono.Addins.ConsoleProgressStatus(verbose), args[0]);
                }
                else
                {
                    Addin addin = registry.GetAddin(args [0]);
                    if (addin != null)
                    {
                        desc = addin.Description;
                    }
                }
                if (desc == null)
                {
                    throw new InstallException(string.Format("Add-in '{0}' not found.", a));
                }
                if (desc != null)
                {
                    addins.Add(desc);
                }
            }

            if (generateAll)
            {
                ArrayList list = new ArrayList();
                list.AddRange(registry.GetAddinRoots());
                list.AddRange(registry.GetAddins());
                foreach (Addin addin in list)
                {
                    if (namespaces.Count > 0)
                    {
                        foreach (string ns in namespaces)
                        {
                            if (addin.Id.StartsWith(ns + "."))
                            {
                                addins.Add(addin.Description);
                                break;
                            }
                        }
                    }
                    else
                    {
                        addins.Add(addin.Description);
                    }
                }
            }

            if (addins.Count == 0)
            {
                throw new InstallException("A file name or add-in ID is required.");
            }


            if (generateXml)
            {
                XmlTextWriter tw = new XmlTextWriter(Console.Out);
                tw.Formatting = Formatting.Indented;
                tw.WriteStartElement("Addins");
                foreach (AddinDescription desc in addins)
                {
                    if (extensionModel && desc.ExtensionPoints.Count == 0)
                    {
                        continue;
                    }
                    PrintAddinXml(tw, desc);
                }
                tw.Close();
            }
            else
            {
                foreach (AddinDescription des in addins)
                {
                    PrintAddin(des);
                }
            }
        }
Esempio n. 18
0
        public Addin GetAddinForHostAssembly(string domain, string assemblyLocation)
        {
            InternalCheck (domain);
            Addin ainfo = null;

            object ob = cachedAddinSetupInfos [assemblyLocation];
            if (ob != null)
                return ob as Addin; // Don't use a cast here is ob may not be an Addin.

            AddinHostIndex index = GetAddinHostIndex ();
            string addin, addinFile, rdomain;
            if (index.GetAddinForAssembly (assemblyLocation, out addin, out addinFile, out rdomain)) {
                string sid = addin + " " + rdomain;
                ainfo = cachedAddinSetupInfos [sid] as Addin;
                if (ainfo == null)
                    ainfo = new Addin (this, rdomain, addin);
                cachedAddinSetupInfos [assemblyLocation] = ainfo;
                cachedAddinSetupInfos [addin + " " + rdomain] = ainfo;
            }

            return ainfo;
        }
Esempio n. 19
0
 protected virtual PadContent CreatePad()
 {
     Counters.PadsLoaded++;
     return((PadContent)Addin.CreateInstance(className, true));
 }
Esempio n. 20
0
        public void InitForUninstall(Addin[] info)
        {
            this.uninstallId = info[0].Id;
            buttonOk.Label = Catalog.GetString ("Uninstall");

            StringBuilder sb = new StringBuilder ();
            sb.Append ("<b>").Append (Catalog.GetString ("The following packages will be uninstalled:")).Append ("</b>\n\n");
            sb.Append (info[0].Name + "\n\n");

            Addin[] sinfos = service.GetDependentAddins (uninstallId, true);
            if (sinfos.Length > 0) {
                sb.Append ("<b>").Append (Catalog.GetString ("There are other add-ins that depend on the previous ones which will also be uninstalled:")).Append ("</b>\n\n");
                foreach (Addin si in sinfos)
                    sb.Append (si.Description.Name + "\n");
            }
            ShowMessage (sb.ToString ());
            Services.PlaceDialog (this, TransientFor);
        }
Esempio n. 21
0
        void IAddinInstaller.InstallAddins(AddinRegistry reg, string message, string[] addinIds)
        {
            if (logLevel > 0)
            {
                if (message != null && message.Length > 0)
                {
                    Console.WriteLine(message);
                }
                else
                {
                    Console.WriteLine("Additional extensions are required to perform this operation.");
                }
            }
            ArrayList    entries = new ArrayList();
            SetupService setup   = new SetupService(reg);
            string       idNotFound;

            do
            {
                idNotFound = null;
                foreach (string id in addinIds)
                {
                    string name    = Addin.GetIdName(id);
                    string version = Addin.GetIdVersion(id);
                    AddinRepositoryEntry[] ares = setup.Repositories.GetAvailableAddin(name, version);
                    if (ares.Length == 0)
                    {
                        idNotFound = id;
                        entries.Clear();
                        break;
                    }
                    else
                    {
                        entries.Add(ares[0]);
                    }
                }
                if (idNotFound != null)
                {
                    if (repoUpdated)
                    {
                        throw new InstallException("Extension '" + idNotFound + "' not found in the registered extension repositories");
                    }
                    if (prompt)
                    {
                        Console.WriteLine("The extension '" + idNotFound + "' could not be found in the registered repositories.");
                        Console.WriteLine("The repository indices may be outdated.");
                        if (!Confirm("Do you wan't to update them now?"))
                        {
                            throw new InstallException("Extension '" + idNotFound + "' not found in the registered extension repositories");
                        }
                    }
                    setup.Repositories.UpdateAllRepositories(new ConsoleProgressStatus(logLevel));
                    repoUpdated = true;
                }
            }while (idNotFound != null);

            if (logLevel > 0)
            {
                Console.WriteLine("The following extensions will be installed:");
                foreach (AddinRepositoryEntry addin in entries)
                {
                    Console.WriteLine(" - " + addin.Addin.Name + " v" + addin.Addin.Version);
                }

                if (prompt)
                {
                    if (!Confirm("Do you want to continue with the installation?"))
                    {
                        throw new InstallException("Installation cancelled");
                    }
                }
            }
            setup.Install(new ConsoleProgressStatus(logLevel), (AddinRepositoryEntry[])entries.ToArray(typeof(AddinRepositoryEntry)));
        }
        public ImageContainer(Addin addin, string fileName) : this()
        {
            string path = System.IO.Path.Combine(addin.Description.BasePath, fileName);

            LoadImage(File.OpenRead(path));
        }
Esempio n. 23
0
 public AddinStateChangedEventArgs(Addin addin, bool state)
 {
     Addin = addin;
     State = state;
 }
Esempio n. 24
0
        string BuildPackageInternal(IProgressStatus monitor, string targetDirectory, string filePath)
        {
            AddinDescription conf = registry.GetAddinDescription(monitor, filePath);

            if (conf == null)
            {
                monitor.ReportError("Could not read add-in file: " + filePath, null);
                return(null);
            }

            string basePath = Path.GetDirectoryName(filePath);

            if (targetDirectory == null)
            {
                targetDirectory = basePath;
            }

            // Generate the file name

            string name;

            if (conf.LocalId.Length == 0)
            {
                name = Path.GetFileNameWithoutExtension(filePath);
            }
            else
            {
                name = conf.LocalId;
            }
            name = Addin.GetFullId(conf.Namespace, name, conf.Version);
            name = name.Replace(',', '_').Replace(".__", ".");

            string outFilePath = Path.Combine(targetDirectory, name) + ".mpack";

            ZipOutputStream s = new ZipOutputStream(File.Create(outFilePath));

            s.SetLevel(5);

            // Generate a stripped down description of the add-in in a file, since the complete
            // description may be declared as assembly attributes

            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = false;
            doc.LoadXml(conf.SaveToXml().OuterXml);
            CleanDescription(doc.DocumentElement);
            MemoryStream  ms = new MemoryStream();
            XmlTextWriter tw = new XmlTextWriter(ms, System.Text.Encoding.UTF8);

            tw.Formatting = Formatting.Indented;
            doc.WriteTo(tw);
            tw.Flush();
            byte[] data = ms.ToArray();

            var infoEntry = new ZipEntry("addin.info")
            {
                Size = data.Length
            };

            s.PutNextEntry(infoEntry);
            s.Write(data, 0, data.Length);

            // Now add the add-in files

            ArrayList list = new ArrayList();

            if (!conf.AllFiles.Contains(Path.GetFileName(filePath)))
            {
                list.Add(Path.GetFileName(filePath));
            }
            foreach (string f in conf.AllFiles)
            {
                list.Add(Util.NormalizePath(f));
            }

            foreach (var prop in conf.Properties)
            {
                try {
                    var file = Util.NormalizePath(prop.Value);
                    if (File.Exists(Path.Combine(basePath, file)))
                    {
                        list.Add(file);
                    }
                } catch {
                    // Ignore errors
                }
            }

            monitor.Log("Creating package " + Path.GetFileName(outFilePath));

            foreach (string file in list)
            {
                string fp = Path.Combine(basePath, file);
                using (FileStream fs = File.OpenRead(fp)) {
                    byte[] buffer = new byte [fs.Length];
                    fs.Read(buffer, 0, buffer.Length);

                    var entry = new ZipEntry(file)
                    {
                        Size = fs.Length
                    };
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                }
            }

            s.Finish();
            s.Close();
            return(outFilePath);
        }
Esempio n. 25
0
 public ServiceDecorator(IService service, Addin addin)
 {
     this.addin   = addin;
     this.service = service;
 }
Esempio n. 26
0
 /// <summary>
 /// Gets information about an add-in
 /// </summary>
 /// <param name="addin">
 /// The add-in
 /// </param>
 /// <returns>
 /// Add-in header data
 /// </returns>
 public static AddinHeader GetAddinHeader(Addin addin)
 {
     return(AddinInfo.ReadFromDescription(addin.Description));
 }
Esempio n. 27
0
 public StreamReader GetStream()
 {
     return(new StreamReader(Addin.GetResource(resource, true)));
 }
Esempio n. 28
0
        public override Result Execute(ExternalCommandData data, ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            var    result   = Result.Failed;
            string rhinoTab = Addin.RhinoVersionInfo?.ProductName ?? "Rhinoceros";

            if (RhinoCommand.Availability.Available)
            {
                if (Keyboard.IsKeyDown(Key.LeftCtrl))
                {
                    return(Rhinoceros.RunCommandAbout());
                }

                using (var modal = new Rhinoceros.ModalScope())
                    result = modal.Run(false, true);

                // If no windows are visible we show the Ribbon tab
                if (result == Result.Cancelled)
                {
                    result = data.Application.ActivateRibbonTab(rhinoTab) ? Result.Succeeded : Result.Failed;
                }

                return(result);
            }

            result = Addin.CheckSetup();
            if (result != Result.Succeeded)
            {
                return(result);
            }

            result = Revit.OnStartup(Revit.ApplicationUI);
            if (RhinoCommand.Availability.Available = result == Result.Succeeded)
            {
                // Update Rhino button Tooltip
                Button.ToolTip         = $"Restores previously visible Rhino windows on top of Revit window";
                Button.LongDescription = $"Use CTRL key to open a Rhino model";

                // Register UI on Revit
                data.Application.CreateRibbonTab(rhinoTab);

                var RhinocerosPanel = data.Application.CreateRibbonPanel(rhinoTab, "Rhinoceros");
                HelpCommand.CreateUI(RhinocerosPanel);
                RhinocerosPanel.AddSeparator();
                CommandRhino.CreateUI(RhinocerosPanel);
                CommandPython.CreateUI(RhinocerosPanel);

                var GrasshopperPanel = data.Application.CreateRibbonPanel(rhinoTab, "Grasshopper");
                CommandGrasshopper.CreateUI(GrasshopperPanel);
                CommandGrasshopperPreview.CreateUI(GrasshopperPanel);

                var SamplesPanel = data.Application.CreateRibbonPanel(rhinoTab, "Samples");
                Samples.Sample1.CreateUI(SamplesPanel);
                Samples.Sample4.CreateUI(SamplesPanel);
                Samples.Sample6.CreateUI(SamplesPanel);
                Samples.Sample8.CreateUI(SamplesPanel);
            }

            if (result == Result.Succeeded)
            {
                // Activate Rhinoceros Tab
                result = data.Application.ActivateRibbonTab(rhinoTab) ? Result.Succeeded : Result.Failed;
            }
            else
            {
                // No more loads in this session
                Button.Enabled = false;
                Button.ToolTip = "Failed to load.";
            }

            return(result);
        }
Esempio n. 29
0
 public Editor GetEditor()
 {
     return((Editor)Addin.CreateInstance(editor_type));
 }
        protected override void OnActivated(object o, EventArgs e)
        {
            IExporter exporter = (IExporter)Addin.CreateInstance(class_name);

            exporter.Run(SelectedImages());
        }
Esempio n. 31
0
        static IEnumerable <Release> ParseReleases(string addinId, AddinRepositoryEntry entry)
        {
            // Format of release notes is:
            // {{version1,date1}} release note text {{version2,date2}} release note text ...
            // Releases msyu
            // for example:
            // {{1.1,2011-01-10}} Release notes for 1.1 {{1.2,2011-03-22}} Release notes for 2.3

            string releaseNotes = entry.Addin.Properties.GetPropertyValue("ReleaseNotes");

            if (releaseNotes.Length == 0)
            {
                string file = entry.Addin.Properties.GetPropertyValue("ReleaseNotesFile");
                if (file.Length > 0)
                {
                    IAsyncResult res = entry.BeginDownloadSupportFile(file, null, null);
                    res.AsyncWaitHandle.WaitOne();
                    try {
                        using (Stream s = entry.EndDownloadSupportFile(res)) {
                            StreamReader sr = new StreamReader(s);
                            releaseNotes = sr.ReadToEnd();
                        }
                    } catch (Exception ex) {
                        LoggingService.LogError("Could not download release notes", ex);
                    }
                }
            }

            if (releaseNotes.Length == 0)
            {
                yield break;
            }

            var    addin          = AddinManager.Registry.GetAddin(Addin.GetIdName(addinId));
            string currentVersion = addin != null ? addin.Version : null;

            int i = releaseNotes.IndexOf("{{");

            while (i != -1)
            {
                int j = releaseNotes.IndexOf("}}", i + 2);
                if (j == -1)
                {
                    break;
                }
                string[] h = releaseNotes.Substring(i + 2, j - i - 2).Trim().Split(',');
                if (h.Length != 2)
                {
                    break;
                }
                DateTime date;
                if (!DateTime.TryParse(h[1].Trim(), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out date))
                {
                    break;
                }
                int    k       = releaseNotes.IndexOf("{{", j + 2);
                string version = h[0].Trim();
                if (currentVersion == null || Addin.CompareVersions(currentVersion, version) > 0)
                {
                    string txt = k != -1 ? releaseNotes.Substring(j + 2, k - j - 2) : releaseNotes.Substring(j + 2);
                    yield return(new Release()
                    {
                        Version = version,
                        Date = date,
                        Notes = txt.Trim(' ', '\t', '\r', '\n')
                    });
                }
                i = k;
            }
        }
 protected virtual ITaskListView CreateView()
 {
     return((ITaskListView)Addin.CreateInstance(className, true));
 }
Esempio n. 33
0
        void LoadAddins()
        {
            object s = tree.SaveStatus();

            tree.Clear();

            Gtk.TreeIter iter;
            if (!repoCombo.GetActiveIter(out iter))
            {
                return;
            }

            bool showUpdates      = filterComboBox.Active >= 1;
            bool showNotInstalled = filterComboBox.Active <= 1;

            string rep = (string)repoStore.GetValue(iter, 1);

            AddinRepositoryEntry[] reps;
            if (rep == "")
            {
                reps = service.Repositories.GetAvailableAddins();
            }
            else
            {
                reps = service.Repositories.GetAvailableAddins(rep);
            }

            foreach (AddinRepositoryEntry arep in reps)
            {
                if (!Services.InApplicationNamespace(service, arep.Addin.Id))
                {
                    continue;
                }

                // Find whatever version is installed
                Addin sinfo = AddinManager.Registry.GetAddin(Addin.GetIdName(arep.Addin.Id));

                if (sinfo == null)
                {
                    if (showNotInstalled)
                    {
                        tree.AddAddin(arep.Addin, arep, true);
                    }
                    continue;
                }

                if (showUpdates && Addin.CompareVersions(sinfo.Version, arep.Addin.Version) <= 0)
                {
                    continue;
                }

                tree.AddAddin(arep.Addin, arep, true);
            }
            FillAddinInfo();

            // Only show the select all button when "Show updates only" is selected
            btnSelectAll.Visible   = filterComboBox.Active == 2;
            btnUnselectAll.Visible = filterComboBox.Active == 2;

            tree.RestoreStatus(s);
        }
Esempio n. 34
0
 public AddinHeader GetUpdate(Addin a)
 {
     AddinRepositoryEntry[] updates = service.Repositories.GetAvailableAddinUpdates (Addin.GetIdName (a.Id));
     AddinHeader best = null;
     string bestVersion = a.Version;
     foreach (AddinRepositoryEntry e in updates) {
         if (Addin.CompareVersions (bestVersion, e.Addin.Version) > 0) {
             best = e.Addin;
             bestVersion = e.Addin.Version;
         }
     }
     return best;
 }
Esempio n. 35
0
 protected string Description(Addin a)
 {
     return(Description(a.Name, a.Description.Description, a.Version));
 }
Esempio n. 36
0
        Addin GetInstalledDomainAddin(string domain, string id, bool exactVersionMatch, bool enabledOnly, bool dbLockCheck)
        {
            Addin sinfo = null;
            string idd = id + " " + domain;
            object ob = cachedAddinSetupInfos [idd];
            if (ob != null) {
                sinfo = ob as Addin;
                if (sinfo != null) {
                    if (!enabledOnly || sinfo.Enabled)
                        return sinfo;
                    if (exactVersionMatch)
                        return null;
                }
                else if (enabledOnly)
                    // Ignore the 'not installed' flag when disabled add-ins are allowed
                    return null;
            }

            if (dbLockCheck)
                InternalCheck (domain);

            using ((dbLockCheck ? fileDatabase.LockRead () : null))
            {
                string path = GetDescriptionPath (domain, id);
                if (sinfo == null && fileDatabase.Exists (path)) {
                    sinfo = new Addin (this, domain, id);
                    cachedAddinSetupInfos [idd] = sinfo;
                    if (!enabledOnly || sinfo.Enabled)
                        return sinfo;
                    if (exactVersionMatch) {
                        // Cache lookups with negative result
                        cachedAddinSetupInfos [idd] = this;
                        return null;
                    }
                }

                // Exact version not found. Look for a compatible version
                if (!exactVersionMatch) {
                    sinfo = null;
                    string version, name, bestVersion = null;
                    Addin.GetIdParts (id, out name, out version);

                    foreach (Addin ia in InternalGetInstalledAddins (domain, name, AddinSearchFlagsInternal.IncludeAll))
                    {
                        if ((!enabledOnly || ia.Enabled) &&
                            (version.Length == 0 || ia.SupportsVersion (version)) &&
                            (bestVersion == null || Addin.CompareVersions (bestVersion, ia.Version) > 0))
                        {
                            bestVersion = ia.Version;
                            sinfo = ia;
                        }
                    }
                    if (sinfo != null) {
                        cachedAddinSetupInfos [idd] = sinfo;
                        return sinfo;
                    }
                }

                // Cache lookups with negative result
                // Ignore the 'not installed' flag when disabled add-ins are allowed
                if (enabledOnly)
                    cachedAddinSetupInfos [idd] = this;
                return null;
            }
        }
Esempio n. 37
0
        bool CheckBug77135()
        {
            try
            {
                // Check for bug 77135. Some versions of gnome-vfs2 and libgda
                // make MD crash in the file open dialog or in FileIconLoader.
                // Only in Suse.

                string path = "/etc/SuSE-release";
                if (!File.Exists(path))
                {
                    return(true);
                }

                // Only run the check for SUSE 10
                StreamReader sr  = File.OpenText(path);
                string       txt = sr.ReadToEnd();
                sr.Close();

                if (txt.IndexOf("SUSE LINUX 10") == -1)
                {
                    return(true);
                }

                string current_libgda;
                string current_gnomevfs;
                string required_libgda   = "1.3.91.5.4";
                string required_gnomevfs = "2.12.0.9.2";

                StringWriter   sw = new StringWriter();
                ProcessWrapper pw = Runtime.ProcessService.StartProcess("rpm", "--qf %{version}.%{release} -q libgda", null, sw, null, null);
                pw.WaitForOutput();
                current_libgda = sw.ToString().Trim(' ', '\n');

                sw = new StringWriter();
                pw = Runtime.ProcessService.StartProcess("rpm", "--qf %{version}.%{release} -q gnome-vfs2", null, sw, null, null);
                pw.WaitForOutput();
                current_gnomevfs = sw.ToString().Trim(' ', '\n');

                bool fail1 = Addin.CompareVersions(current_libgda, required_libgda) == 1;
                bool fail2 = Addin.CompareVersions(current_gnomevfs, required_gnomevfs) == 1;

                if (fail1 || fail2)
                {
                    string msg = GettextCatalog.GetString("Some packages installed in your system are not compatible with MonoDevelop:\n");
                    if (fail1)
                    {
                        msg += "\nlibgda " + current_libgda + " (" + GettextCatalog.GetString("version required: {0}", required_libgda) + ")";
                    }
                    if (fail2)
                    {
                        msg += "\ngnome-vfs2 " + current_gnomevfs + " (" + GettextCatalog.GetString("version required: {0}", required_gnomevfs) + ")";
                    }
                    msg += "\n\n";
                    msg += GettextCatalog.GetString("You need to upgrade the previous packages to start using MonoDevelop.");

                    SplashScreenForm.SplashScreen.Hide();
                    Gtk.MessageDialog dlg = new Gtk.MessageDialog(null, Gtk.DialogFlags.Modal, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, msg);
                    dlg.Run();
                    dlg.Destroy();

                    return(false);
                }
                else
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                // Just ignore for now.
                Console.WriteLine(ex);
                return(true);
            }
        }
		public Addin GetInstalledAddin (string id, bool exactVersionMatch, bool enabledOnly)
		{
			Addin sinfo = null;
			object ob = cachedAddinSetupInfos [id];
			if (ob != null) {
				sinfo = ob as Addin;
				if (sinfo != null) {
					if (!enabledOnly || sinfo.Enabled)
						return sinfo;
					if (exactVersionMatch)
						return null;
				}
				else if (enabledOnly)
					// Ignore the 'not installed' flag when disabled add-ins are allowed
					return null;
			}
		
			InternalCheck ();
			
			using (fileDatabase.LockRead ())
			{
				string path = GetDescriptionPath (id);
				if (sinfo == null && fileDatabase.Exists (path)) {
					sinfo = new Addin (this, path);
					cachedAddinSetupInfos [id] = sinfo;
					if (!enabledOnly || sinfo.Enabled)
						return sinfo;
					if (exactVersionMatch) {
						// Cache lookups with negative result
						cachedAddinSetupInfos [id] = this;
						return null;
					}
				}
				
				// Exact version not found. Look for a compatible version
				if (!exactVersionMatch) {
					sinfo = null;
					string version, name, bestVersion = null;
					Addin.GetIdParts (id, out name, out version);
					
					// FIXME: Not very efficient, will load all descriptions
					foreach (Addin ia in InternalGetInstalledAddins ()) 
					{
						if (Addin.GetIdName (ia.Id) == name && 
						    (!enabledOnly || ia.Enabled) &&
						    (version.Length == 0 || ia.SupportsVersion (version)) && 
						    (bestVersion == null || Addin.CompareVersions (bestVersion, ia.Version) > 0)) 
						{
							bestVersion = ia.Version;
							sinfo = ia;
						}
					}
					if (sinfo != null) {
						cachedAddinSetupInfos [id] = sinfo;
						return sinfo;
					}
				}
				
				// Cache lookups with negative result
				// Ignore the 'not installed' flag when disabled add-ins are allowed
				if (enabledOnly)
					cachedAddinSetupInfos [id] = this;
				return null;
			}
		}
        public void ShowAddins(object[] data)
        {
            selectedEntry.Clear();
            selectedAddin.Clear();
            eboxButs.Visible = true;
            topHeaderBox.Hide();
            urlButton.Hide();

            if (titleIcon != null)
            {
                boxTitle.Remove(titleIcon);
                titleIcon.Destroy();
                titleIcon = null;
            }

            foreach (var img in previewImages)
            {
                ((Gtk.Container)img.Parent).Remove(img);
                img.Destroy();
            }
            previewImages.Clear();

            if (data.Length == 1)
            {
                headerBox.Show();
                ShowAddin(data[0]);
            }
            else if (data.Length > 1)
            {
                headerBox.Hide();
                StringBuilder sb = new StringBuilder();
                sb.Append(Catalog.GetString("Multiple selection:\n\n"));
                bool allowUpdate    = AllowInstall;
                bool allowInstall   = true;
                bool allowUninstall = AllowInstall;
                bool allowEnable    = true;
                bool allowDisable   = true;

                foreach (object o in data)
                {
                    Addin installed;
                    if (o is Addin)
                    {
                        Addin a = (Addin)o;
                        installed = a;
                        selectedAddin.Add(a);
                        sb.Append(a.Name);
                    }
                    else
                    {
                        AddinRepositoryEntry entry = (AddinRepositoryEntry)o;
                        selectedEntry.Add(entry);
                        sb.Append(entry.Addin.Name);
                        installed = AddinManager.Registry.GetAddin(Addin.GetIdName(entry.Addin.Id));
                    }
                    if (installed != null)
                    {
                        if (GetUpdate(installed) == null)
                        {
                            allowUpdate = false;
                        }
                        allowInstall = false;
                        if (installed.Enabled)
                        {
                            allowEnable = false;
                        }
                        else
                        {
                            allowDisable = false;
                        }
                    }
                    else
                    {
                        allowEnable = allowDisable = allowUninstall = allowUpdate = false;
                    }

                    sb.Append('\n');
                    labelDesc.Text = sb.ToString();

                    if (allowEnable)
                    {
                        btnDisable.Visible = true;
                        btnDisable.Label   = Catalog.GetString("Enable");
                    }
                    else if (allowDisable)
                    {
                        btnDisable.Visible = true;
                        btnDisable.Label   = Catalog.GetString("Disable");
                    }
                    else
                    {
                        btnDisable.Visible = false;
                    }
                    btnInstall.Visible   = allowInstall;
                    btnUninstall.Visible = allowUninstall;
                    btnUpdate.Visible    = allowUpdate;
                }
            }
            else
            {
                headerBox.Hide();
                btnDisable.Visible   = false;
                btnInstall.Visible   = false;
                btnUninstall.Visible = false;
                btnUpdate.Visible    = false;
                eboxButs.Visible     = false;
                labelDesc.Text       = Catalog.GetString("No selection");
            }
        }
Esempio n. 40
0
 public static AddinHeader GetAddinHeader(Addin addin)
 {
     return AddinInfo.ReadFromDescription (addin.Description);
 }
        void ShowAddin(object data)
        {
            AddinHeader sinfo        = null;
            Addin       installed    = null;
            AddinHeader updateInfo   = null;
            string      repo         = "";
            string      downloadSize = null;

            topHeaderBox.Hide();

            if (data is Addin)
            {
                installed = (Addin)data;
                sinfo     = SetupService.GetAddinHeader(installed);
                var entry = GetUpdate(installed);
                if (entry != null)
                {
                    updateInfo = entry.Addin;
                    selectedEntry.Add(entry);
                }
                foreach (var prop in sinfo.Properties)
                {
                    if (prop.Name.StartsWith("PreviewImage"))
                    {
                        previewImages.Add(new ImageContainer(installed, prop.Value));
                    }
                }
                string icon32 = sinfo.Properties.GetPropertyValue("Icon32");
                if (icon32.Length > 0)
                {
                    titleIcon = new ImageContainer(installed, icon32);
                }
            }
            else if (data is AddinRepositoryEntry)
            {
                AddinRepositoryEntry entry = (AddinRepositoryEntry)data;
                sinfo     = entry.Addin;
                installed = AddinManager.Registry.GetAddin(Addin.GetIdName(sinfo.Id));
                if (installed != null && Addin.CompareVersions(installed.Version, sinfo.Version) > 0)
                {
                    updateInfo = sinfo;
                }
                selectedEntry.Add(entry);
                string rname = !string.IsNullOrEmpty(entry.RepositoryName) ? entry.RepositoryName : entry.RepositoryUrl;
                repo = "<small><b>" + Catalog.GetString("Available in repository:") + "</b>\n" + GLib.Markup.EscapeText(rname) + "\n\n</small>";
                foreach (var prop in sinfo.Properties)
                {
                    if (prop.Name.StartsWith("PreviewImage"))
                    {
                        previewImages.Add(new ImageContainer(entry, prop.Value));
                    }
                }
                string icon32 = sinfo.Properties.GetPropertyValue("Icon32");
                if (icon32.Length > 0)
                {
                    titleIcon = new ImageContainer(entry, icon32);
                }
                int size;
                if (int.TryParse(sinfo.Properties.GetPropertyValue("DownloadSize"), out size))
                {
                    float fs = ((float)size) / 1048576f;
                    downloadSize = fs.ToString("0.00 MB");
                }
            }
            else
            {
                selectedEntry.Clear();
            }

            if (installed != null)
            {
                selectedAddin.Add(installed);
            }

            string missingDepsTxt = null;

            if (sinfo == null)
            {
                btnDisable.Visible   = false;
                btnUninstall.Visible = false;
                btnUpdate.Visible    = false;
            }
            else
            {
                string version;
                string newVersion = null;
                if (installed != null)
                {
                    btnInstall.Visible   = false;
                    btnUpdate.Visible    = updateInfo != null && AllowInstall;
                    btnDisable.Visible   = true;
                    btnDisable.Label     = installed.Enabled ? "Disable" : "Enable";
                    btnDisable.Visible   = installed.Description.CanDisable;
                    btnUninstall.Visible = installed.Description.CanUninstall;
                    version = installed.Version;
                    var missingDeps = Services.GetMissingDependencies(installed);
                    if (updateInfo != null)
                    {
                        newVersion         = updateInfo.Version;
                        labelHeader.Markup = "<b><span color='black'>" + Catalog.GetString("Update available") + "</span></b>";
//						topHeaderBox.BackgroundColor = new Gdk.Color (0, 132, 208);
                        imageHeader.Pixbuf           = Gdk.Pixbuf.LoadFromResource("software-update-available.png");
                        topHeaderBox.BackgroundColor = new Gdk.Color(255, 176, 0);
                        topHeaderBox.Show();
                    }
                    else if (missingDeps.Any())
                    {
                        labelHeader.Markup           = "<b><span color='black'>" + Catalog.GetString("This add-in can't be loaded due to missing dependencies") + "</span></b>";
                        topHeaderBox.BackgroundColor = new Gdk.Color(255, 176, 0);
                        imageHeader.SetFromStock(Gtk.Stock.DialogWarning, Gtk.IconSize.Menu);
                        topHeaderBox.Show();
                        missingDepsTxt = "";
                        foreach (var mdep in missingDeps)
                        {
                            if (mdep.Found != null)
                            {
                                missingDepsTxt += "\n" + string.Format(Catalog.GetString("Required: {0} v{1}, found v{2}"), mdep.Addin, mdep.Required, mdep.Found);
                            }
                            else
                            {
                                missingDepsTxt += "\n" + string.Format(Catalog.GetString("Missing: {0} v{1}"), mdep.Addin, mdep.Required);
                            }
                        }
                    }
                }
                else
                {
                    btnInstall.Visible   = AllowInstall;
                    btnUpdate.Visible    = false;
                    btnDisable.Visible   = false;
                    btnUninstall.Visible = false;
                    version = sinfo.Version;
                }
                labelName.Markup = "<b><big>" + GLib.Markup.EscapeText(sinfo.Name) + "</big></b>";

                string ver;
                if (newVersion != null)
                {
                    ver  = "<small><b>" + Catalog.GetString("Installed version") + ":</b> " + version + "</small>\n";
                    ver += "<small><b>" + Catalog.GetString("Repository version") + ":</b> " + newVersion + "</small>";
                }
                else
                {
                    ver = "<small><b>" + Catalog.GetString("Version") + " " + version + "</b></small>";
                }

                if (downloadSize != null)
                {
                    ver += "\n<small><b>" + Catalog.GetString("Download size") + ":</b> " + downloadSize + "</small>";
                }
                if (missingDepsTxt != null)
                {
                    ver += "\n\n" + GLib.Markup.EscapeText(Catalog.GetString("The following depedencies required by this add-in are not available:")) + missingDepsTxt;
                }
                labelVersion.Markup = ver;

                string desc = GLib.Markup.EscapeText(sinfo.Description);
                labelDesc.Markup = repo + GLib.Markup.EscapeText(desc);

                foreach (var img in previewImages)
                {
                    vboxDesc.PackStart(img, false, false, 0);
                }

                urlButton.Visible = !string.IsNullOrEmpty(sinfo.Url);
                infoUrl           = sinfo.Url;

                if (titleIcon != null)
                {
                    boxTitle.PackEnd(titleIcon, false, false, 0);
                    labelName.WidthRequest    = titleWidth - 32;
                    labelVersion.WidthRequest = titleWidth - 32;
                }
                else
                {
                    labelName.WidthRequest    = titleWidth;
                    labelVersion.WidthRequest = titleWidth;
                }

                if (IsRealized)
                {
                    SetComponentsBg();
                }
            }
        }