Welcome to mirror list, hosted at ThFree Co, Russian Federation.

PObject.cs « MonoDevelop.Ide.Editor.Highlighting « MonoDevelop.Ide « core « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b4616c511c5beaa855ec7c525bc3a2d0c23e3ccd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
// 
// PObject.cs
//  
// Author:
//       Mike Krüger <mkrueger@xamarin.com>
//       Alex Corrado <corrado@xamarin.com>
// 
// Copyright (c) 2011 Xamarin <http://xamarin.com>
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

// Now a purely managed implementation for plist reading & writing.
// Define POBJECT_MONOMAC to enable the conversions to/from NSObject and friends.

// Binary format reference: http://opensource.apple.com/source/CF/CF-635.21/CFBinaryPList.c

using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Security;
using System.Threading.Tasks;
using MonoDevelop.Core;

namespace MonoDevelop.Ide.Editor.Highlighting
{
	abstract class PObject
	{
		public static PObject Create (PObjectType type)
		{
			switch (type) {
			case PObjectType.Dictionary:
				return new PDictionary ();
			case PObjectType.Array:
				return new PArray ();
			case PObjectType.Number:
				return new PNumber (0);
			case PObjectType.Real:
				return new PReal (0);
			case PObjectType.Boolean:
				return new PBoolean (true);
			case PObjectType.Data:
				return new PData (new byte [0]);
			case PObjectType.String:
				return new PString ("");
			case PObjectType.Date:
				return new PDate (DateTime.Now);
			default:
				throw new ArgumentOutOfRangeException ();
			}
		}

		public static IEnumerable<KeyValuePair<string, PObject>> ToEnumerable (PObject obj)
		{
			if (obj is PDictionary)
				return (PDictionary)obj;

			if (obj is PArray)
				return ((PArray)obj).Select (k => new KeyValuePair<string, PObject> (k is IPValueObject ? ((IPValueObject)k).Value.ToString () : null, k));

			return Enumerable.Empty<KeyValuePair<string, PObject>> ();
		}

		PObjectContainer parent;
		public PObjectContainer Parent {
			get { return parent; }
			set {
				if (parent != null && value != null)
					throw new NotSupportedException ("Already parented.");

				parent = value;
			}
		}

		public abstract PObject Clone ();

		public void Replace (PObject newObject)
		{
			var p = Parent;
			if (p is PDictionary) {
				var dict = (PDictionary)p;
				var key = dict.GetKey (this);
				if (key == null)
					return;
				Remove ();
				dict [key] = newObject;
			} else if (p is PArray) {
				var arr = (PArray)p;
				arr.Replace (this, newObject);
			}
		}

		public string Key {
			get {
				if (Parent is PDictionary) {
					var dict = (PDictionary)Parent;
					return dict.GetKey (this);
				}
				return null;
			}
		}

		public void Remove ()
		{
			if (Parent is PDictionary) {
				var dict = (PDictionary)Parent;
				dict.Remove (Key);
			} else if (Parent is PArray) {
				var arr = (PArray)Parent;
				arr.Remove (this);
			} else {
				if (Parent == null)
					throw new InvalidOperationException ("Can't remove from null parent");
				throw new InvalidOperationException ("Can't remove from parent " + Parent);
			}
		}

#if POBJECT_MONOMAC
		public abstract NSObject Convert ();
#endif

		public abstract PObjectType Type { get; }

		public static implicit operator PObject (string value)
		{
			return new PString (value);
		}

		public static implicit operator PObject (int value)
		{
			return new PNumber (value);
		}

		public static implicit operator PObject (double value)
		{
			return new PReal (value);
		}

		public static implicit operator PObject (bool value)
		{
			return new PBoolean (value);
		}

		public static implicit operator PObject (DateTime value)
		{
			return new PDate (value);
		}

		public static implicit operator PObject (byte [] value)
		{
			return new PData (value);
		}

		protected virtual void OnChanged (EventArgs e)
		{
			if (SuppressChangeEvents)
				return;

			var handler = Changed;
			if (handler != null)
				handler (this, e);

			if (Parent != null)
				Parent.OnCollectionChanged (Key, this);
		}

		protected bool SuppressChangeEvents {
			get; set;
		}

		public event EventHandler Changed;

		public byte [] ToByteArray (bool binary)
		{
			var format = binary ? PropertyListFormat.Binary : PropertyListFormat.Xml;

			using (var stream = new MemoryStream ()) {
				using (var context = format.StartWriting (stream))
					context.WriteObject (this);
				return stream.ToArray ();
			}
		}

		public string ToXml ()
		{
			return Encoding.UTF8.GetString (ToByteArray (false));
		}

#if POBJECT_MONOMAC
		static readonly IntPtr selObjCType = Selector.GetHandle ("objCType");

		public static PObject FromNSObject (NSObject val)
		{
			if (val == null)
				return null;
			
			var dict = val as NSDictionary;
			if (dict != null) {
				var result = new PDictionary ();
				foreach (var pair in dict) {
					string k = pair.Key.ToString ();
					result[k] = FromNSObject (pair.Value);
				}
				return result;
			}
			
			var arr = val as NSArray;
			if (arr != null) {
				var result = new PArray ();
				uint count = arr.Count;
				for (uint i = 0; i < count; i++) {
					var obj = Runtime.GetNSObject (arr.ValueAt (i));
					if (obj != null)
						result.Add (FromNSObject (obj));
				}
				return result;
			}
			
			var str = val as NSString;
			if (str != null)
				return str.ToString ();
			
			var nr = val as NSNumber;
			if (nr != null) {
				char t;
				unsafe {
					t = (char) *((byte*) MonoMac.ObjCRuntime.Messaging.IntPtr_objc_msgSend (val.Handle, selObjCType));
				}
				if (t == 'c' || t == 'C' || t == 'B')
					return nr.BoolValue;
				return nr.Int32Value;
			}
			
			var date = val as NSDate;
			if (date != null)
				return (DateTime) date;
			
			var data = val as NSData;
			if (data != null) {
				var bytes = new byte[data.Length];
				System.Runtime.InteropServices.Marshal.Copy (data.Bytes, bytes, 0, (int)data.Length);
				return bytes;
			}
			
			throw new NotSupportedException (val.ToString ());
		}
#endif

		public static PObject FromByteArray (byte [] array, int startIndex, int length, out bool isBinary)
		{
			var ctx = PropertyListFormat.Binary.StartReading (array, startIndex, length);

			isBinary = true;

			try {
				if (ctx == null) {
					isBinary = false;
					ctx = PropertyListFormat.CreateReadContext (array, startIndex, length);
					if (ctx == null)
						return null;
				}

				return ctx.ReadObject ();
			} finally {
				if (ctx != null)
					ctx.Dispose ();
			}
		}

		public static PObject FromByteArray (byte [] array, out bool isBinary)
		{
			return FromByteArray (array, 0, array.Length, out isBinary);
		}

		public static PObject FromString (string str)
		{
			var ctx = PropertyListFormat.CreateReadContext (Encoding.UTF8.GetBytes (str));
			if (ctx == null)
				return null;
			return ctx.ReadObject ();
		}

		public static PObject FromStream (Stream stream)
		{
			var ctx = PropertyListFormat.CreateReadContext (stream);
			if (ctx == null)
				return null;
			return ctx.ReadObject ();
		}
	}


	abstract class PObjectContainer : PObject
	{
		public abstract int Count { get; }

		public bool Reload (string fileName)
		{
			using (var stream = new FileStream (fileName, FileMode.Open, FileAccess.Read)) {
				using (var ctx = PropertyListFormat.CreateReadContext (stream)) {
					if (ctx == null)
						return false;

					return Reload (ctx);
				}
			}
		}

		protected abstract bool Reload (PropertyListFormat.ReadWriteContext ctx);

		public Task SaveAsync (string filename, bool atomic = false, bool binary = false)
		{
			return Task.Factory.StartNew (() => Save (filename, atomic, binary));
		}

		public void Save (string filename, bool atomic = false, bool binary = false)
		{
			var tempFile = atomic ? GetTempFileName (filename) : filename;
			try {
				if (!Directory.Exists (Path.GetDirectoryName (tempFile)))
					Directory.CreateDirectory (Path.GetDirectoryName (tempFile));

				using (var stream = new FileStream (tempFile, FileMode.Create, FileAccess.Write)) {
					using (var ctx = binary ? PropertyListFormat.Binary.StartWriting (stream) : PropertyListFormat.Xml.StartWriting (stream))
						ctx.WriteObject (this);
				}
				if (atomic) {
					if (File.Exists (filename))
						File.Replace (tempFile, filename, null, true);
					else
						File.Move (tempFile, filename);
				}
			} finally {
				if (atomic)
					File.Delete (tempFile); // just in case- no exception is raised if file is not found
			}
		}

		static string GetTempFileName (string filename)
		{
			var i = 1;
			var tempfile = filename + ".tmp";
			while (File.Exists (tempfile))
				tempfile = filename + ".tmp." + (i++).ToString ();
			return tempfile;
		}

		protected void OnChildAdded (string key, PObject child)
		{
			child.Parent = this;

			OnCollectionChanged (PObjectContainerAction.Added, key, null, child);
		}

		internal void OnCollectionChanged (string key, PObject child)
		{
			OnCollectionChanged (PObjectContainerAction.Changed, key, null, child);
		}

		protected void OnChildRemoved (string key, PObject child)
		{
			child.Parent = null;

			OnCollectionChanged (PObjectContainerAction.Removed, key, child, null);
		}

		protected void OnChildReplaced (string key, PObject oldChild, PObject newChild)
		{
			oldChild.Parent = null;
			newChild.Parent = this;

			OnCollectionChanged (PObjectContainerAction.Replaced, key, oldChild, newChild);
		}

		protected void OnCleared ()
		{
			OnCollectionChanged (PObjectContainerAction.Cleared, null, null, null);
		}

		protected void OnCollectionChanged (PObjectContainerAction action, string key, PObject oldChild, PObject newChild)
		{
			if (SuppressChangeEvents)
				return;

			var handler = CollectionChanged;
			if (handler != null)
				handler (this, new PObjectContainerEventArgs (action, key, oldChild, newChild));

			OnChanged (EventArgs.Empty);

			if (Parent != null)
				Parent.OnCollectionChanged (Key, this);
		}

		public event EventHandler<PObjectContainerEventArgs> CollectionChanged;
	}


	interface IPValueObject
	{
		object Value { get; set; }
		bool TrySetValueFromString (string text, IFormatProvider formatProvider);
	}


	abstract class PValueObject<T> : PObject, IPValueObject
	{
		T val;
		public T Value {
			get {
				return val;
			}
			set {
				val = value;
				OnChanged (EventArgs.Empty);
			}
		}

		object IPValueObject.Value {
			get { return Value; }
			set { Value = (T)value; }
		}

		protected PValueObject (T value)
		{
			Value = value;
		}

		protected PValueObject ()
		{
		}

		public static implicit operator T (PValueObject<T> pObj)
		{
			return pObj != null ? pObj.Value : default (T);
		}

		public abstract bool TrySetValueFromString (string text, IFormatProvider formatProvider);
	}


	class PDictionary : PObjectContainer, IEnumerable<KeyValuePair<string, PObject>>
	{
		static readonly byte [] BeginMarkerBytes = Encoding.ASCII.GetBytes ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		static readonly byte [] EndMarkerBytes = Encoding.ASCII.GetBytes ("</plist>");

		readonly Dictionary<string, PObject> dict;
		readonly List<string> order;

		public PObject this [string key] {
			get {
				PObject value;
				if (dict.TryGetValue (key, out value))
					return value;
				return null;
			}
			set {
				PObject existing;
				bool exists = dict.TryGetValue (key, out existing);
				if (!exists)
					order.Add (key);

				dict [key] = value;

				if (exists)
					OnChildReplaced (key, existing, value);
				else
					OnChildAdded (key, value);
			}
		}

		public void Add (string key, PObject value)
		{
			try {
				dict.Add (key, value);
			} catch (Exception e) {
				LoggingService.LogError ("error while adding " + key);
				throw e;
			}
			order.Add (key);

			OnChildAdded (key, value);
		}

		public void InsertAfter (string keyBefore, string key, PObject value)
		{
			dict.Add (key, value);
			order.Insert (order.IndexOf (keyBefore) + 1, key);

			OnChildAdded (key, value);
		}

		public override int Count {
			get { return dict.Count; }
		}

		#region IEnumerable[KeyValuePair[System.String,PObject]] implementation
		public IEnumerator<KeyValuePair<string, PObject>> GetEnumerator ()
		{
			foreach (var key in order)
				yield return new KeyValuePair<string, PObject> (key, dict [key]);
		}
		#endregion

		#region IEnumerable implementation
		IEnumerator IEnumerable.GetEnumerator ()
		{
			return GetEnumerator ();
		}
		#endregion

		public PDictionary ()
		{
			dict = new Dictionary<string, PObject> ();
			order = new List<string> ();
		}

		public override PObject Clone ()
		{
			var dict = new PDictionary ();
			foreach (var kv in this)
				dict.Add (kv.Key, kv.Value.Clone ());
			return dict;
		}

		public bool ContainsKey (string name)
		{
			return dict.ContainsKey (name);
		}

		public bool Remove (string key)
		{
			PObject obj;
			if (dict.TryGetValue (key, out obj)) {
				dict.Remove (key);
				order.Remove (key);
				OnChildRemoved (key, obj);
				return true;
			}
			return false;
		}

		public void Clear ()
		{
			dict.Clear ();
			order.Clear ();
			OnCleared ();
		}

		public bool ChangeKey (PObject obj, string newKey)
		{
			return ChangeKey (obj, newKey, null);
		}

		public bool ChangeKey (PObject obj, string newKey, PObject newValue)
		{
			var oldkey = GetKey (obj);
			if (oldkey == null || dict.ContainsKey (newKey))
				return false;

			dict.Remove (oldkey);
			dict.Add (newKey, newValue ?? obj);
			order [order.IndexOf (oldkey)] = newKey;
			if (newValue != null) {
				OnChildRemoved (oldkey, obj);
				OnChildAdded (newKey, newValue);
			} else {
				OnChildRemoved (oldkey, obj);
				OnChildAdded (newKey, obj);
			}
			return true;
		}

		public string GetKey (PObject obj)
		{
			foreach (var pair in dict) {
				if (pair.Value == obj)
					return pair.Key;
			}
			return null;
		}

		public T Get<T> (string key) where T : PObject
		{
			PObject obj;

			if (!dict.TryGetValue (key, out obj))
				return null;

			return obj as T;
		}

		public bool TryGetValue<T> (string key, out T value) where T : PObject
		{
			PObject obj;

			if (!dict.TryGetValue (key, out obj)) {
				value = default (T);
				return false;
			}

			value = obj as T;

			return value != null;
		}

		static int IndexOf (byte [] haystack, int startIndex, byte [] needle)
		{
			int maxLength = haystack.Length - needle.Length;
			int n;

			for (int i = startIndex; i < maxLength; i++) {
				for (n = 0; n < needle.Length; n++) {
					if (haystack [i + n] != needle [n])
						break;
				}

				if (n == needle.Length)
					return i;
			}

			return -1;
		}

		public static new PDictionary FromByteArray (byte [] array, int startIndex, int length, out bool isBinary)
		{
			return (PDictionary)PObject.FromByteArray (array, startIndex, length, out isBinary);
		}

		public static new PDictionary FromByteArray (byte [] array, out bool isBinary)
		{
			return (PDictionary)PObject.FromByteArray (array, out isBinary);
		}

		public static PDictionary FromBinaryXml (byte [] array)
		{
			//find the raw plist within the .mobileprovision file
			int start = IndexOf (array, 0, BeginMarkerBytes);
			bool binary;
			int length;

			if (start < 0 || (length = (IndexOf (array, start, EndMarkerBytes) - start)) < 1)
				throw new Exception ("Did not find XML plist in buffer.");

			length += EndMarkerBytes.Length;

			return PDictionary.FromByteArray (array, start, length, out binary);
		}

		public static PDictionary FromFile (string fileName)
		{
			bool isBinary;
			return FromFile (fileName, out isBinary);
		}

		public static Task<PDictionary> FromFileAsync (string fileName)
		{
			return Task<PDictionary>.Factory.StartNew (() => {
				bool isBinary;
				return FromFile (fileName, out isBinary);
			});
		}

		public static PDictionary FromFile (string fileName, out bool isBinary)
		{
			using (var stream = new FileStream (fileName, FileMode.Open, FileAccess.Read)) {
				return FromStream(stream, out isBinary);
			}
		}

		new public static PDictionary FromStream (Stream stream)
		{
			bool isBinary;
			return FromStream (stream, out isBinary);
		}

		public static PDictionary FromStream (Stream stream, out bool isBinary)
		{
			isBinary = true;
			var ctx = PropertyListFormat.Binary.StartReading (stream);
			try {
				if (ctx == null) {
					isBinary = false;
					ctx = PropertyListFormat.CreateReadContext (stream);
					if (ctx == null)
						throw new FormatException ("Unrecognized property list format.");
				}
				return (PDictionary)ctx.ReadObject ();
			} finally {
				if (ctx != null)
					ctx.Dispose ();
			}
		}


		public static PDictionary FromBinaryXml (string fileName)
		{
			return FromBinaryXml (File.ReadAllBytes (fileName));
		}

		protected override bool Reload (PropertyListFormat.ReadWriteContext ctx)
		{
			SuppressChangeEvents = true;
			var result = ctx.ReadDict (this);
			SuppressChangeEvents = false;
			if (result)
				OnChanged (EventArgs.Empty);
			return result;
		}

		public override string ToString ()
		{
			return string.Format ("[PDictionary: Items={0}]", dict.Count);
		}

		public void SetString (string key, string value)
		{
			var result = Get<PString> (key);

			if (result == null)
				this [key] = new PString (value);
			else
				result.Value = value;
		}

		public PString GetString (string key)
		{
			var result = Get<PString> (key);

			if (result == null)
				this [key] = result = new PString ("");

			return result;
		}

		public PArray GetArray (string key)
		{
			var result = Get<PArray> (key);

			if (result == null)
				this [key] = result = new PArray ();

			return result;
		}

		public override PObjectType Type {
			get { return PObjectType.Dictionary; }
		}
	}


	class PArray : PObjectContainer, IEnumerable<PObject>
	{
		List<PObject> list;

		public override int Count {
			get { return list.Count; }
		}

		public PObject this [int i] {
			get {
				return list [i];
			}
			set {
				if (i < 0 || i >= Count)
					throw new ArgumentOutOfRangeException ();
				var existing = list [i];
				list [i] = value;

				OnChildReplaced (null, existing, value);
			}
		}

		public PArray ()
		{
			list = new List<PObject> ();
		}

		public PArray (List<PObject> list)
		{
			this.list = list;
		}

		public override PObject Clone ()
		{
			var array = new PArray ();
			foreach (var item in this)
				array.Add (item.Clone ());
			return array;
		}

		protected override bool Reload (PropertyListFormat.ReadWriteContext ctx)
		{
			SuppressChangeEvents = true;
			var result = ctx.ReadArray (this);
			SuppressChangeEvents = false;
			if (result)
				OnChanged (EventArgs.Empty);
			return result;
		}

		public void Add (PObject obj)
		{
			list.Add (obj);
			OnChildAdded (null, obj);
		}

		public void Insert (int index, PObject obj)
		{
			list.Insert (index, obj);
			OnChildAdded (null, obj);
		}

		public void Replace (PObject oldObj, PObject newObject)
		{
			for (int i = 0; i < Count; i++) {
				if (list [i] == oldObj) {
					list [i] = newObject;
					OnChildReplaced (null, oldObj, newObject);
					break;
				}
			}
		}

		public void Remove (PObject obj)
		{
			if (list.Remove (obj))
				OnChildRemoved (null, obj);
		}

		public void Clear ()
		{
			list.Clear ();
			OnCleared ();
		}

		public override string ToString ()
		{
			return string.Format ("[PArray: Items={0}]", Count);
		}

		public void AssignStringList (string strList)
		{
			SuppressChangeEvents = true;
			try {
				Clear ();
				foreach (var item in strList.Split (',', ' ')) {
					if (string.IsNullOrEmpty (item))
						continue;
					Add (new PString (item));
				}
			} finally {
				SuppressChangeEvents = false;
				OnChanged (EventArgs.Empty);
			}
		}

		public string [] ToStringArray ()
		{
			var strlist = new List<string> ();

			foreach (PString str in list.OfType<PString> ())
				strlist.Add (str.Value);

			return strlist.ToArray ();
		}

		public string ToStringList ()
		{
			var sb = StringBuilderCache.Allocate ();
			foreach (PString str in list.OfType<PString> ()) {
				if (sb.Length > 0)
					sb.Append (", ");
				sb.Append (str);
			}
			return StringBuilderCache.ReturnAndFree (sb);
		}

		public IEnumerator<PObject> GetEnumerator ()
		{
			return list.GetEnumerator ();
		}

		IEnumerator IEnumerable.GetEnumerator ()
		{
			return list.GetEnumerator ();
		}

		public override PObjectType Type {
			get { return PObjectType.Array; }
		}
	}


	class PBoolean : PValueObject<bool>
	{
		public PBoolean (bool value) : base (value)
		{
		}

		public override PObject Clone ()
		{
			return new PBoolean (Value);
		}

		public override PObjectType Type {
			get { return PObjectType.Boolean; }
		}

		public override bool TrySetValueFromString (string text, IFormatProvider formatProvider)
		{
			const StringComparison ic = StringComparison.OrdinalIgnoreCase;

			if ("true".Equals (text, ic) || "yes".Equals (text, ic)) {
				Value = true;
				return true;
			}

			if ("false".Equals (text, ic) || "no".Equals (text, ic)) {
				Value = false;
				return true;
			}

			return false;
		}
	}


	class PData : PValueObject<byte []>
	{
		static readonly byte [] Empty = new byte [0];

#if POBJECT_MONOMAC
		public override NSObject Convert ()
		{
			// Work around a bug in NSData.FromArray as it cannot (currently) handle
			// zero length arrays
			if (Value.Length == 0)
				return new NSData ();
			else
				return NSData.FromArray (Value);
		}
#endif

		public PData (byte [] value) : base (value ?? Empty)
		{
		}

		public override PObject Clone ()
		{
			return new PData (Value);
		}

		public override PObjectType Type {
			get { return PObjectType.Data; }
		}

		public override bool TrySetValueFromString (string text, IFormatProvider formatProvider)
		{
			return false;
		}
	}


	class PDate : PValueObject<DateTime>
	{
		public PDate (DateTime value) : base (value)
		{
		}

		public override PObject Clone ()
		{
			return new PDate (Value);
		}

		public override PObjectType Type {
			get { return PObjectType.Date; }
		}

		public override bool TrySetValueFromString (string text, IFormatProvider formatProvider)
		{
			DateTime result;
			if (DateTime.TryParse (text, formatProvider, DateTimeStyles.None, out result)) {
				Value = result;
				return true;
			}
			return false;
		}
	}


	class PNumber : PValueObject<int>
	{
		public PNumber (int value) : base (value)
		{
		}

		public override PObject Clone ()
		{
			return new PNumber (Value);
		}

#if POBJECT_MONOMAC
		public override NSObject Convert ()
		{
			return NSNumber.FromInt32 (Value);
		}
#endif

		public override PObjectType Type {
			get { return PObjectType.Number; }
		}

		public override bool TrySetValueFromString (string text, IFormatProvider formatProvider)
		{
			int result;
			if (int.TryParse (text, NumberStyles.Integer, formatProvider, out result)) {
				Value = result;
				return true;
			}
			return false;
		}
	}


	class PReal : PValueObject<double>
	{
		public PReal (double value) : base (value)
		{
		}

		public override PObject Clone ()
		{
			return new PReal (Value);
		}

		public override PObjectType Type {
			get { return PObjectType.Real; }
		}

		public override bool TrySetValueFromString (string text, IFormatProvider formatProvider)
		{
			double result;
			if (double.TryParse (text, NumberStyles.AllowDecimalPoint, formatProvider, out result)) {
				Value = result;
				return true;
			}
			return false;
		}
	}


	class PString : PValueObject<string>
	{
		public PString (string value) : base (value)
		{
			if (value == null)
				throw new ArgumentNullException ("value");
		}

		public override PObject Clone ()
		{
			return new PString (Value);
		}

#if POBJECT_MONOMAC
		public override NSObject Convert ()
		{
			return new NSString (Value);
		}
#endif

		public override PObjectType Type {
			get { return PObjectType.String; }
		}

		public override bool TrySetValueFromString (string text, IFormatProvider formatProvider)
		{
			Value = text;
			return true;
		}
	}


	abstract class PropertyListFormat
	{
		public static readonly PropertyListFormat Xml = new XmlFormat ();
		public static readonly PropertyListFormat Binary = new BinaryFormat ();

		// Stream must be seekable
		public static ReadWriteContext CreateReadContext (Stream input)
		{
			return Binary.StartReading (input) ?? Xml.StartReading (input);
		}

		public static ReadWriteContext CreateReadContext (byte [] array, int startIndex, int length)
		{
			return CreateReadContext (new MemoryStream (array, startIndex, length));
		}

		public static ReadWriteContext CreateReadContext (byte [] array)
		{
			return CreateReadContext (new MemoryStream (array, 0, array.Length));
		}

		// returns null if the input is not of the correct format. Stream must be seekable
		public abstract ReadWriteContext StartReading (Stream input);
		public abstract ReadWriteContext StartWriting (Stream output);

		public ReadWriteContext StartReading (byte [] array, int startIndex, int length)
		{
			return StartReading (new MemoryStream (array, startIndex, length));
		}

		public ReadWriteContext StartReading (byte [] array)
		{
			return StartReading (new MemoryStream (array, 0, array.Length));
		}

		class BinaryFormat : PropertyListFormat
		{
			// magic is bplist + 2 byte version id
			static readonly byte [] BPLIST_MAGIC = { 0x62, 0x70, 0x6C, 0x69, 0x73, 0x74 };  // "bplist"
			static readonly byte [] BPLIST_VERSION = { 0x30, 0x30 }; // "00"

			public override ReadWriteContext StartReading (Stream input)
			{
				if (input.Length < BPLIST_MAGIC.Length + 2)
					return null;

				input.Seek (0, SeekOrigin.Begin);
				for (var i = 0; i < BPLIST_MAGIC.Length; i++) {
					if ((byte)input.ReadByte () != BPLIST_MAGIC [i])
						return null;
				}

				// skip past the 2 byte version id for now
				//  we currently don't bother checking it because it seems different versions of OSX might write different values here?
				input.Seek (2, SeekOrigin.Current);
				return new Context (input, true);
			}

			public override ReadWriteContext StartWriting (Stream output)
			{
				output.Write (BPLIST_MAGIC, 0, BPLIST_MAGIC.Length);
				output.Write (BPLIST_VERSION, 0, BPLIST_VERSION.Length);

				return new Context (output, false);
			}

			class Context : ReadWriteContext
			{

				static readonly DateTime AppleEpoch = new DateTime (2001, 1, 1, 0, 0, 0, DateTimeKind.Utc); //see CFDateGetAbsoluteTime

				//https://github.com/mono/referencesource/blob/mono/mscorlib/system/datetime.cs
				const long TicksPerMillisecond = 10000;
				const long TicksPerSecond = TicksPerMillisecond * 1000;

				Stream stream;
				int currentLength;

				CFBinaryPlistTrailer trailer;

				//for writing
				List<object> objectRefs;
				int currentRef;
				long [] offsets;

				public Context (Stream stream, bool reading)
				{
					this.stream = stream;
					if (reading) {
						trailer = CFBinaryPlistTrailer.Read (this);
						ReadObjectHead ();
					}
				}

				#region Binary reading members
				protected override bool ReadBool ()
				{
					return CurrentType == PlistType.@true;
				}

				protected override void ReadObjectHead ()
				{
					var b = stream.ReadByte ();
					var len = 0L;
					var type = (PlistType)(b & 0xF0);
					if (type == PlistType.@null) {
						type = (PlistType)b;
					} else {
						len = b & 0x0F;
						if (len == 0xF) {
							ReadObjectHead ();
							len = ReadInteger ();
						}
					}
					CurrentType = type;
					currentLength = (int)len;
				}

				protected override long ReadInteger ()
				{
					switch (CurrentType) {
					case PlistType.integer:
						return ReadBigEndianInteger ((int)Math.Pow (2, currentLength));
					}

					throw new NotSupportedException ("Integer of type: " + CurrentType);
				}

				protected override double ReadReal ()
				{
					var bytes = ReadBigEndianBytes ((int)Math.Pow (2, currentLength));
					switch (CurrentType) {
					case PlistType.real:
						switch (bytes.Length) {
						case 4:
							return (double)BitConverter.ToSingle (bytes, 0);
						case 8:
							return BitConverter.ToDouble (bytes, 0);
						}
						throw new NotSupportedException (bytes.Length + "-byte real");
					}

					throw new NotSupportedException ("Real of type: " + CurrentType);
				}

				protected override DateTime ReadDate ()
				{
					var bytes = ReadBigEndianBytes (8);
					var seconds = BitConverter.ToDouble (bytes, 0);
					// We need to manually convert the seconds to ticks because
					//  .NET DateTime/TimeSpan methods dealing with (milli)seconds
					//  round to the nearest millisecond (bxc #29079)
					return AppleEpoch.AddTicks ((long)(seconds * TicksPerSecond));
				}

				protected override byte [] ReadData ()
				{
					var bytes = new byte [currentLength];
					stream.Read (bytes, 0, currentLength);
					return bytes;
				}

				protected override string ReadString ()
				{
					byte [] bytes;
					switch (CurrentType) {
					case PlistType.@string: // ASCII
						bytes = new byte [currentLength];
						stream.Read (bytes, 0, bytes.Length);
						return Encoding.ASCII.GetString (bytes);
					case PlistType.wideString: //CFBinaryPList.c: Unicode string...big-endian 2-byte uint16_t
						bytes = new byte [currentLength * 2];
						stream.Read (bytes, 0, bytes.Length);
						return Encoding.BigEndianUnicode.GetString (bytes);
					}

					throw new NotSupportedException ("String of type: " + CurrentType);
				}

				public override bool ReadArray (PArray array)
				{
					if (CurrentType != PlistType.array)
						return false;

					array.Clear ();

					// save currentLength as it will be overwritten by next ReadObjectHead call
					var len = currentLength;
					for (var i = 0; i < len; i++) {
						var obj = ReadObjectByRef ();
						if (obj != null)
							array.Add (obj);
					}

					return true;
				}

				public override bool ReadDict (PDictionary dict)
				{
					if (CurrentType != PlistType.dict)
						return false;

					dict.Clear ();

					// save currentLength as it will be overwritten by next ReadObjectHead call
					var len = currentLength;
					var keys = new string [len];
					for (var i = 0; i < len; i++)
						keys [i] = ((PString)ReadObjectByRef ()).Value;
					for (var i = 0; i < len; i++)
						dict.Add (keys [i], ReadObjectByRef ());

					return true;
				}

				PObject ReadObjectByRef ()
				{
					// read index into offset table
					var objRef = (long)ReadBigEndianUInteger (trailer.ObjectRefSize);

					// read offset in file from table
					var lastPos = stream.Position;
					stream.Seek (trailer.OffsetTableOffset + objRef * trailer.OffsetEntrySize, SeekOrigin.Begin);
					stream.Seek ((long)ReadBigEndianUInteger (trailer.OffsetEntrySize), SeekOrigin.Begin);

					ReadObjectHead ();
					var obj = ReadObject ();

					// restore original position
					stream.Seek (lastPos, SeekOrigin.Begin);
					return obj;
				}

				byte [] ReadBigEndianBytes (int count)
				{
					var bytes = new byte [count];
					stream.Read (bytes, 0, count);
					if (BitConverter.IsLittleEndian)
						Array.Reverse (bytes);
					return bytes;
				}

				long ReadBigEndianInteger (int numBytes)
				{
					var bytes = ReadBigEndianBytes (numBytes);
					switch (numBytes) {
					case 1:
						return (long)bytes [0];
					case 2:
						return (long)BitConverter.ToInt16 (bytes, 0);
					case 4:
						return (long)BitConverter.ToInt32 (bytes, 0);
					case 8:
						return BitConverter.ToInt64 (bytes, 0);
					}
					throw new NotSupportedException (bytes.Length + "-byte integer");
				}

				ulong ReadBigEndianUInteger (int numBytes)
				{
					var bytes = ReadBigEndianBytes (numBytes);
					switch (numBytes) {
					case 1:
						return (ulong)bytes [0];
					case 2:
						return (ulong)BitConverter.ToUInt16 (bytes, 0);
					case 4:
						return (ulong)BitConverter.ToUInt32 (bytes, 0);
					case 8:
						return BitConverter.ToUInt64 (bytes, 0);
					}
					throw new NotSupportedException (bytes.Length + "-byte integer");
				}

				ulong ReadBigEndianUInt64 ()
				{
					var bytes = ReadBigEndianBytes (8);
					return BitConverter.ToUInt64 (bytes, 0);
				}
				#endregion

				#region Binary writing members
				public override void WriteObject (PObject value)
				{
					if (offsets == null)
						InitOffsetTable (value);
					base.WriteObject (value);
				}

				protected override void Write (PBoolean boolean)
				{
					WriteObjectHead (boolean, boolean ? PlistType.@true : PlistType.@false);
				}

				protected override void Write (PNumber number)
				{
					if (WriteObjectHead (number, PlistType.integer))
						Write (number.Value);
				}

				protected override void Write (PReal real)
				{
					if (WriteObjectHead (real, PlistType.real))
						Write (real.Value);
				}

				protected override void Write (PDate date)
				{
					if (WriteObjectHead (date, PlistType.date)) {
						var bytes = MakeBigEndian (BitConverter.GetBytes (date.Value.Subtract (AppleEpoch).TotalSeconds));
						stream.Write (bytes, 0, bytes.Length);
					}
				}

				protected override void Write (PData data)
				{
					var bytes = data.Value;
					if (WriteObjectHead (data, PlistType.data, bytes.Length))
						stream.Write (bytes, 0, bytes.Length);
				}

				protected override void Write (PString str)
				{
					var type = PlistType.@string;
					byte [] bytes;

					if (str.Value.Any (c => c > 127)) {
						type = PlistType.wideString;
						bytes = Encoding.BigEndianUnicode.GetBytes (str.Value);
					} else {
						bytes = Encoding.ASCII.GetBytes (str.Value);
					}

					if (WriteObjectHead (str, type, str.Value.Length))
						stream.Write (bytes, 0, bytes.Length);
				}

				protected override void Write (PArray array)
				{
					if (!WriteObjectHead (array, PlistType.array, array.Count))
						return;

					var curRef = currentRef;

					foreach (var item in array)
						Write (GetObjRef (item), trailer.ObjectRefSize);

					currentRef = curRef;

					foreach (var item in array)
						WriteObject (item);
				}

				protected override void Write (PDictionary dict)
				{
					if (!WriteObjectHead (dict, PlistType.dict, dict.Count))
						return;

					// it sucks we have to loop so many times, but we gotta do it
					//  if we want to lay things out the same way apple does

					var curRef = currentRef;

					//write key refs
					foreach (var item in dict)
						Write (GetObjRef (item.Key), trailer.ObjectRefSize);

					//write value refs
					foreach (var item in dict)
						Write (GetObjRef (item.Value), trailer.ObjectRefSize);

					currentRef = curRef;

					//write keys and values
					foreach (var item in dict)
						WriteObject (item.Key);
					foreach (var item in dict)
						WriteObject (item.Value);
				}

				bool WriteObjectHead (PObject obj, PlistType type, int size = 0)
				{
					var id = GetObjRef (obj);
					if (offsets [id] != 0) // if we've already been written, don't write us again
						return false;
					offsets [id] = stream.Position;
					switch (type) {
					case PlistType.@null:
					case PlistType.@false:
					case PlistType.@true:
					case PlistType.fill:
						stream.WriteByte ((byte)type);
						break;
					case PlistType.date:
						stream.WriteByte (0x33);
						break;
					case PlistType.integer:
					case PlistType.real:
						break;
					default:
						if (size < 15) {
							stream.WriteByte ((byte)((byte)type | size));
						} else {
							stream.WriteByte ((byte)((byte)type | 0xF));
							Write (size);
						}
						break;
					}
					return true;
				}

				void Write (double value)
				{
					if (value >= float.MinValue && value <= float.MaxValue) {
						stream.WriteByte ((byte)PlistType.real | 0x2);
						var bytes = MakeBigEndian (BitConverter.GetBytes ((float)value));
						stream.Write (bytes, 0, bytes.Length);
					} else {
						stream.WriteByte ((byte)PlistType.real | 0x3);
						var bytes = MakeBigEndian (BitConverter.GetBytes (value));
						stream.Write (bytes, 0, bytes.Length);
					}
				}

				void Write (int value)
				{
					if (value < 0) { //they always write negative numbers with 8 bytes
						stream.WriteByte ((byte)PlistType.integer | 0x3);
						var bytes = MakeBigEndian (BitConverter.GetBytes ((long)value));
						stream.Write (bytes, 0, bytes.Length);
					} else if (value >= 0 && value < byte.MaxValue) {
						stream.WriteByte ((byte)PlistType.integer);
						stream.WriteByte ((byte)value);
					} else if (value >= short.MinValue && value < short.MaxValue) {
						stream.WriteByte ((byte)PlistType.integer | 0x1);
						var bytes = MakeBigEndian (BitConverter.GetBytes ((short)value));
						stream.Write (bytes, 0, bytes.Length);
					} else {
						stream.WriteByte ((byte)PlistType.integer | 0x2);
						var bytes = MakeBigEndian (BitConverter.GetBytes (value));
						stream.Write (bytes, 0, bytes.Length);
					}
				}

				void Write (long value, int byteCount)
				{
					byte [] bytes;
					switch (byteCount) {
					case 1:
						stream.WriteByte ((byte)value);
						break;
					case 2:
						bytes = MakeBigEndian (BitConverter.GetBytes ((short)value));
						stream.Write (bytes, 0, bytes.Length);
						break;
					case 4:
						bytes = MakeBigEndian (BitConverter.GetBytes ((int)value));
						stream.Write (bytes, 0, bytes.Length);
						break;
					case 8:
						bytes = MakeBigEndian (BitConverter.GetBytes (value));
						stream.Write (bytes, 0, bytes.Length);
						break;
					default:
						throw new NotSupportedException (byteCount.ToString () + "-byte integer");
					}
				}

				void InitOffsetTable (PObject topLevel)
				{
					objectRefs = new List<object> ();

					var count = 0;
					MakeObjectRefs (topLevel, ref count);
					trailer.ObjectRefSize = GetMinByteLength (count);
					offsets = new long [count];
				}

				void MakeObjectRefs (object obj, ref int count)
				{
					if (obj == null)
						return;

					if (ShouldDuplicate (obj) || !objectRefs.Any (val => PObjectEqualityComparer.Instance.Equals (val, obj))) {
						objectRefs.Add (obj);
						count++;
					}

					// for containers, also count their contents
					var pobj = obj as PObject;
					if (pobj != null) {
						switch (pobj.Type) {

						case PObjectType.Array:
							foreach (var child in (PArray)obj)
								MakeObjectRefs (child, ref count);
							break;
						case PObjectType.Dictionary:
							foreach (var child in (PDictionary)obj)
								MakeObjectRefs (child.Key, ref count);
							foreach (var child in (PDictionary)obj)
								MakeObjectRefs (child.Value, ref count);
							break;
						}
					}
				}

				static bool ShouldDuplicate (object obj)
				{
					var pobj = obj as PObject;
					if (pobj == null)
						return false;

					return pobj.Type == PObjectType.Boolean || pobj.Type == PObjectType.Array || pobj.Type == PObjectType.Dictionary ||
						(pobj.Type == PObjectType.String && ((PString)pobj).Value.Any (c => c > 255)); //LAMESPEC: this is weird. Some things are duplicated
				}

				int GetObjRef (object obj)
				{
					if (currentRef < objectRefs.Count && PObjectEqualityComparer.Instance.Equals (objectRefs [currentRef], obj))
						return currentRef++;

					return objectRefs.FindIndex (val => PObjectEqualityComparer.Instance.Equals (val, obj));
				}

				static int GetMinByteLength (long value)
				{
					if (value >= 0 && value < byte.MaxValue)
						return 1;
					if (value >= short.MinValue && value < short.MaxValue)
						return 2;
					if (value >= int.MinValue && value < int.MaxValue)
						return 4;
					return 8;
				}

				static byte [] MakeBigEndian (byte [] bytes)
				{
					if (BitConverter.IsLittleEndian)
						Array.Reverse (bytes);
					return bytes;
				}
				#endregion

				public override void Dispose ()
				{
					if (offsets != null) {
						trailer.OffsetTableOffset = stream.Position;
						trailer.OffsetEntrySize = GetMinByteLength (trailer.OffsetTableOffset);
						foreach (var offset in offsets)
							Write (offset, trailer.OffsetEntrySize);

						//LAMESPEC: seems like they always add 6 extra bytes here. not sure why
						for (var i = 0; i < 6; i++)
							stream.WriteByte ((byte)0);

						trailer.Write (this);
					}
				}

				class PObjectEqualityComparer : IEqualityComparer<object>
				{
					public static readonly PObjectEqualityComparer Instance = new PObjectEqualityComparer ();

					PObjectEqualityComparer ()
					{
					}

					public new bool Equals (object x, object y)
					{
						var vx = x as IPValueObject;
						var vy = y as IPValueObject;

						if (vx == null && vy == null)
							return EqualityComparer<object>.Default.Equals (x, y);

						if (vx == null && x != null && vy.Value != null)
							return vy.Value.Equals (x);

						if (vy == null && y != null && vx.Value != null)
							return vx.Value.Equals (y);

						if (vx == null || vy == null)
							return false;

						return vx.Value.Equals (vy.Value);
					}

					public int GetHashCode (object obj)
					{
						var valueObj = obj as IPValueObject;
						if (valueObj != null)
							return valueObj.Value.GetHashCode ();
						return obj.GetHashCode ();
					}
				}

				struct CFBinaryPlistTrailer
				{
					const int TRAILER_SIZE = 26;

					public int OffsetEntrySize;
					public int ObjectRefSize;
					public long ObjectCount;
					public long TopLevelRef;
					public long OffsetTableOffset;

					public static CFBinaryPlistTrailer Read (Context ctx)
					{
						var pos = ctx.stream.Position;
						ctx.stream.Seek (-TRAILER_SIZE, SeekOrigin.End);
						var result = new CFBinaryPlistTrailer {
							OffsetEntrySize = ctx.stream.ReadByte (),
							ObjectRefSize = ctx.stream.ReadByte (),
							ObjectCount = (long)ctx.ReadBigEndianUInt64 (),
							TopLevelRef = (long)ctx.ReadBigEndianUInt64 (),
							OffsetTableOffset = (long)ctx.ReadBigEndianUInt64 ()
						};
						ctx.stream.Seek (pos, SeekOrigin.Begin);
						return result;
					}

					public void Write (Context ctx)
					{
						byte [] bytes;
						ctx.stream.WriteByte ((byte)OffsetEntrySize);
						ctx.stream.WriteByte ((byte)ObjectRefSize);
						//LAMESPEC: apple's comments say this is the number of entries in the offset table, but this really *is* number of objects??!?!
						bytes = MakeBigEndian (BitConverter.GetBytes ((long)ctx.objectRefs.Count));
						ctx.stream.Write (bytes, 0, bytes.Length);
						bytes = new byte [8]; //top level always at offset 0
						ctx.stream.Write (bytes, 0, bytes.Length);
						bytes = MakeBigEndian (BitConverter.GetBytes (OffsetTableOffset));
						ctx.stream.Write (bytes, 0, bytes.Length);
					}
				}
			}
		}

		// Adapted from:
		//https://github.com/mono/monodevelop/blob/07d9e6c07e5be8fe1d8d6f4272d3969bb087a287/main/src/addins/MonoDevelop.MacDev/MonoDevelop.MacDev.Plist/PlistDocument.cs
		class XmlFormat : PropertyListFormat
		{
			const string PLIST_HEADER = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<!DOCTYPE plist PUBLIC ""-//Apple//DTD PLIST 1.0//EN"" ""http://www.apple.com/DTDs/PropertyList-1.0.dtd"">
<plist version=""1.0"">
";
			static readonly Encoding outputEncoding = new UTF8Encoding (false, false);

			public override ReadWriteContext StartReading (Stream input)
			{
				//allow DTD but not try to resolve it from web
				var settings = new XmlReaderSettings () {
					CloseInput = true,
					DtdProcessing = DtdProcessing.Ignore,
					XmlResolver = null,
				};

				XmlReader reader = null;
				input.Seek (0, SeekOrigin.Begin);
				try {
					reader = XmlReader.Create (input, settings);
					reader.ReadToDescendant ("plist");
					while (reader.Read () && reader.NodeType != XmlNodeType.Element)
						;
				} catch (Exception ex) {
					Console.WriteLine ("Exception: {0}", ex);
				}

				if (reader == null || reader.EOF)
					return null;

				return new Context (reader);
			}

			public override ReadWriteContext StartWriting (Stream output)
			{
				var writer = new StreamWriter (output, outputEncoding);
				writer.Write (PLIST_HEADER);

				return new Context (writer);
			}

			class Context : ReadWriteContext
			{
				const string DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ssK";

				XmlReader reader;
				TextWriter writer;

				int indentLevel;
				string indentString;

				public Context (XmlReader reader)
				{
					this.reader = reader;
					ReadObjectHead ();
				}
				public Context (TextWriter writer)
				{
					this.writer = writer;
					indentString = "";
				}

				#region XML reading members
				protected override void ReadObjectHead ()
				{
					try {
						CurrentType = (PlistType)Enum.Parse (typeof (PlistType), reader.LocalName);
					} catch (Exception ex) {
						throw new ArgumentException (string.Format ("Failed to parse PList data type: {0}", reader.LocalName), ex);
					}
				}

				protected override bool ReadBool ()
				{
					// Create the PBoolean object, then move to the xml reader to next node
					// so we are ready to parse the next object. 'bool' types don't have
					// content so we have to move the reader manually, unlike integers which
					// implicitly move to the next node because we parse the content.
					var result = CurrentType == PlistType.@true;
					reader.Read ();
					return result;
				}

				protected override long ReadInteger ()
				{
					return reader.ReadElementContentAsLong ();
				}

				protected override double ReadReal ()
				{
					return reader.ReadElementContentAsDouble ();
				}

				protected override DateTime ReadDate ()
				{
					return DateTime.ParseExact (reader.ReadElementContentAsString (), DATETIME_FORMAT, CultureInfo.InvariantCulture).ToUniversalTime ();
				}

				protected override byte [] ReadData ()
				{
					return Convert.FromBase64String (reader.ReadElementContentAsString ());
				}

				protected override string ReadString ()
				{
					return reader.ReadElementContentAsString ();
				}

				public override bool ReadArray (PArray array)
				{
					if (CurrentType != PlistType.array)
						return false;

					array.Clear ();

					if (reader.IsEmptyElement) {
						reader.Read ();
						return true;
					}

					// advance to first node
					reader.ReadStartElement ();
					while (!reader.EOF && reader.NodeType != XmlNodeType.Element && reader.NodeType != XmlNodeType.EndElement) {
						if (!reader.Read ())
							break;
					}

					while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement) {
						if (reader.NodeType == XmlNodeType.Element) {
							ReadObjectHead ();

							var val = ReadObject ();
							if (val != null)
								array.Add (val);
						} else if (!reader.Read ()) {
							break;
						}
					}

					if (!reader.EOF && reader.NodeType == XmlNodeType.EndElement && reader.Name == "array") {
						reader.ReadEndElement ();
						return true;
					}

					return false;
				}

				public override bool ReadDict (PDictionary dict)
				{
					if (CurrentType != PlistType.dict)
						return false;

					dict.Clear ();

					if (reader.IsEmptyElement) {
						reader.Read ();
						return true;
					}

					reader.ReadToDescendant ("key");

					while (!reader.EOF && reader.NodeType == XmlNodeType.Element) {
						var key = reader.ReadElementString ();

						while (!reader.EOF && reader.NodeType != XmlNodeType.Element && reader.Read ()) {
							if (reader.NodeType == XmlNodeType.EndElement)
								throw new FormatException (string.Format ("No value found for key {0}", key));
						}

						ReadObjectHead ();
						var result = ReadObject ();
						if (result != null)
							dict.Add (key, result);

						do {
							if (reader.NodeType == XmlNodeType.Element && reader.Name == "key")
								break;

							if (reader.NodeType == XmlNodeType.EndElement)
								break;
						} while (reader.Read ());
					}

					if (!reader.EOF && reader.NodeType == XmlNodeType.EndElement && reader.Name == "dict") {
						reader.ReadEndElement ();
						return true;
					}

					return false;
				}
				#endregion

				#region XML writing members
				protected override void Write (PBoolean boolean)
				{
					WriteLine (boolean.Value ? "<true/>" : "<false/>");
				}

				protected override void Write (PNumber number)
				{
					WriteLine ("<integer>" + SecurityElement.Escape (number.Value.ToString (CultureInfo.InvariantCulture)) + "</integer>");
				}

				protected override void Write (PReal real)
				{
					WriteLine ("<real>" + SecurityElement.Escape (real.Value.ToString (CultureInfo.InvariantCulture)) + "</real>");
				}

				protected override void Write (PDate date)
				{
					WriteLine ("<date>" + SecurityElement.Escape (date.Value.ToString (DATETIME_FORMAT, CultureInfo.InvariantCulture)) + "</date>");
				}

				protected override void Write (PData data)
				{
					WriteLine ("<data>" + SecurityElement.Escape (Convert.ToBase64String (data.Value)) + "</data>");
				}

				protected override void Write (PString str)
				{
					WriteLine ("<string>" + SecurityElement.Escape (str.Value) + "</string>");
				}

				protected override void Write (PArray array)
				{
					if (array.Count == 0) {
						WriteLine ("<array/>");
						return;
					}

					WriteLine ("<array>");
					IncreaseIndent ();

					foreach (var item in array)
						WriteObject (item);

					DecreaseIndent ();
					WriteLine ("</array>");
				}

				protected override void Write (PDictionary dict)
				{
					if (dict.Count == 0) {
						WriteLine ("<dict/>");
						return;
					}

					WriteLine ("<dict>");
					IncreaseIndent ();

					foreach (var kv in dict) {
						WriteLine ("<key>" + SecurityElement.Escape (kv.Key) + "</key>");
						WriteObject (kv.Value);
					}

					DecreaseIndent ();
					WriteLine ("</dict>");
				}

				void WriteLine (string value)
				{
					writer.Write (indentString);
					writer.Write (value);
					writer.Write ('\n');
				}

				void IncreaseIndent ()
				{
					indentString = new string ('\t', ++indentLevel);
				}

				void DecreaseIndent ()
				{
					indentString = new string ('\t', --indentLevel);
				}
				#endregion

				public override void Dispose ()
				{
					if (writer != null) {
						writer.Write ("</plist>\n");
						writer.Flush ();
						writer.Dispose ();
					}
				}
			}
		}

		public abstract class ReadWriteContext : IDisposable
		{
			// Binary: The type is encoded in the 4 high bits; the low bits are data (except: null, true, false)
			// Xml: The enum value name == element tag name (this actually reads a superset of the format, since null, fill and wideString are not plist xml elements afaik)
			protected enum PlistType : byte
			{
				@null = 0x00,
				@false = 0x08,
				@true = 0x09,
				fill = 0x0F,
				integer = 0x10,
				real = 0x20,
				date = 0x30,
				data = 0x40,
				@string = 0x50,
				wideString = 0x60,
				array = 0xA0,
				dict = 0xD0,
			}

			#region Reading members
			public PObject ReadObject ()
			{
				switch (CurrentType) {
				case PlistType.@true:
				case PlistType.@false:
					return new PBoolean (ReadBool ());
				case PlistType.fill:
					ReadObjectHead ();
					return ReadObject ();

				case PlistType.integer:
					return new PNumber ((int)ReadInteger ()); //FIXME: should PNumber handle 64-bit values? ReadInteger can if necessary
				case PlistType.real:
					return new PReal (ReadReal ());    //FIXME: we should probably make PNumber take floating point as well as ints

				case PlistType.date:
					return new PDate (ReadDate ());
				case PlistType.data:
					return new PData (ReadData ());

				case PlistType.@string:
				case PlistType.wideString:
					return new PString (ReadString ());

				case PlistType.array:
					var array = new PArray ();
					ReadArray (array);
					return array;

				case PlistType.dict:
					var dict = new PDictionary ();
					ReadDict (dict);
					return dict;
				}
				return null;
			}

			protected abstract void ReadObjectHead ();
			protected PlistType CurrentType { get; set; }

			protected abstract bool ReadBool ();
			protected abstract long ReadInteger ();
			protected abstract double ReadReal ();
			protected abstract DateTime ReadDate ();
			protected abstract byte [] ReadData ();
			protected abstract string ReadString ();

			public abstract bool ReadArray (PArray array);
			public abstract bool ReadDict (PDictionary dict);
			#endregion

			#region Writing members
			public virtual void WriteObject (PObject value)
			{
				switch (value.Type) {
				case PObjectType.Boolean:
					Write ((PBoolean)value);
					return;
				case PObjectType.Number:
					Write ((PNumber)value);
					return;
				case PObjectType.Real:
					Write ((PReal)value);
					return;
				case PObjectType.Date:
					Write ((PDate)value);
					return;
				case PObjectType.Data:
					Write ((PData)value);
					return;
				case PObjectType.String:
					Write ((PString)value);
					return;
				case PObjectType.Array:
					Write ((PArray)value);
					return;
				case PObjectType.Dictionary:
					Write ((PDictionary)value);
					return;
				}
				throw new NotSupportedException (value.Type.ToString ());
			}

			protected abstract void Write (PBoolean boolean);
			protected abstract void Write (PNumber number);
			protected abstract void Write (PReal real);
			protected abstract void Write (PDate date);
			protected abstract void Write (PData data);
			protected abstract void Write (PString str);
			protected abstract void Write (PArray array);
			protected abstract void Write (PDictionary dict);
			#endregion

			public abstract void Dispose ();
		}
	}


	enum PObjectContainerAction
	{
		Added,
		Changed,
		Removed,
		Replaced,
		Cleared
	}


	sealed class PObjectContainerEventArgs : EventArgs
	{
		internal PObjectContainerEventArgs (PObjectContainerAction action, string key, PObject oldItem, PObject newItem)
		{
			Action = action;
			Key = key;
			OldItem = oldItem;
			NewItem = newItem;
		}

		public PObjectContainerAction Action {
			get; private set;
		}

		public string Key {
			get; private set;
		}

		public PObject OldItem {
			get; private set;
		}

		public PObject NewItem {
			get; private set;
		}
	}


	enum PObjectType
	{
		Dictionary,
		Array,
		Real,
		Number,
		Boolean,
		Data,
		String,
		Date
	}
}