FlatCAMCommon.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # ########################################################## ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ########################################################## ##
  8. class LoudDict(dict):
  9. """
  10. A Dictionary with a callback for
  11. item changes.
  12. """
  13. def __init__(self, *args, **kwargs):
  14. dict.__init__(self, *args, **kwargs)
  15. self.callback = lambda x: None
  16. def __setitem__(self, key, value):
  17. """
  18. Overridden __setitem__ method. Will emit 'changed(QString)'
  19. if the item was changed, with key as parameter.
  20. """
  21. if key in self and self.__getitem__(key) == value:
  22. return
  23. dict.__setitem__(self, key, value)
  24. self.callback(key)
  25. def update(self, *args, **kwargs):
  26. if len(args) > 1:
  27. raise TypeError("update expected at most 1 arguments, got %d" % len(args))
  28. other = dict(*args, **kwargs)
  29. for key in other:
  30. self[key] = other[key]
  31. def set_change_callback(self, callback):
  32. """
  33. Assigns a function as callback on item change. The callback
  34. will receive the key of the object that was changed.
  35. :param callback: Function to call on item change.
  36. :type callback: func
  37. :return: None
  38. """
  39. self.callback = callback
  40. class FCSignal:
  41. """
  42. Taken from here: https://blog.abstractfactory.io/dynamic-signals-in-pyqt/
  43. """
  44. def __init__(self):
  45. self.__subscribers = []
  46. def emit(self, *args, **kwargs):
  47. for subs in self.__subscribers:
  48. subs(*args, **kwargs)
  49. def connect(self, func):
  50. self.__subscribers.append(func)
  51. def disconnect(self, func):
  52. try:
  53. self.__subscribers.remove(func)
  54. except ValueError:
  55. print('Warning: function %s not removed '
  56. 'from signal %s' % (func, self))