/YEDSelectionManager.j

http://github.com/rheimbuch/YED · Unknown · 94 lines · 78 code · 16 blank · 0 comment · 0 complexity · 50b22f4af900a7ae321a84671dd562d9 MD5 · raw file

  1. @import <Foundation/CPNotificationCenter.j>
  2. @import <Foundation/CPObject.j>
  3. @import <Foundation/CPSet.j>
  4. YEDSelectedItemNotification = "YEDSelectedItemNotification";
  5. @implementation YEDSelectionManager : CPObject
  6. {
  7. CPSet selectedItems @accessors;
  8. id delegate @accessors;
  9. }
  10. - (id)init
  11. {
  12. self = [super init];
  13. if(self)
  14. {
  15. selectedItems = [CPSet set];
  16. [[CPNotificationCenter defaultCenter] addObserver:self
  17. selector:@selector(selectedItemNotification:)
  18. name:YEDSelectedItemNotification
  19. object:nil];
  20. }
  21. return self;
  22. }
  23. - (BOOL)allowMultipleSelections
  24. {
  25. return false;
  26. }
  27. - (void)selectItem:(id)item
  28. {
  29. //Selecting a nil item deselectes all items;
  30. if(!item)
  31. {
  32. [self deselectAll];
  33. return;
  34. }
  35. if(![self handlesSelectableItem:item])
  36. return;
  37. if([selectedItems containsObject:item])
  38. return;
  39. if(![self allowMultipleSelections]) {
  40. [self deselectAll];
  41. }
  42. [selectedItems addObject:item];
  43. [item setIsSelected:YES];
  44. }
  45. - (void)deselectAll
  46. {
  47. CPLog.trace("Deselecting all items");
  48. var itemIter = [selectedItems objectEnumerator],
  49. oldItem = nil;
  50. while(oldItem = [itemIter nextObject])
  51. {
  52. [oldItem setIsSelected:NO];
  53. [selectedItems removeObject:oldItem];
  54. }
  55. }
  56. /**
  57. Handles selection notifications from selectable views
  58. */
  59. - (void)selectedItemNotification:(CPNotification)notification
  60. {
  61. var item = [notification object],
  62. info = [notification userInfo],
  63. mouseDown = [info objectForKey:@"mouseDown"];
  64. [self selectItem:item];
  65. }
  66. /**
  67. Ask the delegate if we should handle a given item
  68. */
  69. - (BOOL)handlesSelectableItem:(id)item
  70. {
  71. if(!([item respondsToSelector:@selector(isSelected)] && [item respondsToSelector:@selector(setIsSelected:)]))
  72. return false;
  73. if([delegate respondsToSelector:@selector(selectionManager:shouldHandle:)])
  74. return [delegate selectionManager:self shouldHandle:item];
  75. else
  76. false;
  77. }
  78. @end