The Battle for Wesnoth  1.15.1+dev
generic_event.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2006 - 2018 by Joerg Hinrichs <joerg.hinrichs@alice-dsl.de>
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
15 #include "generic_event.hpp"
16 
17 #include <algorithm>
18 
19 namespace events{
20 
21 generic_event::generic_event(const std::string& name) :
22  name_(name),
23  observers_(),
24  change_handler_(false),
25  notify_active_(false)
26 {
27 }
28 
30  bool handler_attached = false;
31 
32  //make sure observers are not notified right now
33  if (!notify_active_){
34  change_handler_ = true;
35  try{
36  std::vector<observer*>::const_iterator it = std::find(observers_.begin(), observers_.end(), obs);
37  if (it != observers_.end()){
38  handler_attached = false;
39  }
40  else{
41  observers_.push_back(obs);
42  handler_attached = true;
43  }
44  }
45  catch (...){
46  change_handler_ = false;
47  throw;
48  }
49  change_handler_ = false;
50  }
51 
52  return handler_attached;
53 }
54 
56  bool handler_detached = false;
57 
58  //make sure observers are not notified right now
59  if (!notify_active_){
60  auto it = std::find(observers_.begin(), observers_.end(), obs);
61  if (it == observers_.end()){
62  handler_detached = false;
63  }
64  else{
65  observers_.erase(it);
66  handler_detached = true;
67  }
68  change_handler_ = false;
69  }
70 
71  return handler_detached;
72 }
73 
75  if (!change_handler_){
76  notify_active_ = true;
77  try{
78  for (std::vector<observer*>::const_iterator it = observers_.begin();
79  it != observers_.end(); ++it){
80  (*it)->handle_generic_event(name_);
81  }
82  }
83  catch (...){
84  //reset the flag if event handlers throw exceptions and don't catch them
85  notify_active_ = false;
86  throw;
87  }
88  notify_active_ = false;
89  }
90 }
91 
92 } //namespace events
virtual void notify_observers()
static const char * name(const std::vector< SDL_Joystick *> &joysticks, const std::size_t index)
Definition: joystick.cpp:48
std::vector< observer * > observers_
virtual bool attach_handler(observer *obs)
Handling of system events.
Definition: manager.hpp:41
bool find(E event, F functor)
Tests whether an event handler is available.
virtual bool detach_handler(observer *obs)
generic_event(const std::string &name)