Skip to content

Commit

Permalink
Action, ActionList: Use reference counting to detach condition change…
Browse files Browse the repository at this point in the history
…d handlers
  • Loading branch information
lxn committed May 1, 2013
1 parent 8fd1cc0 commit 1ae244d
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 18 deletions.
18 changes: 18 additions & 0 deletions action.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ type Action struct {
enabledConditionChangedHandle int
visibleCondition Condition
visibleConditionChangedHandle int
refCount int
enabled bool
visible bool
checkable bool
Expand All @@ -50,6 +51,23 @@ func NewAction() *Action {
return a
}

func (a *Action) addRef() {
a.refCount++
}

func (a *Action) release() {
a.refCount--

if a.refCount == 0 {
a.SetEnabledCondition(nil)
a.SetVisibleCondition(nil)

if a.menu != nil {
a.menu.actions.Clear()
}
}
}

func (a *Action) Checkable() bool {
return a.checkable
}
Expand Down
39 changes: 21 additions & 18 deletions actionlist.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ type ActionList struct {
}

func newActionList(observer actionListObserver) *ActionList {
if observer == nil {
panic("observer == nil")
}

return &ActionList{observer: observer}
}

Expand All @@ -32,11 +36,12 @@ func (l *ActionList) At(index int) *Action {
}

func (l *ActionList) Clear() error {
observer := l.observer
if observer != nil {
if err := observer.onClearingActions(); err != nil {
return err
}
if err := l.observer.onClearingActions(); err != nil {
return err
}

for _, a := range l.actions {
a.release()
}

l.actions = l.actions[:0]
Expand Down Expand Up @@ -78,15 +83,14 @@ func (l *ActionList) Insert(index int, action *Action) error {
copy(l.actions[index+1:], l.actions[index:])
l.actions[index] = action

observer := l.observer
if observer != nil {
if err := observer.onInsertedAction(action); err != nil {
l.actions = append(l.actions[:index], l.actions[index+1:]...)
if err := l.observer.onInsertedAction(action); err != nil {
l.actions = append(l.actions[:index], l.actions[index+1:]...)

return err
}
return err
}

action.addRef()

return nil
}

Expand Down Expand Up @@ -115,16 +119,15 @@ func (l *ActionList) Remove(action *Action) error {
}

func (l *ActionList) RemoveAt(index int) error {
observer := l.observer
if observer != nil {
action := l.actions[index]
if action.Visible() {
if err := observer.onRemovingAction(action); err != nil {
return err
}
action := l.actions[index]
if action.Visible() {
if err := l.observer.onRemovingAction(action); err != nil {
return err
}
}

action.release()

l.actions = append(l.actions[:index], l.actions[index+1:]...)

return nil
Expand Down

0 comments on commit 1ae244d

Please sign in to comment.