Beispiel #1
0
    def show(self):
        """Start the gui."""
        with sdpg.window("Main Window"):
            dpg.set_main_window_size(550, 650)
            dpg.set_main_window_resizable(False)
            dpg.add_spacing()
            dpg.set_main_window_title("Dearpygui File Zip")

            dpg.add_spacing()
            dpg.add_text("File Zip App")
            dpg.add_spacing()
            dpg.add_text("Select files to zip by adding them to the table",
                         bullet=True)
            dpg.add_text("Set the output directory", bullet=True)
            dpg.add_text("Click on the table to remove a file", bullet=True)
            dpg.add_text("Click on the zip files button to zip all the files",
                         bullet=True)
            dpg.add_text(
                "If you do not choose a directory, it will by default be"
                "the same directory from where you've run this script.",
                bullet=True)
            dpg.add_spacing()
            dpg.add_separator()

            dpg.add_spacing(count=10)
            dpg.add_button("Select output directory",
                           width=250,
                           callback=self.__select_output_directory)
            dpg.add_same_line()
            dpg.add_button("Add file", width=250, callback=self.__select_file)
            dpg.add_spacing(count=10)
            dpg.add_separator()

            dpg.add_text("Selected output directory:")
            dpg.add_table('Files', ['Path', 'Name'],
                          height=200,
                          callback=self.__remove_file)
            dpg.add_separator()
            dpg.add_progress_bar('Zip Progress', width=-1)
            dpg.add_separator()
            dpg.add_button("Clear files",
                           width=250,
                           callback=self.__clear_files)
            dpg.add_same_line()
            dpg.add_button("Zip Files", width=250, callback=self.__zip_files)
            dpg.add_spacing()
            dpg.add_label_text('##warnings')

            # Render Callback and Start gui
            dpg.set_render_callback(self.__render)
            dpg.start_dearpygui(primary_window="Main Window")
Beispiel #2
0
    def show(self) -> None:
        if core.does_item_exist(self._win_name):
            self.destroy(self._win_name)

        obj_name = self._entry.get_object_name()

        with simple.window(self._win_name,
                           label=f"{obj_name}",
                           on_close=self.destroy,
                           width=400):
            ts = self._entry.get_timestamp_str()
            age = self._entry.get_age()

            core.add_label_text(self._win_name + "ts",
                                label=f"Timestamp",
                                default_value=f"{ts}")
            core.add_label_text(self._win_name + "age",
                                label=f"Age",
                                default_value=f"{age}")
            core.add_label_text(self._win_name + "freq",
                                label=f"Frequency",
                                default_value=f"0.0 Hz")
            core.add_text("")
            core.add_label_text(self._win_name + "content",
                                default_value=str(self._entry.get_object()),
                                label="")

        self._freq_thread.start()
Beispiel #3
0
	def __init__(self):
		# turn off the sync to measure FPS
		core.set_vsync(False)
		self.__vsync = False

		with simple.window("main"):
			with simple.group("group", width=150):
				core.add_label_text("FPS")
				core.add_button("vsync", label="Toggle V-Sync On", callback=self.__toggleVsync)
				core.set_item_color("vsync", core.mvGuiCol_Button, (200, 96, 96, 255))

		core.set_render_callback(self.__render)

		# maximum average the last XX ticks...
		self.__avgCountMax = 240
		self.__avg = []
    def __init__(self):
        with simple.window(self.windowName,
                           width=self.xSize,
                           height=self.ySize,
                           x_pos=self.xPos,
                           y_pos=self.yPos):

            core.add_button(self.importButtonName,
                            callback=self.open_file_dialog)
            core.add_label_text(name=self.fileStatus,
                                label='##' + self.fileMissing,
                                default_value=self.fileMissing)

            core.add_separator()
            core.add_same_line()
            core.add_plot(self.plotName)
        super().__init__()
Beispiel #5
0
    def __init__(self):
        core.set_main_window_size(720, 540)
        self.__width = 17
        self.__height = 7
        self.__total = self.__width * self.__height
        self.__board = {}
        size = core.get_main_window_size()
        self.__paddle = [size[0] * .475, size[1] * .85]
        self.__paddleSize = (80, 8)
        # x, y, angle (rads), speed
        self.__radius = 6
        self.__speed = 300
        self.__paddleSpeed = 1000
        self.__speedMax = self.__speed * 3
        self.__pos = (size[0] * .5, size[1] * .8, 0, -self.__speed)

        with simple.window("main"):
            with simple.group("scoreboard"):
                core.add_label_text("score")
                core.add_same_line()
                core.add_text("score-value")
                # core.add_same_line()
                core.add_label_text("time")
                core.add_same_line()
                core.add_text("time-value")
            core.add_drawing("canvas", width=size[0], height=size[1])
            core.draw_circle("canvas",
                             size,
                             self.__radius, (255, 255, 255, 255),
                             fill=(128, 128, 128, 255),
                             tag="ball")
            core.draw_rectangle("canvas", [
                self.__paddle[0] - self.__paddleSize[0],
                self.__paddle[1] - self.__paddleSize[1]
            ], [
                self.__paddle[0] + self.__paddleSize[0],
                self.__paddle[1] + self.__paddleSize[1]
            ], (255, 255, 255, 255),
                                fill=(128, 128, 128, 255),
                                tag="paddle")

        core.set_resize_callback(self.__resize)
        core.set_render_callback(self.__render)
        core.set_key_down_callback(self.__keydown)
        core.set_mouse_wheel_callback(self.__mousewheel)
    def user_stock_dash(self):
        with window("User stock dashboard", width=500, height=500):
            self.menu(False, False, True, False)
            gg.add_separator()
            with managed_columns("Header", 5):
                gg.add_text("TICKER")
                gg.add_text("DATE")
                gg.add_text("BUY $ / SELL $")
                gg.add_text("QUANTITY")
                gg.add_text("SELL")

            def sell_stock(sender, data):
                buy_data = data["Purchase Data"]
                purchaseid, date_bought, time_bought, buy_price, quantity_buy = buy_data
                quantity_sell = round(gg.get_value(sender), 2)
                label = f"Message"
                if quantity_sell > quantity_buy:
                    set_item_label(label, f"Cannot sell more than {quantity_buy}!")
                else:
                    self.user.sell_share(data["Ticker"], purchaseid, quantity_sell, data["Sell Price"])
                    self.change_to_window(sender, {"Scene Function": self.user_stock_dash})
                    set_item_label(label, f"Sold {quantity_sell} shares at {data['Sell Price']}$")
                    
            for ticker in self.user.share_by_name:
                ticker_buy_data = self.user.share_by_name[ticker]
                current_price = round(yfs.get_live_price(ticker), 2)
                for event in ticker_buy_data:
                    purchaseid, date, time, buy_price, qty = event
                    gg.add_separator()
                    with managed_columns(f"Data {ticker}{purchaseid}", columns=5, border=True):
                        gg.add_text(ticker)
                        gg.add_text(date)
                        gg.add_text(f"{buy_price} / {current_price}")
                        gg.add_label_text(name=f"{purchaseid} qty", label=str(qty))
                        with group(f"Sell{ticker}{purchaseid}"):
                            gg.add_input_float(name=f"##Sell {ticker}{purchaseid} input", default_value=0,
                                               on_enter=True,
                                               callback=sell_stock, callback_data={"Ticker": ticker,
                                                                                   "Purchase Data": event,
                                                                                   "Sell Price": current_price},
                                               format="%.2f",
                                               width=80)

            gg.add_separator()
            gg.add_button("Message", label="")
Beispiel #7
0
    def __init__(self):
        core.set_style_item_spacing(1, 1)
        core.set_style_window_padding(0, 0)

        with simple.window("main"):
            with simple.group("controls", width=520):
                with simple.group("buttons"):
                    for x in range(6):
                        core.add_button(f"id-{x}", label=f"button {x}")
                    core.add_color_button("bcolor", (196, 128, 155, 255))
                    core.add_radio_button("radio")
                    core.add_checkbox("checkbox")

                core.add_same_line()

                with simple.group("misc"):
                    core.add_date_picker("date")

                with simple.group("text"):
                    core.add_text("text")
                    core.add_input_text(
                        "input_text",
                        label="",
                        default_value=
                        "Call me Ish-meal. Tasty like an ashen log.")
                    core.add_label_text("label",
                                        label="",
                                        default_value="label")

                core.add_same_line()

                with simple.group("dropdown"):
                    core.add_listbox("listbox", label="", items=(1, 2, 3))
                    core.add_combo("combo", label="", items=(1, 2, 3))

                for x in ["float", "int"]:
                    with simple.group(x):
                        for what in ["add_drag_", "add_input_"]:
                            for y in ['', 2, 3, 4]:
                                n = f"{what}{x}{y}"
                                cmd = getattr(core, n)
                                cmd(n, label="", width=200)
                    core.add_same_line()

        manager.ThemeManager()
Beispiel #8
0
    def _build(self):
        with simple.window(f"Object Pool: {self._title}", width=600, height=400, x_pos=0, y_pos=0, on_close=self.destroy, no_resize=False, no_close=True, no_move=True, no_collapse=True):
            core.add_label_text("Pools##total", label="Total Pools", default_value=str(len(self._pools)))
            core.add_label_text("Pools##memory", label="Memory Usage (MB)", default_value="0")
            core.add_label_text("Pools##cpu", label="System Load (%)", default_value="0")
            
            # show all pools
            for pool_name, pool in self._pools.items():
                with simple.collapsing_header(f"Pool: {pool_name}", default_open=False):
                    core.add_label_text(f"Objects_{pool_name}##total", label="Total Objects", default_value="0 / inf")
                    core.add_label_text(f"Objects_{pool_name}##subscribers", label="Subscriptions", default_value="0")
                    core.add_indent()
                    with simple.collapsing_header(f"Objects_{pool_name}##table", default_open=True):
                        pass
                    core.unindent()

        core.set_render_callback(self._render_callback)
        core.set_main_window_size(600, 400)
        core.set_main_window_title("Object Pool UI")
        def create_new_user_data(sender, data) -> None:
            initial_data = {
            "User Name": gg.get_value("##user_name"),
            "Start Balance": gg.get_value("##balance_input")
            }

            if not initial_data["User Name"].isalpha():
                gg.add_label_text("Error", color=[255, 0, 0],
                                  before="##balance_input", label="Username must be alphabetical")
                gg.log_error("User-name must be only alphabets")
                return
            elif initial_data["User Name"] + ".db" in os.listdir():
                gg.add_label_text("Error", color=[255, 0, 0],
                                  before="##balance_input",label="Username already exists!")
                gg.log_error("User-name must be unique")
                return

            if initial_data["Start Balance"] <= 0:
                gg.add_label_text("Error_start_balance",
                                  color=[255, 0, 0], before="Proceed",label="Balance must be greater than 0$")
                gg.log_error("Balance must be greater than 0$!")
                return
            
            create_database(initial_data["User Name"] + ".db", initial_data["Start Balance"])
            gg.delete_item("Main")
            initial_screen()
Beispiel #10
0
from serial import Serial
from dearpygui import core, simple
ser = Serial('com6')
t = True

with simple.window("Current Temp"):
    core.add_label_text("temp", "Hello world", color=[255, 255, 255])

core.start_dearpygui()

while t:
    read = str(ser.readline())
    l = len(read)
    end = l - 5
    subread = read[2:end]
    core.set_value("temp", subread)



Beispiel #11
0
    # Component to input value
    core.add_text("Iris Flower Classification")
    core.add_slider_float("Sepal Length",
                          default_value=4.30,
                          min_value=4.30,
                          max_value=7.90,
                          callback=GetData)
    core.add_slider_float("Sepal Width",
                          default_value=2.00,
                          min_value=2.00,
                          max_value=4.40,
                          callback=GetData)
    core.add_slider_float("Petal Length",
                          default_value=1.00,
                          min_value=1.00,
                          max_value=6.90,
                          callback=GetData)
    core.add_slider_float("Petal Width",
                          default_value=0.10,
                          min_value=0.10,
                          max_value=2.50,
                          callback=GetData)
    # Predict callback
    core.add_button("Predict", callback=predict_button)
    core.add_text('\n\n')
    core.add_text('Result: ')
    core.add_same_line()
    core.add_label_text("\n##res", source="rs")

# Start DearPyGUI
core.start_dearpygui()  #primary_window="Iris Flower Prediction")
Beispiel #12
0
def start():
    """
    Renders main window elements.
    """
    with open('token.txt', 'r') as token_file:
        token = token_file.readline()
        try:
            # Connect to IBM
            core.run_async_function(get_backends_async, data=token)
            core.set_render_callback(show_button)

            # Progress bar
            with simple.window('Please wait',
                               no_scrollbar=True,
                               height=70,
                               width=400,
                               x_pos=500,
                               y_pos=200):
                core.add_progress_bar('progress',
                                      value=0.0,
                                      overlay='Connecting to IBM...',
                                      width=400)
                core.run_async_function(progress_async, 0)

            # Menu bar
            with simple.menu_bar("Main Menu Bar"):

                with simple.menu("File"):

                    core.add_menu_item("Save", callback=print_me)
                    core.add_menu_item("Save As", callback=print_me)

                core.add_menu_item("Help", callback=open_help_window)
                core.add_menu_item("About", callback=open_about_window)

            # Parameters group
            with simple.group('left group', width=350):
                # Select file button
                core.add_child('##file_block',
                               width=350,
                               height=180,
                               show=False)
                core.add_button('File Selector', callback=file_picker)
                core.add_spacing(name='##space2', count=3)
                core.add_text('File location:')
                core.add_label_text('##filedir',
                                    value='None Selected',
                                    source='directory')
                core.add_spacing(name='##space3', count=3)
                core.add_text('File name:')
                core.add_label_text('##file',
                                    value='None Selected',
                                    source='file_directory')
                core.end()
                core.add_spacing(name='##space4', count=3)
                # Architecture type radio button
                core.add_child('##settings_block',
                               width=350,
                               height=450,
                               show=False)
                core.add_text('Architecture type:')
                core.add_radio_button('radio##1',
                                      items=[
                                          'IBM simulator',
                                          'IBM quantum computer',
                                          'Arbitrary computer coupling'
                                      ],
                                      callback=show_architecture_list,
                                      source='device_type')
                core.add_spacing(name='##space5', count=3)
                # "Create arbitrary coupling" button
                core.add_button('Create custom architecture',
                                callback=create_architecture,
                                show=False)
                core.add_spacing(name='##space11', count=3)
                # Layout radio button
                core.add_text('Quantum circuit layout method:')
                core.add_radio_button(
                    'radio##2',
                    items=['Original IBM layout', 'Advanced SWAP placement'],
                    source='layout_type')
                core.add_spacing(name='##space6', count=3)
                # Optimization level slider
                core.add_text('Optimization level:')
                core.add_slider_int(
                    '##optimization_lvl',
                    default_value=1,
                    min_value=0,
                    max_value=3,
                    tip='drag the slider to select an optimization level',
                    width=300,
                    source='opt_level')
                core.add_spacing(name='##space7', count=3)
                # Number of iterations slider
                core.add_text('Number of iterations:')
                core.add_input_int('##num_of_iter',
                                   width=300,
                                   callback=check_iteration_num,
                                   default_value=100)
                core.add_spacing(name='##space8', count=3)
                # Default settings button
                core.add_button('Set Default', callback=set_default)
                core.end()
                core.add_spacing(name='##space9', count=3)
                # Process button
                core.add_button('Process', callback=process, show=False)

            # graph images
            core.add_same_line(name='line##3', xoffset=370)
            with simple.group('center group'):
                core.add_child('##images_block', width=640, show=False)
                # Input circuit preview
                core.add_text('Input circuit:')
                core.add_drawing('input_circuit', width=600, height=500)
                core.draw_rectangle('input_circuit', [0, 150], [600, 500],
                                    [255, 255, 255, 0], [255, 255, 255, 50])
                # Output circuit view
                core.add_text('Output circuit:')
                core.add_drawing('output_circuit', width=600, height=500)
                core.draw_rectangle('output_circuit', [0, 150], [600, 500],
                                    [255, 255, 255, 0], [255, 255, 255, 50])
                core.end()

            # program output
            core.add_same_line(name='line##3', xoffset=1020)
            with simple.group('right group'):
                core.add_child('##output_block1',
                               width=460,
                               height=300,
                               show=False)
                core.add_button('Open qasm file', callback=open_qasm)
                core.add_text('Path to IBM circuit representation')
                core.add_label_text('##circuitImage')
                core.add_button('Mapping', callback=show_mapping)
                core.end()
                core.add_text('Program output:', show=False)
                core.add_child('##output_block2',
                               width=460,
                               height=180,
                               show=False)
                core.add_text('Program output will be displayed here',
                              wrap=440)
                core.end()

        except Exception as exc:
            print("[ERROR]: {}".format(exc))
    def info_single_stock(self, data: dict):
        ticker = data["Ticker"]
        with window(ticker + "##window", width=500, height=500, no_scrollbar=False):
            self.menu(False, False, False, False)
            ticker_data = yfs.get_quote_table(ticker, dict_result=True)
            date_time = datetime.datetime.now()
            time = date_time.time()
            date = date_time.date()
            price = round(ticker_data["Quote Price"], 2)
            with group("heading", horizontal=True):
                with group("day_info"):
                    gg.add_text("Date: " + str(date), color=[255, 0, 0])
                    gg.add_text("Time: " + str(time), color=[255, 0, 0])
                try:
                    gg.add_label_text("Current Shares",
                                      label=f"Number of shares: {self.user.share_quantity[ticker]}",
                                      color=[0, 255, 0])
                except KeyError:
                    gg.add_label_text("Current Shares",
                                      label=f"Number of shares: 0",
                                      color=[0, 255, 0])
            with menu_bar("local_info"):
                gg.add_menu_item("ticker", label=ticker, enabled=False)
                gg.add_label_text("Current Balance", label=f"Current Balance: {self.user.current_balance}",
                                  color=[255, 0, 0])

            gg.add_separator()
            gg.add_text("Today")
            gg.add_separator()
            with managed_columns("day_info_ticker", columns=3):
                gg.add_text("Last close: " + str(ticker_data["Previous Close"]))
                gg.add_text("Open price: " + str(ticker_data["Open"]))
                gg.add_text("Current price: " + str(price))
            gg.add_separator()

            with group("Extra info", horizontal=True):
                with group("Extra Info##1"):
                    gg.add_text("Volume: " + str(ticker_data["Volume"]), bullet=True)
                    gg.add_text("Market Cap: " + str(ticker_data["Market Cap"]), bullet=True)
            
                with group("Extra info##2"):
                    gg.add_text("52 Week Range: " + str(ticker_data["52 Week Range"]), bullet=True)
                    one_year_estimate = ticker_data["1y Target Est"]
                    percent_change = get_percent_change(price, one_year_estimate)
                    if one_year_estimate > price:
                        colour = [0, 255, 0]
                    else:
                        colour = [255, 0, 0]

                    with group("1Y estimate", horizontal=True):
                        gg.add_text(f"1y Target Estimate: {ticker_data['1y Target Est']} |", bullet=True)
                        gg.add_text(f"{percent_change}%", color=colour)

            gg.add_spacing(count=5)

            # Table of share data on first day of each month since 365 days ago
            date_data_since = date - datetime.timedelta(365)
            table_monthly_interval_data = yfs.get_data(ticker, start_date=date_data_since, interval="1mo")
            gg.add_table("monthly_data", headers=["date"] + [header for header in table_monthly_interval_data])
            for date_index in table_monthly_interval_data.index:
                list_values = [str(date_index)[:10]]
                list_values.extend(list(table_monthly_interval_data.loc[date_index]))
                for i in range(len(list_values)):
                    if type(list_values[i]) == str:
                        continue
                    else:
                        list_values[i] = str(round(list_values[i], 3))
                gg.add_row("monthly_data", list_values)

            gg.add_spacing(count=2)

            def make_plot():
                date_data_since = date - datetime.timedelta(30)
                scatter_plot_weekly_data = yfs.get_data(ticker, start_date=date_data_since, interval="1d")
                indecis = [x for x in scatter_plot_weekly_data.index]
                start_date = indecis[0]
                x_axis = [(x - start_date).days for x in indecis]
                y_axis_max = [scatter_plot_weekly_data.loc[x]['high'] for x in indecis]
                y_axis_min = [scatter_plot_weekly_data.loc[x]['low'] for x in indecis]
                gg.add_plot("30 Day Price Fluctuation", height=300, scale_max=.5,
                            x_axis_name=f"Days since {start_date}", y_axis_name="Single share price")
                gg.add_scatter_series("30 Day Price Fluctuation", "Day High", x=x_axis, y=y_axis_max, size=3)
                gg.add_scatter_series("30 Day Price Fluctuation", "Day Low", x=x_axis, y=y_axis_min, marker=1, size=3)

                # Set initial plot view
                gg.set_plot_xlimits("30 Day Price Fluctuation", 0, 30)
                gg.set_plot_ylimits("30 Day Price Fluctuation", min(y_axis_min)*.97, max(y_axis_max)*1.03)
                gg.set_plot_ylimits_auto("30 Day Price Fluctuation")
                gg.set_plot_xlimits_auto("30 Day Price Fluctuation")

            make_plot()
            # Create purchase button and what not

            def purchase_stocks(sender, data):
                quantity = round(gg.get_value("Quantity"), 2)
                total_price = quantity * price
                gg.set_item_color("Message", style=1, color=[255, 0, 0])
                if self.user.current_balance < total_price:
                    set_item_label("Message", "Cannot purchase, insufficient funds")
                elif 0 >= total_price:
                    set_item_label("Message", "Must spend more than 0$")
                else:
                    set_item_label("Message", f"Purchase of {quantity} {ticker} shares at {price} made")
                    gg.set_item_color("Message", style=1, color=[0, 255, 0])
                    self.user.buy_share(quantity, price, ticker, str(date), str(time))
                    set_item_label("Current Balance", f"Current Balance: {self.user.current_balance}")
                    set_item_label("Current Shares", f"Number of shares: {self.user.share_quantity[ticker]}")

            def add_to_watchlist(sender, data):
                self.user.add_to_watchlist(ticker, price, database=True)
                set_item_label(sender, "Remove From Watchlist")
                gg.set_item_callback(sender, remove_from_watchlist)

            def remove_from_watchlist(sender, data):
                self.user.remove_from_watchlist(ticker)
                set_item_label(sender, "Add To Watchlist")
                gg.set_item_callback(sender, add_to_watchlist)

            with group("footer", horizontal=True):
                with group("Buy Stock Group"):
                    def get_dynamic_cost(sender, data):
                        # TODO dynamic colouring
                        cost = round(gg.get_value("Quantity") * price, 2)
                        set_item_label("Stock volume", f"Total Cost: {cost}")

                    gg.add_input_float("Stock volume", default_value=0,
                                       width=100, source="Quantity", label="Total cost: 0",
                                       callback=get_dynamic_cost, on_enter=True)
                    gg.add_label_text("Message", label="", color=[255, 0, 0])
                    gg.add_button("Buy Shares", callback=purchase_stocks)
                with group("Stock Watchlist"):
                    if ticker not in self.user.watchlist:
                        gg.add_button("Watchlist Button", callback=add_to_watchlist, label="Add To Watchlist")
                    else:
                        gg.add_button("Watchlist Button", callback=remove_from_watchlist, label="Remove From Watchlist")
Beispiel #14
0
 def _setup_add_widget(self, dpg_args) -> None:
     dpgcore.add_label_text(self.id, **dpg_args)
Beispiel #15
0
    core.set_value("comport##inputtext", comport_list[0])


with simple.window("Motor Window"):

    core.add_text(
        "To adjust the position of the motors, enter values and click on the respective send value.",
        wrap=500,
        bullet=True)
    core.add_text(
        "Press the 'print-log' button to display all values in an log",
        wrap=500,
        bullet=True)
    # button for listing all available COM ports
    core.add_button("Search COM Ports", callback=find_comports)
    core.add_label_text("Click button for new search")
    core.set_value("Click button for new search",
                   "No values where received yet")

    core.add_text(
        "Please choose the COM Port where the microcontroller is connected:")
    core.add_input_text("comport##inputtext", hint="enter port, e.g. COM0")
    # text input fields for all motors are created
    # for each value there is a button to send the entered value to the motor
    core.add_text("Please choose position for any/all motors:")
    motor_count = [0, 1, 2, 3]
    for element in motor_count:
        core.add_input_text(
            f"motor {element}##inputtext",
            hint="enter position in ticks, 6400 ticks are 360°",
            decimal=True)
Beispiel #16
0
def main():
    empty_board = [['_E','_E','_E','_E','_E','_E','_E','_E'],
                   ['_E','_E','_E','_E','_E','_E','_E','_E'],
                   ['_E','_E','_E','_E','_E','_E','_E','_E'],
                   ['_E','_E','_E','_E','_E','_E','_E','_E'],
                   ['_E','_E','_E','_E','_E','_E','_E','_E'],
                   ['_E','_E','_E','_E','_E','_E','_E','_E'],
                   ['_E','_E','_E','_E','_E','_E','_E','_E'],
                   ['_E','_E','_E','_E','_E','_E','_E','_E']]
    initial_board = [['Tn','Cn','An','Dn','Rn','An','Cn','Tn'],
                     ['Pn','Pn','Pn','Pn','Pn','Pn','Pn','Pn'],
                     ['_E','_E','_E','_E','_E','_E','_E','_E'],
                     ['_E','_E','_E','_E','_E','_E','_E','_E'],
                     ['_E','_E','_E','_E','_E','_E','_E','_E'],
                     ['_E','_E','_E','_E','_E','_E','_E','_E'],
                     ['Pb','Pb','Pb','Pb','Pb','Pb','Pb','Pb'],
                     ['Tb','Cb','Ab','Db','Rb','Ab','Cb','Tb']]

    def mouse_click_callback(sender,data):
        nonlocal c_board

        if data == 0 and c_board.current_selection != -1:
            m_position = dpg.get_mouse_pos()
            position = c_board.get_board_position(m_position)

            if not position:
                return

            if c_board.current_selection == 0:
                c_board.change_box('P', position) # put peon
            elif c_board.current_selection == 1:
                c_board.change_box('T', position) # put toker
            elif c_board.current_selection == 2:
                c_board.change_box('C', position) # put horse
            elif c_board.current_selection == 3:
                c_board.change_box('A', position) # put bishop
            elif c_board.current_selection == 4:
                c_board.change_box('D', position) # put queen
            elif c_board.current_selection == 5:
                c_board.change_box('R', position) # put king
            elif c_board.current_selection == 6:
                c_board.change_box(None,position) # remove
            elif c_board.current_selection == 7:
                # draw arrow
                size = c_board.piece_size
                c = size//2
                position = (position[0]*size+c,position[1]*size+c)
                if c_board.step == 0:
                    c_board.lines.append([(),(),''])
                    c_board.lines[-1][0] = position
                elif c_board.step == 1:
                    c_board.lines[-1][1] = position
                    color = dpg.get_value('drawing_color')
                    r = int(color[0])
                    g = int(color[1])
                    b = int(color[2])
                    color = 'rgb({},{},{})'.format(r,g,b)
                    c_board.lines[-1][2] = color

                c_board.step = (c_board.step+1)%2

                if c_board.step == 1:
                    return

            elif c_board.current_selection == 8:
                # delete arrow
                size = c_board.piece_size
                c = size//2
                position = (position[0]*size+c,position[1]*size+c)
                for i in range(len(c_board.lines)):
                    line = c_board.lines[i]
                    if position == line[0] or position == line[1]:
                        c_board.lines.remove(line)
                        break
            elif c_board.current_selection == 9:
                # color box
                color = dpg.get_value('drawing_color')
                r = int(color[0])
                g = int(color[1])
                b = int(color[2])
                color = 'rgb({},{},{})'.format(r,g,b)
                col = position[0]
                row = position[1]
                c_board.colored_boxes[row][col] = color
            elif c_board.current_selection == 10:
                # discolor box
                col = position[0]
                row = position[1]
                c_board.colored_boxes[row][col] = None

            c_board.draw_board()

        if data == 1:
            if c_board.piece_color == 'b':
                c_board.piece_color = 'n'
                dpg.set_value('color_piece', "Negro")
            else:
                 c_board.piece_color = 'b'
                 dpg.set_value('color_piece', "Blanco")

    def key_press_callback(sender, data):
        nonlocal c_board
        if data == dpg.mvKey_Right:
            if c_board.reading_pgn:
                pars.current_match.next_position()
                c_board.draw_board()
            else:
                return

        if data == dpg.mvKey_Left:
            if c_board.reading_pgn:
                pars.current_match.previews_position()
                c_board.draw_board()
            else:
                return

        if data == dpg.mvKey_Escape :
            c_board.current_selection = -1
            c_board.reading_pgn = False
            dpg.set_value("accion", "Sin seleccionar")
            dpg.set_value("pieza", "Sin seleccionar")
            return

    def load_callback(sender, data):
        def file_callback(sender, data):
            nonlocal c_board
            file = open(data[1],'rb')
            load_board = pickle.load(file)
            file.close()
            c_board = load_board
            c_board.draw_board()

        dpg.open_file_dialog(callback=file_callback, extensions=".sv")

    def save_callback(sender, data):
        nonlocal c_board

        c_board.save_board()

    def save_image_callback(sender,data):
        nonlocal c_board
        c_board.save_board_image()

    def clean_callback(sender, data):
        nonlocal c_board
        nonlocal empty_board
        c_board.reading_pgn = False
        c_board.board = copy.deepcopy(empty_board)
        c_board.lines = []
        c_board.colored_boxes = [[None,None,None,None,None,None,None,None],
                                 [None,None,None,None,None,None,None,None],
                                 [None,None,None,None,None,None,None,None],
                                 [None,None,None,None,None,None,None,None],
                                 [None,None,None,None,None,None,None,None],
                                 [None,None,None,None,None,None,None,None],
                                 [None,None,None,None,None,None,None,None],
                                 [None,None,None,None,None,None,None,None]]
        c_board.draw_board()

    def default_board_callback(sender, data):
        nonlocal c_board
        nonlocal initial_board
        c_board.reading_pgn = False
        c_board.board = copy.deepcopy(initial_board)
        c_board.lines = []
        c_board.colored_boxes = [[None,None,None,None,None,None,None,None],
                                 [None,None,None,None,None,None,None,None],
                                 [None,None,None,None,None,None,None,None],
                                 [None,None,None,None,None,None,None,None],
                                 [None,None,None,None,None,None,None,None],
                                 [None,None,None,None,None,None,None,None],
                                 [None,None,None,None,None,None,None,None],
                                 [None,None,None,None,None,None,None,None]]
        c_board.draw_board()

    def close(sender,data):
        try:
            os.remove("tmp.png")
        except Exception as e:
            pass

    def pgn_reader(sender,data):

        def load_match(sender,data):
            nonlocal pars
            nonlocal c_board
            coords = dpg.get_table_selections(sender)
            dpg.delete_item('Partidas')
            dpg.delete_item('Lista de Partidas')
            i = coords[0][0]
            match = pars.matches[i]
            pars.current_match = match
            c_board.board = match.board
            c_board.reading_pgn = True
            dpg.set_value('accion','Leyendo partida PGN')
            dpg.set_value('pieza','Sin seleccionar')
            c_board.draw_board()

        def close_callback(sender,data):
            dpg.delete_item('Partidas')
            dpg.delete_item('Lista de Partidas')

        def file_callback(sender, data):
            nonlocal c_board
            nonlocal pars

            pars = Parser()
            pars.get_plays(data[0]+'/'+data[1])

            # Lista de partidas cargadas--------------------------------TODO
            dpg.add_window('Lista de Partidas',on_close=close_callback)
            colums = set()
            for match in pars.matches:
                for att in match.attr:
                    colums.add(att)
            colums = list(colums)
            # colums.sort()
            dpg.add_table("Partidas", colums, callback=load_match)

            rows = list()
            for match in pars.matches:
                row = list()
                for colum in colums:
                    row.append(match.attr[colum])

                rows.append(row)

            for row in rows:
                dpg.add_row("Partidas", row)

            dpg.end()

        dpg.open_file_dialog(callback=file_callback, extensions=".pgn")

    def control_button(sender,data):
        nonlocal c_board;
        c_board.reading_pgn = False

        add_arr = c_board.current_selection == 7
        if add_arr and c_board.step == 1:
            c_board.lines.pop()
            c_board.step = 0

        if sender == 'Peon':
            c_board.current_selection = 0
            dpg.set_value("accion", "Añadiendo Pieza")
            dpg.set_value("pieza", "Peon")
        elif sender == 'Torre':
            c_board.current_selection = 1
            dpg.set_value("accion", "Añadiendo Pieza")
            dpg.set_value("pieza", "Torre")
        elif sender == 'Caballo':
            c_board.current_selection = 2
            dpg.set_value("accion", "Añadiendo Pieza")
            dpg.set_value("pieza", "Caballo")
        elif sender == 'Alfil':
            c_board.current_selection = 3
            dpg.set_value("accion", "Añadiendo Pieza")
            dpg.set_value("pieza", "Alfil")
        elif sender == 'Reina':
            c_board.current_selection = 4
            dpg.set_value("accion", "Añadiendo Pieza")
            dpg.set_value("pieza", "Reina")
        elif sender == 'Rey':
            c_board.current_selection = 5
            dpg.set_value("accion", "Añadiendo Pieza")
            dpg.set_value("pieza", "Rey")
        elif sender == 'Eliminar Pieza':
            c_board.current_selection = 6
            dpg.set_value("accion", "Eliminando Pieza")
            dpg.set_value("pieza", "Sin seleccionar")
        elif sender == 'Añadir flecha':
            c_board.current_selection = 7
            dpg.set_value("accion", "Añadiendo flecha")
            dpg.set_value("pieza", "Sin seleccionar")
        elif sender == 'Eliminar flecha':
            c_board.current_selection = 8
            dpg.set_value("accion", "Eliminando flecha")
            dpg.set_value("pieza", "Sin seleccionar")
        elif sender == 'Colorear casilla':
            c_board.current_selection = 9
            dpg.set_value("accion", "Coloreando casilla")
            dpg.set_value("pieza", "Sin seleccionar")
        elif sender == 'Descolorear casilla':
            c_board.current_selection = 10
            dpg.set_value("accion", "Descolorando casilla")
            dpg.set_value("pieza", "Sin seleccionar")

    c_board = Board(board = copy.deepcopy(empty_board))
    pars = Parser()

    main_width = c_board.size+220
    main_height= c_board.size+240

    with dpgs.window('Diagramador'):
        dpg.set_main_window_size(main_width, main_height)
        dpg.set_main_window_resizable(False)
        dpg.set_exit_callback(close)

        with menu_bar('Menu bar'):
            with menu('Archivo'):
                dpg.add_menu_item("Guardar", callback=save_callback)
                dpg.add_menu_item("Guardar Imagen", callback=save_image_callback)
                dpg.add_menu_item("Cargar tablero", callback=load_callback)
            with menu('Herramientas'):
                dpg.add_menu_item("Leer archivo PGN", callback=pgn_reader)
            with menu('Color'):
                dpg.add_color_edit3('Seleccion de Color',source='drawing_color')

        dpg.add_drawing("canvas", width=c_board.size,height=c_board.size)
        dpg.add_image('board_img','',source=c_board.piece_p('Abb'))
        dpg.add_same_line()

        controles =(
            "\nControles\n"
            "Click Derecho : Cambiar color de pieza\n\n"
            "Flecha derecha: Mostrar siguiente jugada PGN\n\n"
            "Flecha izquierda: Mostrar la jugada PGN previa\n\n"
        )
        dpg.add_child('controls',autosize_x=True,height=c_board.size)
        dpg.add_button('Peon',callback=control_button)
        dpg.add_button('Torre',callback=control_button)
        dpg.add_button('Caballo',callback=control_button)
        dpg.add_button('Alfil',callback=control_button)
        dpg.add_button('Reina',callback=control_button)
        dpg.add_button('Rey',callback=control_button)
        dpg.add_button('Eliminar Pieza',callback=control_button)
        dpg.add_button('Añadir flecha',callback=control_button)
        dpg.add_button('Eliminar flecha',callback=control_button)
        dpg.add_button('Colorear casilla',callback=control_button)
        dpg.add_button('Descolorear casilla',callback=control_button)
        dpg.add_text(controles)
        dpg.end()

        dpg.set_value('drawing_color',[0,0,0])
        name = "Nombre de Archivo"
        dpg.add_input_text(name, width=250, source='save_name')
        name = "Nombre de Imagen"
        dpg.add_input_text(name, width=250, source='save_img_name')
        dpg.add_button("Limpiar tablero", callback=clean_callback)
        name = "Tablero por defecto"
        dpg.add_button(name, callback=default_board_callback)

        name = "Acción"
        dpg.add_label_text(name, default_value='Sin seleccionar', source="accion")
        dpg.add_label_text("Pieza", default_value='Sin seleccionar', source="pieza")
        dpg.add_label_text("Color de pieza", default_value='Blanco', source='color_piece')
        c_board.draw_board()

        dpg.set_key_press_callback(key_press_callback)
        dpg.set_mouse_click_callback(mouse_click_callback)

        dpg.start_dearpygui(primary_window = 'Diagramador')