aboutsummaryrefslogtreecommitdiff
path: root/cells.hpp
blob: 27b3633c26a3e4fed1d1c47d45db178727c38d1c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright 2012, Matthias Andreas Benkard.

#pragma once

#ifndef CELLS_HPP
#define CELLS_HPP

#include <functional>
#include <memory>
#include <forward_list>
#include <algorithm>

namespace cells {

  class observer : public virtual std::enable_shared_from_this<observer> {
  private:
    std::forward_list<std::weak_ptr<observer>> dependents;
    std::forward_list<std::shared_ptr<observer>> dependencies;

    void clear_dependencies();
    void mark_dependents();

  protected:
    void mark();

  public:
    void add_dependent(std::shared_ptr<observer> dependent);
    void remove_dependent(observer* dependent);
    void reset_dependencies(std::forward_list<std::shared_ptr<observer>> const& newdeps);

    virtual void update() = 0;

    virtual ~observer();
  };


  template <typename T>
  class cell : public observer {
  private:
    T current_value;

  protected:
    cell();
    virtual void update();
    virtual T recompute(T) = 0;
    virtual T init() = 0;

  public:
    T& get();
    T& operator *() { return get(); }
    //T operator ()() { return get(); }
    operator T() { return get(); }

    virtual ~cell();
  };


  template <typename T>
  class formula_cell : public cell<T> {
    //friend class std::shared_ptr<formula_cell<T>>;
    //friend std::shared_ptr<formula_cell<T>> std::make_shared<formula_cell<T>>();
  private:
    std::function<T ()> formula;
    std::function<T (T old)> alt_formula;

  protected:
    formula_cell() { }
    virtual T recompute(T);
    virtual T init();

  public:
    //static std::shared_ptr<formula_cell<T>> make() { return std::make_shared<formula_cell<T>>(); }
    static std::shared_ptr<formula_cell<T>> make() { return std::shared_ptr<formula_cell<T>>(new formula_cell()); }

    void reset(T value);
    void reset(std::function<T ()>);
    void reset(std::function<T ()>, std::function<T (T old)>);

    virtual ~formula_cell();
  };

  void with_transaction(std::function<void ()>);
}

#endif //CELLS_HPP

#include "cells-impl.hpp"