Example #1
0
        public void TestDeleteNestedProperty()
        {
            var plist   = new PDictionary();
            var primary = new PDictionary();
            var icons   = new PDictionary();
            var files   = new PArray();

            plist.Add("CFBundleIdentifier", "com.microsoft.delete-nested-property");
            plist.Add("CFBundleIcons", icons);
            icons.Add("CFBundlePrimaryIcon", primary);
            primary.Add("CFBundleIconFiles", files);
            files.Add("icon0");
            files.Add("icon1");

            var expected = (PDictionary)plist.Clone();

            files.Add("icon2");

            TestExecuteTask(plist, PropertyListEditorAction.Delete, ":CFBundleIcons:CFBundlePrimaryIcon:CFBundleIconFiles:2", null, null, expected);

            var plist2 = (PDictionary)expected.Clone();

            files.Remove();

            var expected2 = (PDictionary)plist.Clone();

            TestExecuteTask(plist2, PropertyListEditorAction.Delete, ":CFBundleIcons:CFBundlePrimaryIcon:CFBundleIconFiles", null, null, expected2);
        }
Example #2
0
        public void TestMergeRoot()
        {
            var expected = new PDictionary();
            var primary  = new PDictionary();
            var icons    = new PDictionary();
            var files    = new PArray();

            expected.Add("CFBundleIdentifier", "com.microsoft.merge-root");
            expected.Add("CFBundleIcons", icons);
            icons.Add("CFBundlePrimaryIcon", primary);
            primary.Add("UIPrerenderedIcon", new PBoolean(true));
            primary.Add("CFBundleIconFiles", files);
            files.Add("icon0");
            files.Add("icon1");
            files.Add("icon2");

            var plist = (PDictionary)expected.Clone();

            plist.Remove("CFBundleIcons");

            var merge = (PDictionary)expected.Clone();

            merge.Remove("CFBundleIdentifier");

            var tmp = Path.Combine(Cache.CreateTemporaryDirectory(), "tmpfile");

            merge.Save(tmp);

            TestExecuteTask(plist, PropertyListEditorAction.Merge, null, null, tmp, expected);
        }
Example #3
0
        public void TestAddNestedProperty()
        {
            var plist = new PDictionary();

            plist.Add("CFBundleIdentifier", "com.microsoft.add-nested-property");

            var expected = (PDictionary)plist.Clone();
            var primary  = new PDictionary();
            var icons    = new PDictionary();

            primary.Add("UIPrerenderedIcon", new PBoolean(true));
            icons.Add("CFBundlePrimaryIcon", primary);
            expected.Add("CFBundleIcons", icons);

            TestExecuteTask(plist, PropertyListEditorAction.Add, ":CFBundleIcons:CFBundlePrimaryIcon:UIPrerenderedIcon", "bool", "true", expected);

            plist = (PDictionary)expected.Clone();
            var files = new PArray();

            primary.Add("CFBundleIconFiles", files);

            TestExecuteTask(plist, PropertyListEditorAction.Add, ":CFBundleIcons:CFBundlePrimaryIcon:CFBundleIconFiles", "array", null, expected);

            plist = (PDictionary)expected.Clone();
            files.Add("icon0");

            TestExecuteTask(plist, PropertyListEditorAction.Add, ":CFBundleIcons:CFBundlePrimaryIcon:CFBundleIconFiles:", "string", "icon0", expected);
        }
Example #4
0
        public void TestMergeArrays()
        {
            var plist  = new PDictionary();
            var array0 = new PArray();

            array0.Add("item0");
            array0.Add("item1");
            array0.Add("item2");
            array0.Add("item3");

            plist.Add("CFBundleIdentifier", "com.microsoft.merge-arrays");
            plist.Add("CFArrayItems", array0);

            var array1 = new PArray();

            array1.Add("item2");
            array1.Add("item3");

            var expected = (PDictionary)plist.Clone();

            array0.RemoveAt(3);
            array0.RemoveAt(2);

            var tmp = Path.Combine(Cache.CreateTemporaryDirectory(), "tmpfile");

            array1.Save(tmp);

            TestExecuteTask(plist, PropertyListEditorAction.Merge, ":CFArrayItems", null, tmp, expected);
        }
        void AddIconPaths(PArray icons, PArray iconFiles, string productsDir)
        {
            foreach (var icon in iconFiles.Cast <PString> ().Where(p => p.Value != null))
            {
                var  path       = string.Format("Applications/{0}/{1}", Path.GetFileName(AppBundleDir.ItemSpec), icon.Value);
                bool addDefault = true;

                if (path.EndsWith(".png", StringComparison.Ordinal))
                {
                    icons.Add(new PString(path));
                    continue;
                }

                if (File.Exists(Path.Combine(productsDir, path + "@3x.png")))
                {
                    icons.Add(new PString(path + "@3x.png"));
                    addDefault = false;
                }

                if (File.Exists(Path.Combine(productsDir, path + "@2x.png")))
                {
                    icons.Add(new PString(path + "@2x.png"));
                    addDefault = false;
                }

                if (addDefault || File.Exists(Path.Combine(productsDir, path + ".png")))
                {
                    icons.Add(new PString(path + ".png"));
                }
            }
        }
        public void WalkScheme_Dictionary_NotPartOfScheme()
        {
            var scheme = Load(@"
<PListScheme>
	<Key name = ""key1"" type = ""Array"" arrayType = ""Dictionary"" />
</PListScheme>");

            var dict = new PDictionary();

            dict.Add("foo", new PNumber(1));

            var tree = new PArray();

            tree.Add(dict);
            tree.Add(new PNumber(1));

            var root = new PDictionary();

            root.Add("foo", tree);

            var result = PListScheme.Match(root, scheme);
            var keys   = result.Keys.ToArray();

            for (int i = 0; i < keys.Length; i++)
            {
                Assert.IsNull(result [keys [i]], "#1." + i);
            }
        }
Example #7
0
        static PDictionary CreateIndex()
        {
            var plist    = new PDictionary();
            var profiles = new PArray();

            foreach (var fileName in Directory.EnumerateFiles(MobileProvision.ProfileDirectory))
            {
                if (!fileName.EndsWith(".mobileprovision", StringComparison.Ordinal) && !fileName.EndsWith(".provisionprofile", StringComparison.Ordinal))
                {
                    continue;
                }

                try {
                    var profile = CreateIndexRecord(fileName);
                    profiles.Add(profile);
                } catch (Exception ex) {
                    LoggingService.LogWarning("Error reading provisioning profile '{0}': {1}", fileName, ex);
                }
            }

            plist.Add("Version", new PNumber(IndexVersion));
            plist.Add("LastModified", new PDate(Directory.GetLastWriteTimeUtc(MobileProvision.ProfileDirectory)));
            plist.Add("ProvisioningProfiles", profiles);

            Save(plist);

            return(plist);
        }
Example #8
0
            internal ArrayEnumerator(PArray arr, int start)
            {
#endif
                this.arr   = arr;
                this.start = start;
                i          = start;
            }
Example #9
0
        public static void SetUISupportedInterfaceOrientations(this PDictionary dict, bool ipad, IPhoneOrientation orientations)
        {
            var key = ipad ? ManifestKeys.UISupportedInterfaceOrientationsIPad : ManifestKeys.UISupportedInterfaceOrientations;

            if (orientations == IPhoneOrientation.None)
            {
                dict.Remove(key);
                return;
            }

            var arr = new PArray();

            if ((orientations & IPhoneOrientation.Portrait) != 0)
            {
                arr.Add(IPhoneOrientationStrings.Up);
            }
            if ((orientations & IPhoneOrientation.UpsideDown) != 0)
            {
                arr.Add(IPhoneOrientationStrings.Down);
            }
            if ((orientations & IPhoneOrientation.LandscapeLeft) != 0)
            {
                arr.Add(IPhoneOrientationStrings.Left);
            }
            if ((orientations & IPhoneOrientation.LandscapeRight) != 0)
            {
                arr.Add(IPhoneOrientationStrings.Right);
            }

            dict[key] = arr;
        }
Example #10
0
        private bool P_ArrayList(PArray arr)
        {
            if (P_Comma())
            {
                if (P_PosOrNeg(out var num))
                {
                    if (int.TryParse(num.Lex, out var lbound))
                    {
                        if (P_Dot() && P_Dot())
                        {
                            if (P_PosOrNeg(out num))
                            {
                                if (int.TryParse(num.Lex, out var rbound))
                                {
                                    arr.AddArrData(new PArray.ArrayData(lbound, rbound));
                                    return(P_ArrayList(arr));
                                }
                            }
                        }
                    }
                }
            }

            return(P_RightBracket());
        }
        public void TestMergeArrays()
        {
            var plist  = new PDictionary();
            var array0 = new PArray();

            array0.Add("item0");
            array0.Add("item1");
            array0.Add("item2");
            array0.Add("item3");

            plist.Add("CFBundleIdentifier", "com.microsoft.merge-arrays");
            plist.Add("CFArrayItems", array0);

            var array1 = new PArray();

            array1.Add("item2");
            array1.Add("item3");

            var expected = (PDictionary)plist.Clone();

            array0.RemoveAt(3);
            array0.RemoveAt(2);

            var tmp = Path.GetTempFileName();

            array1.Save(tmp);

            try {
                TestExecuteTask(plist, PropertyListEditorAction.Merge, ":CFArrayItems", null, tmp, expected);
            } finally {
                File.Delete(tmp);
            }
        }
		public override void Load (string fileName)
		{
			ContentName = fileName;

			if (pobject == null) {
				var dict = new PDictionary ();
				if (dict.Reload (fileName)) {
					pobject = dict;
				} else {
					var arr = new PArray ();
					if (!arr.Reload (fileName)) {
						MessageService.ShowError (GettextCatalog.GetString ("Can't load plist file {0}.", fileName));
						return;
					}
					pobject = arr;
				}
				
				Buffer = null;
				widget.SetPListContainer (pobject);
				pobject.Changed += (sender, e) => {
					Buffer = null;
					IsDirty = true;
				};
			}
			this.IsDirty = false;
		}
Example #13
0
        bool Clear(ref PObject plist)
        {
            if (Type != null)
            {
                switch (Type.ToLowerInvariant())
                {
                case "string": plist = new PString(string.Empty); break;

                case "array": plist = new PArray(); break;

                case "dict": plist = new PDictionary(); break;

                case "bool": plist = new PBoolean(false); break;

                case "real": plist = new PReal(0); break;

                case "integer": plist = new PNumber(0); break;

                case "date": plist = new PDate(DateTime.Now); break;

                case "data": plist = new PData(new byte[1]); break;

                default:
                    Log.LogError(7045, null, $"Unrecognized Type: {Type}");
                    return(false);
                }
            }
            else
            {
                plist = PObject.Create(plist.Type);
            }

            return(true);
        }
Example #14
0
        public void ConstructorTest()
        {
            PArray <int> pa = new PArray <int>(new List <int> {
                1, 2, 3, 4
            });

            Assert.IsNotNull(pa);
        }
Example #15
0
        public void PushOneTest()
        {
            PArray <int> pa = new PArray <int>(new List <int> {
                1, 2, 3, 4
            });

            pa.Push(5);
            Assert.AreEqual(5, pa.Count);
        }
Example #16
0
        public void ShiftOneTest()
        {
            PArray <int> pa = new PArray <int>(new List <int> {
                1, 2, 3, 4
            });
            var i = pa.Shift();

            Assert.AreEqual(3, pa.Count);
            Assert.AreEqual(1, i);
        }
Example #17
0
        public void PopOneTest()
        {
            PArray <int> pa = new PArray <int>(new List <int> {
                1, 2, 3, 4
            });
            var i = pa.Pop();

            Assert.AreEqual(3, pa.Count);
            Assert.AreEqual(4, i);
        }
Example #18
0
        static void CheckArray(PArray array, PArray expected)
        {
            Assert.AreEqual(expected.Count, array.Count, "Unexpected number of array elements");

            for (int i = 0; i < expected.Count; i++)
            {
                Assert.AreEqual(expected[i].Type, array[i].Type, "Type-mismatch for array element {0}", i);
                CheckValue(array[i], expected[i]);
            }
        }
Example #19
0
 public static void SetCFBundleIconFiles(this PDictionary dict, PArray array)
 {
     if (array == null)
     {
         dict.Remove(ManifestKeys.CFBundleIconFiles);
     }
     else
     {
         dict[ManifestKeys.CFBundleIconFiles] = array;
     }
 }
Example #20
0
        static PArray CreateKnownSdkVersionsArray(IList <MacOSXSdkVersion> versions)
        {
            var array = new PArray();

            for (int i = 0; i < versions.Count; i++)
            {
                array.Add(new PString(versions[i].ToString()));
            }

            return(array);
        }
Example #21
0
 public static void SetApplicationGroups(this PDictionary dict, PArray value)
 {
     if (value == null)
     {
         dict.Remove(EntitlementKeys.ApplicationGroups);
     }
     else
     {
         dict[EntitlementKeys.ApplicationGroups] = value;
     }
 }
Example #22
0
 public static void SetApplePayMerchants(this PDictionary dict, PArray value)
 {
     if (value == null)
     {
         dict.Remove(EntitlementKeys.InAppPayments);
     }
     else
     {
         dict[EntitlementKeys.InAppPayments] = value;
     }
 }
        static PDictionary CreateIndexRecord(string fileName)
        {
            var     provision    = MobileProvision.LoadFromFile(fileName);
            var     certificates = new PArray();
            var     record       = new PDictionary();
            PString identifier;

            record.Add("FileName", new PString(Path.GetFileName(fileName)));
            record.Add("LastModified", new PDate(File.GetLastWriteTimeUtc(fileName)));

            record.Add("Name", new PString(provision.Name));
            record.Add("Uuid", new PString(provision.Uuid));
            record.Add("Distribution", new PString(provision.DistributionType.ToString()));
            record.Add("CreationDate", new PDate(provision.CreationDate.ToUniversalTime()));
            record.Add("ExpirationDate", new PDate(provision.ExpirationDate.ToUniversalTime()));

            var platforms = new PArray();

            if (provision.Platforms != null)
            {
                for (int i = 0; i < provision.Platforms.Length; i++)
                {
                    platforms.Add(new PString(provision.Platforms[i].ToString()));
                }
            }
            record.Add("Platforms", platforms);

            if (provision.Entitlements.TryGetValue("com.apple.application-identifier", out identifier))
            {
                record.Add("ApplicationIdentifier", new PString(identifier.Value));
            }
            else if (provision.Entitlements.TryGetValue("application-identifier", out identifier))
            {
                record.Add("ApplicationIdentifier", new PString(identifier.Value));
            }
            else
            {
                record.Add("ApplicationIdentifier", new PString(string.Empty));
            }

            foreach (var certificate in provision.DeveloperCertificates)
            {
                var info = new PDictionary();

                info.Add("Name", new PString(Keychain.GetCertificateCommonName(certificate)));
                info.Add("Thumbprint", new PString(certificate.Thumbprint));

                certificates.Add(info);
            }

            record.Add("DeveloperCertificates", certificates);

            return(record);
        }
Example #24
0
 public static void SetiCloudContainers(this PDictionary dict, PArray value)
 {
     if (value == null)
     {
         dict.Remove(EntitlementKeys.iCloudContainers);
     }
     else
     {
         dict[EntitlementKeys.iCloudContainers] = value;
     }
 }
Example #25
0
 public static void SetPassBookIdentifiers(this PDictionary dict, PArray value)
 {
     if (value == null)
     {
         dict.Remove(EntitlementKeys.PassBookIdentifiers);
     }
     else
     {
         dict[EntitlementKeys.PassBookIdentifiers] = value;
     }
 }
Example #26
0
 public static void SetAssociatedDomains(this PDictionary dict, PArray value)
 {
     if (value == null)
     {
         dict.Remove(EntitlementKeys.AssociatedDomains);
     }
     else
     {
         dict[EntitlementKeys.AssociatedDomains] = value;
     }
 }
Example #27
0
        public void UnshiftOneTest()
        {
            PArray <int> pa = new PArray <int>(new List <int> {
                1, 2, 3, 4
            });

            pa.Unshift(5);
            Assert.AreEqual(5, pa.Count);
            int i = pa.Pop();

            Assert.AreEqual(4, i);
        }
        static bool Contains(PArray platforms, MobileProvisionPlatform platform)
        {
            var value = platform.ToString();

            foreach (var item in platforms.OfType <PString> ())
            {
                if (item.Value == value)
                {
                    return(true);
                }
            }

            return(false);
        }
Example #29
0
        public void ExistsT_should_be_callable_indirectly()
        {
            using (new IndirectionsContext())
            {
                // Arrange
                PArray.ExistsOfTTArrayPredicateOfT <int>().Body = (array, match) => true;

                // Act
                var actual = Array.Exists(new int[] { 1, 2, 3 }, x => x == 42);

                // Assert
                Assert.IsTrue(actual);
            }
        }
Example #30
0
        public void ExistsT_should_throw_NotImplementedException_if_the_behavior_is_set_that()
        {
            using (new IndirectionsContext())
            {
                // Arrange
                PArray.
                ExcludeGeneric().
                IncludeExistsOfTTArrayPredicateOfT <int>().
                DefaultBehavior = IndirectionBehaviors.NotImplemented;

                // Act, Assert
                Assert.Throws <NotImplementedException>(() => Array.Exists(new int[] { 1, 2, 3 }, x => x == 42));
            }
        }
Example #31
0
        public void BinarySearch_should_be_callable_indirectly()
        {
            using (new IndirectionsContext())
            {
                // Arrange
                PArray.BinarySearchArrayInt32Int32ObjectIComparer().Body = (array, index, length, value, comparer) => 42;

                // Act
                var actual = Array.BinarySearch(new int[] { 1, 2, 3 }, 0, 3, (object)2, new LambdaComparer <int>((_1, _2) => _1 - _2));

                // Assert
                Assert.AreEqual(42, actual);
            }
        }
Example #32
0
			public PObject Create ()
			{
				if (Type == PDictionary.Type) {
					var dictionary = new PDictionary ();
					foreach (var v in Values) {
						if (v.Required)
							dictionary.Add (v.Identifier, v.Create ());
					}
					
					// If nothing was required, create an initial one anyway
					if (dictionary.Count == 0) {
						var first = Values.FirstOrDefault ();
						if (first == null) {
							dictionary.Add ("newNode", PObject.Create (PString.Type));
						} else {
							dictionary.Add (first.Identifier ?? "newNode", first.Create ());
						}
					}
					return dictionary;
				} else if (Type == PArray.Type) {
					var array = new PArray ();
					foreach (var v in Values) {
						if (v.Required)
							array.Add (v.Create ());
					}
					
					// If nothing was required, create an initial one anyway
					if (array.Count == 0) {
						var first = Values.FirstOrDefault ();
						if (first == null) {
							array.Add (PObject.Create (ArrayType));
						} else {
							array.Add (first.Create ());
						}
					}
					return array;
				} else if (Values.Any ()){
					return Values.First ().Create ();
				} else {
					var obj = PObject.Create (Type);
					if (!string.IsNullOrEmpty (Identifier) && !(this is Key))
						obj.SetValue (Identifier);
					return obj;
				}
			}
Example #33
0
        PArray MergeEntitlementArray(PArray array, MobileProvision profile)
        {
            var result = new PArray ();

            foreach (var item in array) {
                PObject value;

                if (item is PDictionary)
                    value = MergeEntitlementDictionary ((PDictionary) item, profile);
                else if (item is PString)
                    value = MergeEntitlementString ((PString) item, profile);
                else if (item is PArray)
                    value = MergeEntitlementArray ((PArray) item, profile);
                else
                    value = item.Clone ();

                if (value != null)
                    result.Add (value);
            }

            if (result.Count > 0)
                return result;

            return null;
        }
		void AddToTree (Gtk.TreeStore treeStore, Gtk.TreeIter iter, PArray arr)
		{
			iterTable[arr] = iter;
			
			for (int i = 0; i < arr.Count; i++) {
				var item = arr[i];
				
				var txt = string.Format (GettextCatalog.GetString ("Item {0}"), i);
				var subIter = iter.Equals (TreeIter.Zero) ? treeStore.AppendValues (txt, item) : treeStore.AppendValues (iter, txt, item);
				
				if (item is PArray)
					AddToTree (treeStore, subIter, (PArray)item);
				if (item is PDictionary)
					AddToTree (treeStore, subIter, (PDictionary)item);
				if (expandedObjects.Contains (item))
					treeview.ExpandRow (treeStore.GetPath (subIter), true);
			}

			AddCreateNewEntry  (iter);
			
			if (!rebuildArrays.Contains (arr)) {
				rebuildArrays.Add (arr);
				arr.Changed += HandleArrRebuild;
			}
		}
Example #35
0
        public override bool Execute()
        {
            Log.LogTaskName ("ComputeBundleResourceOutputPaths");
            Log.LogTaskProperty ("AppBundleDir", AppBundleDir);
            Log.LogTaskProperty ("BundleIdentifier", BundleIdentifier);
            Log.LogTaskProperty ("BundleResources", BundleResources);
            Log.LogTaskProperty ("IntermediateOutputPath", IntermediateOutputPath);
            Log.LogTaskProperty ("OutputPath", OutputPath);

            var intermediate = Path.Combine (IntermediateOutputPath, "assetpacks");
            var bundleResources = new List<ITaskItem> ();
            var packs = new HashSet<string> ();

            if (BundleResources != null) {
                foreach (var item in BundleResources) {
                    var logicalName = item.GetMetadata ("LogicalName");
                    var outputPath = item.GetMetadata ("OutputPath");
                    var tags = AssetPackUtils.GetResourceTags (item);
                    string hash;

                    if (tags != null) {
                        var assetpack = AssetPackUtils.GetAssetPackDirectory (OutputPath, BundleIdentifier, tags, out hash);

                        if (packs.Add (hash)) {
                            var path = Path.Combine (intermediate, hash + ".plist");

                            if (!File.Exists (path)) {
                                var plist = new PDictionary ();
                                var array = new PArray ();

                                for (int i = 0; i < tags.Count; i++)
                                    array.Add (new PString (tags[i]));

                                plist.SetCFBundleIdentifier (BundleIdentifier + ".asset-pack-" + hash);
                                plist.Add ("Tags", array);

                                Directory.CreateDirectory (intermediate);

                                plist.Save (path, true, true);
                            }

                            var manifest = new TaskItem (path);
                            manifest.SetMetadata ("OutputPath", Path.Combine (assetpack, "Info.plist"));
                            bundleResources.Add (manifest);
                        }

                        outputPath = Path.Combine (assetpack, logicalName);
                    } else if (string.IsNullOrEmpty (outputPath)) {
                        outputPath = Path.Combine (AppBundleDir.ItemSpec, logicalName);
                    }

                    var bundleResource = new TaskItem (item);

                    bundleResource.SetMetadata ("OutputPath", outputPath);

                    bundleResources.Add (bundleResource);
                }
            }

            BundleResourcesWithOutputPaths = bundleResources.ToArray ();

            return !Log.HasLoggedErrors;
        }
Example #36
0
        public override bool Execute()
        {
            var intermediate = Path.Combine (IntermediateOutputPath, ToolName);
            var intermediateBundleDir = Path.Combine (intermediate, "bundle");
            var manifest = new TaskItem (Path.Combine (intermediate, "asset-manifest.plist"));
            var bundleResources = new List<ITaskItem> ();
            var outputManifests = new List<ITaskItem> ();
            var catalogs = new List<ITaskItem> ();
            var unique = new HashSet<string> ();
            string bundleIdentifier = null;
            var knownSpecs = new HashSet<string> ();
            var specs = new PArray ();
            int rc;

            Log.LogTaskName ("ACTool");
            Log.LogTaskProperty ("AppManifest", AppManifest);
            Log.LogTaskProperty ("DeviceModel", DeviceModel);
            Log.LogTaskProperty ("DeviceOSVersion", DeviceOSVersion);
            Log.LogTaskProperty ("ImageAssets", ImageAssets);
            Log.LogTaskProperty ("IntermediateOutputPath", IntermediateOutputPath);
            Log.LogTaskProperty ("IsWatchApp", IsWatchApp);
            Log.LogTaskProperty ("OptimizePNGs", OptimizePNGs);
            Log.LogTaskProperty ("OutputPath", OutputPath);
            Log.LogTaskProperty ("ProjectDir", ProjectDir);
            Log.LogTaskProperty ("ResourcePrefix", ResourcePrefix);
            Log.LogTaskProperty ("SdkBinPath", SdkBinPath);
            Log.LogTaskProperty ("SdkPlatform", SdkPlatform);
            Log.LogTaskProperty ("SdkVersion", SdkVersion);

            switch (SdkPlatform) {
            case "iPhoneSimulator":
            case "iPhoneOS":
            case "MacOSX":
            case "WatchSimulator":
            case "WatchOS":
            case "AppleTVSimulator":
            case "AppleTVOS":
                break;
            default:
                Log.LogError ("Unrecognized platform: {0}", SdkPlatform);
                return false;
            }

            if (AppManifest != null) {
                try {
                    plist = PDictionary.FromFile (AppManifest.ItemSpec);
                } catch (Exception ex) {
                    Log.LogError (null, null, null, AppManifest.ItemSpec, 0, 0, 0, 0, "{0}", ex.Message);
                    return false;
                }

                bundleIdentifier = plist.GetCFBundleIdentifier ();
            }

            foreach (var asset in ImageAssets) {
                var vpath = BundleResource.GetVirtualProjectPath (ProjectDir, asset);
                if (Path.GetFileName (vpath) != "Contents.json")
                    continue;

                // get the parent (which will typically be .appiconset, .launchimage, .imageset, .iconset, etc)
                var catalog = Path.GetDirectoryName (vpath);

                // keep walking up the directory structure until we get to the .xcassets directory
                while (!string.IsNullOrEmpty (catalog) && Path.GetExtension (catalog) != ".xcassets")
                    catalog = Path.GetDirectoryName (catalog);

                if (string.IsNullOrEmpty (catalog)) {
                    Log.LogWarning (null, null, null, asset.ItemSpec, 0, 0, 0, 0, "Asset not part of an asset catalog: {0}", asset.ItemSpec);
                    continue;
                }

                if (unique.Add (catalog))
                    catalogs.Add (new TaskItem (catalog));

                if (AppleSdkSettings.XcodeVersion.Major >= 7 && !string.IsNullOrEmpty (bundleIdentifier) && SdkPlatform != "WatchSimulator") {
                    var text = File.ReadAllText (asset.ItemSpec);

                    if (string.IsNullOrEmpty (text))
                        continue;

                    var json = JsonConvert.DeserializeObject (text) as JObject;

                    if (json == null)
                        continue;

                    var properties = json.Property ("properties");

                    if (properties == null)
                        continue;

                    var resourceTags = properties.Value.ToObject<JObject> ().Property ("on-demand-resource-tags");

                    if (resourceTags == null || resourceTags.Value.Type != JTokenType.Array)
                        continue;

                    var tagArray = resourceTags.Value.ToObject<JArray> ();
                    var tags = new HashSet<string> ();
                    string hash;

                    foreach (var tag in tagArray.Select (token => token.ToObject<string> ()))
                        tags.Add (tag);

                    var tagList = tags.ToList ();
                    tagList.Sort ();

                    var path = AssetPackUtils.GetAssetPackDirectory (intermediate, bundleIdentifier, tagList, out hash);

                    if (knownSpecs.Add (hash)) {
                        var assetpack = new PDictionary ();
                        var ptags = new PArray ();

                        Directory.CreateDirectory (path);

                        for (int i = 0; i < tags.Count; i++)
                            ptags.Add (new PString (tagList[i]));

                        assetpack.Add ("bundle-id", new PString (string.Format ("{0}.asset-pack-{1}", bundleIdentifier, hash)));
                        assetpack.Add ("bundle-path", new PString (Path.GetFullPath (path)));
                        assetpack.Add ("tags", ptags);
                        specs.Add (assetpack);
                    }
                }
            }

            if (catalogs.Count == 0) {
                // There are no (supported?) asset catalogs
                return true;
            }

            partialAppManifest = new TaskItem (Path.Combine (intermediate, "partial-info.plist"));

            if (specs.Count > 0) {
                outputSpecs = Path.Combine (intermediate, "output-specifications.plist");
                specs.Save (outputSpecs, true);
            }

            var output = new TaskItem (intermediateBundleDir);

            Directory.CreateDirectory (intermediateBundleDir);

            // Note: Compile() will set the PartialAppManifest property if it is used...
            if ((rc = Compile (catalogs.ToArray (), output, manifest)) != 0) {
                if (File.Exists (manifest.ItemSpec)) {
                    try {
                        var log = PDictionary.FromFile (manifest.ItemSpec);

                        LogWarningsAndErrors (log, catalogs[0]);
                    } catch (FormatException) {
                        Log.LogError ("actool exited with code {0}", rc);
                    }

                    File.Delete (manifest.ItemSpec);
                }

                return false;
            }

            if (PartialAppManifest != null && !File.Exists (PartialAppManifest.GetMetadata ("FullPath")))
                Log.LogError ("Partial Info.plist file was not generated: {0}", PartialAppManifest.GetMetadata ("FullPath"));

            try {
                var manifestOutput = PDictionary.FromFile (manifest.ItemSpec);

                LogWarningsAndErrors (manifestOutput, catalogs[0]);

                bundleResources.AddRange (GetCompiledBundleResources (manifestOutput, intermediateBundleDir));
                outputManifests.Add (manifest);
            } catch (Exception ex) {
                Log.LogError ("Failed to load output manifest for {0} for the file {2}: {1}", ToolName, ex.Message, manifest.ItemSpec);
            }

            foreach (var assetpack in specs.OfType<PDictionary> ()) {
                var path = Path.Combine (assetpack.GetString ("bundle-path").Value, "Info.plist");
                var bundlePath = PathUtils.AbsoluteToRelative (intermediate, path);
                var outputPath = Path.Combine (OutputPath, bundlePath);
                var rpath = Path.Combine (intermediate, bundlePath);
                var dict = new PDictionary ();

                dict.SetCFBundleIdentifier (assetpack.GetString ("bundle-id").Value);
                dict.Add ("Tags", assetpack.GetArray ("tags").Clone ());

                dict.Save (path, true, true);

                var item = new TaskItem (rpath);
                item.SetMetadata ("LogicalName", bundlePath);
                item.SetMetadata ("OutputPath", outputPath);
                item.SetMetadata ("Optimize", "false");

                bundleResources.Add (item);
            }

            BundleResources = bundleResources.ToArray ();
            OutputManifests = outputManifests.ToArray ();

            return !Log.HasLoggedErrors;
        }
Example #37
0
        public override bool Execute()
        {
            var manifestPath = Path.Combine (AppBundleDir.ItemSpec, "AssetPackManifestTemplate.plist");
            var onDemandResourcesPath = Path.Combine (AppBundleDir.ItemSpec, "OnDemandResources.plist");
            var onDemandResourcesDir = Path.Combine (OutputPath, "OnDemandResources");
            var onDemandResourcesStamp = File.GetLastWriteTime (onDemandResourcesPath);
            var initialInstallTags = new HashSet<string> (AssetPackUtils.ParseTags (InitialInstallTags));
            var prefetchOrder = AssetPackUtils.ParseTags (PrefetchOrder);
            var manifestStamp = File.GetLastWriteTime (manifestPath);
            var onDemandResources = new PDictionary ();
            var requestTags = new PDictionary ();
            bool updateOnDemandResources = false;
            var assetPacks = new PDictionary ();
            var manifest = new PDictionary ();
            var resources = new PArray ();
            bool updateManifest = false;

            Log.LogTaskName ("CreateAssetPackManifest");
            Log.LogTaskProperty ("AppBundleDir", AppBundleDir);
            Log.LogTaskProperty ("InitialInstallTags", InitialInstallTags);
            Log.LogTaskProperty ("OutputPath", OutputPath);
            Log.LogTaskProperty ("PrefetchOrder", PrefetchOrder);

            if (!Directory.Exists (onDemandResourcesDir))
                return !Log.HasLoggedErrors;

            onDemandResources.Add ("NSBundleResourceRequestAssetPacks", assetPacks);
            onDemandResources.Add ("NSBundleResourceRequestTags", requestTags);

            manifest.Add ("resources", resources);

            foreach (var dir in Directory.EnumerateDirectories (onDemandResourcesDir)) {
                var path = Path.Combine (dir, "Info.plist");
                PDictionary info;

                if (!File.Exists (path))
                    continue;

                var mtime = File.GetLastWriteTime (path);

                updateOnDemandResources = updateOnDemandResources || mtime > onDemandResourcesStamp;
                updateManifest = updateManifest || mtime > manifestStamp;

                try {
                    info = PDictionary.FromFile (path);
                } catch {
                    continue;
                }

                var bundleIdentifier = info.GetCFBundleIdentifier ();
                var primaryContentHash = new PDictionary ();
                var resource = new PDictionary ();
                var items = new PArray ();
                long size = 0;

                // update OnDemandResources.plist:NSBundleResourceRequestAssetPacks
                foreach (var file in Directory.EnumerateFiles (dir)) {
                    var name = Path.GetFileName (file);

                    if (name != "Info.plist")
                        items.Add (new PString (name));

                    size += new FileInfo (file).Length;
                }

                assetPacks.Add (bundleIdentifier, items);

                // update OnDemandResources.plist:NSBundleResourceRequestTags
                var tags = info.GetArray ("Tags").OfType<PString> ().Select (x => x.Value);
                var priority = double.NaN;

                foreach (var tag in tags) {
                    PDictionary dict;
                    PArray packs;

                    if (initialInstallTags.Contains (tag)) {
                        priority = 1.0f;
                    } else {
                        for (int i = 0; i < prefetchOrder.Length; i++) {
                            if (tag == prefetchOrder[i]) {
                                var value = GetDownloadPriority (i, prefetchOrder.Length);

                                priority = double.IsNaN (priority) ? value : Math.Max (priority, value);
                                break;
                            }
                        }
                    }

                    if (!requestTags.TryGetValue (tag, out dict)) {
                        dict = new PDictionary ();
                        dict.Add ("NSAssetPacks", new PArray ());

                        requestTags.Add (tag, dict);
                    }

                    packs = dict.GetArray ("NSAssetPacks");

                    packs.Add (new PString (bundleIdentifier));
                }

                // update AssetPackManifestTemplate.plist
                resource.Add ("URL", new PString ("http://127.0.0.1" + Path.GetFullPath (dir)));
                resource.Add ("bundleKey", new PString (bundleIdentifier));

                if (!double.IsNaN (priority))
                    resource.Add ("downloadPriority", new PReal (priority));

                resource.Add ("isStreamable", new PBoolean (true));
                primaryContentHash.Add ("hash", mtime.ToString ("yyyy-MM-dd HH:mm:ss.000"));
                primaryContentHash.Add ("strategy", "modtime");
                resource.Add ("primaryContentHash", primaryContentHash);
                resource.Add ("uncompressedSize", new PNumber ((int) ((size + 8191) & ~8191)));

                resources.Add (resource);
            }

            if (updateOnDemandResources) {
                try {
                    onDemandResources.Save (onDemandResourcesPath, true, true);
                } catch (Exception ex) {
                    Log.LogError ("Error saving `{0}': {1}", onDemandResourcesPath, ex.Message);
                }
            }

            if (updateManifest) {
                try {
                    manifest.Save (manifestPath, true, true);
                } catch (Exception ex) {
                    Log.LogError ("Error saving `{0}': {1}", manifestPath, ex.Message);
                }
            }

            return !Log.HasLoggedErrors;
        }
		public void SetPListContainer (PObjectContainer container)
		{
			if (!(container is PArray))
				throw new ArgumentException ("The PList container must be a PArray.", "container");
			
			array = (PArray) container;
			array.Changed += OnArrayChanged;
			RefreshList ();
		}
Example #39
0
        bool Compile(PDictionary plist)
        {
            var currentSDK = IPhoneSdks.GetSdk (Framework);

            if (!currentSDK.SdkIsInstalled (sdkVersion, SdkIsSimulator)) {
                Log.LogError (null, null, null, null, 0, 0, 0, 0, "The {0} SDK for '{1}' is not installed.", Framework, sdkVersion);
                return false;
            }

            supportedDevices = plist.GetUIDeviceFamily ();

            if (!IsWatchApp) {
                var version = IPhoneSdks.MonoTouch.ExtendedVersion;
                // This key is our supported way of determining if an app
                // was built with Xamarin, so it needs to be present in all apps.

                var dict = new PDictionary ();
                dict.Add ("Version", new PString (string.Format ("{0} ({1}: {2})", version.Version, version.Branch, version.Hash)));
                plist.Add ("com.xamarin.ios", dict);
            }

            var sdkSettings = currentSDK.GetSdkSettings (sdkVersion, SdkIsSimulator);
            var dtSettings = currentSDK.GetDTSettings ();

            SetValue (plist, ManifestKeys.BuildMachineOSBuild, dtSettings.BuildMachineOSBuild);
            plist.SetIfNotPresent (ManifestKeys.CFBundleDevelopmentRegion, "en");

            plist.SetIfNotPresent (ManifestKeys.CFBundleExecutable, AssemblyName);
            if (IsIOS) {
                var executable = plist.GetCFBundleExecutable ();
                if (executable.EndsWith (".app", StringComparison.Ordinal))
                    LogAppManifestError ("The executable (CFBundleExecutable) name ({0}) cannot end with '.app', because iOS may fail to launch the app.", executable);
            }

            if (IsIOS) {
                if (minimumOSVersion < IPhoneSdkVersion.V5_0 && plist.GetUIMainStoryboardFile (true) != null)
                    LogAppManifestError ("Applications using a storyboard as the Main Interface must have a deployment target greater than 5.0");

                if (!plist.ContainsKey (ManifestKeys.CFBundleName))
                    plist [ManifestKeys.CFBundleName] = plist.ContainsKey (ManifestKeys.CFBundleDisplayName) ? plist.GetString (ManifestKeys.CFBundleDisplayName).Clone () : new PString (AppBundleName);
            } else {
                plist.SetIfNotPresent (ManifestKeys.CFBundleName, AppBundleName);
            }

            plist.SetIfNotPresent (ManifestKeys.CFBundleIdentifier, BundleIdentifier);
            plist.SetIfNotPresent (ManifestKeys.CFBundleInfoDictionaryVersion, "6.0");
            plist.SetIfNotPresent (ManifestKeys.CFBundlePackageType, IsAppExtension ? "XPC!" : "APPL");
            if (!string.IsNullOrEmpty (ResourceRules))
                plist.SetIfNotPresent (ManifestKeys.CFBundleResourceSpecification, Path.GetFileName (ResourceRules));
            plist.SetIfNotPresent (ManifestKeys.CFBundleSignature, "????");
            if (!plist.ContainsKey (ManifestKeys.CFBundleSupportedPlatforms))
                plist[ManifestKeys.CFBundleSupportedPlatforms] = new PArray { SdkPlatform };
            plist.SetIfNotPresent (ManifestKeys.CFBundleVersion, "1.0");

            if (!SdkIsSimulator) {
                SetValue (plist, "DTCompiler", sdkSettings.DTCompiler);
                SetValue (plist, "DTPlatformBuild", dtSettings.DTPlatformBuild);
                SetValue (plist, "DTSDKBuild", sdkSettings.DTSDKBuild);
            }

            plist.SetIfNotPresent ("DTPlatformName", SdkPlatform.ToLowerInvariant ());
            if (!SdkIsSimulator)
                SetValue (plist, "DTPlatformVersion", dtSettings.DTPlatformVersion);

            var sdkName = sdkSettings.CanonicalName;
            // older sdksettings didn't have a canonicalname for sim
            if (SdkIsSimulator && string.IsNullOrEmpty (sdkName)) {
                var deviceSdkSettings = currentSDK.GetSdkSettings (sdkVersion, false);
                sdkName = deviceSdkSettings.AlternateSDK;
            }
            SetValue (plist, "DTSDKName", sdkName);

            if (!SdkIsSimulator) {
                SetValue (plist, "DTXcode", AppleSdkSettings.DTXcode);
                SetValue (plist, "DTXcodeBuild", dtSettings.DTXcodeBuild);
            }

            SetDeviceFamily (plist);

            if (IsWatchExtension) {
                PObject capabilities;

                if (!plist.TryGetValue (ManifestKeys.UIRequiredDeviceCapabilities, out capabilities))
                    plist[ManifestKeys.UIRequiredDeviceCapabilities] = capabilities = new PArray ();
            }

            plist.SetIfNotPresent (ManifestKeys.MinimumOSVersion, minimumOSVersion.ToString ());

            // Remove any Xamarin Studio specific keys
            plist.Remove (ManifestKeys.XSLaunchImageAssets);
            plist.Remove (ManifestKeys.XSAppIconAssets);

            // Merge with any partial plists generated by the Asset Catalog compiler...
            MergePartialPlistTemplates (plist);

            if (IsIOS)
                Validation (plist);

            CompiledAppManifest = new TaskItem (Path.Combine (AppBundleDir, "Info.plist"));
            plist.Save (CompiledAppManifest.ItemSpec, true, true);

            return !Log.HasLoggedErrors;
        }
		void AddNewArrayElement (PArray array)
		{
			var values = PListScheme.AvailableKeys (array, CurrentTree);
			if (values == null) {
				array.Add (PObject.Create (DefaultNewObjectType));
			} else if (values.Any ()) {
				array.Add (values.First ().Create ());
			}
		}
Example #41
0
        void AddIconPaths(PArray icons, PArray iconFiles, string productsDir)
        {
            foreach (var icon in iconFiles.Cast<PString> ().Where (p => p.Value != null)) {
                var path = string.Format ("Applications/{0}/{1}", Path.GetFileName (AppBundleDir.ItemSpec), icon.Value);
                bool addDefault = true;

                if (path.EndsWith (".png", StringComparison.Ordinal)) {
                    icons.Add (new PString (path));
                    continue;
                }

                if (File.Exists (Path.Combine (productsDir, path + "@3x.png"))) {
                    icons.Add (new PString (path + "@3x.png"));
                    addDefault = false;
                }

                if (File.Exists (Path.Combine (productsDir, path + "@2x.png"))) {
                    icons.Add (new PString (path + "@2x.png"));
                    addDefault = false;
                }

                if (addDefault || File.Exists (Path.Combine (productsDir, path + ".png")))
                    icons.Add (new PString (path + ".png"));
            }
        }
Example #42
0
        public override bool Execute()
        {
            Log.LogTaskName ("Archive");
            Log.LogTaskProperty ("AppBundleDir", AppBundleDir);
            Log.LogTaskProperty ("AppExtensionReferences", AppExtensionReferences);
            Log.LogTaskProperty ("ITunesSourceFiles", ITunesSourceFiles);
            Log.LogTaskProperty ("OutputPath", OutputPath);
            Log.LogTaskProperty ("ProjectName", ProjectName);
            Log.LogTaskProperty ("SigningKey", SigningKey);
            Log.LogTaskProperty ("SolutionPath", SolutionPath);

            var archiveDir = CreateArchiveDirectory ();

            try {
                var plist = PDictionary.FromFile (Path.Combine (AppBundleDir.ItemSpec, "Info.plist"));
                var productsDir = Path.Combine (archiveDir, "Products");

                // Archive the OnDemandResources...
                var resourcesDestDir = Path.Combine (productsDir, "OnDemandResources");
                var resourcesSrcDir = Path.Combine (OutputPath, "OnDemandResources");

                if (Directory.Exists (resourcesSrcDir))
                    Ditto (resourcesSrcDir, resourcesDestDir);

                // Archive the Applications...
                var appDestDir = Path.Combine (productsDir, "Applications", Path.GetFileName (AppBundleDir.ItemSpec));
                Ditto (AppBundleDir.ItemSpec, appDestDir);

                // Archive the dSYMs...
                var dsymsDestDir = Path.Combine (archiveDir, "dSYMs", Path.GetFileName (DSYMDir));
                Ditto (DSYMDir, dsymsDestDir);

                // Archive the Bitcode symbol maps
                var bcSymbolMaps = Directory.GetFiles (Path.GetDirectoryName (DSYMDir), "*.bcsymbolmap");
                if (bcSymbolMaps.Length > 0) {
                    var bcSymbolMapsDir = Path.Combine (archiveDir, "BCSymbolMaps");

                    Directory.CreateDirectory (bcSymbolMapsDir);

                    for (int i = 0; i < bcSymbolMaps.Length; i++)
                        File.Copy (bcSymbolMaps[i], Path.Combine (bcSymbolMapsDir, Path.GetFileName (bcSymbolMaps[i])));
                }

                if (AppExtensionReferences != null) {
                    // Archive the dSYMs for each of the referenced App Extensions as well...
                    for (int i = 0; i < AppExtensionReferences.Length; i++)
                        ArchiveAppExtension (AppExtensionReferences[i], archiveDir);
                }

                if (ITunesSourceFiles != null) {
                    // Archive the iTunesMetadata.plist and iTunesArtwork files...
                    var iTunesMetadataDir = Path.Combine (archiveDir, "iTunesMetadata", Path.GetFileName (AppBundleDir.ItemSpec));
                    for (int i = 0; i < ITunesSourceFiles.Length; i++) {
                        var archivedMetaFile = Path.Combine (iTunesMetadataDir, Path.GetFileName (ITunesSourceFiles[i].ItemSpec));

                        Directory.CreateDirectory (iTunesMetadataDir);
                        File.Copy (ITunesSourceFiles[i].ItemSpec, archivedMetaFile, true);
                    }
                }

                // Generate an archive Info.plist
                var arInfo = new PDictionary ();
                // FIXME: figure out this value
                //arInfo.Add ("AppStoreFileSize", new PNumber (65535));

                var props = new PDictionary ();
                props.Add ("ApplicationPath", new PString (string.Format ("Applications/{0}", Path.GetFileName (AppBundleDir.ItemSpec))));
                props.Add ("CFBundleIdentifier", new PString (plist.GetCFBundleIdentifier ()));
                if (plist.GetCFBundleShortVersionString () != null)
                    props.Add ("CFBundleShortVersionString", new PString (plist.GetCFBundleShortVersionString ()));
                else if (plist.GetCFBundleVersion () != null)
                    props.Add ("CFBundleShortVersionString", new PString (plist.GetCFBundleVersion ()));

                var iconFiles = plist.GetCFBundleIconFiles ();
                var iconDict = plist.GetCFBundleIcons ();
                var icons = new PArray ();

                if (iconFiles != null)
                    AddIconPaths (icons, iconFiles, Path.Combine (archiveDir, "Products"));

                if (iconDict != null) {
                    var primary = iconDict.Get<PDictionary> (ManifestKeys.CFBundlePrimaryIcon);
                    if (primary != null && (iconFiles = primary.GetCFBundleIconFiles ()) != null)
                        AddIconPaths (icons, iconFiles, Path.Combine (archiveDir, "Products"));
                }

                if (icons.Count > 0)
                    props.Add ("IconPaths", icons);

                props.Add ("SigningIdentity", new PString (SigningKey));

                arInfo.Add ("ApplicationProperties", props);
                arInfo.Add ("ArchiveVersion", new PNumber (2));
                arInfo.Add ("CreationDate", new PDate (Now.ToUniversalTime ()));
                arInfo.Add ("Name", new PString (plist.GetCFBundleName () ?? plist.GetCFBundleDisplayName ()));
                arInfo.Add ("SchemeName", new PString (ProjectName));

                if (!string.IsNullOrEmpty (SolutionPath)) {
                    arInfo.Add ("SolutionName", new PString (Path.GetFileNameWithoutExtension (SolutionPath)));
                    arInfo.Add ("SolutionPath", new PString (SolutionPath));
                }

                arInfo.Save (Path.Combine (archiveDir, "Info.plist"));

                ArchiveDir = archiveDir;
            } catch (Exception ex) {
                Log.LogErrorFromException (ex);
                Directory.Delete (archiveDir, true);
            }

            return !Log.HasLoggedErrors;
        }