from EtagCircuits import *
from DescriptSketch import *
from SketchIDE import *
from ModifData import *
from AffichData import *
from FindData import *
from Parametres import *
from Zoom import *
from ModeAcquisition import *
import sys
import sqlite3
import shutil
import winsound


class MainAppli(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        ########################################## DECLARATION DES VARIABLES ##########################################
        self.parent = parent
        self.parent.lift()
        self.SX = self.parent.frmwidth
        self.SY = self.parent.frmheight
        self.Nconfig = DeterminAspectRatio()

        self.Init = True
        self.IndexFile = -1
        self.IndexFileFind = -1
        self.ListTitreSketchs = []
        self.ListCircuitSketchs = []
        self.ImgCircuit = []
        self.GoHome = True
        self.SketchIno = False
        self.SerialMonitor = False
        self.AffichSM = False
        self.AffichTab = False
        self.AffichTabSM = False
        self.ModifData = False
        self.AffichData = False
        self.MenuSelected = [False, False, False, False]
        self.FrmDescrip = None
        self.FrmCode = None
        self.FrmDoc = None
        self.FrmINO = None
        self.FrmData = None
        self.FrmDataSketch = None
        self.FrmFindData = None
        self.FrmPara = None
        self.FrmAcqui = None
        self.CircuitZoom = None
        self.DescriptZoom = None
        self.DocZoom = None
        self.CodeZoom = None
        self.AffichDescript = False
        self.AffichCode = False
        self.AffichDoc = False
        self.CheminArduinoProg = "C:/Program Files (x86)/Arduino"
        self.ArduinoPort = ''
        self.PathFileInoToOpen = ''
        self.NameFileINO = ''
        self.imgwsize = 0
        self.imghsize = 0
        self.InfoAction = False
        self.ListInfoAction = ['Ajouter un sketch', "Supprimer le sketch", "Modifier les données du sketch",
                               'Afficher le tableur', 'Mode acquisition']
        self.TooltipAction = None
        self.ListInfoActionV = ['Liste des sketchs', "Code du sketch", "Recherche", "Catégories de sketch",
                                "Modifier les paramètres", "Moniteur série",
                                "Recherche - Liste des sketchs", "Recherche - Code du sketch",
                                "Nouvelle recherche", "Catégories de sketch", "Modifier les paramètres",
                                "Moniteur série"]
        self.TooltipActionV = None
        self.ListRecherch = []
        self.ListTitreRecherch = []
        self.ListCircuitRecherch = []
        self.ActionFind = False
        self.RequeteRecherche = ''
        self.ActionCat = False
        self.ListCat = []
        self.ListSketchsCat = []
        self.ListTitreCat = []
        self.ListCircuitCat = []
        self.SelectCat = False
        self.TypeCat = ""
        self.OtherCircuit = False
        self.ModifPara = False
        self.FrmFindVisible = False
        self.ClicAffichSM = False
        self.ZoomCircuitActif = False
        self.ZoomDescriptActif = False
        self.ZoomCodeActif = False
        self.ZoomDocActif = False
        self.ModeAcquisitionActif = False

        self.ModeControlArduino = False
        self.Nport = []
        self.PortsCOM = list(serial.tools.list_ports.comports())
        for port_numero, description, address in self.PortsCOM:
            self.Nport.append(port_numero)
        if len(self.PortsCOM) > 0:
            self.ModeControlArduino = True
            if len(self.PortsCOM) == 1:
                self.ArduinoPort = self.Nport[0]

        ######################################## OUVERTURE DE LA BASE DE DONNEES #######################################
        self.DataBase = sqlite3.connect("ArdPyLog.sq3")
        self.cur = self.DataBase.cursor()
        self.cur.execute("select titre, circuit, composants, descript, code, doc, categorie from sketchs order by "
                         "titre")
        self.ListSketchs = self.cur.fetchall()

        ######################################## AFFICHAGE FENETRE PRINCIPALE #########################################
        FrmMainFond = Image.open('Media/FrmMain/Fond/Fond.jpg')
        self.RatioFondX = float(self.SX) / float(FrmMainFond.size[0])
        self.RatioFondY = float(self.SY) / float(FrmMainFond.size[1])
        self.RatioFondY2 = float(self.SX) / float(FrmMainFond.size[0])

        self.ImgFrmMain = []
        self.ImgFrmMain = RedimImg(self.SX, self.SY, 'Media/FrmMain/Fond/')
        self.CanvasFrmMain = CanvasApp(self.parent, width=self.SX, height=self.SY)
        self.ImgCanvasFrmMain = self.CanvasFrmMain.create_image(0, 0, anchor=tk.NW, image=self.ImgFrmMain[0])

        SizeFont = int(ConfigResolution(self.Nconfig, 'MT'))
        self.LabelLog = LabelText(self.CanvasFrmMain, 'ArdPyLog - Gestionnaire de sketchs pour Arduino UNO',
                                  '#F7F7F7', font=FontLabel(SizeFont))
        self.CanvasFrmMain.create_window(int(self.SX * 0.02), int(self.SY * 0.009), anchor=tk.NW,
                                         window=self.LabelLog)
        self.LabelTotal = LabelText(self.CanvasFrmMain, '', '#F7F7F7', font=FontLabel(SizeFont))
        self.CanvasFrmMain.create_window(int(self.SX * 0.03), int(self.SY * 0.988), anchor=tk.W,
                                         window=self.LabelTotal)
        self.MAJInfo()

        self.ImgLogo, wsize, hsize, self.Canvaslogo, self.ImgCanvaslogo = CanInWindow(
            'Media/FrmMain/Logo/', self.RatioFondX, self.RatioFondY2, self.CanvasFrmMain, int(self.SX * 0.01),
            int(self.SY * 0.019), 0)

        self.ImgBtnQuit, wsize, hsize, self.CanvasBtnQuit, self.ImgCanvasBtnQuit = CanInWindow(
            'Media/FrmMain/BtnClose/', self.RatioFondX, self.RatioFondY2, self.CanvasFrmMain, int(self.SX * 0.986),
            int(self.SY * 0.016), 0)
        ChangeCursor(self.CanvasBtnQuit)
        self.CanvasBtnQuit.bind('<Motion>',
                                lambda action: self.CanvasBtnQuit.itemconfig(self.ImgCanvasBtnQuit,
                                                                             image=self.ImgBtnQuit[1]))
        self.CanvasBtnQuit.bind('<ButtonRelease-1>', self.quitter)

        self.ListBtnV = []

        self.ImgBtnSketch, wsize, hsize, self.CanvasBtnSketch, self.ImgCanvasBtnSketch = CanInWindow(
            'Media/FrmMain/BtnSketch/', self.RatioFondX, self.RatioFondY2, self.CanvasFrmMain, int(self.SX * 0.014),
            int(self.SY * 0.135), 0)
        ChangeCursor(self.CanvasBtnSketch)
        self.CanvasBtnSketch.bind('<ButtonPress-1>',
                                  lambda action: self.CanvasBtnSketch.itemconfig(self.ImgCanvasBtnSketch,
                                                                                 image=self.ImgBtnSketch[1]))
        self.CanvasBtnSketch.bind('<ButtonRelease-1>', self.AffichEtagSketch)
        self.ListBtnV.append(self.CanvasBtnSketch)

        self.ImgBtnINO, wsize, hsize, self.CanvasBtnINO, self.ImgCanvasBtnINO = CanInWindow(
            'Media/FrmMain/BtnINO/', self.RatioFondX, self.RatioFondY2, self.CanvasFrmMain, int(self.SX * 0.014),
            int(self.SY * 0.295), 0)
        ChangeCursor(self.CanvasBtnINO)
        self.CanvasBtnINO.bind('<ButtonPress-1>',
                               lambda action: self.CanvasBtnINO.itemconfig(self.ImgCanvasBtnINO,
                                                                           image=self.ImgBtnINO[1]))
        self.CanvasBtnINO.bind('<ButtonRelease-1>', self.AffichINO)
        self.ListBtnV.append(self.CanvasBtnINO)

        self.BtnRecherche = BtnAction(self.CanvasFrmMain, int(self.SX * 0.014), int(self.SY * 0.19), self.RatioFondX,
                                      self.RatioFondY2, 'Media/FrmMain/BtnRecherche/')
        self.BtnRecherche.CanvasBtn.bind('<ButtonRelease-1>', self.Recherche)
        self.ListBtnV.append(self.BtnRecherche.CanvasBtn)

        self.BtnCat = BtnAction(self.CanvasFrmMain, int(self.SX * 0.014), int(self.SY * 0.24), self.RatioFondX,
                                self.RatioFondY2, 'Media/FrmMain/BtnCat/')
        self.BtnCat.CanvasBtn.bind('<ButtonRelease-1>', self.AffichCat)
        self.ListBtnV.append(self.BtnCat.CanvasBtn)

        self.BtnPara = BtnAction(self.CanvasFrmMain, int(self.SX * 0.014), int(self.SY * 0.945), self.RatioFondX,
                                 self.RatioFondY2, 'Media/FrmMain/BtnPara/')
        self.BtnPara.CanvasBtn.bind('<ButtonRelease-1>', self.AffichPara)
        self.ListBtnV.append(self.BtnPara.CanvasBtn)

        self.BtnSerie = BtnAction(self.CanvasFrmMain, int(self.SX * 0.014), int(self.SY * 0.35), self.RatioFondX,
                                  self.RatioFondY2, 'Media/FrmMain/BtnSerie/')
        self.BtnSerie.CanvasBtn.bind('<ButtonRelease-1>', self.AffichMoniteurSerie)
        self.ListBtnV.append(self.BtnSerie.CanvasBtn)

        for i in range(len(self.ListBtnV)):
            def GestEvt(_, j=i):
                return self.MotionBtnV(j)

            self.ListBtnV[i].bind('<Motion>', GestEvt)

        self.ListBtn = []
        self.ImgBtnAjout, wsize, hsize, self.CanvasBtnAjout, self.ImgCanvasBtnAjout = CanInWindow(
            'Media/FrmMain/BtnAjout/', self.RatioFondX, self.RatioFondY2, self.CanvasFrmMain, int(self.SX * 0.02),
            int(self.SY * 0.055), 0)
        ChangeCursor(self.CanvasBtnAjout)
        self.CanvasBtnAjout.bind('<ButtonPress-1>',
                                 lambda action: self.CanvasBtnAjout.itemconfig(self.ImgCanvasBtnAjout,
                                                                               image=self.ImgBtnAjout[1]))
        self.CanvasBtnAjout.bind('<ButtonRelease-1>', self.AjoutSketch)
        self.ListBtn.append(self.CanvasBtnAjout)

        self.ImgBtnSupp, wsize, hsize, self.CanvasBtnSupp, self.ImgCanvasBtnSupp = CanInWindow(
            'Media/FrmMain/BtnSupp/', self.RatioFondX, self.RatioFondY2, self.CanvasFrmMain, int(self.SX * 0.05),
            int(self.SY * 0.055), 0)
        ChangeCursor(self.CanvasBtnSupp)
        self.CanvasBtnSupp.bind('<ButtonPress-1>',
                                lambda action: self.CanvasBtnSupp.itemconfig(self.ImgCanvasBtnSupp,
                                                                             image=self.ImgBtnSupp[1]))
        self.CanvasBtnSupp.bind('<ButtonRelease-1>', self.SuppSketch)
        self.ListBtn.append(self.CanvasBtnSupp)

        self.ImgBtnModif, wsize, hsize, self.CanvasBtnModif, self.ImgCanvasBtnModif = CanInWindow(
            'Media/FrmMain/BtnModif/', self.RatioFondX, self.RatioFondY2, self.CanvasFrmMain, int(self.SX * 0.08),
            int(self.SY * 0.055), 0)
        ChangeCursor(self.CanvasBtnModif)
        self.CanvasBtnModif.bind('<ButtonPress-1>',
                                 lambda action: self.CanvasBtnModif.itemconfig(self.ImgCanvasBtnModif,
                                                                               image=self.ImgBtnModif[1]))
        self.CanvasBtnModif.bind('<ButtonRelease-1>', self.ModifDataSketch)
        self.ListBtn.append(self.CanvasBtnModif)

        self.BtnTab = BtnAction(self.CanvasFrmMain, int(self.SX * 0.125), int(self.SY * 0.055), self.RatioFondX,
                                self.RatioFondY2, 'Media/FrmMain/BtnTab/')
        self.BtnTab.CanvasBtn.bind('<ButtonRelease-1>', self.AffichTableur)
        self.ListBtn.append(self.BtnTab.CanvasBtn)

        self.BtnAcqui = BtnAction(self.CanvasFrmMain, int(self.SX * 0.155), int(self.SY * 0.055), self.RatioFondX,
                                  self.RatioFondY2, 'Media/FrmMain/BtnAcqui/')
        self.BtnAcqui.CanvasBtn.bind('<ButtonRelease-1>', self.ModeAcquisition)
        self.ListBtn.append(self.BtnAcqui.CanvasBtn)

        for i in range(len(self.ListBtn)):
            def GestEvt(_, j=i):
                return self.MotionBtn(j)

            self.ListBtn[i].bind('<Motion>', GestEvt)

        self.BtnHome = BtnAction(self.CanvasFrmMain, int(self.SX * 0.166), int(self.SY * 0.092), self.RatioFondX,
                                 self.RatioFondY2, 'Media/FrmMain/BtnMaison/')
        self.BtnHome.CanvasBtn.bind('<ButtonRelease-1>', self.RetourMaison)

        self.AffichInfoActionV(self.ListInfoActionV[0])
        self.CanvasFrmMain.bind('<Motion>', self.MoveOnCanvas)
        self.CanvasFrmMain.bind('<Button-1>', self.ClicOnCanvas)
        self.CanvasFrmMain.pack()

        ####################################### AFFICHAGE PANNEAU LISTE SKETCHS ########################################
        self.CanvasListBox = CanvasApp(self.CanvasFrmMain, bg='white')
        self.CanvasFrmMain.create_window(int(self.SX * 0.0273), int(self.SY * 0.15), anchor=tk.NW,
                                         window=self.CanvasListBox)
        self.ScrollbarListBoxV = tk.Scrollbar(self.CanvasListBox)
        self.ScrollbarListBoxV.pack(side=tk.RIGHT, fill=tk.Y)
        self.ListBoxFichiers = tk.Listbox(self.CanvasListBox, width=int(self.SX * 0.022), height=int(self.SY * 0.05),
                                          activestyle='none')
        self.ListBoxFichiers.config(yscrollcommand=self.ScrollbarListBoxV.set)
        self.ScrollbarListBoxV.config(command=self.ListBoxFichiers.yview)

        self.ScrollbarListBoxH = tk.Scrollbar(self.CanvasListBox, orient=tk.HORIZONTAL)
        self.ScrollbarListBoxH.pack(side=tk.BOTTOM, fill=tk.X)
        self.ListBoxFichiers.config(xscrollcommand=self.ScrollbarListBoxH.set)
        self.ScrollbarListBoxH.config(command=self.ListBoxFichiers.xview)

        self.ListBoxFichiers.bind('<<ListboxSelect>>', self.OnSelectListBoxFichiers)
        self.ListBoxFichiers.pack()

        self.LegendePanneauG = self.CanvasFrmMain.create_text(int(self.SX * 0.007), int(self.SY * 0.093),
                                                              text='Gestion des sketchs', font=FontLabel(10),
                                                              anchor=tk.W)
        self.CanvasFrmMain.addtag_withtag('LegendePanneauG', self.LegendePanneauG)

        self.ChargeListSketch()

        ###################################### AFFICHAGE PANNEAU CIRCUITS SKETCHS ######################################

        self.ImgEtagCircuits, wsize, hsize, self.CanvasEtagCircuits, self.ImgCanvasEtagCircuits = CanInWindow(
            'Media/FrmEtagCircuits/Fond/', self.RatioFondX, self.RatioFondY, self.CanvasFrmMain, int(self.SX * 0.462),
            int(self.SY * 0.527), 1)
        self.DefilCircuit = tk.Scale(self.CanvasEtagCircuits, orient=tk.HORIZONTAL, length=wsize, showvalue=0)
        self.CanvasEtagCircuits.create_window(int(wsize / 2), int(hsize * 0.99), anchor=tk.CENTER,
                                              window=self.DefilCircuit)

        self.defilmax = 0
        self.CalculDefilMax(self.ListTitreSketchs)
        self.DefilCircuit.config(command=self.AffichOtherCircuits)
        self.DefilCircuit.bind('<MouseWheel>', self.MouseWheelDefil)
        self.DefilCircuit.bind('<Motion>', self.MoveOnCanvas)

        self.ChargeCircuitSketch()
        self.NEtagCircuits = 0
        self.EtagereCircuits = FrmEtagCircuits(self.parent, self.NEtagCircuits, self.RatioFondX, self.RatioFondY,
                                               self.ListCircuitSketchs, self.ListTitreSketchs, self)

        ###################################### AFFICHAGE PANNEAU DETAILS SKETCHS ######################################
        self.ImgDetails, self.Dwsize, self.Dhsize, self.CanvasDetails, self.ImgCanvasDetails = CanInWindow(
            'Media/CanvasDetails/Fond/', self.RatioFondX, self.RatioFondY, self.CanvasFrmMain, int(self.SX * 0.875),
            int(self.SY * 0.55), 0)

        self.CanvasDetails.bind('<Motion>', self.MoveOnCanvas)

        self.LabelTitre = LabelText(self.CanvasDetails, '', '#F7F7F7', font=FontLabelTitre(14))
        self.CanvasDetails.create_window(int(self.Dwsize / 2), int(self.Dhsize * 0.010), anchor=tk.CENTER,
                                         window=self.LabelTitre)

        self.ImgMenu, self.Menuwsize, self.Menuhsize, self.CanvasMenu, self.ImgCanvasMenu = CanInWindow(
            'Media/CanvasDetails/BarreMenu/Fond/', self.RatioFondX, self.RatioFondY, self.CanvasFrmMain,
            int(self.SX * 0.8745), int(self.SY * 0.958), 1)

        self.ListCanvasMenu = []
        self.ListImgMenu = []
        self.ListMenu = []

        self.MenuCircuit, wsize, hsize, self.CanvasMenuCircuit, self.ImgMenuCircuit = CanInWindow(
            'Media/CanvasDetails/BarreMenu/Onglets/', self.RatioFondX, self.RatioFondY, self.CanvasMenu,
            int(self.Menuwsize * 0.13), int(self.Menuhsize * 0.5), 3)
        self.ListCanvasMenu.append(self.CanvasMenuCircuit)
        self.ListImgMenu.append(self.ImgMenuCircuit)
        self.ListMenu.append(self.MenuCircuit)

        self.MenuDescript, wsize, hsize, self.CanvasMenuDescript, self.ImgMenuDescript = CanInWindow(
            'Media/CanvasDetails/BarreMenu/Onglets/', self.RatioFondX, self.RatioFondY, self.CanvasMenu,
            int(self.Menuwsize * 0.378), int(self.Menuhsize * 0.5), 3)
        self.ListCanvasMenu.append(self.CanvasMenuDescript)
        self.ListImgMenu.append(self.ImgMenuDescript)
        self.ListMenu.append(self.MenuDescript)

        self.MenuCode, wsize, hsize, self.CanvasMenuCode, self.ImgMenuCode = CanInWindow(
            'Media/CanvasDetails/BarreMenu/Onglets/', self.RatioFondX, self.RatioFondY, self.CanvasMenu,
            int(self.Menuwsize * 0.624), int(self.Menuhsize * 0.5), 3)
        self.ListCanvasMenu.append(self.CanvasMenuCode)
        self.ListImgMenu.append(self.ImgMenuCode)
        self.ListMenu.append(self.MenuCode)

        self.MenuDoc, wsize, hsize, self.CanvasMenuDoc, self.ImgMenuDoc = CanInWindow(
            'Media/CanvasDetails/BarreMenu/Onglets/', self.RatioFondX, self.RatioFondY, self.CanvasMenu,
            int(self.Menuwsize * 0.873), int(self.Menuhsize * 0.5), 3)
        self.ListCanvasMenu.append(self.CanvasMenuDoc)
        self.ListImgMenu.append(self.ImgMenuDoc)
        self.ListMenu.append(self.MenuDoc)

        self.Ongwsize = wsize
        self.Onghsize = hsize

        for i in range(4):
            def GestEvt(evt, j=i):
                return self.MoveOnMenu(evt, j)

            def GestEvt2(evt, j=i):
                return self.ClicOnMenu(evt, j)

            self.ListCanvasMenu[i].bind('<Motion>', GestEvt)
            self.ListCanvasMenu[i].bind('<Button-1>', GestEvt2)

        SizeFont = int(ConfigResolution(self.Nconfig, 'M1'))
        self.LegendCircuit = self.CanvasMenuCircuit.create_text(int(self.Ongwsize * 0.5), int(self.Onghsize * 0.5),
                                                                text='', font=FontLabel(SizeFont), anchor=tk.CENTER)

        self.LegendDescript = self.CanvasMenuDescript.create_text(int(self.Ongwsize * 0.5), int(self.Onghsize * 0.5),
                                                                  text='', font=FontLabel(SizeFont),
                                                                  anchor=tk.CENTER)

        self.LegendCode = self.CanvasMenuCode.create_text(int(self.Ongwsize * 0.5), int(self.Onghsize * 0.5),
                                                          text='', font=FontLabel(SizeFont), anchor=tk.CENTER)

        self.LegendDoc = self.CanvasMenuDoc.create_text(int(self.Ongwsize * 0.5), int(self.Onghsize * 0.5),
                                                        text='', font=FontLabel(SizeFont),
                                                        anchor=tk.CENTER)

        HeightPhotoCircuits = self.Dwsize * 0.95
        PhotoCircuit = Image.open('Media/CanvasDetails/Logo/NoCircuit.jpg')
        WidthPhotoCircuits = HeightPhotoCircuits * float(PhotoCircuit.size[0]) / float(PhotoCircuit.size[1])
        self.RatioImgPhotoCircuitsX = WidthPhotoCircuits / float(PhotoCircuit.size[0])
        self.RatioImgPhotoCircuitsY = HeightPhotoCircuits / float(PhotoCircuit.size[1])

        self.ChargeImgCircuit()

        self.CanvasImgCircuit = CanvasApp(self.CanvasDetails, width=self.imghsize, height=self.imgwsize)
        self.CanvasDetails.create_window(int(self.Dwsize / 2), int(self.Dhsize / 2.1), anchor=tk.CENTER,
                                         window=self.CanvasImgCircuit)
        self.ImgCanvasImgCircuit = self.CanvasImgCircuit.create_image(0, 0, anchor=tk.NW,
                                                                      image=self.ImgCircuit[
                                                                          len(self.ListCircuitSketchs)])
        self.CanvasImgCircuit.bind('<Button-1>', self.ClicOnCanvas)
        self.CanvasImgCircuit.bind('<Double-1>', self.ZoomCircuit)
        ChangeCursor(self.CanvasImgCircuit)

        self.LPDText = 'ArdPyLog - Gestionnaire de sketchs pour Arduino UNO'
        self.LegendePanneauD = self.CanvasFrmMain.create_text(int(self.SX * 0.758), int(self.SY * 0.093),
                                                              text=self.LPDText, font=FontLabel(10),
                                                              anchor=tk.W)
        self.CanvasFrmMain.addtag_withtag('LegendePanneauD', self.LegendePanneauD)

    #################################################### METHODES ####################################################

    def ReInitListSketch(self):
        self.ListSketchs = []
        self.cur.execute("select titre, circuit, composants, descript, code, doc, categorie from sketchs order "
                         "by titre")
        self.ListSketchs = self.cur.fetchall()
        self.MAJInfo()
        self.ListBoxFichiers.delete(0, tk.END)
        self.ChargeListSketch()
        self.ChargeCircuitSketch()
        self.ChargeImgCircuit()
        if not self.SelectCat and not self.ActionFind and not self.ClicAffichSM:
            self.ActionAffichEtagSketch()
        else:
            self.LabelTitre.config(text='')
            self.CanvasImgCircuit.itemconfig(self.ImgCanvasImgCircuit,
                                             image=self.ImgCircuit[len(self.ListCircuitSketchs)])

    def ChargeListSketch(self):
        self.ListTitreSketchs = []
        for i in range(len(self.ListSketchs)):
            self.ListTitreSketchs.append(self.ListSketchs[i][0])
            self.ListBoxFichiers.insert(tk.END, self.ListTitreSketchs[i])

    def ChargeCircuitSketch(self):
        self.ListCircuitSketchs = []
        for i in range(len(self.ListSketchs)):
            if self.ListSketchs[i][1] is not None:
                self.ListCircuitSketchs.append(self.ListSketchs[i][1])
            else:
                self.ListCircuitSketchs.append('Media/CanvasDetails/Logo/NoCircuit.jpg')

    def ChargeImgCircuit(self):
        self.ImgCircuit = []
        for i in range(len(self.ListCircuitSketchs)):
            img = Image.open(self.ListCircuitSketchs[i])
            self.imgwsize = int((float(img.size[0]) * float(self.RatioImgPhotoCircuitsX)))
            self.imghsize = int((float(img.size[1]) * float(self.RatioImgPhotoCircuitsY)))
            img = img.resize((self.imgwsize, self.imghsize), Image.ANTIALIAS)
            img = img.transpose(Image.ROTATE_90)
            self.ImgCircuit.append(ImageTk.PhotoImage(img))
        img = Image.open('Media/CanvasDetails/Logo/LogoArduino.jpg')
        self.imgwsize = int((float(img.size[0]) * float(self.RatioImgPhotoCircuitsX)))
        self.imghsize = int((float(img.size[1]) * float(self.RatioImgPhotoCircuitsY)))
        img = img.resize((self.imgwsize, self.imghsize), Image.ANTIALIAS)
        img = img.transpose(Image.ROTATE_90)
        self.ImgCircuit.append(ImageTk.PhotoImage(img))

    def OnSelectListBoxFichiers(self, evt):
        if not self.AffichTab and not self.AffichSM:
            try:
                w = evt.widget
                self.IndexFile = int(w.curselection()[0])
                if self.ActionFind:
                    self.IndexFileFind = self.ListTitreSketchs.index(self.ListRecherch[self.IndexFile][0])
                if self.SelectCat:
                    self.IndexFileFind = self.ListTitreSketchs.index(self.ListSketchsCat[self.IndexFile][0])
                self.ActionSelectListBoxFichiers()
            except:
                pass
        else:
            self.FrmLift2()
            self.ListBoxFichiers.selection_clear(0, tk.END)
            winsound.PlaySound("*", winsound.SND_ASYNC)
            self.ActionClicOnCanvas()

    def ActionSelectListBoxFichiers(self):
        self.Init = False
        if self.ZoomCircuitActif:
            self.CircuitZoom.destroy()
            self.ZoomCircuitActif = False
            self.ActionClicOnMenu(0)
            self.EtagereCircuits.lift()
        elif self.ZoomDescriptActif:
            self.DescriptZoom.destroy()
            self.ZoomDescriptActif = False
            self.ActionClicOnMenu(0)
            self.EtagereCircuits.lift()
        elif self.ZoomCodeActif:
            self.CodeZoom.destroy()
            self.ZoomCodeActif = False
            self.ActionClicOnMenu(0)
            self.EtagereCircuits.lift()
        elif self.ZoomDocActif:
            self.DocZoom.destroy()
            self.ZoomDocActif = False
            self.ActionClicOnMenu(0)
            self.EtagereCircuits.lift()
        if self.GoHome and not self.ActionCat:
            if self.NEtagCircuits != self.IndexFile // 4:
                self.NEtagCircuits = self.IndexFile // 4

                self.EtagereCircuits.destroy()
                if not self.ActionFind and not self.SelectCat:
                    self.EtagereCircuits = FrmEtagCircuits(self.parent, self.NEtagCircuits, self.RatioFondX,
                                                           self.RatioFondY,
                                                           self.ListCircuitSketchs, self.ListTitreSketchs, self)
                elif not self.SelectCat:
                    self.EtagereCircuits = FrmEtagCircuits(self.parent, self.NEtagCircuits, self.RatioFondX,
                                                           self.RatioFondY,
                                                           self.ListCircuitRecherch, self.ListTitreRecherch, self)
                else:
                    self.EtagereCircuits = FrmEtagCircuits(self.parent, self.NEtagCircuits, self.RatioFondX,
                                                           self.RatioFondY,
                                                           self.ListCircuitCat, self.ListTitreCat, self)
                self.DefilCircuit.set(self.NEtagCircuits)
        elif self.SketchIno and not self.ActionCat:
            self.CloseSM()
            self.FrmINO.destroy()
            if not self.ActionFind and not self.SelectCat:
                self.FrmINO = FrmSketchIDE(self.parent, self.RatioFondX, self.RatioFondY, self.RatioFondY2,
                                           self.IndexFile, self)
            else:
                self.FrmINO = FrmSketchIDE(self.parent, self.RatioFondX, self.RatioFondY, self.RatioFondY2,
                                           self.IndexFileFind, self)

        if not self.ActionCat and not self.AffichTab and not self.AffichSM:
            self.AffichSketch(self.IndexFile)
        elif not self.AffichTab and not self.AffichSM:
            self.TypeCat = self.ListCat[self.IndexFile]
            self.AffichEltCat()

    def AffichSketch(self, j):
        if not self.SketchIno:
            self.EtagereCircuits.SelectCircuits(j)
        self.MAJTitreCircuit(j)
        if not self.ActionFind or len(self.ListRecherch) > 0:
            self.InitMenu()

    def MAJTitreCircuit(self, n):
        if not self.ActionFind and not self.SelectCat:
            self.LabelTitre.config(text=self.ListTitreSketchs[n])
            self.CanvasImgCircuit.itemconfig(self.ImgCanvasImgCircuit, image=self.ImgCircuit[n])
        elif not self.SelectCat:
            if len(self.ListRecherch) > 0:
                self.LabelTitre.config(text=self.ListTitreSketchs[self.ListTitreSketchs.index(self.ListRecherch[n][0])])
                self.CanvasImgCircuit.itemconfig(self.ImgCanvasImgCircuit,
                                                 image=self.ImgCircuit[
                                                     self.ListTitreSketchs.index(self.ListRecherch[n][0])])
            else:
                self.CacheMenu()
                self.Init = True
        else:
            self.LabelTitre.config(text=self.ListTitreSketchs[self.ListTitreSketchs.index(self.ListSketchsCat[n][0])])
            self.CanvasImgCircuit.itemconfig(self.ImgCanvasImgCircuit,
                                             image=self.ImgCircuit[
                                                 self.ListTitreSketchs.index(self.ListSketchsCat[n][0])])

    def AffichOtherCircuits(self, _):
        self.OtherCircuit = False
        if not self.ActionFind and not self.SelectCat:
            if len(self.ListCircuitSketchs) > 4:
                self.OtherCircuit = True
        elif not self.SelectCat:
            if len(self.ListCircuitRecherch) > 4:
                self.OtherCircuit = True
        else:
            if len(self.ListCircuitCat) > 4:
                self.OtherCircuit = True
        if self.OtherCircuit:
            self.NEtagCircuits = self.DefilCircuit.get()
            if self.IndexFile >= 0:
                if not (self.NEtagCircuits * 4 < self.IndexFile <= self.NEtagCircuits * 4 + 3):
                    self.IndexFile = self.NEtagCircuits * 4
                self.ListBoxFichiers.selection_clear(0, tk.END)
                self.ListBoxFichiers.selection_set(self.IndexFile)
                self.MAJTitreCircuit(self.IndexFile)
                self.InitMenu()
            self.EtagereCircuits.destroy()
            if not self.ActionFind and not self.SelectCat:
                self.EtagereCircuits = FrmEtagCircuits(self.parent, self.NEtagCircuits, self.RatioFondX,
                                                       self.RatioFondY, self.ListCircuitSketchs,
                                                       self.ListTitreSketchs, self)
            elif not self.SelectCat:
                self.EtagereCircuits = FrmEtagCircuits(self.parent, self.NEtagCircuits, self.RatioFondX,
                                                       self.RatioFondY, self.ListCircuitRecherch,
                                                       self.ListTitreRecherch, self)
            else:
                self.EtagereCircuits = FrmEtagCircuits(self.parent, self.NEtagCircuits, self.RatioFondX,
                                                       self.RatioFondY, self.ListCircuitCat, self.ListTitreCat, self)

    def MouseWheelDefil(self, event):
        self.OtherCircuit = False
        if not self.ActionFind and not self.SelectCat:
            if len(self.ListCircuitSketchs) > 4:
                self.OtherCircuit = True
        elif not self.SelectCat:
            if len(self.ListCircuitRecherch) > 4:
                self.OtherCircuit = True
        else:
            if len(self.ListCircuitCat) > 4:
                self.OtherCircuit = True
        if self.OtherCircuit:
            if event.delta == -120:
                self.NEtagCircuits = self.NEtagCircuits - 1
                if self.NEtagCircuits < 0:
                    self.NEtagCircuits = 0
            if event.delta == 120:
                self.NEtagCircuits = self.NEtagCircuits + 1
                if self.NEtagCircuits > self.defilmax:
                    self.NEtagCircuits = self.defilmax
            self.DefilCircuit.set(self.NEtagCircuits)

    def MoveOnMenu(self, _, j):
        if self.IndexFile >= 0 and not self.Init:
            self.InitOnglets()
            if not self.MenuSelected[j]:
                self.ListCanvasMenu[j].itemconfig(self.ListImgMenu[j], image=self.ListMenu[j][1])

    def MoveOnCanvas(self, _):
        if not self.Init:
            self.InitOnglets()
        self.CanvasBtnQuit.itemconfig(self.ImgCanvasBtnQuit, image=self.ImgBtnQuit[0])
        if self.InfoAction:
            self.CanvasFrmMain.delete(self.TooltipAction)
            self.InfoAction = False
        if self.GoHome:
            self.MotionBtnV(0)
        if self.SketchIno:
            self.MotionBtnV(1)

    def ClicOnCanvas(self, _):
        self.ActionClicOnCanvas()

    def ActionClicOnCanvas(self):
        if self.GoHome:
            if self.AffichTab and not self.AffichTabSM:
                self.FrmINO.FrmSerialMonitor.FrmTableur.lift()
                self.LiftTab()
            elif self.AffichSM:
                if self.FrmINO.FrmSerialMonitor.AffichTab:
                    self.FrmINO.FrmSerialMonitor.FrmTableur.lift()
                    self.FrmINO.FrmSerialMonitor.FrmTableur.ArdData.lift()
                    self.LiftTab()
                else:
                    self.FrmINO.FrmSerialMonitor.lift()
            elif self.ModeAcquisitionActif:
                self.FrmAcqui.lift()
                if self.FrmAcqui.TableurAcqui is not None:
                    self.FrmAcqui.TableurAcqui.lift()
                if self.FrmAcqui.ParaAcqui is not None:
                    self.FrmAcqui.ParaAcqui.lift()
            else:
                self.EtagereCircuits.lift(self.parent)
        if self.SketchIno:
            if self.SerialMonitor:
                self.FrmINO.FrmSerialMonitor.lift(self.parent)
                if self.AffichTabSM:
                    self.FrmINO.FrmSerialMonitor.FrmTableur.lift()
                    self.FrmINO.FrmSerialMonitor.FrmTableur.ArdData.lift()
                    self.LiftTab()
            else:
                self.FrmINO.lift(self.parent)

    def LiftTab(self):
        if self.FrmINO.FrmSerialMonitor.FrmTableur.ParaTab:
            self.FrmINO.FrmSerialMonitor.FrmTableur.Tableur.ParaTab.lift()
        if self.FrmINO.FrmSerialMonitor.FrmTableur.GraphAffich:
            self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.lift()
            if not self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.ModelShow:
                if not self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.TabShow:
                    self.FrmINO.FrmSerialMonitor.FrmTableur.ParaGraph.lift()
                else:
                    self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.TableurGraph.lift()
            else:
                self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.ModelGraph.lift()
                if self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.ModelGraph.ModelResult is not None:
                    self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.ModelGraph.ModelResult.lift()

    def ClicOnMenu(self, _, j):
        self.ActionClicOnMenu(j)

    def ActionClicOnMenu(self, j):
        if self.GoHome:
            self.EtagereCircuits.lift(self.parent)
        elif self.SketchIno:
            if self.SerialMonitor:
                self.FrmINO.FrmSerialMonitor.lift(self.parent)
            else:
                self.FrmINO.lift(self.parent)
        if self.IndexFile >= 0:
            self.InitOnglets2()
            self.ListCanvasMenu[j].itemconfig(self.ListImgMenu[j], image=self.ListMenu[j][2])
            self.MenuSelected[j] = True

            if j == 0:
                if self.AffichDescript:
                    self.FrmDescrip.destroy()
                    self.AffichDescript = False
                if self.AffichCode:
                    self.FrmCode.destroy()
                    self.AffichCode = False
                if self.AffichDoc:
                    self.FrmDoc.destroy()
                    self.AffichDoc = False

            if j == 1 and not self.AffichDescript:
                if not self.ActionFind and not self.SelectCat:
                    self.FrmDescrip = FrmDescriptSketch(self.parent, self.ListTitreSketchs[self.IndexFile],
                                                        self.RatioFondX, self.RatioFondY, self.IndexFile, self)
                else:
                    self.FrmDescrip = FrmDescriptSketch(self.parent, self.ListTitreSketchs[self.IndexFileFind],
                                                        self.RatioFondX, self.RatioFondY, self.IndexFileFind, self)
                self.AffichDescript = True
                if self.AffichCode:
                    self.FrmCode.destroy()
                    self.AffichCode = False
                if self.AffichDoc:
                    self.FrmDoc.destroy()
                    self.AffichDoc = False

            if j == 2 and not self.AffichCode:
                if not self.ActionFind and not self.SelectCat:
                    self.FrmCode = FrmCodeSketch(self.parent, self.ListTitreSketchs[self.IndexFile],
                                                 self.RatioFondX, self.RatioFondY, self.IndexFile, self)
                else:
                    self.FrmCode = FrmCodeSketch(self.parent, self.ListTitreSketchs[self.IndexFileFind],
                                                 self.RatioFondX, self.RatioFondY, self.IndexFileFind, self)
                self.AffichCode = True
                if self.AffichDescript:
                    self.FrmDescrip.destroy()
                    self.AffichDescript = False
                if self.AffichDoc:
                    self.FrmDoc.destroy()
                    self.AffichDoc = False

            if j == 3 and not self.AffichDoc:
                if not self.ActionFind and not self.SelectCat:
                    self.FrmDoc = FrmDocSketch(self.parent, self.RatioFondX, self.RatioFondY, self.RatioFondY2,
                                               self.IndexFile, self)
                else:
                    self.FrmDoc = FrmDocSketch(self.parent, self.RatioFondX, self.RatioFondY, self.RatioFondY2,
                                               self.IndexFileFind, self)
                self.AffichDoc = True
                if self.AffichDescript:
                    self.FrmDescrip.destroy()
                    self.AffichDescript = False
                if self.AffichCode:
                    self.FrmCode.destroy()
                    self.AffichCode = False

    def InitOnglets(self):
        if self.IndexFile >= 0:
            for i in range(4):
                if not self.MenuSelected[i]:
                    self.ListCanvasMenu[i].itemconfig(self.ListImgMenu[i], image=self.ListMenu[i][0])

    def InitOnglets2(self):
        if self.IndexFile >= 0:
            for i in range(4):
                ChangeCursor(self.ListCanvasMenu[i])
                self.MenuSelected[i] = False
                self.ListCanvasMenu[i].itemconfig(self.ListImgMenu[i], image=self.ListMenu[i][0])
            self.LPDText = 'Détails du sketch'
            self.CanvasFrmMain.itemconfigure('LegendePanneauD', text=self.LPDText)

    def AffichLegendMenu(self):
        self.EffaceLegend()
        SizeFont = int(ConfigResolution(self.Nconfig, 'M1'))
        self.LegendCircuit = self.CanvasMenuCircuit.create_text(int(self.Ongwsize * 0.5), int(self.Onghsize * 0.5),
                                                                text='Circuit', font=FontLabel(SizeFont),
                                                                anchor=tk.CENTER)

        self.LegendDescript = self.CanvasMenuDescript.create_text(int(self.Ongwsize * 0.5), int(self.Onghsize * 0.5),
                                                                  text='Descriptif', font=FontLabel(SizeFont),
                                                                  anchor=tk.CENTER)

        self.LegendCode = self.CanvasMenuCode.create_text(int(self.Ongwsize * 0.5), int(self.Onghsize * 0.5),
                                                          text='Code', font=FontLabel(SizeFont), anchor=tk.CENTER)

        self.LegendDoc = self.CanvasMenuDoc.create_text(int(self.Ongwsize * 0.5), int(self.Onghsize * 0.5),
                                                        text='Documentation', font=FontLabel(SizeFont-1),
                                                        anchor=tk.CENTER)

    def EffaceLegend(self):
        self.CanvasMenuCircuit.delete(self.LegendCircuit)
        self.CanvasMenuDescript.delete(self.LegendDescript)
        self.CanvasMenuCode.delete(self.LegendCode)
        self.CanvasMenuDoc.delete(self.LegendDoc)

    def InitMenu(self):
        self.AffichLegendMenu()
        self.InitOnglets2()
        if self.AffichDescript:
            self.FrmDescrip.destroy()
            self.AffichDescript = False
        if self.AffichCode:
            self.FrmCode.destroy()
            self.AffichCode = False
        if self.AffichDoc:
            self.FrmDoc.destroy()
            self.AffichDoc = False
        self.ListCanvasMenu[0].itemconfig(self.ListImgMenu[0], image=self.ListMenu[0][2])
        self.MenuSelected[0] = True

    def AffichEtagSketch(self, _):
        self.CanvasBtnSketch.itemconfig(self.ImgCanvasBtnSketch, image=self.ImgBtnSketch[0])
        if not self.ActionCat and not self.ModifPara and not self.AffichTab and not self.AffichSM:
            self.CanvasEtagCircuits.itemconfig(self.ImgCanvasEtagCircuits, image=self.ImgEtagCircuits[1])
            OldIndexFile = self.IndexFile
            if self.FrmFindVisible:
                self.EffaceInfo()
                self.FrmFindVisible = False
                self.ActionFind = False
                self.MotionBtnV(0)
                self.ChargeListSketch()
                self.Init = False
                self.GoHome = False
            if not self.GoHome or self.ZoomCircuitActif or self.ZoomDescriptActif or self.ZoomDocActif or \
                    self.ZoomCodeActif:
                self.AnnulZoom()
                self.ActionAffichEtagSketch()
                if OldIndexFile > -1:
                    self.IndexFile = OldIndexFile
                    self.ActionSelectListBoxFichiers()
                    self.ListBoxFichiers.selection_set(self.IndexFile)
            else:
                winsound.PlaySound("*", winsound.SND_ASYNC)
        else:
            self.FrmLift2()
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def ActionAffichEtagSketch(self):
        if not self.Init:
            if self.GoHome:
                self.EtagereCircuits.destroy()
                self.GoHome = False
            if self.SketchIno:
                self.CloseSM()
                self.FrmINO.destroy()
                self.SketchIno = False
            self.NEtagCircuits = 0
            self.IndexFile = -1
            self.ListBoxFichiers.selection_clear(0, tk.END)
            self.LabelTitre.config(text='')
            self.CanvasImgCircuit.itemconfig(self.ImgCanvasImgCircuit,
                                             image=self.ImgCircuit[len(self.ListCircuitSketchs)])
            if not self.ActionFind and not self.SelectCat:
                self.CalculDefilMax(self.ListTitreSketchs)
                self.EtagereCircuits = FrmEtagCircuits(self.parent, self.NEtagCircuits, self.RatioFondX,
                                                       self.RatioFondY, self.ListCircuitSketchs, self.ListTitreSketchs,
                                                       self)
            elif not self.SelectCat:
                self.CalculDefilMax(self.ListTitreRecherch)
                self.EtagereCircuits = FrmEtagCircuits(self.parent, self.NEtagCircuits, self.RatioFondX,
                                                       self.RatioFondY, self.ListCircuitRecherch,
                                                       self.ListTitreRecherch,
                                                       self)
            else:
                self.CalculDefilMax(self.ListTitreCat)
                self.EtagereCircuits = FrmEtagCircuits(self.parent, self.NEtagCircuits, self.RatioFondX,
                                                       self.RatioFondY, self.ListCircuitCat, self.ListTitreCat, self)
            self.DefilCircuit.set(self.NEtagCircuits)
            self.InitOnglets2()
            self.GoHome = True
            self.Init = True
        else:
            self.FrmLift2()
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def AffichINO(self, _):
        self.CanvasBtnINO.itemconfig(self.ImgCanvasBtnINO, image=self.ImgBtnINO[0])
        self.ActionAffichIno()

    def ActionAffichIno(self):
        if not self.SketchIno and not self.ActionCat and not self.ModifPara \
                and not self.AffichTab and not self.AffichSM:
            self.CanvasEtagCircuits.itemconfig(self.ImgCanvasEtagCircuits, image=self.ImgEtagCircuits[0])
            self.AnnulZoom()
            if self.FrmFindVisible:
                self.FrmFindVisible = False
                self.ActionFind = False
                self.MotionBtnV(1)
                self.ChargeListSketch()
            self.EtagereCircuits.destroy()
            if not self.ActionFind and not self.SelectCat:
                self.FrmINO = FrmSketchIDE(self.parent, self.RatioFondX, self.RatioFondY, self.RatioFondY2,
                                           self.IndexFile, self)
            else:
                self.FrmINO = FrmSketchIDE(self.parent, self.RatioFondX, self.RatioFondY, self.RatioFondY2,
                                           self.IndexFileFind, self)
            self.GoHome = False
            self.SketchIno = True
            self.Init = False

        elif not self.ActionCat and not self.ModifPara and not self.FrmFindVisible and not self.AffichTab \
                and not self.AffichSM:
            if self.SerialMonitor:
                self.FrmINO.FrmSerialMonitor.lift(self.parent)
            else:
                self.FrmINO.lift(self.parent)
        else:
            self.FrmLift2()
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def CloseSM(self):
        if self.SerialMonitor:
            if self.FrmINO.FrmSerialMonitor.USBConnect:
                self.FrmINO.FrmSerialMonitor.SerialThread.stop()
                self.FrmINO.FrmSerialMonitor.ConnectSerial.close()
            self.FrmINO.FrmSerialMonitor.destroy()
            self.SerialMonitor = False

    def AjoutSketch(self, _):
        self.CanvasBtnAjout.itemconfig(self.ImgCanvasBtnAjout, image=self.ImgBtnAjout[0])
        if not self.ModifData and not self.ModifPara and not self.ActionCat and not self.FrmFindVisible \
                and not self.AffichTab and not self.AffichSM:
            self.CanvasEtagCircuits.itemconfig(self.ImgCanvasEtagCircuits, image=self.ImgEtagCircuits[0])
            self.AnnulZoom()
            self.ActionClicOnMenu(0)
            self.CanvasFrmMain.delete(self.TooltipAction)
            self.PathFileInoToOpen = ''
            self.PathFileInoToOpen = tkfiledialog.askopenfilename(title="Ouvrir un fichier",
                                                                  filetypes=[('INO files', '.ino')])
            if self.PathFileInoToOpen != '':
                self.NameFileINO = ExtractNameFile(self.PathFileInoToOpen)
                self.cur.execute("Select * from sketchs where Titre = '" +
                                 self.NameFileINO[0:len(self.NameFileINO) - 4] + "'")
                Rep = True
                NOcur = len(self.cur.fetchall())
                if NOcur > 0:
                    Rep = tkMB.askyesno('Attention', 'Un sketch nommé "' + self.NameFileINO[0:len(self.NameFileINO) - 4]
                                        + '" est déja présent dans la base de données, souhaitez-vous mettre à jour '
                                          'les données?')
                if Rep:
                    if NOcur > 0:
                        SQLRequet = "DELETE FROM Sketchs WHERE titre='" \
                                    + self.NameFileINO[0:len(self.NameFileINO) - 4] + "'"
                        self.cur.execute(SQLRequet)
                        self.DataBase.commit()
                    PathDirInoToSave = "Sketchs/Codes/" + self.NameFileINO[0:len(self.NameFileINO) - 4] + '/'
                    os.makedirs(PathDirInoToSave, exist_ok=True)
                    shutil.copy(self.PathFileInoToOpen, PathDirInoToSave + self.NameFileINO)
                    data = [(self.NameFileINO[0:len(self.NameFileINO) - 4], PathDirInoToSave + self.NameFileINO)]
                    self.cur.execute("INSERT INTO sketchs(titre,code) VALUES(?,?)", data[0])
                    self.DataBase.commit()
                    if not self.ActionFind and not self.SelectCat:
                        self.Init = False
                        self.ReInitListSketch()
                    else:
                        self.ActionRetourMaison()
                        self.Init = False
                    self.IndexFile = self.ListTitreSketchs.index(self.NameFileINO[0:len(self.NameFileINO) - 4])
                    self.ListBoxFichiers.selection_clear(0, tk.END)
                    self.ListBoxFichiers.selection_set(self.IndexFile)
                    self.ActionSelectListBoxFichiers()
                    self.AffichInfoActionV(self.ListInfoActionV[0])
            self.FrmLift()
            self.CanvasEtagCircuits.itemconfig(self.ImgCanvasEtagCircuits, image=self.ImgEtagCircuits[1])
        else:
            self.FrmLift2()
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def SuppSketch(self, _):
        self.CanvasBtnSupp.itemconfig(self.ImgCanvasBtnSupp, image=self.ImgBtnSupp[0])
        if self.IndexFile >= 0 and not self.ModifData and not self.ActionCat and not self.ModifPara \
                and not self.FrmFindVisible and not self.AffichTab and not self.AffichSM:
            self.CanvasEtagCircuits.itemconfig(self.ImgCanvasEtagCircuits, image=self.ImgEtagCircuits[0])
            self.CanvasFrmMain.delete(self.TooltipAction)
            self.AnnulZoom()
            self.ActionClicOnMenu(0)
            if not self.ActionFind and not self.SelectCat:
                IndexFile = self.IndexFile
            else:
                IndexFile = self.IndexFileFind
            Rep = tkMB.askyesno('Supprimer un sketch', 'Etes vous sûr de vouloir supprimer le sketch "' +
                                self.ListSketchs[IndexFile][0] + '" ?')
            if Rep:
                SQLRequet = "DELETE FROM Sketchs WHERE titre='" + self.ListSketchs[IndexFile][0] + "'"
                self.cur.execute(SQLRequet)
                for i in range(1, 6):
                    if self.ListSketchs[IndexFile][i] is not None:
                        if i != 4:
                            os.remove(self.ListSketchs[IndexFile][i])
                        else:
                            self.NameFileINO = ExtractNameFile(self.ListSketchs[IndexFile][4])
                            PathDirInoToSupp = "Sketchs/Codes/" + self.NameFileINO[0:len(self.NameFileINO) - 4] + '/'
                            shutil.rmtree(PathDirInoToSupp)
                self.DataBase.commit()
                self.ReInitListSketch()
                if not self.SelectCat and not self.ActionFind:
                    self.ActionRetourMaison()
                elif not self.ActionFind:
                    self.AffichEltCat()
                else:
                    self.ListBoxFichiers.delete(0, tk.END)
                    self.RequeteRecherche = self.FrmFindData.DataFind.get()
                    self.ActionRecherche()
            self.FrmLift()
            self.CanvasEtagCircuits.itemconfig(self.ImgCanvasEtagCircuits, image=self.ImgEtagCircuits[1])
        else:
            self.FrmLift2()
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def ModifDataSketch(self, _):
        self.CanvasBtnModif.itemconfig(self.ImgCanvasBtnModif, image=self.ImgBtnModif[0])
        self.ActionModifDataSketch()

    def ActionModifDataSketch(self):
        if self.IndexFile >= 0 and not self.ActionCat and not self.ModifPara and not self.FrmFindVisible \
                and not self.AffichTab and not self.AffichSM:
            self.CanvasEtagCircuits.itemconfig(self.ImgCanvasEtagCircuits, image=self.ImgEtagCircuits[0])
            self.CanvasFrmMain.delete(self.TooltipAction)
            self.EffaceInfo()
            self.AnnulZoom()
            self.ActionClicOnMenu(0)
            if not self.ActionFind and not self.SelectCat:
                self.FrmData = FrmModifData(self.parent, self.RatioFondX, self.RatioFondY, self.RatioFondY2,
                                            self.IndexFile, self)
            else:
                self.FrmData = FrmModifData(self.parent, self.RatioFondX, self.RatioFondY, self.RatioFondY2,
                                            self.IndexFileFind, self)
            if self.GoHome:
                self.EtagereCircuits.lower(self.parent)
            elif self.SketchIno:
                self.FrmINO.lower(self.parent)
            self.FrmData.lift(self.parent)
            if self.AffichDescript:
                self.FrmDescrip.lower(self.parent)
            if self.AffichCode:
                self.FrmCode.lower(self.parent)
            if self.AffichDoc:
                self.FrmDoc.lower(self.parent)
        else:
            self.FrmLift2()
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def AffichDataSketch(self):
        if self.IndexFile >= 0 and not self.ActionCat and not self.ModifPara and not self.FrmFindVisible \
                and not self.AffichTab and not self.AffichSM:
            self.CanvasFrmMain.delete(self.TooltipAction)
            self.AffichData = True
            self.EffaceInfo()
            if not self.ActionFind and not self.SelectCat:
                self.FrmDataSketch = FrmAffichData(self.parent, self.RatioFondX, self.RatioFondY, self.RatioFondY2,
                                                   self.IndexFile, self)
            else:
                self.FrmDataSketch = FrmAffichData(self.parent, self.RatioFondX, self.RatioFondY, self.RatioFondY2,
                                                   self.IndexFileFind, self)
            if self.GoHome:
                self.EtagereCircuits.lower(self.parent)
            elif self.SketchIno:
                self.FrmINO.lower(self.parent)
            self.FrmDataSketch.lift(self.parent)
            if self.AffichDescript:
                self.FrmDescrip.lower(self.parent)
            if self.AffichCode:
                self.FrmCode.lower(self.parent)
            if self.AffichDoc:
                self.FrmDoc.lower(self.parent)
        else:
            self.FrmLift2()
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def FrmLift(self):
        if self.GoHome and not self.SketchIno:
            self.EtagereCircuits.lift()
            if self.ModifData:
                self.FrmData.destroy()
                self.parent.lift()
                self.EtagereCircuits.lift()
        elif self.SketchIno:
            if self.SerialMonitor:
                self.FrmINO.FrmSerialMonitor.lift()
            else:
                self.FrmINO.lift()

    def FrmLift2(self):
        if self.AffichSM:
            if self.FrmINO.FrmSerialMonitor.AffichTab:
                self.FrmINO.FrmSerialMonitor.FrmTableur.lift()
                if self.FrmINO.FrmSerialMonitor.FrmTableur.GraphAffich:
                    self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.lift()
                    if not self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.ModelShow:
                        if self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.TableurGraph is None:
                            self.FrmINO.FrmSerialMonitor.FrmTableur.ParaGraph.lift()
                        else:
                            self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.TableurGraph.lift()
                    else:
                        self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.ModelGraph.lift()
                        if self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.ModelGraph.ModelResult is not None:
                            self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.ModelGraph.ModelResult.lift()
                else:
                    self.FrmINO.FrmSerialMonitor.FrmTableur.lift()
                    self.FrmINO.FrmSerialMonitor.FrmTableur.ArdData.lift()
                    if self.FrmINO.FrmSerialMonitor.FrmTableur.ParaTab:
                        self.FrmINO.FrmSerialMonitor.FrmTableur.Tableur.ParaTab.lift()
            else:
                self.FrmINO.FrmSerialMonitor.lift()
        elif self.AffichTab:
            if self.FrmINO.FrmSerialMonitor.FrmTableur.ParaTab:
                self.FrmINO.FrmSerialMonitor.FrmTableur.Tableur.ParaTab.lift()
            if self.FrmINO.FrmSerialMonitor.FrmTableur.GraphAffich:
                self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.lift()
                if not self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.ModelShow:
                    if self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.TableurGraph is None:
                        self.FrmINO.FrmSerialMonitor.FrmTableur.ParaGraph.lift()
                    else:
                        self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.TableurGraph.lift()
                else:
                    self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.ModelGraph.lift()
                    if self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.ModelGraph.ModelResult is not None:
                        self.FrmINO.FrmSerialMonitor.FrmTableur.Graph.ModelGraph.ModelResult.lift()
            elif self.AffichTabSM:
                self.FrmINO.FrmSerialMonitor.FrmTableur.lift()
                self.FrmINO.FrmSerialMonitor.FrmTableur.ArdData.lift()

    def MotionBtn(self, i):
        self.AffichInfoAction(self.ListInfoAction[i])

    def AffichInfoAction(self, Action):
        if self.InfoAction:
            self.CanvasFrmMain.delete(self.TooltipAction)
            self.InfoAction = False

        self.TooltipAction = self.CanvasFrmMain.create_text(int(self.SX * 0.18),
                                                            int(self.SY * 0.055), anchor=tk.W, text=Action,
                                                            fill='black', font=FontLabel(10))
        self.InfoAction = True

    def MotionBtnV(self, i):
        if not self.ActionFind and not self.SelectCat and not self.ActionCat:
            self.AffichInfoActionV(self.ListInfoActionV[i])
        elif not self.SelectCat and not self.ActionCat:
            self.AffichInfoActionV(self.ListInfoActionV[i + 6])
        else:
            if self.ActionCat:
                self.AffichInfoActionV(self.ListInfoActionV[9])
            elif i < 2:
                self.AffichInfoActionV(self.TypeCat)
            else:
                self.AffichInfoActionV(self.ListInfoActionV[i])

    def AffichInfoActionV(self, Action):
        self.CanvasFrmMain.delete(self.TooltipActionV)
        self.TooltipActionV = self.CanvasFrmMain.create_text(int(self.SX * 0.03),
                                                             int(self.SY * 0.128), anchor=tk.W, text=Action,
                                                             fill='black', font=FontLabel2(10))

    def Recherche(self, _):
        self.BtnRecherche.CanvasBtn.itemconfig(self.BtnRecherche.ImgCanvasBtn, image=self.BtnRecherche.ImgBtn[0])
        if not self.ModifPara and not self.ActionCat and not self.AffichTab and not self.AffichSM:
            if self.ActionFind or self.SelectCat:
                self.EffaceInfo()
            self.ActionRetourMaison()
            self.SelectCat = False
            self.ActionFind = True
            self.FrmLift()
            self.ListBoxFichiers.delete(0, tk.END)
            self.FrmFindData = FrmFindData(self.parent, self.RatioFondX, self.RatioFondY, self.RatioFondY2, self)
            self.FrmFindVisible = True
        else:
            self.FrmLift2()
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def ActionRecherche(self):
        if self.RequeteRecherche != '':
            ch = self.RequeteRecherche
            self.cur.execute('SELECT titre, '
                             'circuit FROM Sketchs WHERE titre LIKE \'%' + ch + '%\'or categorie '
                                                                                'LIKE ''\'%' + ch + '%\' '
                                                                                                    'order by titre')
            self.ListRecherch = self.cur.fetchall()

            self.ListTitreRecherch = []
            self.ListCircuitRecherch = []
            for i in range(len(self.ListRecherch)):
                self.ListTitreRecherch.append(self.ListRecherch[i][0])
                self.ListCircuitRecherch.append(self.ListRecherch[i][1])
                self.ListBoxFichiers.insert(tk.END, self.ListTitreRecherch[i])
            self.Init = False
            self.ActionAffichEtagSketch()
            if len(self.ListTitreRecherch) > 0:
                self.IndexFile = 0
                self.IndexFileFind = self.ListTitreSketchs.index(self.ListRecherch[self.IndexFile][0])
                self.ActionSelectListBoxFichiers()
                self.ListBoxFichiers.selection_set(0)
            self.MAJInfo()
            self.FrmFindData.destroy()
            self.FrmFindVisible = False
            self.FrmLift()

    def AffichCat(self, _):
        self.BtnCat.CanvasBtn.itemconfig(self.BtnCat.ImgCanvasBtn, image=self.BtnCat.ImgBtn[0])
        if not self.ModifPara and not self.AffichTab and not self.AffichSM:
            self.AnnulZoom()
            self.ActionFind = False
            self.SelectCat = False
            self.FrmFindVisible = False
            self.ActionCat = True
            self.FrmLift()
            self.ListCat = []
            for i in range(len(self.ListSketchs)):
                cat = self.ListSketchs[i][6]
                if cat not in self.ListCat and cat != '':
                    self.ListCat.append(cat)
            self.ListBoxFichiers.delete(0, tk.END)
            self.ListCat.sort()
            for i in range(len(self.ListCat)):
                self.ListBoxFichiers.insert(tk.END, self.ListCat[i])
            self.MAJInfo()
        else:
            self.FrmLift2()
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def AffichEltCat(self):
        self.ListSketchsCat = []
        self.cur.execute("SELECT titre, circuit FROM Sketchs WHERE categorie='" + self.TypeCat + "' order by titre")
        self.ListSketchsCat = self.cur.fetchall()
        if len(self.ListSketchsCat) > 0:
            self.ListBoxFichiers.delete(0, tk.END)
            self.ListTitreCat = []
            self.ListCircuitCat = []
            for i in range(len(self.ListSketchsCat)):
                self.ListTitreCat.append(self.ListSketchsCat[i][0])
                self.ListCircuitCat.append(self.ListSketchsCat[i][1])
                self.ListBoxFichiers.insert(tk.END, self.ListTitreCat[i])
            self.ActionCat = False
            self.SelectCat = True
            self.AffichInfoActionV(self.TypeCat)
            self.ActionAffichEtagSketch()
            self.IndexFile = 0
            self.IndexFileFind = self.ListTitreSketchs.index(self.ListSketchsCat[self.IndexFile][0])
            self.ActionSelectListBoxFichiers()
            self.ListBoxFichiers.selection_set(0)
            self.MAJInfo()
        else:
            self.ActionRetourMaison()

    def AffichPara(self, _):
        self.BtnPara.CanvasBtn.itemconfig(self.BtnPara.ImgCanvasBtn, image=self.BtnPara.ImgBtn[0])
        if not self.ActionCat and not self.AffichTab and not self.AffichSM:
            self.CanvasEtagCircuits.itemconfig(self.ImgCanvasEtagCircuits, image=self.ImgEtagCircuits[0])
            self.ModifPara = True
            self.AnnulZoom()
            if self.FrmFindVisible:
                self.EffaceInfo()
                self.FrmFindVisible = False
                self.ActionFind = False
                self.MotionBtnV(4)
                self.ChargeListSketch()
            self.FrmPara = FrmParametre(self.parent, self.RatioFondX, self.RatioFondY, self.RatioFondY2, self)
            self.FrmLift()
        else:
            self.FrmLift2()
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def AffichMoniteurSerie(self, _):
        self.BtnSerie.CanvasBtn.itemconfig(self.BtnSerie.ImgCanvasBtn, image=self.BtnSerie.ImgBtn[0])
        if not self.ActionCat and not self.ModifPara and not self.AffichTab and not self.AffichSM:
            self.CanvasEtagCircuits.itemconfig(self.ImgCanvasEtagCircuits, image=self.ImgEtagCircuits[0])
            self.ClicAffichSM = True
            if not self.Init:
                self.ActionRetourMaison()
            self.AffichSM = True
            self.ClicAffichSM = False
            self.FrmINO = FrmSketchIDE(self.parent, self.RatioFondX, self.RatioFondY, self.RatioFondY2, -1, self)
            self.FrmINO.ChargeSerialMoniteur()
        else:
            self.FrmLift2()
            winsound.PlaySound("*", winsound.SND_ASYNC)

    def AffichTableur(self, _):
        self.BtnTab.CanvasBtn.itemconfig(self.BtnTab.ImgCanvasBtn, image=self.BtnTab.ImgBtn[0])
        self.CanvasFrmMain.delete(self.TooltipAction)
        self.InfoAction = False
        if not self.FrmFindVisible and not self.ActionCat and not self.ModifPara and not self.AffichTab \
                and not self.AffichSM:
            if not self.Init:
                self.ActionRetourMaison()
            self.CanvasEtagCircuits.itemconfig(self.ImgCanvasEtagCircuits, image=self.ImgEtagCircuits[0])
            self.AffichTab = True
            self.FrmINO = FrmSketchIDE(self.parent, self.RatioFondX, self.RatioFondY, self.RatioFondY2, -1, self)
            self.FrmINO.ChargeSerialMoniteur()
            self.FrmINO.FrmSerialMonitor.ChargeTableur()
            self.FrmINO.FrmSerialMonitor.lower()
            self.FrmINO.FrmSerialMonitor.FrmTableur.lift()
        else:
            winsound.PlaySound("*", winsound.SND_ASYNC)
            self.FrmLift2()

    def RetourMaison(self, _):
        self.AffichInfoActionV(self.ListInfoActionV[0])
        self.ActionRetourMaison()

    def ActionRetourMaison(self):
        self.CanvasEtagCircuits.itemconfig(self.ImgCanvasEtagCircuits, image=self.ImgEtagCircuits[1])
        self.Init = False
        self.AnnulZoom()
        if self.ActionFind:
            if self.FrmFindVisible:
                self.FrmFindData.destroy()
                self.FrmFindVisible = False
            self.ActionFind = False
        if self.AffichTab:
            self.FrmINO.FrmSerialMonitor.FrmTableur.ActionCacheFrmTableur()
        if self.AffichSM:
            if self.FrmINO.FrmSerialMonitor.AffichTab:
                self.FrmINO.FrmSerialMonitor.FrmTableur.ActionCacheFrmTableur()
            self.FrmINO.FrmSerialMonitor.ActionCacheFrmSerialMonitor()
        self.SelectCat = False
        self.ActionCat = False
        self.BtnHome.CanvasBtn.itemconfig(self.BtnHome.ImgCanvasBtn, image=self.BtnHome.ImgBtn[0])
        self.ReInitListSketch()
        self.GoHome = True
        self.SketchIno = False
        if self.AffichDescript:
            self.FrmDescrip.destroy()
            self.AffichDescript = False
        if self.AffichCode:
            self.FrmCode.destroy()
            self.AffichCode = False
        if self.AffichDoc:
            self.FrmDoc.destroy()
            self.AffichDoc = False
        self.CacheMenu()
        self.Init = True
        self.LPDText = 'ArdPyLog - Gestionnaire de sketchs pour Arduino UNO'
        self.CanvasFrmMain.itemconfigure('LegendePanneauD', text=self.LPDText)
        self.MotionBtnV(0)

    def CalculDefilMax(self, l):
        if len(l) <= 4:
            self.defilmax = 0
        elif len(l) % 4 != 0:
            self.defilmax = len(l) // 4
        else:
            self.defilmax = (len(l) // 4) - 1
        self.DefilCircuit.config(from_=0, to=self.defilmax, resolution=1)

    def MAJInfo(self):
        if not self.ActionFind and not self.SelectCat and not self.ActionCat:
            self.LabelTotal.config(text='Total: ' + str(len(self.ListSketchs)) + ' sketch(s)')
        elif not self.SelectCat and not self.ActionCat:
            self.LabelTotal.config(
                text='Total recherche "' + self.RequeteRecherche + '": ' + str(len(self.ListRecherch)) + ' sketch(s)')
        elif not self.ActionCat:
            self.LabelTotal.config(
                text='Total catégorie "' + self.TypeCat + '": ' + str(len(self.ListSketchsCat)) + ' sketch(s)')
        else:
            self.LabelTotal.config(text='')

    def EffaceInfo(self):
        self.LabelTotal.config(text='')

    def CacheMenu(self):
        self.EffaceLegend()
        for j in range(4):
            ChangeCursor3(self.ListCanvasMenu[j])
            self.ListCanvasMenu[j].itemconfig(self.ListImgMenu[j], image=self.ListMenu[j][3])

    def ZoomCircuit(self, _):
        if not self.ZoomCircuitActif:
            self.AnnulZoom()
            ratio = ConfigResolution(self.Nconfig, 'ZC')
            self.CircuitZoom = FrmZoomCircuit(self.parent, self.RatioFondX, self.RatioFondY, ratio, self)
            self.ZoomCircuitActif = True

    def ZoomDescript(self, _):
        if not self.ZoomDescriptActif:
            self.AnnulZoom()
            self.DescriptZoom = FrmZoomDescript(self.parent, self.RatioFondX, self.RatioFondY, self)
            self.DescriptZoom.lift(self.parent)
            self.ZoomDescriptActif = True

    def ZoomCode(self, _):
        if not self.ZoomCodeActif:
            self.AnnulZoom()
            self.CodeZoom = FrmZoomCode(self.parent, self.RatioFondX, self.RatioFondY, self)
            self.CodeZoom.lift(self.parent)
            self.ZoomCodeActif = True

    def ZoomDoc(self, _):
        if not self.ZoomDocActif:
            self.AnnulZoom()
            self.DocZoom = FrmZoomDoc(self.parent, self.RatioFondX, self.RatioFondY, self)
            self.DocZoom.lift(self.parent)
            self.ZoomDocActif = True

    def AnnulZoom(self):
        if self.ZoomCircuitActif:
            self.CircuitZoom.destroy()
            self.ZoomCircuitActif = False
        if self.ZoomDescriptActif:
            self.DescriptZoom.destroy()
            self.ZoomDescriptActif = False
        if self.ZoomCodeActif:
            self.CodeZoom.destroy()
            self.ZoomCodeActif = False
        if self.ZoomDocActif:
            self.DocZoom.destroy()
            self.ZoomDocActif = False

    def ModeAcquisition(self, _):
        self.BtnAcqui.CanvasBtn.itemconfig(self.BtnAcqui.ImgCanvasBtn, image=self.BtnAcqui.ImgBtn[0])
        self.CanvasFrmMain.delete(self.TooltipAction)
        self.InfoAction = False
        if not self.FrmFindVisible and not self.ActionCat and not self.ModifPara and not self.AffichTab \
                and not self.AffichSM and not self.ModeAcquisitionActif:
            if not self.Init:
                self.ActionRetourMaison()
            else:
                self.CanvasEtagCircuits.itemconfig(self.ImgCanvasEtagCircuits, image=self.ImgEtagCircuits[0])
            self.EffaceInfo()
            self.ModeAcquisitionActif = True
            self.FrmAcqui = FrmAcquisition(self.parent, self.RatioFondX, self.RatioFondY, self.RatioFondY2, self)
        else:
            winsound.PlaySound("*", winsound.SND_ASYNC)
            self.FrmLift2()

    def quitter(self, _):
        self.CloseSM()
        if self.ModeAcquisitionActif:
            self.FrmAcqui.CacheFrmAcquisition(_)
        self.cur.close()
        self.DataBase.close()
        self.parent.destroy()
        sys.exit()


if __name__ == '__main__':
    FrmMain = FrmMainApp("")
    ArdPyLog = MainAppli(FrmMain)
    FrmMain.mainloop()
