Ejemplo n.º 1
0
def openfile():
    options = {}
    options['filetypes'] = [('BFLIM files', '.bflim')]
    filename = askopenfilename(parent=top, filetypes=options['filetypes'])

    with open(filename, "rb") as inf:
        inb = inf.read()
        inf.close()

    global menubar
    global filemenu
    
    flim = FLIMData()

    pos = struct.unpack(">I", inb[-4:])[0]

    header = FLIMHeader()
    header.data(inb, pos)
        
    if header.magic != b"FLIM":
        messagebox.showinfo("", "Invalid BFLIM header!")
    else:
        if header.endian == 0xFEFF:
            bom = '>'
        elif header.endian == 0xFFFE:
            bom = '<'

        pos += header.size

        info = imagHeader(bom)
        info.data(inb, pos)

        if info.magic != b'imag':
            messagebox.showinfo("", "Invalid imag header!")
        else:
            flim.width = info.width
            flim.height = info.height

            if info.format_ == 0x00:
                flim.format = 0x01
            elif info.format_ == 0x01:
                flim.format = 0x01
            elif info.format_ == 0x03:
                flim.format = 0x07
            elif info.format_ == 0x05:
                flim.format = 0x08
            elif info.format_ == 0x09:
                flim.format = 0x1a
            elif info.format_ == 0x0C:
                flim.format = 0x31
            elif info.format_ == 0x0D:
                flim.format = 0x32
            elif info.format_ == 0x0E:
                flim.format = 0x33
            elif info.format_ == 0x0F:
                flim.format = 0x34
            elif info.format_ == 0x10:
                flim.format = 0x34
            elif info.format_ == 0x11:
                flim.format = 0x35
            elif info.format_ == 0x12:
                flim.format = 0x31
            elif info.format_ == 0x14:
                flim.format = 0x1a
            elif info.format_ == 0x15:
                flim.format = 0x31
            elif info.format_ == 0x16:
                flim.format = 0x32
            elif info.format_ == 0x17:
                flim.format = 0x33
            else:
                flim.format = 0

            if flim.format == 0:
                messagebox.showinfo("", "Unsupported format!")
            else:
                flim.imageSize = info.imageSize

                flim.swizzle = info.swizzle
                flim.swizzle = (((flim.swizzle & 0xF0) >> 4) // 2) << 8

                flim.alignment = info.alignment

                # Calculate Pitch
                # Welp, does this even work?
                bpp = surfaceGetBitsPerPixel(flim.format)

                try:
                    if (flim.format != 0x31 and flim.format != 0x32 and flim.format != 0x33):
                        size = flim.width
                    else:
                        size = flim.height

                    flim.pitch = size // bpp

                    import math
                    frac, whole = math.modf(flim.pitch)
                    whole = int(whole)

                    while (bpp * whole) < size:
                        whole += 1

                    flim.pitch = (bpp * whole)
                except ZeroDivisionError:
                    flim.pitch = 1

                flim.data = inb[:info.imageSize]

                scr = Scrollbar(top, orient="vertical", command=canvas.yview)
                canvas.configure(yscrollcommand=scr.set)

                scr.pack(side="right", fill="y")
                canvas.pack(side="left", fill="both", expand=True)
                canvas.create_window((4,4), window=frame, anchor="nw")

                frame.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))

                options['filetypes'] = [('DDS files', '.dds')]

                name = os.path.splitext(filename)[0]

                ugh = False

                if os.path.isfile(name + ".dds"):
                    pass
                else:
                    head1 = bytearray.fromhex("4766783200000020000000070000000100000002000000000000000000000000424C4B7B0000002000000001000000000000000B0000009C0000000000000000")
                    head2 = bytearray.fromhex("424C4B7B0000002000000001000000000000000C") + flim.imageSize.to_bytes(4, 'big') + bytearray.fromhex("0000000000000000")
                    head3 = bytearray.fromhex("424C4B7B00000020000000010000000000000001000000000000000000000000")

                    info = bytearray(0x9C)

                    info[:4] = (1).to_bytes(4, 'big')
                    info[4:8] = flim.width.to_bytes(4, 'big')
                    info[8:0xC] = flim.height.to_bytes(4, 'big')
                    info[0xC:0x10] = (1).to_bytes(4, 'big')
                    info[0x10:0x14] = (1).to_bytes(4, 'big')
                    info[0x14:0x18] = flim.format.to_bytes(4, 'big')
                    info[0x18:0x1C] = (0).to_bytes(4, 'big')
                    info[0x1C:0x20] = (1).to_bytes(4, 'big')
                    info[0x20:0x24] = flim.imageSize.to_bytes(4, 'big')
                    info[0x24:0x28] = (0).to_bytes(4, 'big')
                    info[0x28:0x2C] = (0).to_bytes(4, 'big')
                    info[0x2C:0x30] = (0).to_bytes(4, 'big')
                    info[0x30:0x34] = (4).to_bytes(4, 'big')
                    info[0x34:0x38] = flim.swizzle.to_bytes(4, 'big')
                    info[0x38:0x3C] = flim.alignment.to_bytes(4, 'big')
                    info[0x3C:0x40] = flim.pitch.to_bytes(4, 'big')
                    info[0x40:0x4D] = bytearray(0xD)
                    info[0x4D:0x78] = bytearray(0x2B)
                    info[0x78:0x7C] = (1).to_bytes(4, 'big')
                    info[0x7C:0x80] = (0).to_bytes(4, 'big')
                    info[0x80:0x84] = (1).to_bytes(4, 'big')
                    info[0x84:0x88] = (0x10203).to_bytes(4, 'big')
                    info[0x88:0x9C] = bytearray(0x14)

                    file = head1 + info + head2 + flim.data + head3

                    with open(name + "2.gtx", "wb") as output:
                        output.write(file)
                        output.close()

                    print("")
                    os.system('C:/Tex/TexConv2.exe -i "' + name + '2.gtx" -f GX2_SURFACE_FORMAT_TCS_R8_G8_B8_A8_UNORM -o "' + name + '.gtx"')
                    os.system('C:/Tex/gtx_extract.exe "' + name + '.gtx"')

                    try:
                        os.remove(name + '.gtx')
                    except FileNotFoundError:
                        os.system('C:/Tex/TexConv2.exe -i "' + name + '2.gtx" -o "' + name + '.dds"')

                        if os.path.isfile(name + '.dds'):
                            if flim.format == 0x01:
                                format_ = 61
                            elif flim.format == 0x07:
                                format_ = 49
                            elif flim.format == 0x08:
                                format_ = 85
                            elif flim.format == 0x1a:
                                format_ = 28
                            elif flim.format == 0x31:
                                format_ = "BC1"
                            elif flim.format == 0x32:
                                format_ = "BC2"
                            elif flim.format == 0x33:
                                format_ = "BC3"
                            elif flim.format == 0x34:
                                format_ = "BC4U"
                            elif flim.format == 0x35:
                                format_ = "BC5U"

                            hdr = writeHeader(1, flim.width, flim.height, format_, flim.format in BCn_formats)

                            with open(name + ".dds", "rb") as output:
                                out = bytearray(output.read())
                                output.close()

                            with open(name + ".dds", "wb") as output:
                                out[:0x80] = hdr
                                output.write(out)
                                output.close()
                        else:
                            messagebox.showinfo("Whoops", "Something went wrong!")
                            ugh = True

                    os.remove(name + '2.gtx')

                if not ugh:
                    tv = 'Replace "' + os.path.basename(name) + '"\n' + formats2[flim.format]
                    b = Button(frame, text=tv, command=lambda flim=flim : DDStoBFLIM(flim, askopenfilename(parent=top, filetypes=options['filetypes']), filename))
                    b.pack(padx=1, pady=1)
                    
                    menubar.destroy()
                    filemenu.destroy()

                    messagebox.showinfo("", "Done!")
                else:
                    scr.destroy()
Ejemplo n.º 2
0
class mainGUI(Frame, bootloader, GuiController):
    """ Contains the main view for the application """

    def __init__(self):
        """ Create the initial application GUI environment (tool bars, and other static elements) """
        Frame.__init__(self, self.root)
        self.thread_entry_field = ''  # Hold both search string, and drives autoRefresh logic

        self.menuBar = Menu()
        self.fileMenu = Menu(self.menuBar, tearoff=0)
        self.menuBar.add_cascade(label="File", menu=self.fileMenu, underline=1)
        self.fileMenu.add_command(label="Quit", command=self.root.destroy, underline=1)

        self.optionsMenu = Menu(self.menuBar, tearoff=0)
        self.menuBar.add_cascade(label="Options", menu=self.optionsMenu)
        self.optionsMenu.add_command(label="Settings", command=self.editSettings, underline=1)
        self.helpMenu = Menu(self.menuBar, tearoff=0)
        self.menuBar.add_cascade(label="Help", menu=self.helpMenu)
        self.helpMenu.add_command(label="Help", command=self.program_help, underline=1)
        self.helpMenu.add_command(label="About", command=self.program_about, underline=1)
        self.master.config(menu=self.menuBar)

        self.topFrame = Frame()
        self.thread_entry_box = Entry(self.topFrame)
        self.thread_entry_box.insert(0, self.DEFAULT_THREAD_TEXT)
        self.thread_entry_box.bind('<Return>', lambda event: self.add_thread_GUI())
        # Bind needs to send the event to the handler
        self.thread_entry_box.pack(side='left', fill='x', expand='True', padx=5)

        self.add_thread_btn = Button(self.topFrame)
        self.add_thread_btn['text'] = 'Add New Thread'
        self.add_thread_btn['command'] = lambda: self.add_thread_GUI()
        self.add_thread_btn.pack(side='left', padx=0)

        self.topFrame.pack(fill='x')

        self.create_thread_frame()

    def create_thread_frame(self):
        """ Sets up the main thread frame (where the magic happens) """

        # Sets up frame
        self.thread_list_canvas = Canvas(self.root, borderwidth=0)
        self.thread_list_frame = Frame(self.thread_list_canvas)

        # Creates scroll bar
        self.vsb = Scrollbar(self.root, orient="vertical", command=self.thread_list_canvas.yview)
        self.thread_list_canvas.configure(yscrollcommand=self.vsb.set)
        self.vsb.pack(side="right", fill="y")

        self.hsb = Scrollbar(self.root, orient="horizontal", command=self.thread_list_canvas.xview)
        self.thread_list_canvas.configure(xscrollcommand=self.hsb.set)
        self.hsb.pack(side="bottom", fill="x")

        # Packs frame
        self.thread_list_canvas.pack(side="left", fill="both", expand=True)
        self.thread_list_canvas.create_window((4, 4), window=self.thread_list_frame, anchor="nw", tags="self.frame")
        self.thread_list_frame.bind("<Configure>", self.OnFrameConfigure)

        self.create_thread_list_box()

    def OnFrameConfigure(self, event):
        """Reset the scroll region to encompass the inner frame"""
        self.thread_list_canvas.configure(scrollregion=self.thread_list_canvas.bbox("all"))

    # noinspection PyAttributeOutsideInit
    def create_thread_list_box(self):
        """ Creates the message list box for the create method """

        def hover_on(widget):
            widget['fg'] = 'dark blue'
            # widget['underline'] = True

        def hover_off(widget):
            widget['fg'] = 'black'
            # widget['underline'] = False

        for individual_thread in self.MESSAGE_THREADS:  # Fetch Message List from model

            if individual_thread.is_valid_thread():
                self.bg_color = 'green'
            else:
                self.bg_color = 'red'

            self.individual_thread_frame = Frame(self.thread_list_frame,
                                                 bg=self.bg_color)  # Create frame for each thread

            rowToInsertAt = self.MESSAGE_THREADS.index(individual_thread)

            self.text_color = 'black'
            self.threadText = Label(self.individual_thread_frame, bg=self.bg_color, fg=self.text_color)
            self.threadText['text'] = "[ Thread #:  " + individual_thread.threadId + " ]"

            self.threadText.bind("<Enter>", lambda event, text=self.threadText: hover_on(text))
            self.threadText.bind("<Leave>", lambda event, text=self.threadText: hover_off(text))

            self.threadText.bind("<Button-1>",
                                 lambda event, thread_in=individual_thread: self.open_in_web_browser(thread_in))
            self.threadText.grid(column=0, row=0, sticky='w', padx=0)

            self.image_count_text = Label(self.individual_thread_frame, bg=self.bg_color)
            num_of_images = individual_thread.get_number_of_images()
            if 0 < int(num_of_images) < 10:  # Format padding
                num_of_images = '00' + num_of_images
            if 10 < int(num_of_images) < 100:  # Format padding
                num_of_images = '0' + num_of_images

            self.image_count_text['text'] = "  [ # Images: " + num_of_images + " ]"
            self.image_count_text.bind("<Enter>", lambda event, text=self.image_count_text: hover_on(text))
            self.image_count_text.bind("<Leave>", lambda event, text=self.image_count_text: hover_off(text))

            self.image_count_text.bind("<Button-1>",
                                       lambda event, thread_in=individual_thread: self.open_in_file_browser(thread_in))

            self.image_count_text.grid(column=1, row=0, sticky='e', padx=0)

            self.deleteButton = Button(self.individual_thread_frame)
            self.deleteButton['text'] = 'Delete'
            self.deleteButton['command'] = lambda thread_in=individual_thread: self.delete_thread_GUI(thread_in)
            self.deleteButton.grid(column=2, row=0, sticky='e', padx=0)

            self.individual_thread_frame.grid(row=rowToInsertAt, sticky='w', pady=2)

    @staticmethod
    def open_in_file_browser(individual_thread):
        logging.debug(os.getcwd() + os.sep + individual_thread.threadId)
        if os.name == "nt":
            subprocess.Popen('explorer "' + os.getcwd() + os.sep + individual_thread.threadId + '"')

    @staticmethod
    def open_in_web_browser(individual_thread):
        webbrowser.open(
            url="http://boards.4chan.org/" + individual_thread.board + "/thread/" + individual_thread.threadId, new=2)

    def add_thread_GUI(self):
        entry_box_text = str(self.thread_entry_box.get())
        if entry_box_text not in self.MESSAGE_THREADS and entry_box_text != self.DEFAULT_THREAD_TEXT \
                and entry_box_text.isnumeric():
            try:
                self.add_thread(entry_box_text.strip(' '))
            except ThreadNotFound:
                messagebox.showwarning(message="Thread Not Found")
        else:
            messagebox.showwarning(message="Please enter a valid new thread ID")
        self.thread_entry_box.select_range(start=0, end=99)
        # Selects the contents so the user can just type the next message
        self.refresh_GUI()

    def delete_thread_GUI(self, thread_in):
        self.delete_thread(thread_in)
        self.refresh_GUI()

    def refresh_GUI(self):
        """ Refreshes the message list AND GUI window (used by auto refresh)"""
        self.refresh_thread_list()
        self.refresh_GUI_Window()

    def refresh_GUI_Window(self):
        """ Refreshes just the GUI window"""
        self.thread_list_canvas.destroy()
        self.vsb.destroy()
        self.hsb.destroy()
        self.create_thread_frame()

    @staticmethod
    def program_about():
        message = settings.__desc__ + '\n' + settings.__version__
        messagebox.showinfo(title='About', message=message)

    @staticmethod
    def program_help():
        message = 'See readme.md'
        messagebox.showinfo(title='About', message=message)
Ejemplo n.º 3
0
class CanvasPicture(Frame):
    def __init__(self, root, master=None, cnf={}, **kw):
        self.root = root
        self.fun_dict = {
            "sin x": np.sin,
            "cos x": np.cos,
            "tg x": self.tg,
            "ctg x": self.ctg,
            "x^2": self.x2,
            "x^3": self.x3
        }
        self.view = Canvas(self.root,
                           width=800,
                           height=800,
                           bg="white",
                           scrollregion=(0, 0, 800, 800))
        self.a = float()
        self.b = float()
        self.var = StringVar()
        self.vbar = Scrollbar()
        self.hbar = Scrollbar()

    EPS = 0.1

    def x2(self, x):
        return list(map(lambda t: t * t, x))

    def x3(self, x):
        return list(map(lambda t: t * t * t, x))

    def ctg(self, arr):
        def t(x):
            h = np.math.sin(x)
            if abs(h) > self.EPS:
                return np.math.cos(x) / h
            else:
                return float("nan")

        return list(map(lambda a: t(a), arr))

    def tg(self, arr):
        def t(x):
            h = np.math.cos(x)
            if abs(h) > self.EPS:
                return np.math.sin(x) / h
            else:
                return float("nan")

        return list(map(lambda a: t(a), arr))

    def create_picture(self):
        self.view.delete("all")
        self.vbar.destroy()
        self.hbar.destroy()
        path = askopenfilename()
        if path != "":
            try:
                self.image = ImageTk.PhotoImage(Image.open(path))
                if self.image.height() > 800 or self.image.width() > 800:
                    self.hbar = Scrollbar(self.root, orient=HORIZONTAL)
                    self.hbar.pack(side=BOTTOM, fill=X)
                    self.hbar.config(command=self.view.xview)
                    self.vbar = Scrollbar(self.root, orient=VERTICAL)
                    self.vbar.pack(side=RIGHT, fill=Y)
                    self.vbar.config(command=self.view.yview)
                    self.view.config(xscrollcommand=self.hbar.set,
                                     yscrollcommand=self.vbar.set)
                    self.view.create_image(0, 0, image=self.image, anchor=NW)
                    self.view.pack(side=RIGHT, expand=True, fill=BOTH)
                else:
                    self.view.create_image(0, 0, image=self.image, anchor=NW)
                    self.view.pack()
            except IOError:
                print("Incorrect file format or name")

    def print_plot(self):
        self.view.delete("all")
        self.choose_plot()

    def choose_plot(self):
        self.view.delete("all")
        self.c = Tk()
        self.c.title("Test")
        self.c.option_add("*Font", "arial 18")
        self.c.geometry("800x200")
        self.c.grid()
        self.c.protocol("WM_DELETE_WINDOW", self.c.destroy)
        funcs = ["sin x", "cos x", "tg x", "ctg x", "x^2", "x^3"]
        self.var.set(funcs[0])
        opt = OptionMenu(self.c, self.var, *funcs)
        opt.pack(side=TOP)
        self.e1 = Entry(self.c)
        self.e1.pack(side=RIGHT)
        self.e2 = Entry(self.c)
        self.e2.pack(side=RIGHT)
        b = Button(self.c, text="OK", command=self.extract_data)
        b.pack(side=BOTTOM)

    def extract_data(self):
        self.a = float(self.e2.get())
        self.b = float(self.e1.get())
        print(self.b)
        self.create_plot(self.var.get(), self.a, self.b)
        self.c.destroy()

    def create_plot(self, func, a, b):
        x = np.linspace(a, b, 100)
        y = self.fun_dict[func](x)
        fig, ax = plt.subplots()
        ax.plot(x, y, color="black", label="график функции")
        ax = plt.gca()
        ax.autoscale()
        ax.spines['left'].set_position('center')
        ax.spines['bottom'].set_position('center')
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        plt.savefig('foo.png')
        img = Image.open('foo.png')
        img.thumbnail((800, 800))
        self.imgObj = self.view.create_image(0, 0)
        self.image = ImageTk.PhotoImage(img)
        self.view.create_image(0, 0, image=self.image, anchor=NW)
        self.view.pack()