Exemple #1
0
class StrategyShareToplevel(Parent):
    """
    Toplevel to display a list of strategy with checkboxes to allow
    selecting which should be shared.
    """
    def __init__(self, master, client, database, strategy_frame, **kwargs):
        """
        :param master: master widget
        :param client: network.strategy.client.StrategyClient
        :param database: results.strategies.StrategyDataBase
        :param strategy_frame: frames.strategy.StrategyFrame
        :param kwargs: SnapToplevel keyword arguments
        """
        resizable = kwargs.pop("resizable", False)
        self._client = client
        self._database = database
        self._frame = strategy_frame
        Parent.__init__(self, master, **kwargs)
        self.wm_title("GSF Parser: Strategy Sharing")
        self.wm_resizable(resizable, resizable)
        # Configure the Treeview
        self.tree = CheckboxTreeview(master=self, height=16)
        self.tree.column("#0", width=200)
        self.tree.heading("#0", text="Strategy")
        self.tree.config(show=("headings", "tree"))
        self.scroll_bar = ttk.Scrollbar(self, orient=tk.VERTICAL, command=self.tree.yview)
        self.tree.config(yscrollcommand=self.scroll_bar.set)
        self.update_strategy_tree()
        self.share_button = ttk.Button(self, text="Share Strategies", command=self.share_strategies)
        self.grid_widgets()

    def grid_widgets(self):
        self.tree.grid(row=1, column=1, sticky="nswe", padx=5, pady=5)
        self.scroll_bar.grid(row=1, column=2, sticky="ns", padx=(0, 5), pady=5)
        self.share_button.grid(row=2, column=1, columnspan=2, sticky="nswe", padx=5, pady=(0, 5))

    def share_strategies(self):
        for strategy in self.strategies_to_share:
            self._client.send_strategy(strategy)
        messagebox.showinfo("Info", "Selected Strategies sent.")

    def update_strategy_tree(self):
        self.tree.delete(*self.tree.get_children(""))
        for strategy in sorted(self._database.keys()):
            self.tree.insert("", tk.END, iid=strategy, text=strategy)

    @property
    def strategies_to_share(self):
        for strategy in self.tree.get_checked():
            yield self._database[strategy]
Exemple #2
0
class TreeviewConstructor(object):
    logger = CustomAdapter(logging.getLogger(str(__name__)), None)

    @debug(lvl=logging.NOTSET, prefix='')
    def __init__(self, master, frame_main, checkwidth=0):
        self.master = master  # Done
        self.frame = frame_main  # Done
        self.col_obj_dict = {}  # Done
        self.column_lst = []  # Done
        self.col_disp_lst = []  # Done
        self.item_obj_dict = {}
        self.treeview = CheckboxTreeview(self.frame)  # Done
        self.ysb = ttk.Scrollbar(self.frame)  # Done
        self.xsb = ttk.Scrollbar(self.frame)  # Done
        self.checkwidth = checkwidth
        self.manager = BusyManager(self.frame)
        self.populate_frame()  # Done

    @debug(lvl=logging.NOTSET, prefix='')
    def populate_frame(self):
        self.frame.columnconfigure(0, weight=1)  # Done
        self.frame.rowconfigure(0, weight=1)  # Done
        self.treeview.grid(row=0, column=0, sticky=tk.NSEW)  # Done
        self.ysb.config(orient=tk.VERTICAL, command=self.treeview.yview)  # Done
        self.xsb.config(orient=tk.HORIZONTAL, command=self.treeview.xview)  # Done
        self.treeview['yscroll'] = self.ysb.set  # Done
        self.treeview['xscroll'] = self.xsb.set  # Done
        self.ysb.grid(row=0, column=1, sticky=tk.NS)  # Done
        self.xsb.grid(row=1, column=0, sticky=tk.EW)  # Done

    @debug(lvl=logging.NOTSET, prefix='')
    def populate_cols(self):
        col_obj = TreeColumn(order=0,
                             col_id='#0',
                             hdr_txt="",
                             anchor=tk.W,
                             stretch=tk.NO,
                             minwidth=0,
                             width=self.checkwidth,
                             display=False)
        TreeviewConstructor.logger.log(logging.NOTSET, "Column ID: {col_id} Header Text: {hdr_txt}".
                                       format(col_id=col_obj.col_id, hdr_txt=col_obj.hdr_txt))
        self.col_obj_dict[col_obj.col_id] = col_obj

        for col_key, column in sorted(self.col_obj_dict.items(), key=lambda x: x[1].order):
            self.column_lst.append(column.col_id)
            if column.display:
                self.col_disp_lst.append(column.col_id)

        self.treeview.config(columns=self.column_lst, displaycolumns=self.col_disp_lst)
        self.treeview.tag_configure('red', foreground='red2')
        self.treeview.tag_configure('evenrow', background='gray85')
        self.treeview.tag_configure('oddrow', background='white')

        for col in self.col_obj_dict.values():
            TreeviewConstructor.logger.log(
                logging.NOTSET,
                "Column ID: {col_id} Header Text: {hdr_txt} Anchor: {anchor}".format(
                    col_id=col.col_id, hdr_txt=col.hdr_txt, anchor=col.anchor))
            if col.hdr_txt in (None, ""):
                header = col.col_id
            else:
                header = col.hdr_txt
            self.treeview.heading(column=col.col_id,
                                  text=header,
                                  anchor=col.anchor,
                                  command=lambda _col=col.col_id: self.treeview_sort_column(_col, False))
            self.treeview.column(col.col_id, minwidth=col.minwidth, width=col.width, stretch=col.stretch)

    @debug(lvl=logging.DEBUG, prefix='')
    def populate_items(self):
        for item in self.item_obj_dict.values():
            TreeRow.logger.log(logging.NOTSET, "Item Info: {0}".format(item.iid))
            self.treeview.insert(item.parent, item.index, iid=item.iid, values=item.values_list)
            for tag in item.tags_list:
                self.treeview.tag_add(item.iid, tag)

    @debug(lvl=logging.DEBUG, prefix='')
    def stripe_rows(self):
        for item in self.item_obj_dict.values():
            self.treeview.tag_del(item.iid, 'evenrow')
            self.treeview.tag_del(item.iid, 'oddrow')
            row_num = self.treeview.index(item.iid)
            if row_num % 2 == 0:
                self.treeview.tag_add(item.iid, 'evenrow')
            elif row_num % 2 != 0:
                self.treeview.tag_add(item.iid, 'oddrow')

    @debug(lvl=logging.DEBUG, prefix='')
    def treeview_sort_column(self, col, reverse):
        self.manager.busy()
        item_list = [(self.treeview.set(k, col), k) for k in self.treeview.get_children('')]
        item_list.sort(reverse=reverse)
        # rearrange items in sorted positions
        for index, (val, k) in enumerate(item_list):
            self.treeview.move(k, '', index)
        self.stripe_rows()
        # reverse sort next time
        self.treeview.heading(col, command=lambda: self.treeview_sort_column(col, not reverse))
        self.manager.not_busy()

    @debug(lvl=logging.DEBUG, prefix='')
    def tv_refresh(self):
        # self.manager.busy()
        item_list = list(self.treeview.get_children(''))
        item_list.sort(key=lambda x: int(x))
        for item_iid, item_obj in sorted(self.item_obj_dict.items()):
            TreeRow.logger.log(logging.NOTSET, "Item ID: {0}".format(item_iid))
            # l = self.treeview.get_children('')
            for index, k in enumerate(item_list):
                TreeRow.logger.log(logging.NOTSET, "k: {0}".format(k))
                if str(item_iid) == str(k):
                    self.treeview.delete(k)
                    item_obj.index = index
                    self.treeview.insert(item_obj.parent, item_obj.index, iid=item_obj.iid, values=item_obj.values_list)
                    item_list.remove(k)
                    break
        self.stripe_rows()
Exemple #3
0
class CompareApp():

    def __init__(self, master, title):
        self.master = master
        self.master.title(title)
        self.pathList = set([])
        self.fileLists = []
        self.groupFiles = {}
        self.InitUI()

    def InitUI(self):
        self.wholeContainer = tk.Frame(self.master)
        self.wholeContainer.pack()

        button_width = 3  ### (1)
        button_padx = "2m"  ### (2)
        button_pady = "1m"  ### (2)
        buttons_frame_padx = "3m"  ### (3)
        buttons_frame_pady = "2m"  ### (3)
        buttons_frame_ipadx = "3m"  ### (3)
        buttons_frame_ipady = "1m"  ### (3)

        self.buttons_frame = tk.Frame(self.wholeContainer, height=10,
                                      width=980)  ###
        self.buttons_frame.pack(
            side=tk.TOP,  ###
            fill=tk.BOTH,
            expand=tk.YES,
            anchor="w",
            ipadx=buttons_frame_ipadx,
            ipady=buttons_frame_ipady,
            padx=buttons_frame_padx,
            pady=buttons_frame_pady,
        )
        self.button1 = tk.Button(self.buttons_frame, command=self.Add)
        self.button1.configure(text="Add")
        self.button1.focus_force()
        self.button1.configure(
            width=button_width,  ### (1)
            padx=button_padx,  ### (2)
            pady=button_pady  ### (2)
        )
        self.button1.pack(side=tk.LEFT)
        self.button2 = tk.Button(self.buttons_frame, command=self.Remove)
        self.button2.configure(text="Remove")
        self.button2.configure(
            width=6,  ### (1)
            padx=button_padx,  ### (2)
            pady=button_pady  ### (2)
        )
        self.button2.pack(side=tk.LEFT)

        self.btnCompare = tk.Button(self.buttons_frame, command=self.compareFiles)
        self.btnCompare.configure(text="Compare Files")
        self.btnCompare.pack(side=tk.LEFT)
        self.btnCompare.bind("<Return>", self.compareFiles)

        self.btnDel = tk.Button(self.buttons_frame, command=self.deleteSelectedFiles)
        self.btnDel.configure(text="Deleted Selected")
        self.btnDel.pack(side=tk.LEFT)
        self.btnCompare.bind("<Return>", self.deleteSelectedFiles)

        # top frame
        self.top_frame = tk.Frame(self.wholeContainer, relief=tk.RIDGE,
                                  height=100,
                                  width=980,padx=10, pady=10)
        self.top_frame.pack(side=tk.TOP,
                            fill=tk.BOTH,
                            expand=tk.YES,
                            )  ###
        # left frame
        self.left_frame = tk.Frame(self.top_frame, relief=tk.RIDGE,
                                  height=100,
                                  width=500, )
        self.left_frame.grid(row=0, column=0, sticky=("nsew"))
        # right frame
        self.right_frame = tk.Frame(self.top_frame, relief=tk.RIDGE,
                                  height=100,
                                  width=100, )
        self.right_frame.grid(row=0, column=1, sticky=("nsew"))
        self.top_frame.columnconfigure(0, weight=1)
        self.top_frame.rowconfigure(0, weight=1)
        self.top_frame.columnconfigure(1, weight=2)
        self.top_frame.rowconfigure(1, weight=2)


        self.boxScroll = tk.Scrollbar(self.left_frame, orient="vertical", command=self.boxScrollFun)
        self.boxScroll.pack(side=tk.RIGHT,fill=tk.BOTH,expand=tk.NO,)
        self.folderBox = tk.Listbox(self.left_frame, selectmode=tk.MULTIPLE, relief=tk.RIDGE,
                                  height=20,
                                  width=10, yscrollcommand=self.boxScroll.set, )
        self.folderBox.pack(side=tk.LEFT,fill=tk.BOTH,expand=tk.YES,)
        #self.boxScroll.pack(side="right", fill="y")

        self.checkScroll = tk.Scrollbar(self.right_frame, orient="vertical", command=self.checkScrollFun)
        self.checkScroll.pack(side=tk.RIGHT,fill=tk.BOTH,expand=tk.NO,)

        self.checkwithfile = CheckboxTreeview(self.right_frame, height=20, yscrollcommand=self.checkScroll.set)
        self.checkwithfile.pack(side=tk.LEFT,fill=tk.BOTH,expand=tk.YES,)

        # bottom frame
        self.bottom_frame = tk.Frame(self.wholeContainer,
                                     relief=tk.RIDGE,
                                     height=20,
                                     width=970,padx=10, pady=10
                                     )  ###
        self.bottom_frame.pack(side=tk.BOTTOM,
                               fill=tk.BOTH,
                               expand=tk.YES,
                               )  ###


        self.output = tkscrolled.ScrolledText(self.bottom_frame, width=970, height=20, wrap='word')
        self.output.config(state=tk.DISABLED)
        self.output.pack(side=tk.LEFT)


    def boxScrollFun(self, *args):
        return self.folderBox.yview

    def checkScrollFun(self, *args):
        return self.checkwithfile.yview

    def Add(self):

        # otherwise ask the user what new file to open
        pathname = filedialog.askdirectory()
        pathname = os.path.abspath(pathname)
        print(pathname)
        if pathname in self.pathList:
            print("folder already exist" + pathname)
            return
        else:
            self.pathList.add(pathname)
            for id, path in enumerate(self.pathList):
                if path == pathname:
                    self.folderBox.insert(id, pathname)
        if os.path.exists(pathname):
            for i in self.checkwithfile.get_children():
                self.checkwithfile.delete(i)
            #self.fileLists = {}
            self.groupFiles = {}
        else:
            print("folder not found:"+pathname)
            return

        allFiles = set(self.fileLists)
        allFiles.update(self.getAllFileListByPath(pathname))
        #print("allFiles:")
        #print(allFiles)
        self.fileLists = list(allFiles)
        #print("converted fileLists:")
        #print(self.fileLists)
        self.renewFileList()

    def renewFileList(self):
        fileList = [0 for i in range(len(self.fileLists))]
        for i in range(len(self.fileLists)):
            if os.path.exists(self.fileLists[i]):
                fileList[i]=(self.fileLists[i], os.path.getsize(self.fileLists[i]))
            else:
                print("remove not exist file:"+self.fileLists[i])
                fileList.pop(i)
        fileList.sort(key=lambda filename: filename[1], reverse=True)
        for i in range(len(fileList)):
            self.fileLists[i] = fileList[i][0]
        print("file list:")
        print(self.fileLists)
        print("file list end")
        self.groupFileListSameSize()
        print("groupFiles:")
        print(self.groupFiles)
        index=0
        for fileSize, fileList in self.groupFiles.items():
            rootIndex = "r_" + str(index)
            sizeCal = str(fileSize)+'b'
            if fileSize > 1024:

                if fileSize > 1024*1024:
                    if fileSize >1024*1024*1024:
                        if fileSize >1024*1024*1024*1024:
                            sizeCal = "{:.3f}".format(float(fileSize) / (1024*1024*1024*1024)) + 'T'
                        else:
                            sizeCal = "{:.3f}".format(float(fileSize) / (1024*1024*1024)) + 'G'
                    else:
                        sizeCal = "{:.3f}".format(float(fileSize) / (1024*1024)) + 'M'
                else:
                    sizeCal = "{:.3f}".format(float(fileSize) / 1024) + 'k'
            fileNum = len(fileList)
            self.checkwithfile.insert('', "end", rootIndex, text=sizeCal+'('+str(fileNum)+')')

            self.checkwithfile.tag_configure("evenrow", background='white', foreground='black')
            self.checkwithfile.tag_configure("oddrow", background='black', foreground='white')
            for i in range(len(fileList)):
                childIndex = "c_"+str(fileSize)+'_i_'+str(i)
                textC = fileList[i]
                print("textC:"+textC)
                self.checkwithfile.insert(rootIndex, "end", childIndex, text=fileList[i])
            index = index+1

    def Remove(self):
        print("selected:")
        for i in self.folderBox.curselection():
            print(i)
            filePath = self.folderBox.get(i)
            print(filePath)
            self.folderBox.delete(i)
            self.pathList.remove(filePath)
        #selected_text_list = [self.folderBox.get(i) for i in self.folderBox.curselection()]
        #print(selected_text_list)
        for i in self.checkwithfile.get_children():
            self.checkwithfile.delete(i)
        # self.fileLists = {}
        self.groupFiles = {}
        if len(self.pathList) > 0:
            allFiles = set([])
            for pathname in self.pathList:
                allFiles.update(self.getAllFileListByPath(pathname))
            self.fileLists = list(allFiles)
            self.renewFileList()

    def getAllFileListByPath(self, pathname):
        fileSet = set([])
        try:
            if os.path.isdir(pathname):
                fileList = os.listdir(pathname)
                print('pathname')
                print(pathname)
                print('filelist:')
                print(fileList)

                for file in fileList:
                    if not file.startswith('.'):
                        fullPath = pathname + os.sep +  file
                        if os.path.exists(fullPath):
                            if os.path.isdir(fullPath):
                                fileSet.update(self.getAllFileListByPath(fullPath))
                            else:
                                fileSet.add(fullPath)
            elif os.path.exists(pathname):
                fileSet.add(pathname)

        except IOError:
            wx.LogError("Cannot open Directoy '%s'." % pathname)
        return fileSet

    def compareFiles(self):
        print("compare")

        for i in self.checkwithfile.get_children():
            self.checkwithfile.delete(i)
        rootIn = 0
        for fileSize, fileList in self.groupFiles.items():
            rootIndex = "r_" + str(rootIn)
            sizeCal = str(fileSize)+'b'
            if fileSize > 1024:

                if fileSize > 1024*1024:
                    if fileSize >1024*1024*1024:
                        if fileSize >1024*1024*1024*1024:
                            sizeCal = "{:.3f}".format(float(fileSize) / (1024*1024*1024*1024)) + 'T'
                        else:
                            sizeCal = "{:.3f}".format(float(fileSize) / (1024*1024*1024)) + 'G'
                    else:
                        sizeCal = "{:.3f}".format(float(fileSize) / (1024*1024)) + 'M'
                else:
                    sizeCal = "{:.3f}".format(float(fileSize) / 1024) + 'k'
            fileNum = len(fileList)
            self.checkwithfile.insert('', "end", rootIndex, text=sizeCal+'('+str(fileNum)+')')


            indexFileGroup = {}
            groupedSameList = self.compareSameSizeFiles(fileList)

            childIn = 0
            for groupIndex in range(len(groupedSameList)):
                #indexFileGroup[child] = fileList[groupIndex]


                textC = fileList[groupIndex]
                print("textC:"+textC)
                self.checkwithfile.tag_configure("evenrow", background='white', foreground='black')
                self.checkwithfile.tag_configure("oddrow", background='black', foreground='white')
                for i in range(len(groupedSameList[groupIndex])):
                    childIndex = "c_" + str(fileSize) + '_i_' + str(childIn)
                    if groupIndex % 2 == 0:
                        self.checkwithfile.insert(rootIndex, "end", childIndex, text=fileList[i], tags=('evenrow',))
                    else:
                        self.checkwithfile.insert(rootIndex, "end", childIndex, text=fileList[i], tags=('oddrow',))
                    if i > 0:
                        self.checkwithfile.change_state(childIndex, 'checked')


                    childIn = childIn + 1

            rootIn = rootIn+1


    def compareSameSizeFiles(self, fileList):
        groupComparedFiles=[]
        groupMap = []
        compareIndex = ""
        groupComparedFiles.append(groupMap)
        for index in range(len(fileList)):
            fileName = fileList[index]
            groupMap = []
            if len(groupComparedFiles) == 1 and len(groupComparedFiles[0]) == 0:
                groupComparedFiles[0].append(fileName)
                continue

            for i in range(len(groupComparedFiles)):
                (groupIndex, fileIndex) = self.getIndexInGroup(groupComparedFiles, fileName)
                if groupIndex == -1:
                    outputStr = "Comparing: " + groupComparedFiles[i][0] + " and " + fileName + "\n"
                    self.output.config(state=tk.NORMAL)
                    self.output.insert("end", outputStr)
                    self.output.see("end")
                    self.output.config(state=tk.DISABLED)
                    if filecmp.cmp(groupComparedFiles[i][0], fileName):
                        groupComparedFiles[i].append(fileName)
                        break
                    else:
                        groupMap.append(fileName)
                        groupComparedFiles.append(groupMap)


        print("groupComparedFiles:")
        print(groupComparedFiles)
        return groupComparedFiles

    def getIndexInGroup(self, groupList, fileName):
        for groupIndex in range(len(groupList)):
            for fileIndex in range(len(groupList[groupIndex])):
                if groupList[groupIndex][fileIndex] == fileName:
                    return (groupIndex, fileIndex)
        return  (-1, -1)

    def groupFileListSameSize(self):

        if (len(self.fileLists)>0):
            fileSize = os.path.getsize(self.fileLists[0])
            groupList = []
            groupList.append(self.fileLists[0])
            for i in range(len(self.fileLists)-1):
                fileNewSize = os.path.getsize(self.fileLists[i+1])
                if(fileSize != fileNewSize):
                    self.groupFiles[fileSize] = groupList
                    fileSize = fileNewSize
                    groupList = []
                groupList.append(self.fileLists[i+1])
            if len(groupList) > 0:
                self.groupFiles[fileSize] = groupList

    def deleteSelectedFiles(self):
        print("enter deleteSelectedFiles")
        for i in self.checkwithfile.get_children():
            orgLen = len(self.checkwithfile.get_children(i))
            newLen = orgLen
            for item in self.checkwithfile.get_children(i):
                if self.checkwithfile.tag_has("checked", item):
                    fileName = self.checkwithfile.item(item)['text']
                    print(fileName)
                    os.chmod(fileName, stat.S_IWUSR)
                    os.remove(fileName)
                    self.checkwithfile.delete(item)
                    newLen -= 1
            if orgLen > newLen:
                text = self.checkwithfile.item(i)['text'].replace("("+str(orgLen)+")", "("+str(newLen)+")")
                self.checkwithfile.item(i, text=text)
class TreeviewConstructor(ttk.Frame):
    logger = CustomAdapter(logging.getLogger(str(__name__)), None)

    @debug(lvl=logging.DEBUG, prefix='')
    def __init__(self, master, *args, **kwargs):
        self.col_obj_dict = {}
        self.column_lst = []
        self.col_disp_lst = []
        self.item_obj_dict = {}
        self.master = master

        # noinspection PyArgumentList
        super().__init__(self.master, *args, **kwargs)

        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        self.treeview = CheckboxTreeview(self)
        TreeviewConstructor.logger.log(logging.DEBUG, "10")
        self.treeview.grid(row=0, column=0, sticky=tk.NSEW)
        TreeviewConstructor.logger.log(logging.DEBUG, "11")

        self.ysb = ttk.Scrollbar(self)
        TreeviewConstructor.logger.log(logging.DEBUG, "12")
        self.ysb.grid(row=0, column=1, sticky=tk.NS)
        TreeviewConstructor.logger.log(logging.DEBUG, "13")
        self.ysb.config(orient=tk.VERTICAL, command=self.treeview.yview)
        TreeviewConstructor.logger.log(logging.DEBUG, "14")

        self.xsb = ttk.Scrollbar(self)
        TreeviewConstructor.logger.log(logging.DEBUG, "15")
        self.xsb.grid(row=1, column=0, sticky=tk.EW)
        TreeviewConstructor.logger.log(logging.DEBUG, "16")
        self.xsb.config(orient=tk.HORIZONTAL, command=self.treeview.xview)
        TreeviewConstructor.logger.log(logging.DEBUG, "17")

        self.treeview['yscroll'] = self.ysb.set
        TreeviewConstructor.logger.log(logging.DEBUG, "18")
        self.treeview['xscroll'] = self.xsb.set
        TreeviewConstructor.logger.log(logging.DEBUG, "19")
        # self.manager = BusyManager(self.frame)

    @debug(lvl=logging.DEBUG, prefix='')
    def populate_cols(self, checkwidth):
        col_obj = TreeColumn(order=0,
                             col_id='#0',
                             hdr_txt="",
                             anchor=tk.W,
                             stretch=tk.NO,
                             minwidth=0,
                             width=checkwidth,
                             display=False)
        TreeviewConstructor.logger.log(
            logging.DEBUG, "Column ID: {col_id} Header Text: {hdr_txt}".format(
                col_id=col_obj.col_id, hdr_txt=col_obj.hdr_txt))
        self.col_obj_dict[col_obj.col_id] = col_obj

        for col_key, column in sorted(self.col_obj_dict.items(),
                                      key=lambda x: x[1].order):
            self.column_lst.append(column.col_id)
            if column.display:
                self.col_disp_lst.append(column.col_id)

        self.treeview.config(columns=self.column_lst,
                             displaycolumns=self.col_disp_lst)
        self.treeview.tag_configure('red',
                                    foreground='red4',
                                    background='IndianRed1')
        self.treeview.tag_configure('parent_evenrow', background='gray85')
        self.treeview.tag_configure('child_evenrow', background="honeydew3")
        self.treeview.tag_configure('parent_oddrow', background='white')
        self.treeview.tag_configure('child_oddrow', background="honeydew2")

        for col in self.col_obj_dict.values():
            TreeviewConstructor.logger.log(
                logging.DEBUG,
                "Column ID: {col_id} Header Text: {hdr_txt} Anchor: {anchor}".
                format(col_id=col.col_id,
                       hdr_txt=col.hdr_txt,
                       anchor=col.anchor))
            if col.hdr_txt in (None, ""):
                header = col.col_id
            else:
                header = col.hdr_txt
            if col.col_id == '#0':
                self.treeview.heading(column=col.col_id,
                                      text="",
                                      anchor=col.anchor,
                                      command=lambda _col=col.col_id: self.
                                      treeview_sort_column(_col, False))
            else:
                self.treeview.heading(column=col.col_id,
                                      text=header,
                                      anchor=col.anchor,
                                      command=lambda _col=col.col_id: self.
                                      treeview_sort_column(_col, False))

            self.treeview.column(col.col_id,
                                 minwidth=col.minwidth,
                                 width=col.width,
                                 stretch=col.stretch)

    @debug(lvl=logging.DEBUG, prefix='')
    def populate_items(self):
        for item in self.item_obj_dict.values():
            TreeviewConstructor.logger.log(logging.NOTSET,
                                           "Item Info: {0}".format(item.iid))
            self.treeview.insert(item.parent,
                                 item.index,
                                 iid=item.iid,
                                 values=item.values_list)
            for tag in item.tags_list:
                self.treeview.tag_add(item.iid, tag)

    @debug(lvl=logging.DEBUG, prefix='')
    def stripe_rows(self):
        for item in self.item_obj_dict.values():
            self.treeview.tag_del(item.iid, 'parent_evenrow')
            self.treeview.tag_del(item.iid, 'child_evenrow')
            self.treeview.tag_del(item.iid, 'parent_oddrow')
            self.treeview.tag_del(item.iid, 'child_oddrow')
            row_num = self.treeview.index(item.iid)
            if row_num % 2 == 0:
                if item.parent == "":
                    self.treeview.tag_add(item.iid, 'child_evenrow')
                else:
                    self.treeview.tag_add(item.iid, 'parent_evenrow')
            elif row_num % 2 != 0:
                if item.parent == "":
                    self.treeview.tag_add(item.iid, 'child_oddrow')
                else:
                    self.treeview.tag_add(item.iid, 'parent_oddrow')

    @debug(lvl=logging.DEBUG, prefix='')
    def treeview_sort_column(self, col, reverse):
        # self.manager.busy()
        item_list = [(self.treeview.set(k, col), k)
                     for k in self.treeview.get_children('')]
        item_list.sort(reverse=reverse)
        # rearrange items in sorted positions
        for index, (val, k) in enumerate(item_list):
            self.treeview.move(k, '', index)
        self.stripe_rows()
        # reverse sort next time
        self.treeview.heading(
            col, command=lambda: self.treeview_sort_column(col, not reverse))
        # self.manager.not_busy()

    @debug(lvl=logging.DEBUG, prefix='')
    def tv_refresh(self):
        # self.manager.busy()
        item_list = list(self.treeview.get_children(''))
        item_list.sort(key=lambda x: int(x))
        for item_iid, item_obj in sorted(self.item_obj_dict.items()):
            TreeviewConstructor.logger.log(logging.DEBUG,
                                           "Item ID: {0}".format(item_iid))
            # l = self.treeview.get_children('')
            for index, k in enumerate(item_list):
                TreeviewConstructor.logger.log(logging.DEBUG,
                                               "k: {0}".format(k))
                if str(item_iid) == str(k):
                    self.treeview.delete(k)
                    item_obj.index = index
                    self.treeview.insert(item_obj.parent,
                                         item_obj.index,
                                         iid=item_obj.iid,
                                         values=item_obj.values_list)
                    item_list.remove(k)
                    break
        self.stripe_rows()
        # self.manager.not_busy()

    @debug(lvl=logging.DEBUG, prefix='')
    def add_column(self,
                   order=None,
                   col_id=None,
                   hdr_txt="",
                   anchor=tk.W,
                   stretch=tk.YES,
                   minwidth=0,
                   width=50,
                   display=True,
                   desc=None):
        col_obj = TreeColumn(order=order,
                             col_id=col_id,
                             hdr_txt=hdr_txt,
                             anchor=anchor,
                             stretch=stretch,
                             minwidth=minwidth,
                             width=width,
                             display=display,
                             desc=desc)
        self.col_obj_dict[col_obj.col_id] = col_obj

    @debug(lvl=logging.NOTSET, prefix='')
    def add_item(self, iid, parent="", index=tk.END, values_dict=None):
        item_obj = TreeRow(treeview_const=self,
                           iid=iid,
                           parent=parent,
                           index=index,
                           values_dict=values_dict)
        self.item_obj_dict[item_obj.iid] = item_obj

    @debug(lvl=logging.DEBUG, prefix='')
    def columns_from_query(self, query, hide_list=None, pref_order=None):
        if pref_order is None:
            pref_order = []
        if hide_list is None:
            hide_list = []

        col_order = 1
        col_order += len(pref_order)
        TreeviewConstructor.logger.log(
            logging.DEBUG,
            "Column Order Starting Value: {0}".format(str(col_order)))

        for desc in query.column_descriptions:
            name = desc.get('name').replace("'", "").replace('"', "")
            TreeviewConstructor.logger.log(logging.DEBUG,
                                           "Column Name: {0}".format(name))
            disp = True
            if name in hide_list:
                disp = False
            cust_order = col_order
            if name in pref_order:
                cust_order = pref_order.index(name) + 1
            self.add_column(order=cust_order,
                            col_id=name.replace(" ", "_"),
                            hdr_txt=name,
                            display=disp,
                            desc=desc)
            if name not in pref_order:
                col_order += 1

    @debug(lvl=logging.DEBUG, prefix='')
    def rows_from_query(self,
                        query,
                        id_col="line_number",
                        limit=None,
                        parent_col=None):
        counter = 1
        for row in query.all():
            temp_dict = {}
            for col_obj in self.col_obj_dict.values():
                # noinspection PyProtectedMember
                value = row._asdict().get(col_obj.hdr_txt)
                if isinstance(value, str):
                    value.replace("{", "").replace("}", "")
                temp_dict[str(col_obj.order)] = value
            counter += 1
            if counter == limit:
                break
            parent = ""
            if parent_col is not None:
                # noinspection PyProtectedMember
                if str(row._asdict().get(id_col)) != str(
                        row._asdict().get(parent_col)):
                    # noinspection PyProtectedMember
                    parent = str(row._asdict().get(parent_col))
            # noinspection PyProtectedMember
            self.add_item(iid=str(row._asdict().get(id_col)),
                          values_dict=temp_dict,
                          parent=parent)

    @debug(lvl=logging.DEBUG, prefix='')
    def populate_query(self,
                       query,
                       hide_list=None,
                       pref_order=None,
                       id_col="line_number",
                       limit=None,
                       checkwidth=0,
                       parent_col=None):
        the_query = query
        self.columns_from_query(the_query, hide_list, pref_order)
        self.populate_cols(checkwidth=checkwidth)
        self.rows_from_query(the_query, id_col, limit, parent_col)
        self.populate_items()
        self.stripe_rows()
class ScriptManager:
    """
    Open the scripts window manager
    """
    folder_icon = None
    def __init__(self, parent):
        """
            parent: the tkinter parent view to use for this window construction.
        """
        self.parent = parent
        self.app = tk.Toplevel(parent)
        self.app.title("Scripts Manager")
        self.app.resizable(True, True)
        self.rvalue = None
        appFrame = ttk.Frame(self.app)
         #PANED PART
        self.paned = tk.PanedWindow(appFrame, height=300)
        #RIGHT PANE : TAble
        self.viewframe = ttk.Frame(self.paned)
        self.file_tree = CheckboxTreeview(self.viewframe)
        self.file_tree['columns'] = ('name', 'category')
        self.file_tree.heading('#0', text='Name')
        self.file_tree.column("#0", stretch=tk.YES, minwidth=300, width=300)
        self.file_tree.heading('#1', text='Category')
        self.file_tree.column("#1", stretch=tk.YES, minwidth=300, width=300)
        self.file_tree.pack(fill=tk.BOTH, expand=True)
        btn_pane = ttk.Frame(self.viewframe)
        self.execute_icone = tk.PhotoImage(file = Utils.getIcon("execute.png"))
        btn_execute = ttk.Button(btn_pane, text="Execute", image=self.execute_icone, command=self.executedSelectedScripts, tooltip="Execute all selected scripts", style="Toolbutton")        
        btn_execute.pack(side=tk.RIGHT, padx=3, pady=5)
        self.open_folder_icone = tk.PhotoImage(file = Utils.getIcon("folder.png"))
        btn_openPathForUser = ttk.Button(btn_pane, text="Execute", image=self.open_folder_icone, command=self.openPathForUser, tooltip="Open scripts folder", style="Toolbutton")        
        btn_openPathForUser.pack(side=tk.RIGHT, padx=3, pady=5)
        
        btn_pane.pack(fill=tk.X, side=tk.BOTTOM, anchor=tk.E)
        #LEFT PANE : Treeview
        self.frameTw = ttk.Frame(self.paned)
        self.treevw = ttk.Treeview(self.frameTw)
        self.treevw.pack()
        scbVSel = ttk.Scrollbar(self.frameTw,
                                orient=tk.VERTICAL,
                                command=self.treevw.yview)
        self.treevw.configure(yscrollcommand=scbVSel.set)
        self.treevw.grid(row=0, column=0, sticky=tk.NSEW)
        scbVSel.grid(row=0, column=1, sticky=tk.NS)
        self.treevw.grid(row=0, column=0, sticky=tk.NSEW)
        scbVSel.grid(row=0, column=1, sticky=tk.NS)
        self.paned.add(self.frameTw)
        self.paned.add(self.viewframe)
        self.paned.pack(fill=tk.BOTH, expand=1)
        self.frameTw.rowconfigure(0, weight=1) # Weight 1 sur un layout grid, sans ça le composant ne changera pas de taille en cas de resize
        self.frameTw.columnconfigure(0, weight=1) # Weight 1 sur un layout grid, sans ça le composant ne changera pas de taille en cas de resize

        appFrame.pack(fill=tk.BOTH, ipady=10, ipadx=10, expand=True)

        self.treevw.bind("<<TreeviewSelect>>", self.onTreeviewSelect)
        try:
            self.app.wait_visibility()
            self.app.focus_force()
            self.app.lift()
        except tk.TclError:
            pass
        self.refreshUI()

    def refreshUI(self):
        for widget in self.treevw.winfo_children():
            widget.destroy()
        script_dir = self.getScriptsDir()
        if self.__class__.folder_icon is None:
            self.__class__.folder_icon = ImageTk.PhotoImage(Image.open(Utils.getIcon("folder.png")))
        parent = self.treevw.insert("", "end", " ", text="Scripts", image=self.__class__.folder_icon, open=True)
        self.treevw.focus(parent)
        self.treevw.selection_set(parent)
        for root, subFolders, files in os.walk(script_dir):
            root_name = root.replace(script_dir, "")
            for folder in subFolders:
                if folder.startswith("__") or folder.endswith("__"):
                    continue
                folder_iid = os.path.join(root_name, folder)
                parent_node = parent if root_name == "" else root_name
                self.treevw.insert(parent_node, "end", folder_iid, text=folder, image=self.__class__.folder_icon)
        self.openScriptFolderView()
        
    def getScriptsDir(self):
        return os.path.join(Utils.getMainDir(), "scripts/")

    def onTreeviewSelect(self, _event=None):
        
        selec = self.treevw.selection()
        if len(selec) == 0:
            return None
        item = selec[0]
        self.openScriptFolderView(str(item))

    def openScriptFolderView(self, script_folder=""):
        full_script_path = os.path.join(self.getScriptsDir(), script_folder.strip())
        script_shown = set()
        self.file_tree.delete(*self.file_tree.get_children())

        for root, _, files in os.walk(full_script_path):
            for file in files:
                filepath = root + '/' + file
                if file.endswith(".py"):
                    script_shown.add(filepath)
        scripts_list = sorted(script_shown)
        script_dir = self.getScriptsDir()
        for script in scripts_list:
            scriptName = os.path.basename(script)
            category_name = os.path.dirname(script.replace(script_dir, ""))
            self.file_tree.insert("", "end", script, text=scriptName, values=(category_name))
        

    def executedSelectedScripts(self):
        for selected in self.file_tree.get_checked():
            self.executeScript(selected)

    def executeScript(self, script_path):
        script_dir = self.getScriptsDir()
        category_name = os.path.dirname(script_path.replace(script_dir, ""))
        script_name = ".".join(os.path.splitext(os.path.basename(script_path))[:-1])
        module = os.path.join("pollenisatorgui/scripts/",category_name, script_name).replace("/", '.')
        imported = importlib.import_module(module)
        success, res = imported.main(APIClient.getInstance())
        if success:
            tk.messagebox.showinfo("Script finished", f"Script {script_name} finished.\n{res}")
        else:
            tk.messagebox.showwarning("Script failed", f"Script {script_name} failed.\n{res}")

    def openPathForUser(self):
        selection = self.treevw.selection()
        if selection:
            folder = os.path.join(self.getScriptsDir(), selection[0])
        else:
            folder = self.getScriptsDir()
        Utils.openPathForUser(folder)