"""Some tools for Zwolle19."""

dprint = print  #pylint: disable=invalid-name, unused-variable

def is_coupled(label1, label2):
    """Say if the given two labels are coupled."""
    couples = [{"G", "H"}, {"C", "E"}, {"A", "D"}, {"B", "F"}]
    #couples = [{"G", "H"}, {"C", "D"}, {"A", "E"}, {"B", "F"}]

    for couple in couples:
        if {label1, label2} in couples:
            return True
    return False

def is_ok_line(line):
    """
    Say if the given line is ok.

    @param {list of Card} `line`
    """
    card1 = line[0]
    card2 = line[1]
    card3 = line[2]

    if not is_coupled(card1.east, card2.west):
        return False
    if not is_coupled(card2.east, card3.west):
        return False
    return True

def is_ok_two_lines(line1, line2):
    """
    Say if `line2` can be bellow `line1`

    - check that the two lines do not contain the same identifiers
    - check that the labels match
    """
    card1 = line1[0]
    card2 = line1[1]
    card3 = line1[2]
    card4 = line2[0]
    card5 = line2[1]
    card6 = line2[2]
    idents1 = [card.ident for card in line1]
    idents2 = [card.ident for card in line2]
    intersection = list(set(idents1) & set(idents2))
    if intersection:
        return False
    if not is_coupled(card1.south, card4.north):
        return False
    if not is_coupled(card2.south, card5.north):
        return False
    if not is_coupled(card3.south, card6.north):
        return False
    return True

def is_ok_three_lines(line1, line2, line3):
    """
    Say if `line2` can be bellow `line1` and `line3` bellow `line2`

    - check that the two lines do not contain the same identifiers
    - check that the labels match
    """
    card1 = line1[0]
    card2 = line1[1]
    card3 = line1[2]
    card4 = line2[0]
    card5 = line2[1]
    card6 = line2[2]

    card7 = line3[0]
    card8 = line3[1]
    card9 = line3[2]
    idents1 = [card.ident for card in line1]
    idents2 = [card.ident for card in line2]
    idents3 = [card.ident for card in line3]

    intersection = list(set(idents1) & set(idents2))
    if intersection:
        dprint("intersection 12")
        return False

    intersection = list(set(idents1) & set(idents3))
    if intersection:
        return False

    intersection = list(set(idents2) & set(idents3))
    if intersection:
        return False

    print("??????????????")
    show_triple(line1, line2, line3)
    print("??????????????")

    if not is_ok_two_lines(line1, line2):
        return False
    if not is_ok_two_lines(line2, line3):
        return False

    return True

def show_double(line1, line2):
    """Show the two lines."""
    card1 = line1[0]
    card2 = line1[1]
    card3 = line1[2]
    card4 = line2[0]
    card5 = line2[1]
    card6 = line2[2]
    print("---")
    print(card1, card2, card3)
    print(card4, card5, card6)

def show_triple(line1, line2, line3):
    """Show the three lines."""
    card1 = line1[0]
    card2 = line1[1]
    card3 = line1[2]
    card4 = line2[0]
    card5 = line2[1]
    card6 = line2[2]
    card7 = line3[0]
    card8 = line3[1]
    card9 = line3[2]
    print(card1.ident, card2.ident, card3.ident)
    print(card4.ident, card5.ident, card6.ident)
    print(card7.ident, card8.ident, card9.ident)
    print(card1, card2, card3)
    print(card4, card5, card6)
    print(card7, card8, card9)


import ssl, json, zmq, os, logging, sys, sched, time, signal
from urllib.request import Request, urlopen

def signal_handler(signal, frame):
    print('You pressed Ctrl+C! Shutting down')
    socket.close(linger=1)
    sys.exit(0)

signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)

logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
report_time = float(os.getenv('WATT_REPORT_TIME', 3600))
socket_address = os.getenv('WATT_SOCKET').strip()
api_url = os.getenv('WATT_API_URL').strip()
api_token = os.getenv('WATT_API_TOKEN').strip()

context = zmq.Context()
socket = context.socket(zmq.PUB)
logging.info('Connected to address %s', socket_address)
socket.connect(socket_address)

def send(message):
    logging.debug('Send value: %s to server', message)
    socket.send_multipart([b'sensor', bytes(json.dumps(message),'utf8')])

def get_data_from_api():
    q = Request(api_url)
    q.add_header('Accept', 'application/json')
    q.add_header('X-Version', '1.0')
    q.add_header('X-Token', api_token)
    response = urlopen(q, context=ssl._create_unverified_context()).read()
    return json.loads(response.decode('utf-8'))

def report(sc):
    filterd_elements = [element for element in get_data_from_api() if element[1] != 'nan']
    messages = [{"name": "Electrical sensor",
                 "type": "external_api",
                 "sensor": "electricity",
                 "unix_timestamp": element[0],
                 "value": element[1]} for element in filterd_elements]
    [send(message) for message in messages]
    sc.enter(report_time, 1, report, (sc,))

s = sched.scheduler(time.time, time.sleep)
s.enter(report_time, 1, report, (s,))
logging.info('Add report jobb to scheduler, will run every %s second', report_time)
s.run()


import numpy as np
from unittest import TestCase

from algotrader.technical import Indicator
from algotrader.technical.pipeline import PipeLine
from algotrader.technical.pipeline.cross_sessional_apply import Average, Abs, Tail, Sign, DecayLinear, Scale
from algotrader.technical.pipeline.cross_sessional_apply import Sum as GSSum
from algotrader.technical.pipeline.make_vector import MakeVector
from algotrader.technical.pipeline.pairwise import Minus
from algotrader.technical.pipeline.rank import Rank
from algotrader.technical.talib_wrapper import SMA
from algotrader.trading.context import ApplicationContext

class PipelineTest(TestCase):
    def setUp(self):
        self.app_context = ApplicationContext()

    def test_name(self):

        bar = self.app_context.inst_data_mgr.get_series("bar")
        bar.start(self.app_context)
        sma3 = SMA(inputs=bar, input_keys='close', length=3)
        sma20 = SMA(inputs=bar, input_keys='close', length=20)
        sma50 = SMA(inputs=bar, input_keys='close', length=50)
        sma3.start(self.app_context)
        sma20.start(self.app_context)
        sma50.start(self.app_context)

        rank = Rank(inputs=[sma3, sma20, sma50], input_keys='close')
        rank.start(self.app_context)
        self.assertEquals("Rank(SMA(bar[close],length=3)[close],SMA(bar[close],length=20)[close],SMA(bar[close],length=50)[close],ascending=True)",
                          rank.name)

        bar0 = self.app_context.inst_data_mgr.get_series("bar0")
        bar1 = self.app_context.inst_data_mgr.get_series("bar1")
        bar2 = self.app_context.inst_data_mgr.get_series("bar2")
        bar3 = self.app_context.inst_data_mgr.get_series("bar3")
        bar0.start(self.app_context)
        bar1.start(self.app_context)
        bar2.start(self.app_context)
        bar3.start(self.app_context)
        barlist = [bar0, bar1, bar2, bar3]

        avg = Average(inputs=barlist, input_keys='close')
        gssum = GSSum(inputs=barlist, input_keys='close')
        basket = MakeVector(inputs=barlist, input_keys='close')
        # TODO: the name printed by pipeline now break the "parse" machnism so we have to review it
        self.assertEquals("Average(bar0[close],bar1[close],bar2[close],bar3[close],length=1)", avg.name)
        self.assertEquals("Sum(bar0[close],bar1[close],bar2[close],bar3[close],length=1)", gssum.name)
        self.assertEquals("MakeVector(bar0[close],bar1[close],bar2[close],bar3[close],length=1)", basket.name)

        bar4 = self.app_context.inst_data_mgr.get_series("bar4")
        bar5 = self.app_context.inst_data_mgr.get_series("bar5")
        bar6 = self.app_context.inst_data_mgr.get_series("bar6")
        bar7 = self.app_context.inst_data_mgr.get_series("bar7")
        basket2 = MakeVector(inputs=[bar4, bar5, bar6, bar7], input_keys='close')
        self.assertEquals("MakeVector(bar4[close],bar5[close],bar6[close],bar7[close],length=1)", basket2.name)

        cross_basket_spread = Minus(inputs=[basket2, basket])
        self.assertEquals("Minus(MakeVector(bar4[close],bar5[close],bar6[close],bar7[close],length=1)[close],MakeVector(bar0[close],bar1[close],bar2[close],bar3[close],length=1)[close],length=1)", cross_basket_spread.name)

    def test_empty_at_initialize(self):
        close = self.app_context.inst_data_mgr.get_series("bar")
        close.start(self.app_context)
        sma3 = SMA(inputs=close, input_keys='close', length=3)
        sma20 = SMA(inputs=close, input_keys='close', length=20)
        sma50 = SMA(inputs=close, input_keys='close', length=50)

        sma3.start(self.app_context)
        sma20.start(self.app_context)

        rank = Rank(inputs=[sma3, sma20, sma50], input_keys='close')
        rank.start(self.app_context)
        self.assertEquals(0, len(rank.get_data()))

    def test_shape(self):
        close = self.app_context.inst_data_mgr.get_series("bar")
        close.start(self.app_context)

        sma3 = SMA(inputs=close, input_keys='close', length=3)
        sma20 = SMA(inputs=close, input_keys='close', length=20)
        sma50 = SMA(inputs=close, input_keys='close', length=50)

        sma3.start(self.app_context)
        sma20.start(self.app_context)
        sma50.start(self.app_context)

        rank = Rank(inputs=[sma3, sma20, sma50], input_keys='close')
        rank.start(self.app_context)
        try:
            np.testing.assert_almost_equal(np.array([1, 3]), rank.shape(), 5)
        except AssertionError as e:
            self.fail(e.message)

    def test_with_spread(self):
        bar0 = self.app_context.inst_data_mgr.get_series("bar0")
        bar1 = self.app_context.inst_data_mgr.get_series("bar1")
        bar2 = self.app_context.inst_data_mgr.get_series("bar2")
        bar3 = self.app_context.inst_data_mgr.get_series("bar3")

    def __np_assert_almost_equal(self, target, output, precision=10):
        try:
            np.testing.assert_almost_equal(target, output, precision)
        except AssertionError as e:
            self.fail(e.message)

    def test_sync(self):
        bar0 = self.app_context.inst_data_mgr.get_series("bar0")
        bar1 = self.app_context.inst_data_mgr.get_series("bar1")
        bar2 = self.app_context.inst_data_mgr.get_series("bar2")
        bar3 = self.app_context.inst_data_mgr.get_series("bar3")
        bar4 = self.app_context.inst_data_mgr.get_series("bar4")
        bar5 = self.app_context.inst_data_mgr.get_series("bar5")
        bar6 = self.app_context.inst_data_mgr.get_series("bar6")
        bar7 = self.app_context.inst_data_mgr.get_series("bar7")

        bar0.start(self.app_context)
        bar1.start(self.app_context)
        bar2.start(self.app_context)
        bar3.start(self.app_context)
        bar4.start(self.app_context)
        bar5.start(self.app_context)
        bar6.start(self.app_context)
        bar7.start(self.app_context)

        basket = MakeVector(inputs=[bar0, bar1, bar2, bar3], input_keys='close')
        basket2 = MakeVector(inputs=[bar4, bar5, bar6, bar7], input_keys='close')

        basket.start(self.app_context)
        basket2.start(self.app_context)

        basket_open = MakeVector(inputs=[bar0, bar1, bar2, bar3], input_keys='open')
        basket_open2 = MakeVector(inputs=[bar4, bar5, bar6, bar7], input_keys='open')
        cross_basket_spread = Minus(inputs=[basket2, basket], input_keys=PipeLine.VALUE)

        basket_open.start(self.app_context)
        basket_open2.start(self.app_context)
        cross_basket_spread.start(self.app_context)

        nan_arr = np.empty([1, 4])
        nan_arr[:] = np.nan

        t1 = 1
        bar0.add(data={"timestamp": t1, "close": 80.0, "open": 0})
        self.__np_assert_almost_equal(nan_arr, basket.now()["value"])

        bar1.add(data={"timestamp": t1, "close": 95.0, "open": 0})
        self.__np_assert_almost_equal(nan_arr, basket.now()["value"])

        bar2.add(data={"timestamp": t1, "close": 102.0, "open": 0})
        self.__np_assert_almost_equal(nan_arr, basket.now()["value"])

        sync_vec = np.array([[80.0, 95.0, 102.0, 105.0]])

        bar3.add(data={"timestamp": t1, "close": 105.0, "open": 0})
        self.__np_assert_almost_equal(sync_vec, basket.now()["value"])

        bar4.add(data={"timestamp": t1, "close": 102.0, "open": 0})
        bar5.add(data={"timestamp": t1, "close": 95.0, "open": 0})
        bar6.add(data={"timestamp": t1, "close": 107.0, "open": 0})
        bar7.add(data={"timestamp": t1, "close": 101.0, "open": 0})

        sync_vec2 = np.array([[102.0, 95.0, 107.0, 101.0]])
        self.__np_assert_almost_equal(sync_vec2, basket2.now()["value"])

        target_spread = np.array([[22.0, 0.0, 5.0, -4.0]])
        self.__np_assert_almost_equal(target_spread, cross_basket_spread.now()["value"])
        self.__np_assert_almost_equal(sync_vec, basket.now()["value"])

    # def test_nan_before_size(self):
    def test_with_multiple_bar(self):
        bar0 = self.app_context.inst_data_mgr.get_series("bar0")
        bar1 = self.app_context.inst_data_mgr.get_series("bar1")
        bar2 = self.app_context.inst_data_mgr.get_series("bar2")
        bar3 = self.app_context.inst_data_mgr.get_series("bar3")

        bar0.start(self.app_context)
        bar1.start(self.app_context)
        bar2.start(self.app_context)
        bar3.start(self.app_context)

        barlist = [bar0, bar1, bar2, bar3]

        rank = Rank(inputs=barlist, input_keys='close')
        avg = Average(inputs=barlist, input_keys='close')
        gssum = GSSum(inputs=barlist, input_keys='close')
        absv = Abs(inputs=barlist, input_keys='close')
        tail = Tail(inputs=barlist, input_keys='close', lb=94, ub=103, newval=101)
        signvec = Sign(inputs=barlist, input_keys='close')
        decaylinear = DecayLinear(inputs=barlist, input_keys='close', length=3)
        scale = Scale(inputs=barlist, input_keys='close')

        rank.start(self.app_context)
        avg.start(self.app_context)
        gssum.start(self.app_context)
        absv.start(self.app_context)
        tail.start(self.app_context)
        signvec.start(self.app_context)
        decaylinear.start(self.app_context)
        scale.start(self.app_context)

        t1 = 1
        bar_t1_array = np.array([80, 95, 102, 105])
        bar0.add(data={"timestamp": t1, "close": bar_t1_array[0], "open": 0})
        bar1.add(data={"timestamp": t1, "close": bar_t1_array[1], "open": 0})
        bar2.add(data={"timestamp": t1, "close": bar_t1_array[2], "open": 0})
        bar3.add(data={"timestamp": t1, "close": bar_t1_array[3], "open": 0})

        # self.assertEquals([{"timestamp": t1,
        #                     "name": "'Rank('bar0','bar1','bar2','bar3',close)'",
        #                     "value": np.arange(4)/3.0}],
        #                   rank.get_data())

        rank_target = np.arange(4) / 3.0
        rank_target = rank_target.reshape((1, 4))
        avg_target = np.array([[95.5]])
        sum_target = np.array([[382.0]])
        abs_target = np.array([[80.0, 95.0, 102.0, 105.0]])
        tail_target = np.array([[80.0, 101.0, 101.0, 105.0]])
        signvec_target = np.array([[1.0, 1.0, 1.0, 1.0]])
        scale_target = bar_t1_array / np.sum(bar_t1_array)
        scale_target = scale_target.reshape(1, 4)

        self.__np_assert_almost_equal(abs_target, absv.now()["value"])
        self.__np_assert_almost_equal(rank_target, rank.get_data()[0]["value"], 5)
        self.__np_assert_almost_equal(avg_target, avg.get_data()[0]["value"], 5)
        self.__np_assert_almost_equal(sum_target, gssum.get_data()[0]["value"], 5)
        self.__np_assert_almost_equal(tail_target, tail.get_data()[0]["value"], 5)
        self.__np_assert_almost_equal(signvec_target, signvec.get_data()[0]["value"], 5)
        self.__np_assert_almost_equal(scale_target, scale.get_data()[0]["value"], 5)

        t2 = t1 + 3
        bar_t2_array = np.array([85, 98, 101.5, 103])
        bar0.add(data={"timestamp": t2, "close": bar_t2_array[0], "open": 0})
        bar1.add(data={"timestamp": t2, "close": bar_t2_array[1], "open": 0})
        bar2.add(data={"timestamp": t2, "close": bar_t2_array[2], "open": 0})
        bar3.add(data={"timestamp": t2, "close": bar_t2_array[3], "open": 0})

        t3 = t2 + 3
        bar_t3_array = np.array([87, 91, 107.0, 115])
        bar0.add(data={"timestamp": t3, "close": bar_t3_array[0], "open": 0})
        bar1.add(data={"timestamp": t3, "close": bar_t3_array[1], "open": 0})
        bar2.add(data={"timestamp": t3, "close": bar_t3_array[2], "open": 0})
        bar3.add(data={"timestamp": t3, "close": bar_t3_array[3], "open": 0})

        stack = np.vstack([bar_t1_array, bar_t2_array, bar_t3_array])
        decaylinear_target = np.dot(np.arange(3, 0, -1), stack) / np.sum(np.arange(3, 0, -1))
        scale_target = bar_t3_array / np.sum(bar_t3_array)
        scale_target = scale_target.reshape(1, 4)
        self.__np_assert_almost_equal(decaylinear_target, decaylinear.now(keys=PipeLine.VALUE))
        self.__np_assert_almost_equal(scale_target, scale.now(keys=PipeLine.VALUE))

    def test_with_multi_bar_multi_indicator(self):
        bar0 = self.app_context.inst_data_mgr.get_series("bar0")
        bar1 = self.app_context.inst_data_mgr.get_series("bar1")

        bar0.start(self.app_context)
        bar1.start(self.app_context)

        sma_2_bar0 = SMA(inputs=bar0, input_keys="close", length=2)
        sma_4_bar0 = SMA(inputs=bar0, input_keys="close", length=4)
        sma_3_bar1 = SMA(inputs=bar1, input_keys="close", length=3)

        sma_2_bar0.start(self.app_context)
        sma_4_bar0.start(self.app_context)
        sma_3_bar1.start(self.app_context)

        rank = Rank(inputs=[sma_2_bar0, sma_3_bar1, sma_4_bar0], input_keys=Indicator.VALUE)
        rank.start(self.app_context)

        t = 1
        bar0.add(data={"timestamp": t, "close": 80.0, "open": 0})
        bar1.add(data={"timestamp": t, "close": 95.0, "open": 0})
        print(rank.now(keys=PipeLine.VALUE))

        t = t + 3
        bar0.add(data={"timestamp": t, "close": 85.0, "open": 0})
        bar1.add(data={"timestamp": t, "close": 93.0, "open": 0})
        print(rank.now(keys=PipeLine.VALUE))

        t = t + 3
        bar0.add(data={"timestamp": t, "close": 86.0, "open": 0})
        bar1.add(data={"timestamp": t, "close": 91.0, "open": 0})
        print(rank.now(keys=PipeLine.VALUE))

        t = t + 3
        bar0.add(data={"timestamp": t, "close": 90.0, "open": 0})
        bar1.add(data={"timestamp": t, "close": 95.0, "open": 0})
        print(rank.now(keys=PipeLine.VALUE))


"""This package contains data which must be edited by hand when adding new
   bindings.
"""

from adaformat import naming, Enum, Proxy, Record, GObject, List, Callback

# General packages that don't depend on others and must be processed first

enums = ("GtkEnums",
         "PangoEnums",
         )

# List of interfaces to bind. These are processed before the widgets themselves
# These are GIR names

interfaces = (
    "Actionable",
    "Activatable",
    # "AppChooser",
    "--Atk.ImplementorIface",
    "Buildable",
    "CellEditable",
    "CellLayout",
    "ColorChooser",
    "Editable",
    "FileChooser",
    "FontChooser",
    "Icon",
    "Orientable",
    "PrintOperationPreview",
    "RecentChooser",
    "Scrollable",
    "StyleProvider",
    "ToolShell",
    "TreeDragDest",
    "TreeDragSource",
    "TreeSortable",
    "TreeModel",

    "Action",
    "ActionGroup",
    "ActionMap",
    "ListModel",
    "--AppInfo",  # Not tested yet, from Gio
    "--AsyncInitable",  # Not tested yet, from Gio
    "--AsyncResult",  # Not tested yet, from Gio
    "--Converter",  # Not tested yet, from Gio
    "--DBusInterface",  # Not tested yet, from Gio
    "--DBusObject",  # Not tested yet, from Gio
    "--DBusObjectManager",  # Not tested yet, from Gio
    "--DesktopAppInfoLookup",  # Not tested yet, from Gio
    "--Drive",  # Not tested yet, from Gio
    "--File",  # Not tested yet, from Gio
    "--FileDescriptorBased",  # Not tested yet, from Gio
    "--Initable",  # Not tested yet, from Gio
    "--LoadableIcon",  # Not tested yet, from Gio
    "--Mount",  # Not tested yet, from Gio
    "--NetworkMonitor",  # Not tested yet, from Gio
    "--PollableInputStream",  # Not tested yet, from Gio
    "--PollableOutputStream",  # Not tested yet, from Gio
    "--Proxy",  # Not tested yet, from Gio
    "--ProxyResolver",  # Not tested yet, from Gio
    "--RemoteActionGroup",  # Not tested yet, from Gio
    "--Seekable",  # Not tested yet, from Gio
    "--SocketConnectable",  # Not tested yet, from Gio
    "--TlsBackend",  # Not tested yet, from Gio
    "--TlsClientConnection",  # Not tested yet, from Gio
    "--TlsFileDatabase",  # Not tested yet, from Gio
    "--TlsServerConnection",  # Not tested yet, from Gio
    "--Volume",  # Not tested yet, from Gio
)

# List of widgets to bind.
# Contains C type names.
# Start the name with -- for objects we do not want to bind

binding = ("--GdkAtom",   # No binding necessary, too low-level
           "GdkCursor",
           "GdkDevice",
           "GdkDeviceManager",
           "GdkDeviceTool",
           "GdkDisplay",
           "GdkDragContext",
           "GdkDrawingContext",
           "GdkEvent",
           "GdkFrameClock",
           "GdkFrameTimings",
           "GdkGLContext",
           "GdkRGBA",
           "GdkMonitor",
           "GdkScreen",
           "GdkSeat",
           "GdkWindow",

           "GApplication",
           "GApplicationCommandLine",
           "--GBytes",   # Function returning arrays
           "--GBufferedInputStream",  # Not tested yet, from Gio
           "--GBufferedOutputStream",  # Not tested yet, from Gio
           "GCancellable",
           "--GCharsetConverter",  # Not tested yet, from Gio
           "--GConverterInputStream",  # Not tested yet, from Gio
           "--GConverterOutputStream",  # Not tested yet, from Gio
           "--GCredentials",  # Not tested yet, from Giov
           "--GDBusActionGroup",  # Not tested yet, from Gio
           "--GDBusAnnotationInfo",  # Not tested yet, from Gio
           "--GDBusArgInfo",  # Not tested yet, from Gio
           "--GDBusAuthObserver",  # Not tested yet, from Gio
           "--GDBusConnection",  # Not tested yet, from Gio
           "--GDBusInterfaceInfo",  # Not tested yet, from Gio
           "--GDBusInterfaceSkeleton",  # Not tested yet, from Gio
           "--GDBusMenuModel",  # Not tested yet, from Gio
           "--GDBusMessage",  # Not tested yet, from Gio
           "--GDBusMethodInfo",  # Not tested yet, from Gio
           "--GDBusMethodInvocation",  # Not tested yet, from Gio
           "--GDBusNodeInfo",  # Not tested yet, from Gio
           "--GDBusObjectManagerClient",  # Not tested yet, from Gio
           "--GDBusObjectManagerServer",  # Not tested yet, from Gio
           "--GDBusObjectProxy",  # Not tested yet, from Gio
           "--GDBusObjectSkeleton",  # Not tested yet, from Gio
           "--GDBusPropertyInfo",  # Not tested yet, from Gio
           "--GDBusProxy",  # Not tested yet, from Gio
           "--GDBusServer",  # Not tested yet, from Gio
           "--GDBusSignalInfo",  # Not tested yet, from Gio
           "--GDataInputStream",  # Not tested yet, from Gio
           "--GDataOutputStream",  # Not tested yet, from Gio
           "--GDesktopAppInfo",  # Not tested yet, from Gio
           "--GEmblem",  # Not tested yet, from Gio
           "--GEmblemedIcon",  # Not tested yet, from Gio
           "--GFileAttributeInfoList",  # Not tested yet, from Gio
           "--GFileAttributeMatcher",  # Not tested yet, from Gio
           "--GFileEnumerator",  # Not tested yet, from Gio
           "--GFileIOStream",  # Not tested yet, from Gio
           "--GFileIcon",  # Not tested yet, from Gio
           "--GFileInfo",  # Not tested yet, from Gio
           "--GFileInputStream",  # Not tested yet, from Gio
           "--GFileMonitor",  # Not tested yet, from Gio
           "--GFileOutputStream",  # Not tested yet, from Gio
           "--GFilenameCompleter",  # Not tested yet, from Gio
           "--GFilterInputStream",  # Not tested yet, from Gio
           "--GFilterOutputStream",  # Not tested yet, from Gio
           "--GIOExtension",  # Not tested yet, from Gio
           "--GIOExtensionPoint",  # Not tested yet, from Gio
           "GIOChannel",
           "--GIOModule",  # Not tested yet, from Gio
           "--GIOModuleScope",  # Not tested yet, from Gio
           "--GIOSchedulerJob",  # Not tested yet, from Gio
           "--GIOStream",  # Not tested yet, from Gio
           "--GInetAddress",  # Not tested yet, from Gio
           "--GInetAddressMask",  # Not tested yet, from Gio
           "--GInetSocketAddress",  # Not tested yet, from Gio
           "--GInputStream",  # Not tested yet, from Gio
           "--GMemoryInputStream",  # Not tested yet, from Gio
           "--GMemoryOutputStream",  # Not tested yet, from Gio
           "GMenuModel",  # Not tested yet, from Gio
           "GMenu",  # Not tested yet, from Gio
           "GMenuAttributeIter",  # Not tested yet, from Gio
           "GMenuItem",  # Not tested yet, from Gio
           "GMenuLinkIter",  # Not tested yet, from Gio
           "--GMountOperation",  # Not tested yet, from Gio
           "--GNativeVolumeMonitor",  # Not tested yet, from Gio
           "--GNetworkAddress",  # Not tested yet, from Gio
           "--GNetworkService",  # Not tested yet, from Gio
           "GNotification",
           "--GOutputStream",  # Not tested yet, from Gio
           "GOptionContext",
           "GPoll",
           "Spawn",
           "Utils",

           "--GParamSpec",   # Bound manually
           "--GParamSpecBoolean",   # Bound manually
           "--GParamSpecBoxed",   # Bound manually
           "--GParamSpecChar",   # Bound manually
           "--GParamSpecDouble",   # Bound manually
           "--GParamSpecEnum",   # Bound manually
           "--GParamSpecFlags",   # Bound manually
           "--GParamSpecFloat",   # Bound manually
           "--GParamSpecGType",   # Bound manually
           "--GParamSpecInt",   # Bound manually
           "--GParamSpecInt64",   # Bound manually
           "--GParamSpecLong",   # Bound manually
           "--GParamSpecObject",   # Bound manually
           "--GParamSpecOverride",   # Bound manually
           "--GParamSpecParam",   # Bound manually
           "--GParamSpecPointer",   # Bound manually
           "--GParamSpecPool",   # Bound manually
           "--GParamSpecString",   # Bound manually
           "--GParamSpecUChar",   # Bound manually
           "--GParamSpecUInt",   # Bound manually
           "--GParamSpecUInt64",   # Bound manually
           "--GParamSpecULong",   # Bound manually
           "--GParamSpecUnichar",   # Bound manually
           "--GParamSpecValueArray",   # Bound manually
           "--GParamSpecVariant",   # Bound manually

           "--GPermission",  # Not tested yet, from Gio
           "--GProxyAddress",  # Not tested yet, from Gio
           "--GProxyAddressEnumerator",  # Not tested yet, from Gio
           "--GResolver",  # Not tested yet, from Gio
           "--GResource",  # Not tested yet, from Gio
           "--GSettings",  # Not tested yet, from Gio
           "--GSettingsSchema",  # Not tested yet, from Gio
           "--GSettingsSchemaSource",  # Not tested yet, from Gio
           "GSimpleAction",
           "GSimpleActionGroup",
           "--GSimpleAsyncResult",  # Not tested yet, from Gio
           "--GSimplePermission",  # Not tested yet, from Gio
           "--GSocket",  # Not tested yet, from Gio
           "--GSocketAddress",  # Not tested yet, from Gio
           "--GSocketAddressEnumerator",  # Not tested yet, from Gio
           "--GSocketClient",  # Not tested yet, from Gio
           "--GSocketConnection",  # Not tested yet, from Gio
           "--GSocketControlMessage",  # Not tested yet, from Gio
           "--GSocketListener",  # Not tested yet, from Gio
           "--GSocketService",  # Not tested yet, from Gio
           "--GSource",   # Manually bound in Glib.Main
           "--GSrvTarget",  # Not tested yet, from Gio
           "--GStaticResource",  # Not tested yet, from Gio
           "GString",
           "--GTcpConnection",  # Not tested yet, from Gio
           "--GTcpWrapperConnection",  # Not tested yet, from Gio
           "--GThemedIcon",  # Not tested yet, from Gio
           "--GThreadedSocketService",  # Not tested yet, from Gio
           "--GTlsCertificate",  # Not tested yet, from Gio
           "--GTlsConnection",  # Not tested yet, from Gio
           "--GTlsDatabase",  # Not tested yet, from Gio
           "--GTlsInteraction",  # Not tested yet, from Gio
           "--GTlsPassword",  # Not tested yet, from Gio
           "--GUnixConnection",  # Not tested yet, from Gio
           "--GUnixCredentialsMessage",  # Not tested yet, from Gio
           "--GUnixFDList",  # Not tested yet, from Gio
           "--GUnixFDMessage",  # Not tested yet, from Gio
           "--GUnixInputStream",  # Not tested yet, from Gio
           "--GUnixMountMonitor",  # Not tested yet, from Gio
           "--GUnixMountPoint",  # Not tested yet, from Gio
           "--GUnixOutputStream",  # Not tested yet, from Gio
           "--GUnixSocketAddress",  # Not tested yet, from Gio
           "GVariant",
           "GVariantIter",
           "GVariantType",
           "--GVfs",  # Not tested yet, from Gio
           "--GVolumeMonitor",  # Not tested yet, from Gio
           "--GZlibCompressor",  # Not tested yet, from Gio
           "--GZlibDecompressor",  # Not tested yet, from Gio

           "--PangoAttrIterator",
           "PangoAttrList",
           "PangoAttribute",
           "--PangoColor",
           "PangoContext",
           "PangoCoverage",
           "PangoFont",
           "PangoFontDescription",
           "PangoFontFace",
           "PangoFontFamily",
           "PangoFontMap",
           "PangoFontMetrics",
           "PangoFontset",
           "--PangoGlyphItem",
           "--PangoGlyphItemIter",
           "--PangoGlyphString",
           "--PangoItem",
           "--PangoRenderer",
           "--PangoScriptIter",
           "PangoLanguage",
           "PangoLayout",
           "PangoLayoutIter",
           "PangoLayoutLine",
           "PangoMatrix",
           "PangoTabArray",

           "GtkAboutDialog",
           "GtkAccelGroup",
           "GtkAccelLabel",
           "GtkAccelMap",
           "--GtkAccessible",  # Needs ATK
           "GtkAction",
           "GtkActionGroup",
           "GtkActionBar",
           "GtkAdjustment",
           "GtkAlignment",
           "--GtkAppChooserButton",  # Needs GFile
           "--GtkAppChooserDialog",  # Needs GFile
           "--GtkAppChooserWidget",  # Needs GFile
           "GtkApplication",
           "GtkApplicationWindow",
           "GtkArrow",
           "--GtkArrowAccessible",  # We do not support atk
           "GtkAspectFrame",
           "GtkAssistant",
           "GtkBin",
           "GtkBindingEntry",
           "GtkBindingSet",
           "GtkBorder",
           "GtkBox",
           "--GtkBooleanCellAccessible",  # We do not support atk
           "GtkBuilder",
           "GtkButton",
           "--GtkButtonAccessible",  # We do not support atk
           "GtkButtonBox",
           "GtkCalendar",
           "--GtkCellAccessible",  # We do not support atk
           "GtkCellArea",
           "GtkCellAreaBox",
           "--GtkCellAreaClass",
           "GtkCellAreaContext",
           "GtkCellRenderer",
           "GtkCellRendererAccel",
           "--GtkCellRendererClass",  # Useless in Ada
           "GtkCellRendererCombo",
           "GtkCellRendererPixbuf",
           "GtkCellRendererProgress",
           "GtkCellRendererSpin",
           "GtkCellRendererSpinner",
           "GtkCellRendererText",
           "GtkCellRendererToggle",
           "GtkCellView",
           "GtkCheckButton",
           "GtkCheckMenuItem",
           "--GtkCheckMenuItemAccessible",  # We do not support atk
           "GtkClipboard",
           "GtkColorButton",
           "GtkColorChooserDialog",
           "GtkColorChooserWidget",
           "GtkColorSelection",
           "GtkColorSelectionDialog",
           "GtkComboBox",
           "--GtkComboBoxAccessible",  # We do not support atk
           "GtkComboBoxText",
           "GtkContainer",
           "--GtkContainerAccessible",  # We do not support atk
           "--GtkContainerCellAccessible",  # We do not support atk
           "--GtkContainerClass",
           "GtkCssProvider",
           "GtkCssSection",
           "GtkDialog",
           "GtkDrawingArea",
           "GtkEntry",
           "--GtkEntryAccessible",  # We do not support atk
           "GtkEntryBuffer",
           "GtkEntryCompletion",
           "--GtkEntryIconAccessible",  # We do not support atk
           "GtkEventBox",
           "GtkEventController",
           "GtkExpander",
           "--GtkExpanderAccessible",  # We do not support atk
           "GtkFileChooserButton",
           "GtkFileChooserDialog",
           "GtkFileChooserWidget",
           "GtkFileFilter",
           "GtkFixed",
           "GtkFlowBox",
           "--GtkFlowBoxAccessible",  # We do not support atk
           "GtkFlowBoxChild",
           "--GtkFlowBoxChildAccessible",  # We do not support atk
           "GtkFontButton",
           "GtkFontChooserDialog",
           "GtkFontChooserWidget",
           "GtkFontSelection",
           "GtkFontSelectionDialog",
           "GtkFrame",
           "--GtkFrameAccessible",  # We do not support atk
           "GtkGesture",
           "GtkGestureDrag",
           "GtkGestureLongPress",
           "GtkGestureMultiPress",
           "GtkGesturePan",
           "GtkGestureRotate",
           "GtkGestureSingle",
           "GtkGestureSwipe",
           "GtkGestureZoom",
           "GtkGradient",
           "GtkGLArea",
           "GtkGrid",
           "GtkHandleBox",
           "GtkHBox",
           "GtkHButtonBox",
           "GtkHeaderBar",
           "GtkHPaned",
           "GtkHScale",
           "GtkHScrollbar",
           "GtkHSeparator",
           "GtkHSV",
           "GtkIconFactory",
           "GtkIconInfo",
           "GtkIconSet",
           "GtkIconSource",
           "GtkIconTheme",
           "GtkIconView",
           "--GtkIconViewAccessible",  # We do not support atk
           "GtkIMContext",
           "GtkIMContextSimple",
           "GtkIMMulticontext",
           "GtkImage",
           "--GtkImageAccessible",  # We do not support atk
           "--GtkImageCellAccessible",  # We do not support atk
           "GtkImageMenuItem",
           "GtkInfoBar",
           "GtkInvisible",
           "GtkLabel",
           "--GtkLabelAccessible",  # We do not support atk
           "GtkLayout",
           "GtkLevelBar",
           "--GtkLevelBarAccessible",  # We do not support atk
           "GtkLinkButton",
           "--GtkLinkButtonAccessible",  # We do not support atk
           "GtkListBox",
           "--GtkListBoxAccessible",  # We do not support atk
           "GtkListBoxRow",
           "--GtkListBoxRowAccessible",  # We do not support atk
           "GtkListStore",
           "--GtkLockButton",  # requires GPermission
           "--GtkLockButtonAccessible",  # We do not support atk
           "GtkMain",
           "GtkMisc",
           "GtkMenu",
           "--GtkMenuAccessible",  # We do not support atk
           "GtkMenuBar",
           "GtkMenuButton",
           "--GtkMenuButtonAccessible",  # We do not support atk
           "GtkMenuItem",
           "--GtkMenuItemAccessible",  # We do not support atk
           "GtkMenuShell",
           "--GtkMenuShellAccessible",  # We do not support atk
           "GtkMenuToolButton",
           "GtkMessageDialog",
           "--GtkMountOperation",  # Requires a lot of GIO
           "GtkNotebook",
           "--GtkNotebookAccessible",  # We do not support atk
           "--GtkNotebookPageAccessible",  # We do not support atk
           "--GtkNumerableIcon",   # Requires a lot of GIO
           "GtkOffscreenWindow",
           "GtkOverlay",
           "GtkPaned",
           "--GtkPanedAccessible",  # We do not support atk
           "GtkPageSetup",
           "GtkPaperSize",
           "--GtkPlacesSidebar",  # Requires GFile
           "GtkPopover",
           "--GtkPopoverAccessible",  # We do not support atk
           "GtkPrintContext",
           "GtkPrintOperation",
           "GtkPrintSettings",
           "--GtkPlug",  # X11-specific, no binding
           "GtkProgressBar",
           "--GtkProgressBarAccessible",  # We do not support atk
           "GtkRadioAction",
           "GtkRadioButton",
           "--GtkRadioButtonAccessible",  # We do not support atk
           "GtkRadioMenuItem",
           "--GtkRadioMenuItemAccessible",  # We do not support atk
           "GtkRadioToolButton",
           "GtkRange",
           "--GtkRangeAccessible",  # We do not support atk
           "--GtkRcStyle",  # manual binding for these deprecated routines
           "GtkRecentAction",
           "GtkRecentChooserDialog",
           "GtkRecentChooserMenu",
           "GtkRecentChooserWidget",
           "GtkRecentFilter",
           "GtkRecentInfo",
           "GtkRecentManager",
           "--GtkRendererCellAccessible",  # We do not support atk
           "GtkRevealer",
           "GtkScale",
           "--GtkScaleAccessible",  # We do not support atk
           "GtkScaleButton",
           "--GtkScaleButtonAccessible",  # We do not support atk
           "GtkSearchBar",
           "GtkSearchEntry",
           "GtkSelectionData",
           "GtkSeparator",
           "GtkSeparatorMenuItem",
           "GtkSeparatorToolItem",
           "GtkShortcutsWindow",
           "GtkSizeGroup",
           "GtkScrollbar",
           "GtkScrolledWindow",
           "--GtkScrolledWindowAccessible",  # We do not support atk
           "GtkSettings",
           "--GtkSocket",  # X11-specific, no binding
           "GtkSpinner",
           "--GtkSpinnerAccessible",  # We do not support atk
           "GtkSpinButton",
           "--GtkSpinButtonAccessible",  # We do not support atk
           "GtkStack",
           "GtkStackSwitcher",
           "GtkStatusbar",
           "--GtkStatusbarAccessible",  # We do not support atk
           "GtkStatusIcon",
           "GtkStockItem",
           "GtkStyle",
           "GtkStyleContext",
           "GtkStyleProperties",
           "GtkSwitch",
           "--GtkSwitchAccessible",  # We do not support atk
           "GtkSymbolicColor",
           "GtkTable",
           "GtkTargetEntry",
           "GtkTargetList",
           "GtkTearoffMenuItem",
           "GtkTextAttributes",
           "GtkTextBuffer",
           "--GtkTextCellAccessible",  # We do not support atk
           "GtkTextChildAnchor",
           "GtkTextIter",
           "GtkTextMark",
           "GtkTextTag",
           "GtkTextTagTable",
           "GtkTextView",
           "--GtkTextViewAccessible",  # We do not support atk
           "GtkThemingEngine",
           "GtkTreeIter",
           "GtkTreeModelFilter",
           "GtkTreeModelSort",
           "GtkTreePath",
           "GtkTreeRowReference",
           "GtkTreeSelection",
           "GtkTreeStore",
           "GtkTreeView",
           "--GtkTreeViewAccessible",  # We do not support atk
           "GtkTreeViewColumn",
           "GtkToggleAction",
           "GtkToggleButton",
           "--GtkToggleButtonAccessible",  # We do not support atk
           "GtkToggleToolButton",
           "GtkToolButton",
           "GtkToolbar",
           "GtkToolItem",
           "GtkToolItemGroup",
           "GtkTooltip",
           "GtkToolPalette",
           "--GtkToplevelAccessible",  # We do not support atk
           "GtkUIManager",
           "GtkVBox",
           "GtkVButtonBox",
           "GtkVPaned",
           "GtkVScale",
           "GtkVScrollbar",
           "GtkVSeparator",
           "GtkViewport",
           "GtkVolumeButton",
           "GtkWidget",
           "--GtkWidgetAccessible",  # We do not support atk
           "GtkWidgetClass",
           "GtkWindow",
           "--GtkWindowAccessible",  # We do not support atk
           "GtkWindowGroup",
           )

# Handling of functions with user data. The names below are the likely names
# for callback functions that accept user_data. The GIR file doesn't point to
# these specific parameters.

user_data_params = ["Data", "Func_Data", "User_Data", "D", "Search_Data"]
destroy_data_params = ["destroy", "func_notify", "notify"]

# Maps c methods to Ada subprograms or enumeration (for docs).
# All methods that are generated automatically will be added
# as they are processed.

naming.cname_to_adaname = {
    "gtk_show_uri":                 "gtk_show_uri()",
    "gtk_icon_factory_add_default": "Gtk.Icon_Factory.Add_Default",
    "gtk_icon_factory_add":         "Gtk.Icon_Factory.Add",
    "gdk_pixbuf_new_from_data":     "Gdk.Pixbuf.Gdk_New_From_Data",
    "gdk_pixbuf_new_from_file":     "Gdk.Pixbuf.Gdk_New_From_File",
    "gdk_pixbuf_new_from_xpm_data": "Gdk.Pixbuf.Gdk_New_From_Xpm_Data",
    "gdk_pixbuf_animation_new_from_file":
                                    "Gdk.Pixbuf.Gdk_New_From_File",
    "gdk_pixbuf_new":               "Gdk.Pixbuf.Gdk_New",
    "gdk_pixbuf_new_subpixbuf":     "Gdk.Pixbuf.Gdk_New_Subpixbuf",
    "gtk_drag_finish":              "Gtk.Dnd.Finish",

    "TRUE": "True",
    "FALSE": "False",
    "NULL": "null",

    "GDK_2BUTTON_PRESS": "Gdk_2button_Press",
    "GDK_3BUTTON_PRESS": "Gdk_3button_Press",
    "GDK_EVENT_LAST": None,

    # ??? Doesn't exist
    "gtk_activatable_get_action": "Gtk.Activatable.Get_Action",
}

# Maps GIR's "name" to a "c:type". This isn't needed for the classes
# themselves, since this is automatically read from the GIR file.
# Mostly used for properties. The values must correspond to entries in
# self.type_exceptions.

naming.girname_to_ctype = {
    "GdkPixbuf.Pixbuf":    "GdkPixbuf",
    "Pango.EllipsizeMode": "PangoEllipsizeMode",
    "Pango.FontDescription": "PangoFontDescription*",
    "Pango.AttrList":      "PangoAttrList",
    "Gio.Action":          "Action",
    "Gio.ActionGroup":     "ActionGroup",
    "Gio.ActionMap":       "ActionMap",
    "Gio.Application":     "GApplication",
    "Gio.ApplicationCommandLine": "GApplicationCommandLine",
    "ApplicationCommandLine": "GApplicationCommandLine",
    "Gio.Icon":            "GIcon*",
    "GLib.Variant":        "GVariant",
    "Gdk.Event":           "GdkEvent*",
    "Gdk.EventButton":     "GdkEventButton*",
    "Gdk.EventMotion":     "GdkEventMotion*",
    "Gdk.EventProximity":  "GdkEventProximity*",
    "Gdk.EventAny":        "GdkEventAny*",
    "Gdk.EventConfigure":  "GdkEventConfigure*",
    "Gdk.EventExpose":     "GdkEventExpose*",
    "Gdk.EventKey":        "GdkEventKey*",
    "Gdk.EventCrossing":   "GdkEventCrossing*",
    "Gdk.EventScroll":     "GdkEventScroll*",
    "Gdk.EventSequence":   "GdkEventSequence*",
    "Gdk.EventWindowState": "GdkEventWindowState*",
    "Gdk.EventVisibility":  "GdkEventVisibility*",
    "Gdk.EventSelection":   "GdkEventSelection*",
    "Gdk.EventFocus":       "GdkEventFocus*",
    "Gdk.EventProperty":    "GdkEventProperty*",
    "Gdk.EventGrabBroken":  "GdkEventGrabBroken*",
    "Gdk.EventOwnerChange": "GdkEventOwnerChange*",
    "Gdk.Pixmap":          "GdkPixmap*",
    "Gdk.Image":           "GdkImage*",
    "Gdk.GLContext":       "GdkGLContext*",
    "Gdk.DragContext":     "GdkDragContext",
    "GdkPixbuf.PixbufAnimation": "GdkPixbufAnimation*",
    "Gdk.Bitmap":          "GdkBitmap*",
    "Gdk.Color":           "GdkColor*",
    "Gdk.Screen":          "GdkScreen",
    "Gdk.RGBA":            "GdkRGBA",
    "GObject.Object":      "GObject*",
    "GObject.Closure":     "GClosure*",
    "cairo.Surface":       "cairo_surface_t*",
    "cairo.Context":       "cairo_t*",
    "cairo.RectangleInt":  "cairo_rectangle_int_t*",
    "ModifierType":        "GdkModifierType",
    "PropertyState":       "GdkPropertyState",
    "TreePath":            "GtkTreePath*",
    "TreeModel":           "GtkTreeModel*",
    "GObject.InitiallyUnowned": "GObject*",  # An alias
    "GObject.ParamSpec":   "GParamSpec",
    "Giochannel":          "GIOChannel*",
}

# Naming exceptions. In particular maps Ada keywords.

naming.exceptions = {
    "Entry": "GEntry",
    "Type":  "The_Type",
    "Range": "GRange",
    "Delay": "The_Delay",
    "Select": "Gtk_Select",
    "End":   "The_End",
    "Return": "Do_Return",
    "Function": "Func",
    "Digits": "The_Digits",
    "Reverse": "Gtk_Reverse",
    "Raise": "Gdk_Raise",
    "Use": "GUse",
    "Uri": "URI",
    "In": "Gtk_In",

    "Gtk_Imcontext": "Gtk_IM_Context",
    "Gtk_Imcontext_Simple": "Gtk_IM_Context_Simple",
    "Gtk_Immulticontext": "Gtk_IM_Multi_Context",

    "Gtk_Uimanager": "Gtk_UI_Manager",
    "Gicon": "G_Icon",
    "Gtk_Glarea": "Gtk_GLArea",
    "Gdk_Glcontext": "Gdk_GLContext",
}

# Maps C types to type descriptions.
# All standard widgets will be added automatically. Only special
# namings are needed here

naming.type_exceptions = {
    "gboolean":          Enum("Boolean",
                              "Glib.Properties.Property_Boolean"),
    "gdouble":  Proxy("Gdouble", "Glib.Properties.Property_Double"),
    "double":   Proxy("Gdouble", "Glib.Properties.Property_Double"),
    "gshort":   Proxy("Gshort",  "Glib.Properties.Property_Int"),
    "gushort":  Proxy("Gushort",  "Glib.Properties.Property_Uint"),
    "int":      Proxy("Glib.Gint",    "Glib.Properties.Property_Int"),
    "gint":     Proxy("Glib.Gint",    "Glib.Properties.Property_Int",
                      default_record_field="0"),
    "gint8":    Proxy("Gint8",   "Glib.Properties.Property_Int"),
    "gint16":   Proxy("Gint16",  "Glib.Properties.Property_Int"),
    "gint32":   Proxy("Gint32",  "Glib.Properties.Property_Int"),
    "gint64":   Proxy("Gint64",  "Glib.Properties.Property_Int"),
    "guint":    Proxy("Guint",   "Glib.Properties.Property_Uint"),
    "guint8":   Proxy("Guint8",  "Glib.Properties.Property_Uint"),
    "guint16":  Proxy("Guint16", "Glib.Properties.Property_Uint"),
    "guint32":  Proxy("Guint32", "Glib.Properties.Property_Uint"),
    "guint64":  Proxy("Guint64", "Glib.Properties.Property_Uint"),
    "gfloat":   Proxy("Gfloat",  "Glib.Properties.Property_Float"),
    "glong":    Proxy("Glong",   "Glib.Properties.Property_Long"),
    "gulong":   Proxy("Gulong"),
    "gsize":    Proxy("Gsize"),
    "gssize":   Proxy("Gssize"),
    "gunichar": Proxy("Gunichar"),
    "gchar":    Proxy("Gchar"),
    "guchar":   Proxy("Guchar"),
    "GAppInfo": Proxy("Glib.GApp_Info"),

    # These should not be necessary, but if we don't put them the gnerated
    # binding is wrong (for instance we end up passing Gdk_Event_Record as
    # parameters to functions, or Gdk_RGBA directly to C)
    "GdkRGBA":  Record("Gdk.RGBA.Gdk_RGBA",  # impose casing
                       "Gdk.RGBA.Property_RGBA"),
    "GdkRGBA*":  Proxy("Gdk.RGBA.Gdk_RGBA", "Gdk.RGBA.Property_RGBA",
                       "Gdk.RGBA.Gdk_RGBA_Or_Null"),
    "GdkEvent*": Proxy("Gdk.Event.Gdk_Event", ""),
    "GIOChannel*": Proxy("Glib.IOChannel.Giochannel", ""),

    "cairo_t*":              Proxy("Cairo.Cairo_Context"),
    "cairo_format_t":        Proxy("Cairo.Cairo_Format"),
    "cairo_rectangle_int_t*": Proxy("Cairo.Region.Cairo_Rectangle_Int"),
    "cairo_content_t":       Proxy("Cairo.Cairo_Content"),
    "cairo_pattern_t*":      Proxy("Cairo.Cairo_Pattern"),
    "cairo_surface_t*":      Proxy("Cairo.Cairo_Surface"),
    "cairo_region_t*":       Proxy("Cairo.Region.Cairo_Region"),
    "cairo_font_options_t":  Proxy("Cairo.Cairo_Font_Options"),

    "GtkWidgetClass":    Proxy("Glib.Object.GObject_Class"),
    "GtkWidgetClass*":   Proxy("Glib.Object.GObject_Class"),

    # Force mapping to a Proxy. This is also hard-coded in GITClass.__init__
    "PangoFontDescription": Proxy("Pango.Font.Pango_Font_Description",
                                  "Pango.Font.Property_Font_Description"),
    "PangoFontDescription*": Proxy("Pango.Font.Pango_Font_Description",
                                   "Pango.Font.Property_Font_Description"),
    "GtkTreeIter*":    Record("Gtk.Tree_Model.Gtk_Tree_Iter",
                              val_or_null="Iter_Or_Null"),
    "GtkTextIter*":    Record("Gtk.Text_Iter.Gtk_Text_Iter",
                              val_or_null="Iter_Or_Null"),
    "PangoAttribute": Proxy("Pango.Attributes.Pango_Attribute"),
    "PangoAttribute*": Proxy("Pango.Attributes.Pango_Attribute"),

    "GError*":           Proxy("Glib.Error.GError"),
    "GObject*":          GObject("Glib.Object.GObject"),
    "GClosure*":         Proxy("System.Address", ""),
    "GInitiallyUnowned": GObject("Glib.Object.GInitiallyUnowned"),
    "GIcon*":            Proxy("Glib.G_Icon.G_Icon"),
    "GValue":            Proxy("Glib.Values.GValue", ""),
    "GdkAtom":           Proxy("Gdk.Types.Gdk_Atom"),
    "GVariantType":      Proxy("Glib.Variant.Gvariant_Type"),
    "GVariantType*":     Proxy("Glib.Variant.Gvariant_Type"),
    "GVariantIter":      Proxy("Glib.Variant.Gvariant_Iter"),

    # Proper generation of lists
    "GdkEventSequence":  Proxy("Gdk.Event.Gdk_Event_Sequence"),

    # Specific to this binding generator (referenced from binding.xml)
    "VisualList":  List("Gdk.Visual.Gdk_Visual_List.Glist"),
    "ObjectList":  List("Glib.Object.Object_Simple_List.Glist"),
    "ObjectSList": List("Glib.Object.Object_List.GSlist"),
    "StringList":  List("Gtk.Enums.String_List.Glist"),
    "StringSList": List("Gtk.Enums.String_SList.GSlist"),
    "TreePathList": List("Gtk.Tree_Model.Gtk_Tree_Path_List.Glist"),
    "TextTagList": List("Gtk.Text_Tag.Text_Tag_List.GSlist"),
    "DeviceList": List("Gdk.Device.Device_List.Glist"),

    "gpointer":       Proxy("System.Address", "",
                            default_record_field="System.Null_Address"),
    "GDestroyNotify": Proxy("Glib.G_Destroy_Notify_Address"),
    "GQuark":        Proxy("Glib.GQuark"),
    "GObject":       Proxy("Glib.Object.GObject"),
    "GParamSpec":    Proxy("Glib.Param_Spec"),
    "GClosure":      Proxy("GClosure"),
    "GConnectFlags": Proxy("Glib.G_Connect_Flags"),
    "GSource":       Proxy("Glib.Main.G_Source"),

    "WidgetPath*":     Proxy("Gtk.Widget.Widget_Path"),

    # ??? Shouldn't we use a naming exception instead ?
    "GtkStatusbar":    GObject("Gtk.Status_Bar.Gtk_Status_Bar"),

    "GtkRcStyle":      GObject("Gtk.Rc.Gtk_Rc_Style"),

    "GtkTreeViewRowSeparatorFunc":
        Callback("Gtk.Tree_View.Gtk_Tree_View_Row_Separator_Func"),

    "GKeyFile*":           Proxy("Glib.Key_File.G_Key_File"),

    "GdkColor*": Proxy("Gdk.Color.Gdk_Color",
                       "Gdk.Color.Property_Gdk_Color",
                       "Gdk.Color.Gdk_Color_Or_Null"),
    "GdkDragContext":     GObject("Gdk.Drag_Contexts.Drag_Context"),
    "GdkFont":            Proxy("Gdk.Font.Gdk_Font"),
    "GdkVisual*":         Proxy("Gdk.Visual.Gdk_Visual"),
    "GdkPixmap*":         Proxy("Gdk.Pixmap.Gdk_Pixmap"),
    "GdkBitmap*":         Proxy("Gdk.Bitmap.Gdk_Bitmap"),
    "GdkImage*":          Proxy("Gdk.Image.Gdk_Image"),
    "GdkPixbuf":          GObject("Gdk.Pixbuf.Gdk_Pixbuf"),
    "GdkPixbufAnimation*": Proxy("Gdk.Pixbuf.Gdk_Pixbuf_Animation"),

    "GdkRectangle*":      Proxy("Gdk.Rectangle.Gdk_Rectangle"),

    # in gdkevents.h
    "GdkRectangle":      Proxy("Gdk.Rectangle.Gdk_Rectangle"),

    # ??? The above should not be needed, we should infer it from the Gir.
    # we need it to generate the "Stub" object in Gdk.Device.Get_Position
    "Gdk.ModifierType":   Proxy("Gdk.Types.Gdk_Modifier_Type"),
    "GdkModifierType":    Proxy("Gdk.Types.Gdk_Modifier_Type"),
    "GdkKeyType":         Proxy("Gdk.Types.Gdk_Key_Type"),
    "GdkWindowAttr*":     Proxy("Gdk.Gdk_Window_Attr"),

    # Override type: we do not want to show they derive from GObject
    "GdkCursor":         Proxy("Gdk.Gdk_Cursor"),
    "GdkCursor*":        Proxy("Gdk.Gdk_Cursor"),
    "GdkWindow":         Proxy("Gdk.Gdk_Window"),
    "GdkWindow*":        Proxy("Gdk.Gdk_Window"),
}


from brownie import (
    network,
    accounts,
    config,
    interface,
    Contract,
)
from scripts.helpful_scripts import (
    get_account,
    get_new_instance,
    submit_instance,
    get_web3,
)
from web3 import Web3

def main():
    player = get_account()
    instance_address = get_new_instance(level_id=12, player=player)
    w3 = get_web3()

    privacy_contract = interface.IPrivacy(instance_address)

    for slot_id in range(8):
        print(f'slot {slot_id}')
        print(Web3.toInt(w3.eth.get_storage_at(instance_address, slot_id)))
        print()

    print("Examining data[2]...")
    data_2 = w3.eth.get_storage_at(instance_address, 5)
    print(data_2)
    print(data_2[:16])
    print(data_2[16:])
    print()

    tx = privacy_contract.unlock(data_2[:16], {"from": player})
    tx.wait(1)

    submit_instance(instance_address, player)


# -*- coding: utf-8 -*-
import math
from core import dthandler

from core.common import BaseHandler, authorized, clear_cache_by_pathlist, getAttr
from model.categories import Categories
from model.showtypes import ShowTypes

try:
    import json
except:
    import simplejson as json

class CategoryController(BaseHandler):
    @authorized()
    def get(self):
        act = self.get_argument("act", '').encode('utf-8')
        category_id = self.get_argument("id", '').encode('utf-8')

        obj = None
        if act == 'del':
            if category_id:
                Categories.delete(category_id)
                clear_cache_by_pathlist(['/'])
            self.set_header("Content-Type", "application/json")
            self.write(json.dumps("OK"))
            return
        elif act == 'edit':
            if category_id:
                obj = Categories.get(category_id)

        # 分类列表
        page = self.get_argument("page", 1)
        category = Categories.get_paged(page, getAttr('ADMIN_CATEGORY_NUM'))
        total = int(math.ceil(Categories.count_all() / float(getAttr('ADMIN_CATEGORY_NUM'))))
        if page == 1:
            self.echo('admin_category.html', {
                'title': "分类列表",
                'objs': category,
                'obj': obj,
                'category_kv': Categories.get_all_kv(0),
                'show_types': ShowTypes.get_all(),
                'total': total,
            }, layout='_layout_admin.html')
        else:
            result = {
                'list': category,
                'total': total,
            }
            self.set_header("Content-Type", "application/json")
            self.write(json.dumps(result, default=dthandler))
            return

    @authorized()
    def post(self):
        try:
            tf = {'true': 1, 'false': 0}
            act = self.get_argument("act", '').encode('utf-8')
            category_id = self.get_argument("id", '').encode('utf-8')
            father_category_id = self.get_argument("father_id", 0).encode('utf-8')
            category_name = self.get_argument("name", '').encode('utf-8')
            show_type = self.get_argument("show_type", '').encode('utf-8')
            display_order = self.get_argument("sort", '0').encode('utf-8')
            allow_comment = tf[self.get_argument("allow_comment", "false").encode('utf-8')]
            allow_publish = tf[self.get_argument("allow_publish", "false").encode('utf-8')]
            description = self.get_argument("description", '').encode('utf-8')
        except:
            self.write(json.dumps("用户名、密码、验证码均为必填项！"))
            return

        if category_name:
            params = {'category_id': category_id, 'father_category_id': father_category_id,
                      'category_name': category_name, 'show_type': show_type, 'display_order': display_order,
                      'allow_comment': allow_comment, 'allow_publish': allow_publish, 'description': description}
            if act == 'add':
                Categories.create(params)

            if act == 'edit':
                Categories.update(params)

            clear_cache_by_pathlist(['/'])

            self.set_header("Content-Type", "application/json")
            self.write(json.dumps("OK"))
        else:
            self.set_header("Content-Type", "application/json")
            self.write(json.dumps("参数异常"))

#####
urls = [
    # 分类管理
    (r"/admin/category", CategoryController),
]