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

FileService.cs « MonoDevelop.Core « MonoDevelop.Core « core « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6968d7b7760acf67ef7e301f306224084fe13d0f (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
//
// FileService.cs
//
// Author:
//   Mike Krüger <mkrueger@novell.com>
//   Lluis Sanchez Gual <lluis@novell.com>
//
// Copyright (C) 2007 Novell, Inc (http://www.novell.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.
//

using System;
using System.Diagnostics;
using System.IO;
using System.Text;

using Mono.Addins;
using Mono.Unix.Native;
using MonoDevelop.Core.FileSystem;
using System.Collections.Generic;
using System.Threading;
using System.Linq;
using System.Threading.Tasks;
using System.Net;

namespace MonoDevelop.Core
{
	public static class FileService
	{
		const string addinFileSystemExtensionPath = "/MonoDevelop/Core/FileSystemExtensions";

		static FileServiceErrorHandler errorHandler;
		
		static FileSystemExtension fileSystemChain;
		static readonly FileSystemExtension defaultExtension = new DefaultFileSystemExtension ();
		
		static readonly EventQueue eventQueue = new EventQueue ();
		
		static readonly string applicationRootPath = Path.Combine (PropertyService.EntryAssemblyPath, "..");
		public static string ApplicationRootPath {
			get {
				return applicationRootPath;
			}
		}
		
		static FileService()
		{
			AddinManager.ExtensionChanged += delegate (object sender, ExtensionEventArgs args) {
				if (args.PathChanged (addinFileSystemExtensionPath))
					UpdateExtensions ();
			};
			UpdateExtensions ();
		}
		
		static void UpdateExtensions ()
		{
			if (!Runtime.Initialized) {
				fileSystemChain = defaultExtension;
				return;
			}
			
			var extensions = AddinManager.GetExtensionObjects (addinFileSystemExtensionPath, typeof(FileSystemExtension)).Cast<FileSystemExtension> ().ToArray ();
			for (int n=0; n<extensions.Length - 1; n++) {
				extensions [n].Next = extensions [n + 1];
			}

			if (extensions.Length > 0) {
				extensions [extensions.Length - 1].Next = defaultExtension;
				fileSystemChain = extensions [0];
			} else {
				fileSystemChain = defaultExtension;
			}
		}
		
		public static void DeleteFile (string fileName)
		{
			Debug.Assert (!String.IsNullOrEmpty (fileName));
			try {
				GetFileSystemForPath (fileName, false).DeleteFile (fileName);
			} catch (Exception e) {
				if (!HandleError (GettextCatalog.GetString ("Can't remove file {0}", fileName), e))
					throw;
				return;
			}
			OnFileRemoved (new FileEventArgs (fileName, false));
		}
		
		public static void DeleteDirectory (string path)
		{
			Debug.Assert (!String.IsNullOrEmpty (path));
			try {
				GetFileSystemForPath (path, true).DeleteDirectory (path);
			} catch (Exception e) {
				if (!HandleError (GettextCatalog.GetString ("Can't remove directory {0}", path), e))
					throw;
				return;
			}
			OnFileRemoved (new FileEventArgs (path, true));
		}
		
		public static void RenameFile (string oldName, string newName)
		{
			Debug.Assert (!String.IsNullOrEmpty (oldName));
			Debug.Assert (!String.IsNullOrEmpty (newName));
			if (Path.GetFileName (oldName) != newName) {
				var newPath = ((FilePath)oldName).ParentDirectory.Combine (newName);
				InternalRenameFile (oldName, newName);
				OnFileRenamed (new FileCopyEventArgs (oldName, newPath, false));
			}
		}
		
		public static void RenameDirectory (string oldName, string newName)
		{
			Debug.Assert (!String.IsNullOrEmpty (oldName));
			Debug.Assert (!String.IsNullOrEmpty (newName));
			if (Path.GetFileName (oldName) != newName) {
				string newPath = Path.Combine (Path.GetDirectoryName (oldName), newName);
				InternalMoveDirectory (oldName, newPath);
				OnFileRenamed (new FileCopyEventArgs (oldName, newPath, true));
				OnFileCreated (new FileEventArgs (newPath, false));
				OnFileRemoved (new FileEventArgs (oldName, false));
			}
		}
		
		public static void CopyFile (string srcFile, string dstFile)
		{
			Debug.Assert (!String.IsNullOrEmpty (srcFile));
			Debug.Assert (!String.IsNullOrEmpty (dstFile));
			GetFileSystemForPath (dstFile, false).CopyFile (srcFile, dstFile, true);
			OnFileCopied (new FileCopyEventArgs (srcFile, dstFile, false));
			OnFileCreated (new FileEventArgs (dstFile, false));
		}

		public static void MoveFile (string srcFile, string dstFile)
		{
			Debug.Assert (!String.IsNullOrEmpty (srcFile));
			Debug.Assert (!String.IsNullOrEmpty (dstFile));
			InternalMoveFile (srcFile, dstFile);
			OnFileMoved (new FileCopyEventArgs (srcFile, dstFile, false));
			OnFileCreated (new FileEventArgs (dstFile, false));
			OnFileRemoved (new FileEventArgs (srcFile, false));
		}
		
		static void InternalMoveFile (string srcFile, string dstFile)
		{
			Debug.Assert (!String.IsNullOrEmpty (srcFile));
			Debug.Assert (!String.IsNullOrEmpty (dstFile));
			FileSystemExtension srcExt = GetFileSystemForPath (srcFile, false);
			FileSystemExtension dstExt = GetFileSystemForPath (dstFile, false);
			
			if (srcExt == dstExt) {
				// Everything can be handled by the same file system
				srcExt.MoveFile (srcFile, dstFile);
			} else {
				// If the file system of the source and dest files are
				// different, decompose the Move operation into a Copy
				// and Delete, so every file system can handle its part
				dstExt.CopyFile (srcFile, dstFile, true);
				srcExt.DeleteFile (srcFile);
			}
		}
		
		static void InternalRenameFile (string srcFile, string newName)
		{
			Debug.Assert (!string.IsNullOrEmpty (srcFile));
			Debug.Assert (!string.IsNullOrEmpty (newName));
			FileSystemExtension srcExt = GetFileSystemForPath (srcFile, false);
			
			srcExt.RenameFile (srcFile, newName);
		}
		
		public static void CreateDirectory (string path)
		{
			if (!Directory.Exists (path)) {
				Debug.Assert (!String.IsNullOrEmpty (path));
				GetFileSystemForPath (path, true).CreateDirectory (path);
				OnFileCreated (new FileEventArgs (path, true));
			}
		}
		
		public static void CopyDirectory (string srcPath, string dstPath)
		{
			Debug.Assert (!String.IsNullOrEmpty (srcPath));
			Debug.Assert (!String.IsNullOrEmpty (dstPath));
			GetFileSystemForPath (dstPath, true).CopyDirectory (srcPath, dstPath);
		}
		
		public static void MoveDirectory (string srcPath, string dstPath)
		{
			Debug.Assert (!String.IsNullOrEmpty (srcPath));
			Debug.Assert (!String.IsNullOrEmpty (dstPath));
			InternalMoveDirectory (srcPath, dstPath);
			OnFileMoved (new FileCopyEventArgs (srcPath, dstPath, true));
			OnFileCreated (new FileEventArgs (dstPath, true));
			OnFileRemoved (new FileEventArgs (srcPath, true));
		}
		
		static void InternalMoveDirectory (string srcPath, string dstPath)
		{
			Debug.Assert (!String.IsNullOrEmpty (srcPath));
			Debug.Assert (!String.IsNullOrEmpty (dstPath));
			FileSystemExtension srcExt = GetFileSystemForPath (srcPath, true);
			FileSystemExtension dstExt = GetFileSystemForPath (dstPath, true);
			
			if (srcExt == dstExt) {
				// Everything can be handled by the same file system
				srcExt.MoveDirectory (srcPath, dstPath);
			} else {
				// If the file system of the source and dest files are
				// different, decompose the Move operation into a Copy
				// and Delete, so every file system can handle its part
				dstExt.CopyDirectory (srcPath, dstPath);
				srcExt.DeleteDirectory (srcPath);
			}
		}

		/// <summary>
		/// Requests permission for modifying a file
		/// </summary>
		/// <param name="fileName">The file to be modified</param>
		/// <param name="throwIfFails">If set to false, it will catch the exception that would've been thrown.</param>
		/// <remarks>This method must be called before trying to write any file. It throws an exception if permission is not granted.</remarks>
		public static bool RequestFileEdit (FilePath fileName, bool throwIfFails = true)
		{
			Debug.Assert (!String.IsNullOrEmpty (fileName));
			return RequestFileEdit (new FilePath[] { fileName }, throwIfFails);
		}

		/// <summary>
		/// Requests permission for modifying a set of files
		/// </summary>
		/// <param name="fileNames">Files</param>
		/// <remarks>This method must be called before trying to write any file. It throws an exception if permission is not granted.</remarks>
		public static bool RequestFileEdit (IEnumerable<FilePath> fileNames, bool throwIfFails = true)
		{
			try {
				foreach (var fg in fileNames.GroupBy (f => GetFileSystemForPath (f, false)))
					fg.Key.RequestFileEdit (fg);
				return true;
			} catch (Exception ex) {
				if (throwIfFails)
					throw;
				LoggingService.LogError ("File can't be written", ex);
				return false;
			}
		}

		public static void NotifyFileChanged (FilePath fileName)
		{
			NotifyFileChanged (fileName, false);
		}

		public static void NotifyFileChanged (FilePath fileName, bool autoReload)
		{
			NotifyFilesChanged (new FilePath[] { fileName }, autoReload);
		}
		
		public static void NotifyFilesChanged (IEnumerable<FilePath> files)
		{
			NotifyFilesChanged (files, false);
		}

		public static void NotifyFilesChanged (IEnumerable<FilePath> files, bool autoReload)
		{
			try {
				foreach (var fsFiles in files.GroupBy (f => GetFileSystemForPath (f, false)))
					fsFiles.Key.NotifyFilesChanged (fsFiles);
				OnFileChanged (new FileEventArgs (files, false, autoReload));
			} catch (Exception ex) {
				LoggingService.LogError ("File change notification failed", ex);
			}
		}
		
		public static void NotifyFileRemoved (string fileName)
		{
			NotifyFilesRemoved (new FilePath[] { fileName });
		}
		
		public static void NotifyFilesRemoved (IEnumerable<FilePath> files)
		{
			try {
				OnFileRemoved (new FileEventArgs (files, false));
			} catch (Exception ex) {
				LoggingService.LogError ("File remove notification failed", ex);
			}
		}
		
		internal static FileSystemExtension GetFileSystemForPath (string path, bool isDirectory)
		{
			Debug.Assert (!String.IsNullOrEmpty (path));
			FileSystemExtension nx = fileSystemChain;
			while (nx != null && !nx.CanHandlePath (path, isDirectory))
				nx = nx.Next;
			return nx;
		}
		
/*
		readonly static char[] separators = { Path.DirectorySeparatorChar, Path.VolumeSeparatorChar, Path.AltDirectorySeparatorChar };
		public static string AbsoluteToRelativePath (string baseDirectoryPath, string absPath)
		{
			if (!Path.IsPathRooted (absPath))
				return absPath;
			
			absPath           = Path.GetFullPath (absPath);
			baseDirectoryPath = Path.GetFullPath (baseDirectoryPath.TrimEnd (Path.DirectorySeparatorChar));
			
			string[] bPath = baseDirectoryPath.Split (separators);
			string[] aPath = absPath.Split (separators);
			int indx = 0;
			
			for (; indx < Math.Min (bPath.Length, aPath.Length); indx++) {
				if (!bPath[indx].Equals(aPath[indx]))
					break;
			}
			
			if (indx == 0) 
				return absPath;
			
			StringBuilder result = new StringBuilder ();
			
			for (int i = indx; i < bPath.Length; i++) {
				result.Append ("..");
				if (i + 1 < bPath.Length || aPath.Length - indx > 0)
					result.Append (Path.DirectorySeparatorChar);
			}
			
			
			result.Append (String.Join(Path.DirectorySeparatorChar.ToString(), aPath, indx, aPath.Length - indx));
			if (result.Length == 0)
				return ".";
			return result.ToString ();
		}*/
		
		static bool IsSeparator (char ch)
		{
			return ch == Path.DirectorySeparatorChar || ch == Path.AltDirectorySeparatorChar || ch == Path.VolumeSeparatorChar;
		}
		
		public unsafe static string AbsoluteToRelativePath (string baseDirectoryPath, string absPath)
		{
			if (!Path.IsPathRooted (absPath) || string.IsNullOrEmpty (baseDirectoryPath))
				return absPath;
				
			absPath = GetFullPath (absPath);
			baseDirectoryPath = GetFullPath (baseDirectoryPath).TrimEnd (Path.DirectorySeparatorChar);
			
			fixed (char* bPtr = baseDirectoryPath, aPtr = absPath) {
				var bEnd = bPtr + baseDirectoryPath.Length;
				var aEnd = aPtr + absPath.Length;
				char* lastStartA = aEnd;
				char* lastStartB = bEnd;
				
				int indx = 0;
				// search common base path
				var a = aPtr;
				var b = bPtr;
				while (a < aEnd) {
					if (*a != *b)
						break;
					if (IsSeparator (*a)) {
						indx++;
						lastStartA = a + 1;
						lastStartB = b; 
					}
					a++;
					b++;
					if (b >= bEnd) {
						if (a >= aEnd || IsSeparator (*a)) {
							indx++;
							lastStartA = a + 1;
							lastStartB = b;
						}
						break;
					}
				}
				if (indx == 0) 
					return absPath;
				
				if (lastStartA >= aEnd)
					return ".";

				// handle case a: some/path b: some/path/deeper...
				if (a >= aEnd) {
					if (IsSeparator (*b)) {
						lastStartA = a + 1;
						lastStartB = b;
					}
				}
				
				// look how many levels to go up into the base path
				int goUpCount = 0;
				while (lastStartB < bEnd) {
					if (IsSeparator (*lastStartB))
						goUpCount++;
					lastStartB++;
				}
				var size = goUpCount * 2 + goUpCount + aEnd - lastStartA;
				var result = new char [size];
				fixed (char* rPtr = result) {
					// go paths up
					var r = rPtr;
					for (int i = 0; i < goUpCount; i++) {
						*(r++) = '.';
						*(r++) = '.';
						*(r++) = Path.DirectorySeparatorChar;
					}
					// copy the remaining absulute path
					while (lastStartA < aEnd)
						*(r++) = *(lastStartA++);
				}
				return new string (result);
			}
		}
		
		public static string RelativeToAbsolutePath (string baseDirectoryPath, string relPath)
		{
			return Path.GetFullPath (Path.Combine (baseDirectoryPath, relPath));
		}
		
		public static bool IsValidPath (string fileName)
		{
			if (String.IsNullOrEmpty (fileName) || fileName.Trim() == string.Empty) 
				return false;
			if (fileName.IndexOfAny (Path.GetInvalidPathChars ()) >= 0)
				return false;
			return true;
		}

		public static bool IsValidFileName (string fileName)
		{
			if (String.IsNullOrEmpty (fileName) || fileName.Trim() == string.Empty) 
				return false;
			if (fileName.IndexOfAny (Path.GetInvalidFileNameChars ()) >= 0)
				return false;
			return true;
		}
		
		public static bool IsDirectory (string filename)
		{
			return Directory.Exists (filename);
		}
		
		public static string GetFullPath (string path)
		{
			if (path == null)
				throw new ArgumentNullException ("path");
			if (!Platform.IsWindows || path.IndexOf ('*') == -1)
				return Path.GetFullPath (path);
			else {
				// On Windows, GetFullPath doesn't work if the path contains wildcards.
				path = path.Replace ("*", wildcardMarker);
				path = Path.GetFullPath (path);
				return path.Replace (wildcardMarker, "*");
			}
		}

		static readonly string wildcardMarker = "_" + Guid.NewGuid ().ToString () + "_";
		
		public static string CreateTempDirectory ()
		{
			Random rnd = new Random ();
			string result;
			while (true) {
				result = Path.Combine (Path.GetTempPath (), "mdTmpDir" + rnd.Next ());
				if (!Directory.Exists (result))
					break;
			} 
			Directory.CreateDirectory (result);
			return result;
		}

		public static string NormalizeRelativePath (string path)
		{
			string result = path.Trim (Path.DirectorySeparatorChar, ' ');
			while (result.StartsWith ("." + Path.DirectorySeparatorChar)) {
				result = result.Substring (2);
				result = result.Trim (Path.DirectorySeparatorChar);
			}
			return result == "." ? "" : result;
		}

		// Atomic rename of a file. It does not fire events.
		public static void SystemRename (string sourceFile, string destFile)
		{
			if (string.IsNullOrEmpty (sourceFile))
				throw new ArgumentException ("sourceFile");

			if (string.IsNullOrEmpty (destFile))
				throw new ArgumentException ("destFile");

			//FIXME: use the atomic System.IO.File.Replace on NTFS
			if (Platform.IsWindows) {
				string wtmp = null;
				if (File.Exists (destFile)) {
					do {
						wtmp = Path.Combine (Path.GetTempPath (), Guid.NewGuid ().ToString ());
					} while (File.Exists (wtmp));

					File.Move (destFile, wtmp);
				}
				try {
					File.Move (sourceFile, destFile);
				}
				catch {
					try {
						if (wtmp != null)
							File.Move (wtmp, destFile);
					}
					catch {
						wtmp = null;
					}
					throw;
				}
				finally {
					if (wtmp != null) {
						try {
							File.Delete (wtmp);
						}
						catch { }
					}
				}
			}
			else {
				if (Syscall.rename (sourceFile, destFile) != 0) {
					switch (Stdlib.GetLastError ()) {
					case Errno.EACCES:
					case Errno.EPERM:
						throw new UnauthorizedAccessException ();
					case Errno.EINVAL:
						throw new InvalidOperationException ();
					case Errno.ENOTDIR:
						throw new DirectoryNotFoundException ();
					case Errno.ENOENT:
						throw new FileNotFoundException ();
					case Errno.ENAMETOOLONG:
						throw new PathTooLongException ();
					default:
						throw new IOException ();
					}
				}
			}
		}

		/// <summary>
		/// Renames a directory
		/// </summary>
		/// <param name="sourceDir">Source directory</param>
		/// <param name="destDir">Destination directory</param>
		/// <remarks>
		/// It works like Directory.Move, but it supports changing the case of a directory name in case-insensitive file systems
		/// </remarks>
		public static void SystemDirectoryRename (string sourceDir, string destDir)
		{
			if (Directory.Exists (destDir) && string.Equals (Path.GetFullPath (sourceDir), Path.GetFullPath (destDir), StringComparison.CurrentCultureIgnoreCase)) {
				// If the destination directory exists but we can't find it with the provided name casing, then it means we are just changing the case
				var existingDir = Directory.GetDirectories (Path.GetDirectoryName (destDir), Path.GetFileName (destDir)).FirstOrDefault ();
				if (existingDir == null || (Path.GetFileName (existingDir) == Path.GetFileName (sourceDir))) {
					var temp = destDir + ".renaming";
					int n = 0;
					while (Directory.Exists (temp) || File.Exists (temp))
						temp = destDir + ".renaming_" + (n++);
					Directory.Move (sourceDir, temp);
					try {
						Directory.Move (temp, destDir);
					} catch {
						Directory.Move (temp, sourceDir);
					}
					return;
				}
			}
			Directory.Move (sourceDir, destDir);
		}
		
		/// <summary>
		/// Removes the directory if it's empty.
		/// </summary>
		public static void RemoveDirectoryIfEmpty (string directory)
		{
			// HACK: we should use EnumerateFiles but it's broken in some Mono releases
			// https://bugzilla.xamarin.com/show_bug.cgi?id=2975
			if (Directory.Exists (directory) && !Directory.GetFiles (directory).Any ())
				Directory.Delete (directory);
		}
		
		/// <summary>
		/// Makes the path separators native.
		/// </summary>
		public static string MakePathSeparatorsNative (string path)
		{
			if (string.IsNullOrEmpty (path))
				return path;
			char c = Path.DirectorySeparatorChar == '\\'? '/' : '\\'; 
			return path.Replace (c, Path.DirectorySeparatorChar);
		}

		static bool HandleError (string message, Exception ex)
		{
			return errorHandler != null ? errorHandler (message, ex) : false;
		}
		
		public static FileServiceErrorHandler ErrorHandler {
			get { return errorHandler; }
			set { errorHandler = value; }
		}
		
		public static void FreezeEvents ()
		{
			eventQueue.Freeze ();
		}
		
		public static void ThawEvents ()
		{
			eventQueue.Thaw ();
		}

		public static event EventHandler<FileEventArgs> FileCreated;
		static void OnFileCreated (FileEventArgs args)
		{
			foreach (FileEventInfo fi in args) {
				if (fi.IsDirectory)
					Counters.DirectoriesCreated++;
				else
					Counters.FilesCreated++;
			}

			eventQueue.RaiseEvent (() => FileCreated, args);
		}

		public static event EventHandler<FileCopyEventArgs> FileCopied;
		static void OnFileCopied (FileCopyEventArgs args)
		{
			eventQueue.RaiseEvent (() => FileCopied, args);
		}

		public static event EventHandler<FileCopyEventArgs> FileMoved;
		static void OnFileMoved (FileCopyEventArgs args)
		{
			eventQueue.RaiseEvent (() => FileMoved, args);
		}
		
		public static event EventHandler<FileCopyEventArgs> FileRenamed;
		static void OnFileRenamed (FileCopyEventArgs args)
		{
			foreach (FileCopyEventInfo fi in args) {
				if (fi.IsDirectory)
					Counters.DirectoriesRenamed++;
				else
					Counters.FilesRenamed++;
			}
			
			eventQueue.RaiseEvent (() => FileRenamed, args);
		}
		
		public static event EventHandler<FileEventArgs> FileRemoved;
		static void OnFileRemoved (FileEventArgs args)
		{
			foreach (FileEventInfo fi in args) {
				if (fi.IsDirectory)
					Counters.DirectoriesRemoved++;
				else
					Counters.FilesRemoved++;
			}
			
			eventQueue.RaiseEvent (() => FileRemoved, args);
		}
		
		public static event EventHandler<FileEventArgs> FileChanged;
		static void OnFileChanged (FileEventArgs args)
		{
			Counters.FileChangeNotifications++;
			eventQueue.RaiseEvent (() => FileChanged, null, args);
		}

		public static Task<bool> UpdateDownloadedCacheFile (string url, string cacheFile,
			Func<Stream,bool> validateDownload = null, CancellationToken ct = default (CancellationToken))
		{
			return WebRequestHelper.GetResponseAsync (
				() => (HttpWebRequest)WebRequest.Create (url),
				r => {
					//check to see if the online file has been modified since it was last downloaded
					var localNewsXml = new FileInfo (cacheFile);
					if (localNewsXml.Exists)
						r.IfModifiedSince = localNewsXml.LastWriteTime;
				},
				ct
			).ContinueWith (t => {
				bool deleteTempFile = true;
				var tempFile = cacheFile + ".temp";

				try {
					ct.ThrowIfCancellationRequested ();

					if (t.IsFaulted) {
						var wex = t.Exception.Flatten ().InnerException as WebException;
						if (wex != null) {
							var resp = wex.Response as HttpWebResponse;
							if (resp != null && resp.StatusCode == HttpStatusCode.NotModified)
								return false;
						}
					}

					//TODO: limit this size in case open wifi hotspots provide junk data
					var response = t.Result;
					if (response.StatusCode == HttpStatusCode.OK) {
						using (var fs = File.Create (tempFile))
								response.GetResponseStream ().CopyTo (fs, 2048);
					}

					//check the document is valid, might get bad ones from wifi hotspots etc
					if (validateDownload != null) {
						ct.ThrowIfCancellationRequested ();

						using (var f = File.OpenRead (tempFile)) {
							bool validated;
							try {
								validated = validateDownload (f);
							} catch (Exception ex) {
								throw new Exception ("Failed to validate downloaded file", ex);
							}
							if (!validated) {
								throw new Exception ("Failed to validate downloaded file");
							}
						}
					}

					ct.ThrowIfCancellationRequested ();

					SystemRename (tempFile, cacheFile);
					deleteTempFile = false;
					return true;
				} finally {
					if (deleteTempFile) {
						try {
							File.Delete (tempFile);
						} catch (Exception ex) {
							LoggingService.LogError ("Failed to delete temp download file", ex);
						}
					}
				}
			}, ct);
		}
	}
	
	class EventQueue
	{
		class EventData
		{
			public Func<Delegate> Delegate;
			public object ThisObject;
			public EventArgs Args;
		}
		
		List<EventData> events = new List<EventData> ();
		
		int frozen;
		object defaultSourceObject;
		
		public EventQueue ()
		{
		}
		
		public EventQueue (object defaultSourceObject)
		{
			this.defaultSourceObject = defaultSourceObject;
		}
		
		public void Freeze ()
		{
			lock (events) {
				frozen++;
			}
		}
		
		public void Thaw ()
		{
			List<EventData> pendingEvents = null;
			lock (events) {
				if (--frozen == 0) {
					pendingEvents = events;
					events = new List<EventData> ();
				}
			}
			if (pendingEvents != null) {
				for (int n=0; n<pendingEvents.Count; n++) {
					EventData ev = pendingEvents [n];
					Delegate del = ev.Delegate ();
					if (ev.Args is IEventArgsChain) {
						EventData next = n < pendingEvents.Count - 1 ? pendingEvents [n + 1] : null;
						if (next != null && (next.Args.GetType() == ev.Args.GetType ()) && next.Delegate() == del && next.ThisObject == ev.ThisObject) {
							((IEventArgsChain)next.Args).MergeWith ((IEventArgsChain)ev.Args);
							continue;
						}
					}
					if (del != null)
						del.DynamicInvoke (ev.ThisObject, ev.Args);
				}
			}
		}
		
		public void RaiseEvent (Func<Delegate> d, EventArgs args)
		{
			RaiseEvent (d, defaultSourceObject, args);
		}
		
		public void RaiseEvent (Func<Delegate> d, object thisObj, EventArgs args)
		{
			Delegate del = d ();
			lock (events) {
				if (frozen > 0) {
					EventData ed = new EventData ();
					ed.Delegate = d;
					ed.ThisObject = thisObj;
					ed.Args = args;
					events.Add (ed);
					return;
				}
			}
			if (del != null) {
				Runtime.MainSynchronizationContext.Post (delegate {
					del.DynamicInvoke (thisObj, args);
				}, null);
			}
		}
	}
	
	public delegate bool FileServiceErrorHandler (string message, Exception ex);
}