~and471/+junk/do-with-docky

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
// ItemsService.cs
// 
// Copyright (C) 2008 GNOME Do
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Security.Permissions;

using Do;
using Do.Interface;
using Do.Interface.Wink;
using Do.Universe;
using Do.Platform;

using Docky.Interface;
using Docky.Utilities;

using Wnck;

namespace Docky.Core.Default
{
	public class ItemsService : IItemsService
	{
		const int UpdateDelay = 20;
		
		// stores items tied with their original identifier so we can remove them later
		Dictionary<string, AbstractDockItem> custom_items;
		
		// a collection for each of the major types of item
		List<AbstractDockItem> output_items, task_items, stat_items;
		
		// this will be a readonly collection to track out output items
		ReadOnlyCollection<AbstractDockItem> readonly_output_items;
		
		bool CustomItemsRead { get; set; }
		
		IEnumerable<AbstractDockItem> Docklets {
			get { return DockServices.DockletService.ActiveDocklets.Cast<AbstractDockItem> (); }
		}
		
		//// <value>
		/// Our main menu.  We only ever need one so we will store it here
		/// </value>
		AbstractDockItem MenuItem { get; set; }
		
		/// <value>
		/// Our separator.  we can re-use this to render over and over if need be.
		/// </value>
		AbstractDockItem Separator { get; set; }
		
		/// <value>
		/// The path to the file we will use to serialize out our custom items
		/// </value>
		string CustomItemsPath {
			get {
				return Path.Combine (Services.Paths.UserDataDirectory, GetType ().Name + "_CustomItems");
			}
		}
		
		/// <value>
		/// The path to the file we will use to store our sort dictionary
		/// </value>
		string SortDictionaryPath {
			get { 
				return Path.Combine (Services.Paths.UserDataDirectory, GetType ().Name + "_SortDictionary");
			}
		}
		
		string DesktopFilesDirectory {
			get {
				return Path.Combine (Services.Paths.UserDataDirectory, GetType ().Name + "_DesktopFiles");
			}
		}
		
		IEnumerable<AbstractDockItem> OrderedItems {
			get {
				return stat_items
					    .Concat (custom_items.Values)
						.Concat (task_items)
						.OrderBy (di => di.Position);
			}
		}
		
		int LastPosition {
			get {
				if (!OrderedItems.Any ())
					return 0;
				return OrderedItems.Max ((Func<AbstractDockItem, int>) (di => di.Position));
			}
		}
		
		#region Constructor
		
		public ItemsService ()
		{
			// build our data structures
			custom_items = new Dictionary<string, AbstractDockItem> ();
			task_items = new List<AbstractDockItem> ();
			output_items = new List<AbstractDockItem> ();
			stat_items = new List<AbstractDockItem> ();
			
			// hook up our read only collection
			readonly_output_items = output_items.AsReadOnly ();
			
			Separator = new SeparatorItem ();
			MenuItem = new DoDockItem ();
			
			if (!Directory.Exists (DesktopFilesDirectory))
				Directory.CreateDirectory (DesktopFilesDirectory);
			
			RegisterEvents ();
		}
		
		#endregion
		
		#region Event Handling
		void RegisterEvents ()
		{
			// core services
			Services.Core.UniverseInitialized += HandleUniverseInitialized;
			
			// wnck events
			Wnck.Screen.Default.WindowClosed += HandleWindowClosed; 
			Wnck.Screen.Default.WindowOpened += HandleWindowOpened; 
			
			// Dock Services
			DockPreferences.AutomaticIconsChanged += HandleAutomaticIconsChanged; 
			DockServices.DockletService.AppletVisibilityChanged += HandleAppletVisibilityChanged; 
			
			RegisterDocklets ();
		}
		
		void RegisterDocklets ()
		{
			RegisterDockItem (MenuItem);
			
			foreach (AbstractDockItem item in DockServices.DockletService.Docklets) {
				RegisterDockItem (item);
			}
		}
		
		void UnregisterEvents ()
		{
			// core services
			Services.Core.UniverseInitialized -= HandleUniverseInitialized;
			
			// wnck events
			if (Wnck.Screen.Default != null) {
				Wnck.Screen.Default.WindowClosed -= HandleWindowClosed; 
				Wnck.Screen.Default.WindowOpened -= HandleWindowOpened; 
			}
			
			// Dock Services
			DockPreferences.AutomaticIconsChanged -= HandleAutomaticIconsChanged; 
			DockServices.DockletService.AppletVisibilityChanged -= HandleAppletVisibilityChanged; 
			
			UnregisterDocklets ();
		}
		
		void UnregisterDocklets ()
		{
			UnregisterDockItem (MenuItem);
			
			foreach (AbstractDockItem item in DockServices.DockletService.Docklets) {
				UnregisterDockItem (item);
			}
		}
		
		void ResetDockelts ()
		{
			UnregisterDocklets ();
			RegisterDocklets ();
		}
		
		void RegisterDockItem (AbstractDockItem dockItem)
		{
			dockItem.UpdateNeeded += HandleUpdateNeeded;
			if (dockItem is IRightClickable)
				(dockItem as IRightClickable).RemoveClicked += HandleRemoveClicked;
		}
		
		void UnregisterDockItem (AbstractDockItem dockItem)
		{
			dockItem.UpdateNeeded -= HandleUpdateNeeded;
			if (dockItem is IRightClickable)
				(dockItem as IRightClickable).RemoveClicked -= HandleRemoveClicked;
		}

		void HandleAppletVisibilityChanged (object sender, EventArgs e)
		{
			ResetDockelts ();
			OnDockItemsChanged ();
		}

		void HandleAutomaticIconsChanged ()
		{
			UpdateItems ();
		}
		
		void HandleRemoveClicked (object sender, EventArgs e)
		{
			if (sender is AbstractDockItem)
				RemoveItem (sender as AbstractDockItem);
		}

		void HandleWindowOpened (object o, WindowOpenedArgs args)
		{
			// we do a delayed update so that we allow a small gap for wnck to catch up
			if (!args.Window.IsSkipTasklist || args.Window.Pid != System.Diagnostics.Process.GetCurrentProcess ().Id)
				DelayUpdateItems ();
		}

		void HandleWindowClosed (object o, WindowClosedArgs args)
		{
			if (!args.Window.IsSkipTasklist || args.Window.Pid != System.Diagnostics.Process.GetCurrentProcess ().Id)
				DelayUpdateItems ();
		}

		void HandleUniverseInitialized (object sender, EventArgs e)
		{
			UpdatesEnabled = true;
			UpdateItems ();
		}
		
		void HandleUpdateNeeded (object sender, UpdateRequestArgs args)
		{
			if (!DockItems.Contains (args.Item))
				return;
			if (ItemNeedsUpdate != null)
				ItemNeedsUpdate (this, args);
		}
		
		#endregion
		
		#region Item Updating
		AbstractDockItem MaybeCreateCustomItem (ref string identifier)
		{
			ItemDockItem customItem = null;
			
			if (identifier.StartsWith ("file://"))
				identifier = identifier.Substring ("file://".Length);
			
			if (File.Exists (identifier) || Directory.Exists (identifier)) {
				if (identifier.EndsWith (".desktop")) {
					bool writeable = true;
					try {
						using (FileStream stream = File.OpenWrite (identifier)) {
							;
						}
					} catch {
						writeable = false;
					}
					if (writeable && Path.GetDirectoryName (identifier) != DesktopFilesDirectory) {
						string newFile = Path.Combine (DesktopFilesDirectory, Path.GetFileName (identifier));
						try {
							Log<ItemsService>.Error ("Could not add custom item with id: {0}, File already exists", identifier);
							File.Copy (identifier, newFile);
						} catch {
							
							return null; 
						}
						identifier = newFile;
					}
					Item o = Services.UniverseFactory.NewApplicationItem (identifier) as Item;
					customItem = new ItemDockItem (o);
				} else {
					Item o = Services.UniverseFactory.NewFileItem (identifier) as Item;
					customItem = new ItemDockItem (o);
				}
			} else {
				Item e = Services.Core.GetItem (identifier);
				if (e != null)
					customItem = new ItemDockItem (e);
				else
					Log<ItemsService>.Error ("Could not add custom item with id: {0}", identifier);
			}
			return customItem;
		}
		
		void SimplifyPositions (IEnumerable<AbstractDockItem> items)
		{
			int i = 0;
			// we call ToArray so our enumerator does get screwed up when we change the Position
			foreach (AbstractDockItem item in items.OrderBy (di => di.Position).ToArray ())
				item.Position = i++;
		}
		
		void DelayUpdateItems ()
		{
			GLib.Timeout.Add (UpdateDelay, delegate {
				UpdateItems ();
				return false;
			});
		}
		
		void UpdateItems ()
		{
			if (!UpdatesEnabled)
				return;
			
			if (!CustomItemsRead) {
				foreach (string s in ReadCustomItems ())
					InternalAddItemToDock (s, LastPosition + 1);
				
				UpdateStatItems ();
				
				Dictionary<string, int> sortDictionary = ReadSortDictionary ();
				foreach (ItemDockItem item in OrderedItems.Where (di => di is ItemDockItem)) {
					if (item.Item == null)
						continue;
					
					if (sortDictionary.ContainsKey (item.Item.UniqueId))
						item.Position = sortDictionary [item.Item.UniqueId];
				}
				foreach (AbstractDockItem item in Docklets) {
					if (sortDictionary.ContainsKey (item.GetType ().FullName))
					    item.Position = sortDictionary [item.GetType ().FullName];
				}
				
				CustomItemsRead = true;
			} else {
				UpdateStatItems ();
			}
			
			UpdateTaskItems ();
			SimplifyPositions (OrderedItems);
			SimplifyPositions (Docklets);
			
			OnDockItemsChanged ();
		}
		
		void UpdateStatItems ()
		{
			List<ItemDockItem> old_items = new List<ItemDockItem> (stat_items.Where (di => di is ItemDockItem)
			                                                       .Cast<ItemDockItem> ());
			List<ItemDockItem> local_cust = new List<ItemDockItem> (custom_items.Values
			                                                        .Where (di => di is ItemDockItem)
			                                                        .Cast<ItemDockItem> ());
			
			stat_items = new List<AbstractDockItem> ();
			
			IEnumerable<Item> mostUsedItems = MostUsedItems ();
			
			DateTime currentTime = DateTime.UtcNow;
			foreach (Item item in mostUsedItems.Where (i => !local_cust.Any (ci => ci.Item != null && ci.Item.UniqueId == i.UniqueId))) {
				
				if (old_items.Any (di => di.Item == item)) {
					stat_items.AddRange (old_items
					                     .Where (di => di.Item != null && di.Item.UniqueId == item.UniqueId)
					                     .Cast<AbstractDockItem> ());
				} else {
					ItemDockItem di = new ItemDockItem (item);
					RegisterDockItem (di);
					di.DockAddItem = currentTime;
					
					int position = LastPosition + 1;

					// TODO fixme once mono 1.9 support is dropped
					if (old_items.Any ())
						position += old_items.Max ((Func<ItemDockItem, int>) (oi => oi.Position));

					di.Position = position;
					stat_items.Add (di);
				}
			}
			
			// potential leak if not all items in stat_items were ItemDockItems!!!
			foreach (ItemDockItem item in  old_items.Where (di => !stat_items.Contains (di))) {
				UnregisterDockItem (item);
				item.Dispose ();
			}
		}
		
		void UpdateTaskItems ()
		{
			foreach (ItemDockItem item in OrderedItems.Where (di => di is ItemDockItem))
				item.UpdateApplication ();
			
			List<ApplicationDockItem> out_items = new List<ApplicationDockItem> ();

			IEnumerable<Window> knownWindows = OrderedItems
				    .Where (di => di is ItemDockItem)
					.Cast<ItemDockItem> ()
					.SelectMany (di => di.Windows);
			
			var prunedWindows = WindowUtils.GetWindows ()
				    .Where (w => !w.IsSkipTasklist && !knownWindows.Contains (w))
					.GroupBy (w => SafeResClass (w));
			
			IEnumerable<ApplicationDockItem> apps = WindowUtils.GetWindows ()
				    .Where (w => !w.IsSkipTasklist && !knownWindows.Contains (w))
					.GroupBy (w => SafeResClass (w))
					.Select (ws => CreateApplicationDockItem (ws, task_items));
			
			apps.ForEach (a => RegisterDockItem (a));
			out_items.AddRange (apps);
			
			foreach (AbstractDockItem item in task_items) {
				UnregisterDockItem (item);
				item.Dispose ();
			}
			
			foreach (ApplicationDockItem adi in out_items.OrderBy (di => di.DockAddItem)) {
				if (adi.Position == 0) // raw and unpositioned items
					adi.Position = LastPosition + 1;
			}
					
			task_items.Clear ();
			task_items.AddRange (out_items.Cast<AbstractDockItem> ());
		}
		
		ApplicationDockItem CreateApplicationDockItem (IEnumerable<Wnck.Window> windows, IEnumerable<AbstractDockItem> lastSet)
		{
			ApplicationDockItem adi = new ApplicationDockItem (windows);
			
			if (lastSet.Any (di => di.Equals (adi))) {
				AbstractDockItem match = lastSet.Where (di => di.Equals (adi)).First ();
				adi.DockAddItem = match.DockAddItem;
				adi.Position = match.Position;
				} else {
				adi.DockAddItem = DateTime.UtcNow;
			}
			
			return adi;
		}
		
		string SafeResClass (Wnck.Window window)
		{
			if (window.ClassGroup != null && window.ClassGroup.ResClass != null)
				return window.ClassGroup.ResClass;
			return string.Empty;
		}
		
		void OnDockItemsChanged ()
		{
			output_items.Clear ();
			
			if (DockItemsChanged != null)
				DockItemsChanged (DockItems);
		}
		#endregion
		
		#region Item Management
		bool InternalAddItemToDock (Item item, int position)
		{
			if (!(item is Item)) {
				Log<ItemsService>.Error ("Could not add {0} to custom items for dock", item.Safe.Name);
				return false;
			}
			
			string id = item.UniqueId;
			if (custom_items.ContainsKey (id))
				return false;
			
			AbstractDockItem dockItem = new ItemDockItem (item as Item);
			RegisterDockItem (dockItem);
			
			MakeHoleAtPosition (position);
			
			dockItem.Position = position;
			custom_items [id] = dockItem;
			
			return true;
		}
		
		bool InternalAddItemToDock (string identifier, int position)
		{
			if (custom_items.ContainsKey (identifier)) return false;
			
			AbstractDockItem customItem = MaybeCreateCustomItem (ref identifier);
			
			if (customItem == null) return false;
			
			RegisterDockItem (customItem);
			
			MakeHoleAtPosition (position);
			
			customItem.Position = position;
			custom_items [identifier] = customItem;
			
			return true;
		}
		#endregion
		
		#region Disk Utilities
		void WriteData ()
		{
			WriteSortDictionary ();
			WriteCustomItems ();
		}
		
		void WriteSortDictionary ()
		{
			try {
				if (File.Exists (SortDictionaryPath))
					File.Delete (SortDictionaryPath);
				
				using (StreamWriter writer = new StreamWriter (SortDictionaryPath)) {
					foreach (ItemDockItem di in OrderedItems.Where (di => di is ItemDockItem)) {
						if (di.Item == null)
							continue;
						
						writer.WriteLine ("{0}|{1}", di.Item.UniqueId, di.Position);
					}
					foreach (AbstractDockItem di in Docklets) {
						writer.WriteLine ("{0}|{1}", di.GetType ().FullName, di.Position);
					}
				}
			} catch (Exception e) {
				Log<ItemsService>.Error ("Could not write out sort items");
				Log<ItemsService>.Error (e.Message);
			}
		}
		
		Dictionary<string, int> ReadSortDictionary ()
		{
			Dictionary<string, int> sortDictionary = new Dictionary<string, int> ();
			try {
				using (StreamReader reader = new StreamReader (SortDictionaryPath)) {
					string [] line;
					while (!reader.EndOfStream) {
						line = reader.ReadLine ().Split ('|');
						sortDictionary [line [0]] = Convert.ToInt32 (line [1]);
					}
				}
			} catch (FileNotFoundException e) {
				Log<ItemsService>.Debug ("Sort Dictionary file not present, nothing to add. " + e.Message);
			} catch (Exception e) {
				Log<ItemsService>.Error ("Could not deserialize sort dictionary");
			}
			return sortDictionary;
		}
		
		void WriteCustomItems ()
		{
			try {
				using (Stream s = File.OpenWrite (CustomItemsPath)) {
					BinaryFormatter f = new BinaryFormatter ();
					f.Serialize (s, custom_items.Keys.ToArray ());
				}
			} catch (Exception e) {
				Log<ItemsService>.Error ("Could not serialize custom items");
				Log<ItemsService>.Error (e.Message);
			}
		}
		
		IEnumerable<string> ReadCustomItems ()
		{
			string[] filenames;
			try {
				using (Stream s = File.OpenRead (CustomItemsPath)) {
					BinaryFormatter f = new BinaryFormatter ();
					filenames = f.Deserialize (s) as string[];
				}
			} catch (FileNotFoundException e) {
				Log<ItemsService>.Debug ("Custom items file not present, nothing to add. " + e.Message);
				filenames = new string[0];
			} catch {
				Log<ItemsService>.Error ("Could not deserialize custom items");
				filenames = new string[0];
			}
			return filenames;
		}
		#endregion
		
		#region Random Useful Functions
		bool ItemCanInteractWithPosition (AbstractDockItem item, int position)
		{
			return (DockItems.Contains (item) || Docklets.Contains (item)) && position >= 0 && position < DockItems.Count; 
		}
		
		/// <summary>
		/// Returns the most used items out of GNOME Do and does a tiny bit of filtering and sorting on them
		/// This is mostly to encourage a better first run experience, but overall this can be improved
		/// </summary>
		/// <returns>
		/// A <see cref="IEnumerable"/> of the most used items from Do's core universe
		/// </returns>
		IEnumerable<Item> MostUsedItems ()
		{
			return Services.Core
				.GetItemsOrderedByRelevance ()
				.Where (item => item.GetType ().Name != "SelectedTextItem" && 
					        item.GetType ().Name != "GNOMETrashFileItem")
				.Where (item => !DockPreferences.ItemBlacklist.Contains (item.UniqueId))
				.Take (DockPreferences.AutomaticIcons)
				.OrderByDescending (item => item is IApplicationItem)
				.ThenBy (item => item.GetType ().Name)
				.ThenBy (item => item.Safe.Name);
		}
		
		void MakeHoleAtPosition (int position)
		{
			foreach (AbstractDockItem di in OrderedItems) {
				if (di.Position >= position)
					di.Position++;
			}
		}
		#endregion
		
		#region IItemsService implementation
		public event DockItemsChangedHandler DockItemsChanged;
		public event UpdateRequestHandler ItemNeedsUpdate;
		
		public bool UpdatesEnabled { get; private set; }
		
		public ReadOnlyCollection<AbstractDockItem> DockItems {
			get {
				if (output_items.Count == 0) {
					output_items.Add (MenuItem);
					
					// Add our custom/task/statistical items in one shot
					output_items.AddRange (OrderedItems);
				
					// add a separator and any docklets that are active
					if (DockServices.DockletService.ActiveDocklets.Any ()) {
						output_items.Add (Separator);
						output_items.AddRange (Docklets.OrderBy (docklet => docklet.Position));
					}
				}
				return readonly_output_items;
			}
		}
		
		public void AddItemToDock (Item item)
		{
			AddItemToDock (item, LastPosition + 1);
		}
		
		public void AddItemToDock (string identifier)
		{
			AddItemToDock (identifier, LastPosition + 1);
		}
		
		public void AddItemToDock (Item item, int position)
		{
			position = DockItems [position].Position;
			if (InternalAddItemToDock (item, position)) {
				UpdateItems ();
				WriteData ();
				OnDockItemsChanged ();
			}
		}
		
		public void AddItemToDock (string identifier, int position)
		{
			position = DockItems [position].Position;
			if (InternalAddItemToDock (identifier, position)) {
				UpdateItems ();
				WriteData ();
				OnDockItemsChanged ();
			}
		}
		
		public bool ItemCanBeMoved (int item)
		{
			if (item < 0 || item > DockItems.Count)
				return false;
			
			return (OrderedItems.Contains (DockItems [item]) || Docklets.Contains (DockItems [item]));
		}
		
		public bool ItemCanBeRemoved (int item)
		{
			if (item < 0 || item >= DockItems.Count) return false;
			AbstractDockItem adi = DockItems [item];
			return Docklets.Contains (DockItems [item]) ||
					(adi.WindowCount == 0 && ((GetIconSource (adi) == IconSource.Statistics && adi is ItemDockItem) ||
											(GetIconSource (adi) == IconSource.Custom)));
		}
		
		public void DropItemOnPosition (AbstractDockItem item, int position)
		{
			do {
				if (!ItemCanInteractWithPosition (item, position)) continue;
			
				if (DockItems [position] is TrashDockItem && !(item is TrashDockItem)) {
					RemoveItem (item);
					continue;
				}
				
				if (item is ApplicationDockItem) {
					ApplicationDockItem adi = item as ApplicationDockItem;
					
					if (adi.Launcher == null) continue;
					
					Item launcher = adi.Launcher as Item;
					if (launcher == null)
						continue;
					
					AbstractDockItem newItem = new ItemDockItem (launcher);
					
					newItem.Position = item.Position;
					newItem.DockAddItem = item.DockAddItem;
					custom_items [launcher.UniqueId] = newItem;
					
					RegisterDockItem (newItem);
					UpdateItems ();
					WriteData ();
				}
			} while (false);
		}
		
		public void MoveItemToPosition (AbstractDockItem item, int position)
		{
			if (ItemCanInteractWithPosition (item, position))
				MoveItemToPosition (DockItems.IndexOf (item), position);
		}
		
		public void MoveItemToPosition (int item, int position)
		{
			if (item == position || 
			    item < 0 || 
			    position < 0 || 
			    position > DockItems.Count || 
			    item > DockItems.Count)
				return;
			
			IconSource itemSource = GetIconSource (DockItems [item]);
			IconSource targetSource = GetIconSource (DockItems [position]);
			
			if (itemSource == IconSource.Unknown || 
			    targetSource == IconSource.Unknown || 
			    (itemSource == IconSource.Docklet && targetSource != IconSource.Docklet) ||
			    (itemSource != IconSource.Docklet && targetSource == IconSource.Docklet))
				return;
			
			AbstractDockItem primaryItem = DockItems [item];
			AbstractDockItem targetItem = DockItems [position];
			
			int startPosition = primaryItem.Position;
			int targetPosition = targetItem.Position;
			
			IEnumerable<AbstractDockItem> itemSet;
			if (itemSource == IconSource.Docklet)
				itemSet = Docklets;
			else
				itemSet = OrderedItems;
			
			foreach (AbstractDockItem di in itemSet) {
				if (startPosition < targetPosition) {
					// the item is being shifted to the right.  Everything greater than item up to and including target item
					// needs to be shifted to the left
					if (di.Position > startPosition && di.Position <= targetPosition)
						di.Position--;
				} else {
					// the item is being shifted to the left.  Everthing less than the item and up to and including target item
					// needs to be shifted to the right
					if (di.Position < startPosition && di.Position >= targetPosition)
						di.Position++;
				}
			}
			
			primaryItem.Position = targetPosition;
			
			OnDockItemsChanged ();
			WriteData ();
		}
		
		public void ForceUpdate ()
		{
			UpdateItems ();
		}
		
		public IconSource GetIconSource (AbstractDockItem item)
		{
			if (task_items.Contains (item))
				return IconSource.Application;
			
			if (stat_items.Contains (item))
				return IconSource.Statistics;
			
			if (custom_items.Values.Contains (item))
				return IconSource.Custom;
			
			if (Docklets.Contains (item))
				return IconSource.Docklet;
			
			return IconSource.Unknown;
		}
		
		public bool RemoveItem (AbstractDockItem item)
		{
			if (!DockItems.Contains (item))
				return false;
			return RemoveItem (DockItems.IndexOf (item));
		}
		
		public bool RemoveItem (int item)
		{
			bool result = ItemCanBeRemoved (item);
			
			if (result) {
				if (Docklets.Contains (DockItems [item])) {
					DockServices.DockletService.ToggleDocklet (DockItems [item] as AbstractDockletItem);
				} else if (GetIconSource (DockItems [item]) == IconSource.Statistics) {
					ItemDockItem di = (DockItems [item] as ItemDockItem);
					DockPreferences.AddBlacklistItem ((DockItems [item] as ItemDockItem).Item.UniqueId);
					DockPreferences.AutomaticIcons = Math.Max (0, DockPreferences.AutomaticIcons - 1);
				} else if (GetIconSource (DockItems [item]) == IconSource.Custom) {
					KeyValuePair<string, AbstractDockItem> kvp = custom_items
						.Where (k => k.Value.Equals (DockItems [item]))
						.First ();
					
					custom_items.Remove (kvp.Key);
					
					if (kvp.Key.EndsWith (".desktop") && Path.GetDirectoryName (kvp.Key) == DesktopFilesDirectory) {
						try {
							File.Delete (kvp.Key);
						} catch {
							// Don't really care, it was only a nice thing to do...
						}
					}
				}
				
				UpdateItems ();
				WriteData ();
			}
			
			return result;
		}
		
		public bool HotSeatItem (AbstractDockItem item, List<AbstractDockItem> seatedItems)
		{
			Log<ItemsService>.Error ("Items Service cannot currently handle hotseating");
			return false;
		}
		
		public bool ResetHotSeat (AbstractDockItem item)
		{
			Log<ItemsService>.Error ("Items Service cannot currently handle hotseating");
			return false;
		}
		#endregion

		#region IDisposable implementation
		public void Dispose ()
		{
			UnregisterEvents ();
			
			foreach (AbstractDockItem di in DockItems) {
				if (di.Disposed)
					continue;
				
				UnregisterDockItem (di);
				di.Dispose ();
			}
			
			if (!Separator.Disposed)
				Separator.Dispose ();
			
			custom_items.Clear ();
			stat_items.Clear ();
			output_items.Clear ();
			task_items.Clear ();
		}
		#endregion
		
		
	}
}