Forráskód Böngészése

big cleanup: baselib save/save_as as function

micha 11 hónapja
szülő
commit
26586b1741
11 módosított fájl, 432 hozzáadás és 347 törlés
  1. 7 1
      LibreLightDesk.py
  2. 96 77
      _LibreLightDesk.py
  3. 1 2
      arc/unittest_run.py
  4. 194 124
      lib/baselib.py
  5. 4 5
      lib/fixlib.py
  6. 18 33
      lib/libtk.py
  7. 45 29
      lib/libwin.py
  8. 2 2
      lib/zchat.py
  9. 1 1
      tkgui/GUI.py
  10. 2 0
      tksdl/midi.py
  11. 62 73
      tool/movewin.py

+ 7 - 1
LibreLightDesk.py

@@ -14,8 +14,10 @@ print()
 
 import pathlib
 
+BASE_PATH = "/opt/LibreLight/Xdesk/"
+
 _file_path=pathlib.Path(__file__)
-print("file:",_file_path)
+print("__file__ =",_file_path)
 
 import tool.movewin as movewin
 
@@ -42,6 +44,7 @@ pygame.display.set_icon(icon)
 
 import tool.movewin as movewin
 import tool.sdl_elm as sdl_elm
+import lib.baselib as baselib
 
 
 CAPTION = 'LibreLight Start '
@@ -79,6 +82,9 @@ import os
 import lib.fork as fork
 BASE_PATH = "/opt/LibreLight/Xdesk/"
 
+import lib.baselib as baselib
+SHOW_NAME = baselib.current_show_name()
+print([SHOW_NAME])
                 
 import lib.restart as restart
 

+ 96 - 77
_LibreLightDesk.py

@@ -19,7 +19,8 @@ import os
 
 import _thread as thread
 
-
+for i in range(30):
+    print() # boot space
 
 IS_GUI = 0
 if __name__ == "__main__":
@@ -1173,6 +1174,47 @@ class BLINKI():
         e.after(d, lambda: e.config(bg='white')) # after 1000ms
         e.after(d, lambda: e.config(activebackground='white')) # after 1000ms
 
+
+def save_show(fpath=None,new=0):
+    if fpath:
+        a=PRESETS.backup_presets(save_as=fpath,new=new)
+        b=FIXTURES.backup_patch(save_as=fpath,new=new)
+        c=libwin.save_window_position(save_as=fpath)
+        d=movewin.store_all_sdl()
+    else:
+        print()
+        print()
+        cprint("SAVE SHOW ..",color="yellow")
+        a=PRESETS.backup_presets()
+        b=FIXTURES.backup_patch()
+        c=libwin.save_window_position() 
+        d=movewin.store_all_sdl()
+
+    if a and b and c and d:
+        cprint("SAVE SHOW OK",[fpath,new],[a,b,c,d],color="green")
+        print()
+        print()
+        print()
+        return 1
+    cprint("SAVE SHOW FAIL",[fpath,new],[a,b,c,d],color="red")
+    print()
+    print()
+    print()
+
+def save_show_as(fname,new=0):
+    print()
+    print()
+    fpath = baselib.generate_show_path(fname)
+
+    info = "SAVE SHOW AS"
+    if new:
+        info = "SAVE (NEW) SHOW AS"
+
+    cprint(info,fpath,fname,color="green")
+
+    if baselib.create_new_show_path(fpath):
+        return save_show(fpath,new)
+
 class Xevent():
     """ global input event Handeler for short cut's ... etc
     """
@@ -1183,34 +1225,31 @@ class Xevent():
         self.elem = elem
         self.mode = mode
 
-    def _save_show(self):
-        self.elem["bg"] = "orange"
-        self.elem["text"] = "SAVING..."
-        self.elem["bg"] = "red"
-        self.elem.config(activebackground="orange")
-        modes.val(self.attr,1)
-        PRESETS.backup_presets()
-        FIXTURES.backup_patch()
-        libwin.save_window_position()
-        movewin.store_all_sdl()
-        self.elem["bg"] = "lightgrey"
-        self.elem.config(activebackground="lightgrey")
-        b = BLINKI(self.elem)
-        b.blink()
-        self.elem["text"] = "SAVE\nSHOW"
-
     def setup(self,event):       
         cprint("xevent.SETUP",[self.mode,self.attr],color="red")
         if self.mode != "SETUP":
             return 0
 
         if self.attr == "SAVE\nSHOW":
-            self._save_show()
+            self.elem["bg"] = "orange"
+            self.elem["text"] = "SAVING..."
+            self.elem["bg"] = "red"
+            self.elem.config(activebackground="orange")
+
+            modes.val(self.attr,1)
+
+            save_show()
+
+            self.elem["bg"] = "lightgrey"
+            self.elem.config(activebackground="lightgrey")
+            b = BLINKI(self.elem)
+            b.blink()
+            self.elem["text"] = "SAVE\nSHOW"
         elif self.attr == "LOAD\nSHOW":
             name = "LOAD-SHOW"
-            base = baselib.Base()
-            line1 = "PATH: "+base.show_path1 +base.show_name
-            line2 = "DATE: "+ time.strftime("%Y-%m-%d %X",  time.localtime(time.time()))
+            line1 = "PATH: " + baselib.current_show_path()
+            line2 = "DATE: " + time.strftime("%Y-%m-%d %X",  time.localtime(time.time()))
+
             class cb():
                 def __init__(self,name=""):
                     self.name=name
@@ -1225,27 +1264,23 @@ class Xevent():
             print(line1,line2)
             frame = pw.sframe(line1=line1,line2=line2)
             r = frame_of_show_list(frame,cb=cb)
+
         elif self.attr == "NEW\nSHOW":
-            base = baselib.Base()
 
-            #def _cb(fname):
             def _cb(data):
                 if not data:
                     cprint("err443",self,"_cb",data)
                     return None
                 fname = data["Value"]
-                cprint(self,"save_show._cb()",fname)
-                fpath,fname = base.build_path(fname)
+                fpath = baselib.generate_show_path(fname)
                 cprint("SAVE NEW SHOW",fpath,fname)
-                if base._create_path(fpath):
-                    a=PRESETS.backup_presets(save_as=fpath,new=1)
-                    b=FIXTURES.backup_patch(save_as=fpath,new=1)
-                    #base._set(fname)
-                    
-                    libwin.save_window_position(save_as=fpath)
+
+                if save_show_as(fname,new=1):
                     LOAD_SHOW_AND_RESTART(fname).cb() 
+
             dialog._cb = _cb
             dialog.askstring("CREATE NEW SHOW","CREATE NEW SHOW:")
+
         elif self.attr == "SAVE\nSHOW AS":
             base = baselib.Base()
 
@@ -1255,29 +1290,23 @@ class Xevent():
                     cprint("err443",self,"_cb",data)
                     return None
                 fname = data["Value"]
-                cprint(self,"save_show._cb()",fname)
-                fpath,fname = base.build_path(fname)
-                cprint("SAVE AS",fpath,fname)
-                if base._create_path(fpath):
-                    a=PRESETS.backup_presets(save_as=fpath)
-                    b=FIXTURES.backup_patch(save_as=fpath)
-                    #base._set(fname)
-                    
-                    libwin.save_window_position(save_as=fpath)
+
+                if save_show_as(fname):
                     LOAD_SHOW_AND_RESTART(fname).cb() 
+
+
             dialog._cb = _cb
             dialog.askstring("SAVE SHOW AS","SAVE SHOW AS:")
+
         elif self.attr == "SAVE &\nRESTART":
             self.elem["bg"] = "orange"
             self.elem["text"] = "SAVING..."
             self.elem["bg"] = "red"
             self.elem.config(activebackground="orange")
             modes.val(self.attr,1)
-            PRESETS.backup_presets()
-            FIXTURES.backup_patch()
 
-            movewin.store_all_sdl()
-            libwin.save_window_position()
+            save_show()
+
             self.elem["text"] = "RESTARTING..."
             self.elem["bg"] = "lightgrey"
             self.elem.config(activebackground="lightgrey")
@@ -1365,8 +1394,9 @@ class Xevent():
 
         elif self.attr == "SAVE":
             modes.val(self.attr,1)
-            PRESETS.backup_presets()
-            FIXTURES.backup_patch()
+            save_show()
+            #PRESETS.backup_presets()
+            #FIXTURES.backup_patch()
             #time.sleep(1)
             modes.val(self.attr,0)
         elif self.attr == "S-KEY":
@@ -1414,7 +1444,6 @@ class Xevent():
 
         cprint("-- Xevent","_ENC",self.fix,self.attr,self.mode)
         cprint("-- SHIFT_KEY",_shift_key,"??????????")
-        #cprint(self.data)
         val=""
         if event.num == 1:
             val ="click"
@@ -1840,7 +1869,7 @@ class MASTER():
             if not data:
                 cprint("err443",self,"_cb",data)
                 return None
-            cprint(self,"btn_cfg._cb()",data)
+            cprint("btn_cfg._cb()",data)
             if data:
 
                 if "Button" in  data and type(data["Button"]) is str:
@@ -1896,7 +1925,7 @@ class MASTER():
                 cprint("err443",self,"_cb",data)
                 return None
             txt = data["Value"]
-            cprint(self,"label._cb()",nr,txt)
+            cprint("label._cb()",nr,txt)
             if txt:
                 PRESETS.label(nr,txt) 
                 self.elem_presets[nr].configure(text = PRESETS.get_btn_txt(nr))
@@ -1909,7 +1938,6 @@ class MASTER():
 
     def xcb(self,mode,value=None):
         cprint("MODE CALLBACK",mode,value,color="green",end="")
-        #cprint(self,"xcb","MODE CALLBACK",mode,value,color="green")
         if value:
             cprint("===== ON  ======",color="red")
             txt = ""
@@ -1932,12 +1960,11 @@ class MASTER():
 
     def load(self,fname=""):
         pass
+
     def exit(self):
         cprint("__del__",self)
-        PRESETS.backup_presets()
-        #print("********************************************************")
-        FIXTURES.backup_patch()
-        #print("*********del",self,"***********************************************")
+        save_show()
+        
     def refresh_exec(self):
         refresher_exec.reset() # = Refresher()
 
@@ -1967,7 +1994,7 @@ class MASTER():
     def refresh_fix(self):
         refresher_fix.reset() # = Refresher()
     def _refresh_fix(self):
-        cprint(self,"_refresh_fix")
+        cprint("_refresh_fix")
         s=time.time(); _XXX=0
 
         menu_buff = {"DIM":0,"DIM-SUB":0,"FIX":0,"FIX-SUB":0}
@@ -2337,7 +2364,7 @@ def frame_of_show_list(frame,cb=None):
         b.grid(row=r, column=c, sticky=tk.W+tk.E)
         c+=1
     r+=1
-    blist = base._list()
+    blist = baselib.list_shows()
     for i in range(10):
         blist.append(["",""])
 
@@ -2414,17 +2441,13 @@ def PRESET_CFG_CHECKER(sdata):
 
 class Presets():
     def __init__(self):
-        #super().__init__() 
         self.base = baselib.Base()
-        #self.load()
         self._last_copy = None
         self._last_move = None
         self.fx_buffer = {}
 
     def load_presets(self): 
-        #self._load()
         filename="presets"
-        #self.base._init()
         d,l = self.base._load(filename)
         for i in d:
             sdata = d[i]
@@ -2462,16 +2485,10 @@ class Presets():
         data   = self.val_presets
         labels = self.label_presets
         if new:
-            #a = []
-            #for i in range(512):
-            #    e = PRESET_CFG_CHECKER({})
-            #    e["NAME"] = str(i)
-            #    a.append(e)
-            #data = a 
-            data = []#*512
+            data  = [] #*512
             labls = [""]*512
-        #self.base._init()
-        self.base._backup(filename,data,labels,save_as)
+        r=self.base._backup(filename,data,labels,save_as)
+        return r
         
 
     def get_cfg(self,nr):
@@ -2789,7 +2806,7 @@ class WindowManager():
         self.windows[self.first].mainloop()
 
     def get_win(self,name):
-        cprint(self,".get_win(name) =",name)
+        cprint(".get_win(name) =",name)
         name = str(name)
         if name in self.windows:
             out = self.windows[name]
@@ -2806,7 +2823,7 @@ class WindowManager():
             return out
 
     def create(self,name):
-        cprint( "create Window",name)
+        #cprint( "create Window",name)
 
         if name in self.window_init_buffer:
             c = self.window_init_buffer[name] 
@@ -2833,11 +2850,13 @@ class WindowManager():
 
     def _check(self,name):
         try:
+            if "tk" not in dir(self.windows[name]):
+                return 0
             self.windows[name].tk.state(newstate='normal')
             return 1
         except Exception as e:
             cprint("exception",e,color="red")
-            cprint("info",name,self.windows[name],color="red")
+            cprint(" info",name,self.windows[name],color="red")
 
     def top(self,name):
         name = str(name)
@@ -2850,7 +2869,7 @@ class WindowManager():
         
         w = self.windows[name]
         #def get_lineno():
-        print(" 2.1- ln",movewin.get_lineno(),w,str(type(w)))
+        #print(" on TOP: 2.1- ln",movewin.get_lineno(),w,str(type(w)))
         #if type(w) is type(window_create_buffer):
         if not str(type(w)).startswith("<class 'function'>"): 
             w.tk.attributes('-topmost',True)
@@ -2919,7 +2938,7 @@ class Refresher():
         self.name = "name" # exec
         self.cb = None #self.dummy_cb
     def dummy_cb(self):
-        cprint(self,"dummy_cd()",time.time()-self.time)
+        cprint("dummy_cd()",time.time()-self.time)
 
     def reset(self):
         self.time = time.time() 
@@ -3026,9 +3045,9 @@ class window_create_buffer():
         self.gui    = gui
 
     def create(self,hidde=0):
-        cprint()
-        cprint()
-        cprint("window_create_buffer.create()",id(self),self.args["title"],color="green")
+        #cprint()
+        #cprint()
+        #cprint("window_create_buffer.create()",id(self),self.args["title"],color="green")
 
         obj = None
         w = libtk.Window(self.args)

+ 1 - 2
arc/unittest_run.py

@@ -89,8 +89,7 @@ class Test_Fixture(unittest.TestCase):
 
 class Test_Desk(unittest.TestCase):
     def test_file_list(self):
-        base = desk.Base()
-        _list = base._list()
+        _list =  = baselib.list_shows()
         for i in _list: 
             print(i)
         self.assertTrue(len(_list))

+ 194 - 124
lib/baselib.py

@@ -2,6 +2,9 @@
 
 import os
 import time
+import sys
+sys.path.insert(0,"/opt/LibreLight/Xdesk/")
+
 import json
 from collections import OrderedDict
 
@@ -13,8 +16,9 @@ import string
 import tkinter
 tk = tkinter
 
-
-HOME = os.getenv('HOME')
+HOME      = os.getenv('HOME')
+BASE_PATH = HOME+"/LibreLight/"
+SHOW_DIR  = BASE_PATH+"/show/"
 
 def _clean_path(fpath):
     _path=[]
@@ -25,49 +29,89 @@ def _clean_path(fpath):
     path = "".join(_path)
     return path
 
-def _read_init_txt(show_path):
-    fname = show_path+"init.txt"
-    show_name = None
+
+
+def current_show_name(base_path=""):
+    if not base_path:
+        base_path = BASE_PATH
+
+    fname = base_path+"/init.txt"
+    show_name = "null"
     msg = ""
 
     if not os.path.isfile( fname ):
-        msg = "_read_init_txt Errror: " +fname +"\n NOT FOUND !"
-        return [None,msg]
+        msg = "current_show_path Error: " +fname +"\n NOT FOUND !"
+        cprint(msg,color="red")
+        return show_name #,msg]
 
     try:
         f = open(fname,"r")
-        for line in f.readlines():
+        lines = f.readlines()
+        f.close()
+
+        for line in lines:
             line = line.strip()
-            print("  init.txt:",[line])
+            #print("  init.txt:",[line])
             if line.startswith("#"):
                 continue
             if not line:
                 continue
 
             show_name = line
-            show_name = show_name.replace(".","")
-            show_name = show_name.replace("\\","")
-            show_name = show_name.replace("/","")
+        show_name = show_name.replace(".","")
+        show_name = show_name.replace("\\","")
+        show_name = show_name.replace("/","")
     except Exception as e:
-        cprint("show name exception",color="red")
-        msg="read_init_txt Error:{}".format(e)
-    finally:
-        f.close()
+        msg="current_show_path \nError:{}".format(e)
+        cprint(msg,color="red")
+
+    #return [show_name,msg]
+    return show_name
+
+def current_show_path():
+    SHOW_PATH = SHOW_DIR + current_show_name()
+    while "//" in SHOW_PATH: 
+        SHOW_PATH = SHOW_PATH.replace("//","/")
+    return SHOW_PATH
+
+def generate_show_path(show_name):
+    show_name = _clean_path(show_name)
+    SHOW_PATH = SHOW_DIR + show_name
+    while "//" in SHOW_PATH: 
+        SHOW_PATH = SHOW_PATH.replace("//","/")
+    return SHOW_PATH
+
+
+def build_path(fn):
+    fn = _clean_path(fn)
+    path = current_show_path().split("/")
+    path = "/".join(path[:-2])
+    fpath = path+"/show/"+fn
+    cprint(fpath,fn,color="red")
+    return fpath,fn
+
+def create_new_show_path(fpath):
+    if os.path.isdir(fpath):
+        cprint("   CREATE DIR FAIL (exist)",[fpath],color="red")
+        return 0
+    os.mkdir(fpath)
+    cprint("   CREATE DIR OK",[fpath],color="green")
+    return 1
 
-    return [show_name,msg]
 
 def _read_sav_file(xfname):
     cprint("load",xfname)
     lines = []
+    data   = OrderedDict()
+    labels = OrderedDict()
+
     if not os.path.isfile(xfname):
-        return []
+        return [] #data,labels
 
     f = open(xfname,"r")
     lines = f.readlines()
     f.close()    
 
-    data   = OrderedDict()
-    labels = OrderedDict()
     i=0
     for line in lines:
         r = fixlib._fixture_decode_sav_line(line)
@@ -79,20 +123,21 @@ def _read_sav_file(xfname):
         
     return data,labels
 
+def list_shows(path=None):
+    if not path:
+        path = SHOW_DIR
 
-def _listdir(show_path):
-    #self._check()
-    show_list =  list(os.listdir( show_path ))
+    show_list =  list(os.listdir( path ))
     out = []
     for fname in show_list:
+        fpath = path+fname
         if fname == "EASY": #hidde EASY show in list !
             continue
-        #print(fname)
-        ctime = os.path.getmtime(show_path+fname)
-        ctime = time.strftime("%Y-%m-%d %X",  time.localtime(ctime)) #1650748726.6604707))
+        ctime = os.path.getmtime(fpath)
+        ctime = time.strftime("%Y-%m-%d %X",  time.localtime(ctime)) 
         try:
-            mtime = os.path.getmtime(show_path+fname+"/patch.sav")
-            mtime = time.strftime("%Y-%m-%d %X",  time.localtime(mtime)) #1650748726.6604707))
+            mtime = os.path.getmtime(fpath+"/patch.sav")
+            mtime = time.strftime("%Y-%m-%d %X",  time.localtime(mtime)) 
         except:
             mtime = 0
 
@@ -104,134 +149,159 @@ def _listdir(show_path):
     out.reverse()
     return out
 
+def set_current_show_name(fname):
+    ok= os.path.isdir(SHOW_DIR+"/"+fname)
+    ini = BASE_PATH+"init.txt"
+    print()
+    print()
+    cprint("SET SHOW NAME",fname,ok,ini,color="green")
+    print()
+    try:
+        f = open( ini ,"r")
+        lines = f.readlines()
+        f.close()
+        if len(lines) >= 10: # cut show history
+            cprint("_set",ini,len(lines))
+            lines = lines[-10:]
+            f = open( ini ,"w")
+            f.writelines(lines)
+            f.close()
+            exit()
+
+    except:pass
+    if ok:
+        #self.show_name = fname
+        f = open( ini ,"a")
+        f.write(fname+"\n")
+        f.close()
+        return 1
 
 class Base():
     def __init__(self):
-        cprint("Base.init()",color="red")
-        self._init()
-
-    def _init(self):
-        show_name = "" #DemoShow #"ErrorRead-init.txt"
-        self.show_path0 = HOME +"/LibreLight/"
-        self.show_path  = self.show_path0 
-        self.show_path1 = self.show_path0 + "show/"
-        
-        msg = " X "
-        self.show_name,msg = _read_init_txt(self.show_path)
+        self.show_path = current_show_path() 
+        self.show_name = current_show_name() 
+        cprint("Base.init()",self.show_path,self.show_name,color="yellow")
+
+        msg = "<msg>"
+
+
         if not self.show_name:
-            #r=tkinter.messagebox.showwarning(message=msg,parent=None)
-            r=tkinter.messagebox.showwarning(message=msg,title="Error",parent=None)
+            r=tkinter.messagebox.showwarning(message=msg,title="444 Error",parent=None)
             sys.exit()
         
-        fpath = self.show_path1 +show_name 
-        if not os.path.isdir(fpath):
-            cprint(fpath)
-            cprint( os.path.isdir(fpath))
-
-            msg="'{}'\n Show Does Not Exist\n\n".format(show_name)
+        if not os.path.isdir(self.show_path):
+            msg += "Show does not exist\n\n"
             msg += "please check\n"
-            msg += "-{}init.txt\n".format(self.show_path0)
-            msg += "-{}".format(self.show_path1)
-
-            #showwarning(msg=msg,title="Show Error")
+            msg += "-{} init.txt\n".format(BASE_PATH)
+            msg += "-{}".format(self.show_path)
+            cprint(msg,color="red")
             r=tkinter.messagebox.showwarning(message=msg,title="Show Error",parent=None)
             exit()
 
         self._check()
+
     def _set(self,fname):
-        ok= os.path.isdir(self.show_path1+"/"+fname)
-        ini = self.show_path0+"init.txt"
-        cprint("SET SHOW NAME",fname,ok,ini)
-        try:
-            f = open( ini ,"r")
-            lines = f.readlines()
-            f.close()
-            if len(lines) >= 10: # cut show history
-                cprint("_set",ini,len(lines))
-                lines = lines[-10:]
-                f = open( ini ,"w")
-                f.writelines(lines)
-                f.close()
-                exit()
-
-        except:pass
-        if ok:
-            #self.show_name = fname
-            f = open( ini ,"a")
-            f.write(fname+"\n")
-            f.close()
-            return 1
-        
+        set_current_show_name(fname)
+
     def _check(self):
         if not os.path.isdir(self.show_path):
             os.mkdir(self.show_path)
-        self.show_path += "/show/"
-        if not os.path.isdir(self.show_path):
-            os.mkdir(self.show_path)
-        self.show_path += "/" +self.show_name +"/"
-        if not os.path.isdir(self.show_path):
-            os.mkdir(self.show_path)
-        pass
-    def _list(self):
-        cprint("BASE._list()")
-        out = _listdir(self.show_path1)
-        return out
+
 
     def _load(self,filename):
         xpath = self.show_path+"/"+str(filename)+".sav"
         if not os.path.isfile(xpath):
-            msg = ""#"Exception: {}".format(e)
-            msg += "\n\ncheck\n-init.txt"
+            msg = ""
+            msg += "\n"*2
+            msg += "check init.txt"
+            msg += "\n"*2
+            msg += xpath
             cprint(msg,color="red")
-            #showwarning(msg=msg,title="load Error")
-            r=tkinter.messagebox.showwarning(message=msg,title="Error",parent=None)
+            r=tkinter.messagebox.showwarning(message=msg,title="123 Error",parent=None)
             return
         return _read_sav_file(xpath)
 
 
-
-    def build_path(self,save_as):
-        save_as = _clean_path(save_as)
-        path = self.show_path.split("/")
-        path = "/".join(path[:-2])
-        fpath = path+"/"+save_as
-        return fpath,save_as
-
     def _create_path(self,fpath):
-        if os.path.isdir(fpath):
+        if not create_new_show_path(fpath):
             msg="STOP SHOW EXIST !"
             cprint(msg,color="red")
-            #showwarning(msg=msg,title="Error")
-            r=tkinter.messagebox.showwarning(message=msg,title="Error",parent=None)
-            #r=tkinter.messagebox.showwarning(message=msg,parent=None)
+            r=tkinter.messagebox.showwarning(message=msg,title="333 Error",parent=None)
             return 0
-        else:
-            cprint("CREATE DIR ",fpath,color="green")
-            os.mkdir(fpath)
-        #self._set(save_as)
         return fpath
 
     def _backup(self,filename,data,labels,save_as):
+        try:
+            fpath = self.show_path
+            if save_as:
+                fpath = save_as 
 
-        if save_as:
-            xfname = save_as +"/"+str(filename)+".sav"
-        else:
-            xfname = self.show_path+"/"+str(filename)+".sav"
-
-        cprint("backup",xfname)
-        f = open(xfname,"w")
-        for key in data:
-            line = data[key]
-            #print(line)
-            label = "label" 
-            if key in labels:
-                label = labels[key]
-            if label == "Name-"+str(key):
-                label = ""
-            #print(xfname,"load",key,label,len(line))
-
-            f.write( "{}\t{}\t{}\n".format( key,label,json.dumps(line) ) )
-        f.close()
+            fpath += "/"+str(filename)+".sav"
+
+            f = open(fpath,"w")
+            for key in data:
+                line = data[key]
+                label = "label" 
+                if key in labels:
+                    label = labels[key]
+                if label == "Name-"+str(key):
+                    label = ""
+
+                nline = "{}\t{}\t{}\n".format( key,label,json.dumps(line) ) 
+                f.write( nline )
+
+            f.close()
+            cprint("  Base._backup",[fpath],len(data),"OK",color="green")
+        except Exception as e:
+            cprint("  Base._backup",[fpath],len(data),"FAIL !",color="red")
+            raise e
 
         return 1
 
+def test():
+    print()
+    print("-- "*40)
+    print("HOME        ",HOME)
+    print("BASE_PATH   ",BASE_PATH)
+    print("SHOW_DIR    ",SHOW_DIR)
+    print()
+
+    print("-- "*20)
+    print("TEST  ")
+    print("current_show_path",current_show_path())
+    print()
+
+    print("-- "*20)
+    dl = list_shows()
+    for i in dl:
+        print(" - ",i)
+
+    print("-- "*20)
+    xpath = SHOW_DIR + "/" + dl[0][1] +"/presets.sav"
+    print(xpath)
+    x= _read_sav_file(xpath)
+    print("len.x",len(x))
+
+
+    base = Base()
+    print("::")
+    #x=base.build_path("TOST")
+    #print(x)
+
+    x=build_path("TEST")
+    print(x)
+
+    show_name = "tEsT"
+    x= generate_show_path(show_name)
+    print("generate_show_path",x)
+
+    #x=base.build_path(show_name)
+    #print("build_path",[show_name,x])
+
+
+if __name__ == "__main__":
+    test()
+
+
+
+

+ 4 - 5
lib/fixlib.py

@@ -43,7 +43,7 @@ def _fixture_repair_nr0(jdata):
     #return jdata
 
 def FIXTURE_CHECK_SDATA(ID,sdata):
-    print("FIXTURE_CHECK_SDATA",ID)
+    #print("FIXTURE_CHECK_SDATA",ID)
     new_f = OrderedDict()
     #print("++++")
     for k,j in sdata.items():
@@ -94,7 +94,7 @@ def FIXTURE_CHECK_SDATA(ID,sdata):
             _tmp =  {"NR": 0, "MASTER": "0", "MODE": "F", "VALUE": 255, "ACTIVE": 0, "FX": "", "FX2": {}}
             _tmp = OrderedDict(_tmp)
             sdata["ATTRIBUT"]["DIM"] =_tmp 
-        print("ADD ---- VDIM",vdim_count,_tmp)
+        print("   ADD ---- VDIM",vdim_count,_tmp)
         #input("STOP")
 
     for attr in sdata["ATTRIBUT"]:
@@ -324,8 +324,8 @@ class Fixtures():
 
 
     def load_patch(self):
+        cprint("FIXTURES.load_patch ..")
         filename="patch"
-        #self.base._init()
         d,l = self.base._load(filename)
         self.fixtures = OrderedDict()
         for i in l:
@@ -364,8 +364,7 @@ class Fixtures():
         if new:
             data = []
             labels = {}
-        #self.base._init()
-        self.base._backup(filename,data,labels,save_as)
+        return self.base._backup(filename,data,labels,save_as)
 
     def fx_get(self,fix=None):
         out={}

+ 18 - 33
lib/libtk.py

@@ -17,14 +17,14 @@ class on_focus():
         self.name = name
         self.mode = mode
     def cb(self,event=None):
-        print("on_focus",event,self.name,self.mode)
+        #print("on_focus",event,self.name,self.mode)
         try:
             e = MAIN.master.commands.elem["."]
         except:pass
 
         if self.mode == "Out":
             cmd="xset -display :0.0 r rate 240 20"
-            print(cmd)
+            #print(cmd)
             os.system(cmd)
             try:
                 e["bg"] = "#aaa"
@@ -32,7 +32,7 @@ class on_focus():
             except:pass
         if self.mode == "In":
             cmd = "xset -display :0.0 r off"
-            print(cmd)
+            #print(cmd)
             os.system(cmd)
             try:
                 e["bg"] = "#fff"
@@ -51,8 +51,9 @@ class Window():
         self.args = {"title":"title","master":0,"width":100,"height":100,"left":None,"top":None,"exit":0,"cb":None,"resize":1}
         self.args.update(args)
         
-        cprint("Window.init()",id(self.args),color="yellow")
-        cprint("  ",self.args,color="yellow")
+        cprint("Window.init()",self.args["title"],color="yellow")
+        #cprint("Window.init()",id(self.args),color="yellow")
+        #cprint("  ",self.args,color="yellow")
 
         ico_path="./icon/"
         self.cb = MAIN.cb
@@ -73,7 +74,7 @@ class Window():
             try:
                 self.tk.iconphoto(False, tk.PhotoImage(file=ico_path+"main.png"))
             except Exception as e:
-                cprint("Exception GUIWindow.__init__",e)
+                cprint(" Exception GUIWindow.__init__",e)
         else:
             # addtional WINDOW
             self.tk = tkinter.Toplevel()
@@ -94,8 +95,8 @@ class Window():
                 else:
                     self.tk.iconphoto(False, tk.PhotoImage(file=ico_path+"scribble.png"))
             except Exception as e:
-                cprint("Exception on load window icon",self.args["title"])
-                cprint("Exception:",e)
+                cprint(" Exception on load window icon",self.args["title"])
+                cprint(" Exception:",e)
             #time.sleep(3)
             self.tk.deiconify()
 
@@ -120,6 +121,7 @@ class Window():
         #self._event_clear = Xevent(fix=0,elem=None,attr="CLEAR",data=self,mode="ROOT").cb
         self.tk.geometry(geo)
         self.show()
+
     def update_idle_task(self):
         if MAIN.INIT_OK:
             tkinter.Tk.update_idletasks(MAIN.gui_menu_gui.tk)
@@ -154,7 +156,7 @@ class Window():
         finally:
             self.tk.quit()
             cmd="xset -display :0.0 r rate 240 15"
-            print(cmd)
+            #print(cmd)
             os.system(cmd)
 
     def callback(self,event,data={}):#value=255):
@@ -175,24 +177,15 @@ class Window():
             #print([event.state,event.keysym,event.type])
             if event.state == 4  and str(2) == str(event.type): # strg + s
                 if str(event.keysym) == "s":
-                    cprint("tTtT ReW "*20)
-                    #print("numbersign !!")
-                    MAIN.PRESETS.backup_presets()
-                    MAIN.FIXTURES.backup_patch()
-                    libwin.save_window_position()
-
-                    e =  MAIN.master.setup_elem["SAVE\nSHOW"]
-                    #print(e)
+                    MAIN.save_show()
+
+                    e = MAIN.master.setup_elem["SAVE\nSHOW"]
                     b = MAIN.BLINKI(e)
                     b.blink()
                 if str(event.keysym) == "c":
-                    MAIN.PRESETS.backup_presets()
-                    MAIN.FIXTURES.backup_patch()
+                    if MAIN.save_show():
+                        MAIN.LOAD_SHOW_AND_RESTART("").cb(force=1)
 
-                    libwin.save_window_position()
-                    #self.elem.config(activebackground="lightgrey")
-                    MAIN.LOAD_SHOW_AND_RESTART("").cb(force=1)
-                #cprint("oipo "*10,round(int(time.time()-sstart)*1000,2))
                 return
 
         if "keysym" in dir(event):
@@ -256,10 +249,7 @@ class Window():
                 MAIN.master.preset_go(nr-1,xfade=None,val=value)
             elif "numbersign" == event.keysym and value: # is char "#"
                 cprint("numbersign !!")
-                MAIN.PRESETS.backup_presets()
-                MAIN.FIXTURES.backup_patch()
-
-                libwin.save_window_position()
+                MAIN.save_show()
 
                 for e in MAIN.master.setup_cmd:
                     cprint(e)
@@ -278,7 +268,7 @@ class Window():
                 if value:
                     MAIN.modes.val("DEL",1)
 
-        cprint("oipo "*10,round(int(time.time()-sstart)*1000,2))
+        #cprint("oipo "*10,round(int(time.time()-sstart)*1000,2))
  
 
 class PopupList():
@@ -352,11 +342,6 @@ def showwarning(msg="<ERROR>",title="<TITLE>"):
             time.sleep(1/10)
             _main.quit()
         thread.start_new_thread(_main.mainloop,())
-        #_main.quit()
 
-        #msg="'{}'\n Show Does Not Exist\n\n".format(show_name)
-        #msg += "please check\n"
-        #msg += "-{}init.txt\n".format(self.show_path0)
-        #msg += "-{}".format(self.show_path1)
 
         r=tkinter.messagebox.showwarning(message=msg,title=title,parent=None)

+ 45 - 29
lib/libwin.py

@@ -11,56 +11,75 @@ window_list_buffer = {}
 
 def save_window_position(save_as=""):
     global window_list_buffer
-    cprint()
-    cprint("save_window_position",[save_as])
+    #cprint("save_window_position as=",[save_as])
+    error = 0
 
-    base = baselib.Base()
-    fname = HOME+"/LibreLight"
-    fname = base.show_path1 +base.show_name 
     if save_as:
         fname = save_as 
-    fname +=  "/gui.txt"
-    cprint("- fname",fname)
+        fpath=fname
+    else:
+        fname = baselib.current_show_name() 
+        fpath = baselib.SHOW_DIR + fname
+    if not os.path.isdir(fpath):
+        cprint("  -0 save_window_position no dir:",fpath,color="red")
+        error += 1
+
+    fpath +=  "/gui.txt"
+    #cprint(" fpath:",fpath)
+    
 
     for k in window_list_buffer:
         window_list_buffer[k][0] = 0   
 
     for k,win in MAIN.window_manager.windows.items():
         try:
+            if not win:
+                continue
+            if "tk" not in dir(win):
+                continue
+
             geo = win.tk.geometry()
             data = [1,k,geo]
             if k not in  window_list_buffer:
-                cprint("-- new:win:pos",k.ljust(15," "),data)
+                cprint("  -- new:win:pos",k.ljust(15," "),data)
             elif window_list_buffer[k][2] != geo:
-                cprint("-- update:win:pos",k.ljust(15," "),data)
+                cprint("  -- update:win:pos",k.ljust(15," "),data)
             window_list_buffer[k] = data
 
             if k in ["PATCH","FIXTURES","DIMMER","FIXTURE-EDITOR","CONFIG"]:
                 window_list_buffer[k][0] = 0   
 
         except Exception as e:
-            cprint("-A save_window_position Exception:",k,e,color="red")
+            cprint("  -1 Exception:",[k,e],color="red")
+            cprint("  --- ",[win],color="red")
+            error += 1
 
     lines = ""
     for k,data in window_list_buffer.items():
         try:
-            #print("-- save:win:pos",k.ljust(15," "),data)
             if not data[2]:
                 continue
             line ="{} {} {}\n"
             line = line.format(data[0],k,data[2])
             lines += line
         except Exception as e:
-            cprint("-A save_window_position Exception:",e,color="red")
+            cprint("  -2 Exception:",e,color="red")
+            error += 1
 
     try:
-        f = open(fname,"w")
+        f = open(fpath,"w")
         f.write( lines )
-    except Exception as e:
-        cprint("-B save_window_position Exception:",e,color="red")
-    finally:
         f.close() #f.flush()
+        
+    except Exception as e:
+        cprint(" -3 Exception:",fpath,fname,e,color="red")
+        error += 1
 
+    if not error:
+        cprint("  save_window_position",fpath,"OK",color="green")
+
+        return 1
+    cprint("  save_window_position",fpath,"FAIL",color="red")
 
 
 def save_window_position_loop(): # like autosave
@@ -76,12 +95,11 @@ def save_window_position_loop(): # like autosave
 
 def get_window_position(_filter="",win=None):
     global window_list_buffer
-    cprint()
     show = None
     k = _filter
     geo = ""
 
-    cprint("get_window_position",[_filter])
+    #cprint("get_window_position",[_filter])
     if _filter in window_list_buffer:
         show,k,geo  = window_list_buffer[_filter]
         if win:
@@ -91,10 +109,8 @@ def get_window_position(_filter="",win=None):
 
 def read_window_position():
     try:
-        base = baselib.Base()
-        fname = HOME+"/LibreLight"
-        fname = base.show_path1 +base.show_name 
-        fname +=  "/gui.txt"
+        fname = baselib.current_show_path() + "/gui.txt"
+
         cprint("- fname:",fname)
         f = open(fname,"r")
         lines = f.readlines()
@@ -117,7 +133,7 @@ def read_window_position():
 
         return out
     except Exception as e:
-        cprint("- load_window_position 345 Exception:",e,color="red")
+        cprint("- load_window_position 145 Exception:",e,color="red")
         return 
     return []
 
@@ -128,7 +144,7 @@ def split_window_show(lines,_filter=""):
             if _filter in name:
                 return int(show)
     except Exception as e:
-        cprint("- split_window_show 345 Exception:",e,color="red")
+        cprint("- split_window_show 315 Exception:",e,color="red")
 
 def split_window_position(lines,_filter=""):
     try:
@@ -148,15 +164,15 @@ def split_window_position(lines,_filter=""):
                     args["top"]    = int(geo[3])
                     return args
     except Exception as e:
-        cprint("- split_window_position 345 Exception:",e,color="red")
+        cprint("- split_window_position 341 Exception:",e,color="red")
 
 
 
 def load_window_position(_filter=""):
-    print()
+    #print()
     global window_list_buffer
-    cprint()
-    cprint("load_window_position",[_filter])
+    #cprint()
+    cprint("  load_window_position",[_filter])
     try:
         lines = read_window_position()
 
@@ -185,5 +201,5 @@ def load_window_position(_filter=""):
                 cprint("- load_window_position 544 Exception:",e,color="red")
 
     except Exception as e:
-        cprint("- load_window_position 345 Exception:",e,color="red")
+        cprint("- load_window_position 335 Exception:",e,color="red")
         return 

+ 2 - 2
lib/zchat.py

@@ -187,7 +187,7 @@ class Server():
 
     def client_loop(self):
         self.client_lock = _thread.allocate_lock()
-        print(dir(self.client_lock),"-----2:") # = _thread.allocate_lock()
+        #print(dir(self.client_lock),"-----2:") # = _thread.allocate_lock()
         _thread.start_new_thread(self._client_loop,())
 
     def _client_loop(self):
@@ -331,7 +331,7 @@ def single_client():
     while 1:
         try:
             i=""
-            print()
+            # print()
             i = input("cmd:: ")
             c.send(bytes(i,"utf8"))
             time.sleep(0.5)

+ 1 - 1
tkgui/GUI.py

@@ -273,7 +273,7 @@ class X_CLOCK():
         self.bb.delete(tag)
 
     def draw_clock(self,gui,xframe,data=[]):
-        print("draw_clock",self)
+        #print("draw_clock",self)
         xframe.pack(fill="both",expand=1)
         frame = tk.Frame(xframe,bg="black")
         frame.pack(fill=tk.X, side=tk.TOP)

+ 2 - 0
tksdl/midi.py

@@ -233,6 +233,7 @@ while 1:
             msgs = []
         except Exception as e:
             time.sleep(1)
+            print("EXC",e)
             pass#print("MIDI INI",e)
 
     try:
@@ -249,6 +250,7 @@ while 1:
                 buf_exec.append(b)
         apc_main.buf = []
     except Exception as e:
+        print("EXC",e)
         pass #print("midi",e)
 
 

+ 62 - 73
tool/movewin.py

@@ -1,23 +1,26 @@
 #!/usr/bin/python3
+
 import os
-import sys
 import time
+import sys
+sys.path.insert(0,"/opt/LibreLight/Xdesk/")
+
+
 import psutil
 import json    
 import inspect
 import _thread as thread
 
-HOME = os.getenv('HOME')
-show_path = HOME+"/LibreLight/"
-show_path2 = HOME+"/LibreLight/show/"
+import lib.baselib as baselib
+from lib.cprint import cprint
+
+
+SHOW_PATH = baselib.current_show_path() #SHOW_PATH 
+
 
 # python3 movewin.py window-title x y
 # python3 movewin.py COMMA 723 943
 
-sys.path.insert(0,"/opt/LibreLight/Xdesk/")
-print(sys.path)
-from lib.cprint import cprint
-
 class Control():
     def __init__(self):
         self.title = "WinfoWinName"
@@ -108,11 +111,11 @@ def parse_winfo_line(line):
                 return _line 
 
 def winfo2(name="WinfoWinName"):
-    print("--------------")
+    #print("--------------")
     search = name
     cmd = "xwininfo -root -children -all | grep '{}'"
     cmd = cmd.format(search)
-    print(cmd)
+    #print(cmd)
 
     r = os.popen(cmd)
     lines = r.readlines()
@@ -122,12 +125,12 @@ def winfo2(name="WinfoWinName"):
         if a:
             _data.append(a)
 
-    print("--------------")
+    #print("--------------")
     return _data
 
 def get_store_sdl_line():
-    print()
-    print("-> def",inspect.currentframe().f_code.co_name,"-"*10)
+    #print()
+    #print("-> def",inspect.currentframe().f_code.co_name,"-"*10)
     lines = winfo2(name="SDL-")
     out_lines=[]
     for line in lines:
@@ -144,14 +147,13 @@ def get_store_sdl_line():
     return out_lines
 
 def load_all_sdl(title="X"):
-    fname ="/home/user/gui-sdl.txt"
-    fname = show_path2+ _read_init_txt()[0]+ "/gui-sdl.txt"
+    fname = SHOW_PATH + "/gui-sdl.txt"
     if os.path.isfile(fname):
         f=open(fname,"r")
         lines = f.readlines()
         f.close()
 
-        print("  read",fname)
+        print("  load_all_sdl fname:",fname)
         for line in lines:
             if title in line:
                 return json.loads(line)
@@ -171,27 +173,31 @@ def _start_sub(cmd,name,mute=0):
     #BrokenPipeError: [Errno 32] Broken pipe
 
 def start_sub(cmd,name="<PROCESS>",mute=0):
+    cprint("  start_sub",cmd,name,"mute-stdout:",mute,color="green")
     thread.start_new_thread(_start_sub,(cmd,name,mute)) # SERVER
 
 def startup_all_sdl():
-    print()
-    print("-> def",inspect.currentframe().f_code.co_name,"-"*10)
-    fname ="/home/user/gui-sdl.txt"
-    fname = show_path2+ _read_init_txt()[0]+ "/gui-sdl.txt"
+    #print()
+    #print("-> def",inspect.currentframe().f_code.co_name,"-"*10)
+
+    fname = SHOW_PATH + "/gui-sdl.txt"
     if os.path.isfile(fname):
         f=open(fname,"r")
         xlines = f.readlines()
         f.close()
 
-        print("  read",fname)
+        print()
+        cprint("startup_all_sdl() ",fname,color="yellow")
         for line in xlines:
             line = line.strip()
             if line.startswith("#-- history"):
                 break
             elif line.startswith("#"):
                 continue
+            if not line:
+                continue
             else:
-                print("    line >> ",[line])
+                #print("    line >> ",[line])
                 try:
                     line = json.loads(line)
                     cmd = "python3 /opt/LibreLight/Xdesk/tksdl/{}"
@@ -210,45 +216,15 @@ def startup_all_sdl():
                 except json.decoder.JSONDecodeError as e:
                     cprint("ERR",e,color="red")
             time.sleep(0.3)
-def _read_init_txt():#show_path):
-    fname = show_path+"init.txt"
-    show_name = None
-    msg = ""
-
-    if not os.path.isfile( fname ):
-        msg = "_read_init_txt Errror: " +fname +"\n NOT FOUND !"
-        return [None,msg]
 
-    try:
-        f = open(fname,"r")
-        for line in f.readlines():
-            line = line.strip()
-            print("  init.txt:",[line])
-            if line.startswith("#"):
-                continue
-            if not line:
-                continue
+        print()
 
-            show_name = line
-            show_name = show_name.replace(".","")
-            show_name = show_name.replace("\\","")
-            show_name = show_name.replace("/","")
-    except Exception as e:
-        cprint("show name exception",color="red")
-        msg="read_init_txt Error:{}".format(e)
-    finally:
-        f.close()
 
-    return [show_name,msg]
-#example test use
-#python3 -i -c "import tool.movewin as w;d=w.Control();d.title='SDL-DMX';d.winfo()"
-#w.store_all_sdl()
-#d.get_winfo2()
-#d.move(100,100)
 def store_all_sdl():
-    print()
-    print("-> def",inspect.currentframe().f_code.co_name,"-"*10)
-    fname = show_path2+ _read_init_txt()[0]+ "/gui-sdl.txt"
+    #print()
+    #print("-> def",inspect.currentframe().f_code.co_name,"-"*10)
+    error = 0   
+    fname = SHOW_PATH + "/gui-sdl.txt"
     in_lines = []
 
     if os.path.isfile(fname):
@@ -256,14 +232,14 @@ def store_all_sdl():
         xlines = f.readlines()
         f.close()
 
-        print("  read",fname)
+        #print("  store_all_sdl fname",fname)
         for line in xlines:
             line = line.strip()
             if not line.startswith("#") and line:
                 in_lines.append(line)
         #in_lines.append('[0,"xx aa",0,0,0,0]')
-        for line in in_lines:
-            print(" R:",[line])
+        #for line in in_lines:
+        #    print(" R:",[line])
 
     lines = get_store_sdl_line()
     ap_line = []
@@ -275,13 +251,14 @@ def store_all_sdl():
             if line[1] in iline:
                 if j not in pop:
                     pop.append(j)
-                print(" del ",j,line)
+                #print(" del ",j,line)
 
     for i in pop[::-1]:
         try:
             in_lines.pop(i)
         except Exception as e:
-            print("ERR:",e) 
+            cprint("  ERR:",e,color="red") 
+            error += 0   
     temp = {}
     for i in in_lines:
         k = json.loads(i)[1]
@@ -296,20 +273,25 @@ def store_all_sdl():
     f.write("\n")
     f.write("#-- history \n")
     for k,line in temp.items(): #in_lines:
-        print("+++>",line)
+        #print("+++>",line)
         f.write(line+"\n")
     f.write("\n")
     f.close()
 
+    if not error:
+        cprint("  store_all_sdl OK fname:",fname,color="green")
+        return 1
+    cprint("  store_all_sdl FAIL fname:",fname,color="red")
+
 def movewin(_id="0xWinId",x=None,y=None):
     print()
-    print("-> def",inspect.currentframe().f_code.co_name,"-"*10)
+    #print("-> def",inspect.currentframe().f_code.co_name,"-"*10)
     cmd="xdotool windowmove {} {} {}".format(_id,x,y)
     return cmd
 
 def sizewin(_id="0xWinId",x=None,y=None):
     print()
-    print("-> def",inspect.currentframe().f_code.co_name,"-"*10)
+    #print("-> def",inspect.currentframe().f_code.co_name,"-"*10)
     cmd="xdotool windowsize {} {} {}".format(_id,x,y)
     return cmd
 
@@ -340,8 +322,8 @@ def search_process(_file_path,exact=1):
         if "python" not in ps[0]:
             continue
 
-        print(" ",[ps[1]])
-        print("exact_search",exact)
+        #print(" ",[ps[1]])
+        #print("exact_search",exact)
         if exact:
             if str(_file_path) == str(ps[1]):
                 print(ps)
@@ -359,12 +341,19 @@ def search_process(_file_path,exact=1):
 def process_kill(path):
     pids = search_process(path,exact=0)
     for pid in pids:
-        print("process_kill:",pid)
-        p = psutil.Process(pid)   
-        #p.name()
-        #p.cmdline()
-        p.terminate()
-        p.wait()
+        print("process_kill:",[path,pid])
+        cmd="kill -kill {} ".format(pid)
+
+        os.system(cmd)
+    time.sleep(0.2)
+    #for pid in pids:
+    #    print("process_kill:",path,pid)
+    #    p = psutil.Process(pid)   
+    #    #p.name()
+    #    #p.cmdline()
+    #    p.terminate()
+    #    p.wait()
+    print("process_kill OK")
 
 def get_lineno():
   callerframerecord = inspect.stack()[1]    # 0 represents this line