AceScottie

aceutil.py

Aug 20th, 2019
420
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.86 KB | None | 0 0
  1. import sys, time, os
  2. def no(): #fix for cButton function, used as a default command
  3.     pass
  4. class Error(Exception):
  5.     pass
  6. class utils():
  7.     def __init__(self):
  8.         import time
  9.         self.varstore = {}
  10.         self.textlen = 0
  11.     def writelines(self, text): #print over same line
  12.         self.text = text
  13.         sys.stdout.write('\r' + ' ' * self.textlen + '\r')
  14.         sys.stdout.flush()
  15.         sys.stdout.write('\r' + str(self.text) + '\r')
  16.         sys.stdout.flush()
  17.         self.textlen = len(text)
  18.     def sleeper(self, interval): #sleep in miliseconds
  19.         interval = interval/1000
  20.         time.sleep(interval)
  21.     def var_store(self, text="", key=""):
  22.         if ley != "":
  23.             if text != "":
  24.                 self.varstore[key] = text
  25.             else:
  26.                 return self.varstore[key]
  27.     def pad(self, input, length):
  28.         x = ""
  29.         for i in range(length-len(str(input))):
  30.             x+="0"
  31.         x+=str(input)
  32.         return x
  33.     def help(self):
  34.         commands = """
  35.         writelines(text): wrights the text string to the stdout and then flushes the line, overwrights line each time.
  36.         sleeper(interval): same as time.sleep(interval) but uses interval in miliseconds rather than seconds.
  37.         var_store(text, key): stores the text string as a instanced variable. Stores multiple using unique key.
  38.         pad(input, length): adds leading 0s to input untill input meets lenght
  39.         """
  40.         return commands
  41. class serialHandler():
  42.     def __init__(self, ser="", timeout=1, baudrate=9600):
  43.         import serial
  44.         if ser == "" or not isinstance(ser, basestring):
  45.             raise Error("Exception: 'serialHandler(address)'. please include the serial port address as a string")
  46.         self.ser = serial.Serial(ser, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=timeout, xonxoff=False, rtscts=False, dsrdtr=False)
  47.         print("created serial port with options p:%s b:%s t:%s" %(ser, str(baudrate), str(timeout)))
  48.     def read(self):
  49.         count = 0
  50.         msg = ""
  51.         tries = 4
  52.         while len(msg) < 1:
  53.             msg = self.ser.readline()
  54.             count += 1
  55.             if count >= tries:
  56.                 return "Error reading from serial"
  57.                 break
  58.         return msg
  59.     def write(self, text):
  60.         if text == "" or not isinstance(text, basestring):
  61.             raise Error("Exception: 'serialHandler.write(text)'. text must be a valid string")
  62.         else:
  63.             self.ser.write(text)
  64.             self.ser.flush()
  65.     def close(self):
  66.         self.ser.close()
  67.         pass
  68.     def help():
  69.         commands = """
  70.         init(serial): uses serial string to create an instanced serial connection using default values. serial string is the port.
  71.         'baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=1, xonxoff=False, rtscts=False, dsrdtr=False'
  72.         read(): reads data from the serial. if there is no data will retry untill there is data or it has tried 1000 times. returs string of the data.
  73.         write(text): wrights data to the instanced serial connection.
  74.         """
  75.         return commands
  76. class TkUtils:
  77.     def __init__(self, log, root):
  78.         try:
  79.             import Tkinter
  80.             self.TkUtil = Tkinter
  81.         except:
  82.             import tkinter
  83.             self.TkUtil = tkinter
  84.         import threading
  85.         import time
  86.         import traceback
  87.         self.traceback = traceback
  88.         self.time = time
  89.         self.threading = threading
  90.         self.log = log
  91.         self.root = root
  92.         self.active_window = None
  93.         self.active_side = None
  94.         self.active_scroll = None
  95.         self.run = False
  96.         self.moving = False
  97.     def cButton(self, element, borderwidth=0, width=0, height=0, fg="#07a501", bg="white", text="", relief="groove", padx=0, pady=0, command=no(), side=None, expand=0, fill=None, state="normal", anchor="nsew", cursor="hand2", font=None, image=None, justify=None): #basic button
  98.         try:
  99.             if state != "normal":
  100.                 cursor="arrow"
  101.             b = self.TkUtil.Button(element, borderwidth=borderwidth, width=width, height=height, fg=fg, bg=bg, text=text, padx=padx, pady=pady, relief=relief, command=command, state=state, cursor=cursor, font=font, image=image, justify=justify)
  102.             b.pack(side=side, expand=expand, fill=fill)
  103.             return b
  104.         except Exception as err:
  105.             self.log.error("atk.cButton failed\n%s" %err)      
  106.     def cFrame(self, element, bg="white", borderwidth=0, relief="groove", side=None, padx=0, pady=0, height=0, width=0, expand=0, fill=None, image=None, highlightbackground=None, highlightcolor=None, highlightthickness=0):#basic frame
  107.         try:
  108.             f = self.TkUtil.Frame(element, bg=bg, borderwidth=borderwidth, relief=relief, height=height, width=width, image=image, highlightbackground=highlightbackground, highlightcolor=highlightcolor, highlightthickness=highlightthickness)
  109.             f.pack(side=side, padx=padx, pady=pady, expand=expand, fill=fill)
  110.             return f
  111.         except Exception as err:
  112.             self.log.error("atk.cFrame failed\n%s" %err)
  113.             return None
  114.     def create_overlay(self, over, event, title, height=400, width=400):
  115.         if self.active_window != None:
  116.             self.clear_overlay(self.TkUtil.Event())
  117.             self.create_overlay(over, event, title, height, width)
  118.         else:
  119.             try:
  120.                 try:
  121.                     rootx = self.root.winfo_width()
  122.                     rooty = self.root.winfo_height()
  123.                 except:
  124.                     rootx = 200
  125.                     rooty = 150
  126.                     self.log.log("create_overlay could not get width or height")
  127.                 window = self.TkUtil.Canvas(over, width=width, height=height, bg="white", relief="groove", highlightbackground="black", highlightcolor="black", highlightthickness=1, borderwidth=4)
  128.                 self.active_window = window
  129.                 window.pack_propagate(False)
  130.                 window.place(x=rootx/2-(width/2), y=(rooty/2)-(height/4))
  131.                 self.root.update_idletasks()
  132.                 self.root.update()
  133.                 spacer = self.cFrame(window, padx=7, pady=7, fill=self.TkUtil.BOTH)
  134.                 Title = self.TkUtil.Label(spacer, text=title, justify=self.TkUtil.RIGHT, font=("Helvetica", 10), bg="#EEEEEE", padx=10, pady=5, cursor="fleur")
  135.                 Title.pack(side=self.TkUtil.LEFT,  expand=1, fill=self.TkUtil.X)
  136.                 #Title.bind("<ButtonPress-1>", lambda e=self.TkUtil.Event(), w=window, run=True: self.move_window(e, w, run))
  137.                 #Title.bind("<ButtonRelease-1>", lambda e=self.TkUtil.Event(), w=window, run=False: self.move_window(e, w, run))
  138.                 Title.bind("<B1-Motion>", lambda e=event, w=window: self.move_window_thread(w, e))
  139.                 close = self.cButton(spacer, text="X", relief="raised", borderwidth=1, fg="black", side=self.TkUtil.RIGHT, command=lambda e=self.TkUtil.Event(): self.clear_overlay(e))
  140.                 spacer = self.cFrame(window, side=self.TkUtil.BOTTOM, pady=3)
  141.                 self.set_pos(window)
  142.             except:
  143.                 self.log.log("atk.create_overlay failed")
  144.                 pass
  145.             return "break"
  146.     def clear_overlay(self, event): #clear overlayed canvas
  147.         self.log.log("atk.autil clearing windows")
  148.         if self.active_window != None:
  149.             self.active_window.destroy()
  150.             self.active_window = None
  151.         return "break"
  152.     def overlay(self, over, event, title, height=400, width=400):
  153.         if self.active_window == None:
  154.             self.create_overlay(over, event, title, width=width, height=height)
  155.             return self.active_window
  156.         else:
  157.             self.clear_overlay(self.TkUtil.Event())
  158.             self.create_overlay(over, event, title, width=width, height=height)
  159.             return self.active_window
  160.     def move_window(self, event, window, run):
  161.         self.run = run
  162.         if self.run:
  163.             t= self.threading.Thread(target=self.move_window_thread,args=(window, event))
  164.             t.start()
  165.     def move_window_thread(self, window, event):
  166.         try:
  167.             if not self.moving:
  168.                 self.moving = True
  169.                 self.root.update_idletasks()
  170.                 self.root.update()
  171.                 #self.time.sleep(0.05)
  172.                 if(self.root.winfo_pointerx() != "??" and self.root.winfo_pointery() != "??"):
  173.                     window.place(x=(self.root.winfo_pointerx() - self.root.winfo_rootx())-window.winfo_width()/2, y=self.root.winfo_pointery() - self.root.winfo_rooty()-10)
  174.                     #self.time.sleep(0.05)
  175.                 self.moving= False
  176.         except Exception as err:
  177.             exc_type, exc_obj, exc_tb = sys.exc_info()
  178.             self.log.error("move_window_thread failed\n%s, %s, %s, %s" %(err, exc_type, exc_obj, self.traceback.print_tb(exc_tb)))
  179.             pass   
  180.     def set_pos(self, window):
  181.         try:
  182.             rootx = self.root.winfo_width()
  183.             rooty= self.root.winfo_height()
  184.             wx = window.winfo_width()
  185.             wy = window.winfo_height()
  186.         except:
  187.             rootx = 200
  188.             rooty = 150
  189.             wx = 400
  190.             wy = 400
  191.             self.log.log("set_pos failed")
  192.         window.place(x=(rootx/2)-(wx/2), y=(rooty/2)-(wy/2))
  193.     def scrollable_area2(self, holder):
  194.         try:
  195.             base_frame = self.cFrame(holder, fill=self.TkUtil.BOTH, expand=1, padx=5, pady=5)
  196.             base_frame.rowconfigure(0, weight=0)
  197.             base_frame.columnconfigure(0, weight=1)
  198.             can = self.TkUtil.Canvas(base_frame, bg="white")
  199.             can.pack(side=self.TkUtil.LEFT, expand=1, fill=self.TkUtil.BOTH)
  200.             scrollArea = self.cFrame(base_frame, bg="white", side=self.TkUtil.LEFT, expand=1, fill=self.TkUtil.BOTH)
  201.             can.create_window(0, 0, window=scrollArea, anchor='nw')
  202.             Scroll = self.TkUtil.Scrollbar(base_frame, orient=self.TkUtil.VERTICAL)
  203.             Scroll.config(command=can.yview)
  204.             Scroll.pack(side=self.TkUtil.RIGHT, fill=self.TkUtil.Y)
  205.             can.config(yscrollcommand=Scroll.set)
  206.             scrollArea.bind("<Configure>",  lambda e=self.TkUtil.Event(), c=can: self.update_scrollregion(e, c))
  207.             base_frame.bind("<Enter>", lambda e=self.TkUtil.Event():self.set_active(e, can))
  208.             base_frame.bind("<Leave>", lambda e=self.TkUtil.Event():self.unset_active(e))
  209.             return scrollArea, can
  210.         except Exception as err:
  211.             exc_type, exc_obj, exc_tb = sys.exc_info()
  212.             self.log.error("get_access_users failed\n%s, %s, %s, %s" %(err, exc_type, exc_obj, self.traceback.print_tb(exc_tb)))
  213.     def h_scrollable_area(self, holder):
  214.         try:
  215.             base_frame = self.cFrame(holder, fill=self.TkUtil.BOTH, expand=1, padx=5, pady=5)
  216.             base_frame.rowconfigure(0, weight=0)
  217.             base_frame.columnconfigure(0, weight=1)
  218.             can = self.TkUtil.Canvas(base_frame, bg="white")
  219.             can.pack(side=self.TkUtil.TOP, expand=1, fill=self.TkUtil.BOTH)
  220.             scrollArea = self.cFrame(base_frame, bg="white", side=self.TkUtil.TOP, expand=1, fill=self.TkUtil.BOTH)
  221.             can.create_window(0, 0, window=scrollArea, anchor='nw')
  222.             Scroll = self.TkUtil.Scrollbar(base_frame, orient=self.TkUtil.HORIZONTAL)
  223.             Scroll.config(command=can.xview)
  224.             Scroll.pack(side=self.TkUtil.BOTTOM, fill=self.TkUtil.X)
  225.             can.config(xscrollcommand=Scroll.set)
  226.             scrollArea.bind("<Configure>",  lambda e=self.TkUtil.Event(), c=can: self.update_scrollregion(e, c))
  227.             return scrollArea, can
  228.         except Exception as err:
  229.             exc_type, exc_obj, exc_tb = sys.exc_info()
  230.             self.log.error("get_access_users failed\n%s, %s, %s, %s" %(err, exc_type, exc_obj, self.traceback.print_tb(exc_tb)))   
  231.     def set_active(self, event, canvas):
  232.         self.active_scroll = canvas
  233.         pass
  234.     def unset_active(self, event):
  235.         self.active_scroll = None
  236.         pass
  237.     def reset_scroll(self, element):
  238.         self.root.nametowidget(element.winfo_parent()).yview_moveto(0)
  239.         self.root.nametowidget(element.winfo_parent()).yview_scroll(0, "units")
  240.     def _on_mousescroll(self, event):
  241.         if self.active_scroll != None:
  242.             self.active_scroll.yview_scroll(-1*(event.delta/120), "units")
  243.     def update_scrollregion(self, event, can):
  244.         can.configure(scrollregion=can.bbox("all"))
  245.         pass
  246.     def OnCanvasConfigure(self, event, can, scroll):
  247.         canvas_width = event.width
  248.         can.itemconfig(scroll, width = canvas_width)
  249.     def test_buttons(self, main, defaultIcon):
  250.         self.root.update_idletasks()
  251.         self.root.update()
  252.         for i in range(20):
  253.             Packer, state = self.cFrame(main, bg="white", borderwidth=2, width=400, relief=self.TkUtil.RAISED, fill=self.TkUtil.X, expand=1)
  254.             L= self.TkUtil.Label(Packer, anchor=self.TkUtil.W, justify=self.TkUtil.LEFT, text="Test %s"%i, bg="red", borderwidth=0)
  255.             L.pack(side=self.TkUtil.LEFT, fill=self.TkUtil.X)
  256.             L2= self.TkUtil.Label(Packer, anchor=self.TkUtil.W, image=defaultIcon)
  257.             L2.pack(side=self.TkUtil.RIGHT)
  258. class Log: #class to write to log file with time stamps
  259.     def __init__(self, appname):
  260.         import os, traceback, time
  261.         self.traceback = traceback
  262.         self.os = os
  263.         self.time = time
  264.         if getattr(sys, 'frozen', False): #windows path fix
  265.             self.exe = self.os.path.dirname(sys.executable)
  266.         elif __file__:
  267.             self.exe = self.os.path.dirname(__file__)
  268.         if not os.path.exists(os.path.dirname(str(os.environ['USERPROFILE'])+"\\Documents\\%s\\" %appname)):
  269.             os.makedirs(str(os.environ['USERPROFILE'])+"\\Documents\\%s\\" %appname)
  270.         self.fname = str(os.environ['USERPROFILE'])+"\\Documents\\%s\\debug.log" %appname
  271.         self.logfile = None
  272.     def error(self, error):
  273.         exc_type, exc_obj, exc_tb = sys.exc_info()
  274.         trace_stack = self.traceback.extract_tb(exc_tb)[-1]
  275.         trace_format = "Error in file "+str(trace_stack[0])+"\r     on line "+str(trace_stack[1])+", from module '"+str(trace_stack[2])+"'\r        "+str(trace_stack[3])
  276.         try:
  277.             self.logfile = open(self.fname, "a+")
  278.         except:
  279.             self.logfile = open(self.fname, "w+")
  280.         strtime = str(self.time.strftime("%d-%m-%Y,(%z),%H:%M:%S"))
  281.         self.logfile.write("error: %s, %s, %s\r" %(strtime, error, trace_format))
  282.         self.logfile.close()
  283.         self.logfile = None
  284.     def log(self, log):
  285.         try:
  286.             self.logfile = open(self.fname, "a+")
  287.         except:
  288.             self.logfile = open(self.fname, "w+")
  289.         strtime = str(self.time.strftime("%d-%m-%Y,(%z),%H:%M:%S"))
  290.         self.logfile.write("log: %s, %s\r" %(strtime, log))
  291.         self.logfile.close()
  292.         self.logfile = None
Add Comment
Please, Sign In to add comment