signals.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. ########################################################################
  2. # Hello Worlds - Libre 3D RPG game.
  3. # Copyright (C) 2020 CYBERDEViL
  4. #
  5. # This file is part of Hello Worlds.
  6. #
  7. # Hello Worlds is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # Hello Worlds is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. #
  20. ########################################################################
  21. class Signal:
  22. def __init__(self, *argTypes):
  23. self._argTypes = argTypes
  24. self._cbFuncs = [] # callbacks
  25. def connect(self, cbFunc):
  26. if cbFunc not in self._cbFuncs:
  27. self._cbFuncs.append(cbFunc)
  28. return 0
  29. else:
  30. print("Signal.connect : Callback function {0} connection already exists.".format(cbFunc))
  31. return 1
  32. def disconnect(self, cbFunc=None):
  33. if cbFunc == None:
  34. self._cbFuncs.clear()
  35. return 0
  36. elif cbFunc in self._cbFuncs:
  37. self._cbFuncs.remove(cbFunc)
  38. return 0
  39. else:
  40. print("Signal.disconnect : Callback function {0} not found.".format(cbFunc))
  41. return 1
  42. def emit(self, *args):
  43. _args = []
  44. index = 0
  45. for argType in self._argTypes:
  46. if type(args[index]) != argType:
  47. print("Signal.emit : Expected a {0} type instead got a {1} type for argument {2}".format(argType, type(args[index]), index))
  48. return 1
  49. _args.append(args[index])
  50. index += 1
  51. for cbFunc in self._cbFuncs.copy():
  52. cbFunc(*_args)
  53. return 0