movewin.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. #!/usr/bin/python3
  2. import os
  3. import sys
  4. import time
  5. import psutil
  6. import json
  7. import inspect
  8. import _thread as thread
  9. HOME = os.getenv('HOME')
  10. show_path = HOME+"/LibreLight/"
  11. show_path2 = HOME+"/LibreLight/show/"
  12. # python3 movewin.py window-title x y
  13. # python3 movewin.py COMMA 723 943
  14. sys.path.insert(0,"/opt/LibreLight/Xdesk/")
  15. print(sys.path)
  16. from lib.cprint import cprint
  17. class Control():
  18. def __init__(self):
  19. self.title = "WinfoWinName"
  20. self.winid = ""
  21. def winfo(self):
  22. winid = winfo(self.title)
  23. if type(winid) == list:
  24. if len(winid) >= 1:
  25. self.winid = winid[0]
  26. def winfo2(self):
  27. winid = winfo2(self.title)
  28. #if type(winid) == list:
  29. # if len(winid) >= 1:
  30. # self.winid = winid[0]
  31. def move(self,x=None,y=None):
  32. if self.winid:
  33. cmd=movewin(_id=self.winid,x=x,y=y)
  34. system(cmd)
  35. def size(self,x=None,y=None):
  36. if self.winid:
  37. cmd = sizewin(_id=self.winid,x=x,y=y)
  38. system(cmd)
  39. def activate(self):
  40. if self.winid:
  41. cmd=activate(_id=self.winid)
  42. system(cmd)
  43. def winfo(name="WinfoWinName"):
  44. search = name
  45. cmd = "xwininfo -root -children -all | grep '{}'"
  46. cmd = cmd.format(search)
  47. print(cmd)
  48. r = os.popen(cmd)
  49. lines = r.readlines()
  50. _id = [] #"xxxx"
  51. if lines and lines[0]:
  52. _id.append( lines[0].split()[0] )
  53. print("ID:",_id)
  54. for line in lines:
  55. line = line.strip()
  56. print("-",line)
  57. return _id
  58. def parse_winfo_line(line):
  59. a1 = 0
  60. a2 = 0
  61. ps_name = ""
  62. ps_title = ""
  63. ps_id = ""
  64. ps_pos = ""
  65. ps_size = ""
  66. if line: # in lines:
  67. a1 = line.index(' ("')+2
  68. a2 = line.index('") ')+1
  69. ps_id = line.split()[0]
  70. ps_id = ps_id.replace(" ","")
  71. ps_pos = line.split()[-1]
  72. ps_size = line.split()[-2]
  73. ps_pos = ps_pos.replace("+"," ").replace("x"," ")
  74. ps_size = ps_size.replace("+"," ").replace("x"," ")
  75. ps_pos = ps_pos.strip().split()
  76. ps_size = ps_size.strip().split()
  77. for i in range(len(ps_pos)):
  78. ps_pos[i] = int(ps_pos[i])
  79. for i in range(len(ps_size)):
  80. ps_size[i] = int(ps_size[i])
  81. ps_pos[-2] -= ps_size[-2]
  82. ps_pos[-1] -= ps_size[-1]
  83. #ps_pos_x1 = int(ps_apos.split("+")[-2])
  84. #ps_pos_y1 = int(ps_pos.split("+")[-1])
  85. if a1 >= 0 and a2 >= 0:
  86. ps_name = line[a1:a2]
  87. line = line[:a1]+line[a2:]
  88. if ' "' in line and '":' in line:
  89. a1 = line.index(' "')+2
  90. a2 = line.index('":')
  91. ps_title = line[a1:a2]
  92. _line = [ps_id,ps_name,ps_title,ps_size,ps_pos]
  93. print(" ",_line)
  94. return _line
  95. def winfo2(name="WinfoWinName"):
  96. print("--------------")
  97. search = name
  98. cmd = "xwininfo -root -children -all | grep '{}'"
  99. cmd = cmd.format(search)
  100. print(cmd)
  101. r = os.popen(cmd)
  102. lines = r.readlines()
  103. _data = []
  104. for line in lines:
  105. a = parse_winfo_line(line)
  106. if a:
  107. _data.append(a)
  108. print("--------------")
  109. return _data
  110. def get_store_sdl_line():
  111. print()
  112. print("-> def",inspect.currentframe().f_code.co_name,"-"*10)
  113. lines = winfo2(name="SDL-")
  114. out_lines=[]
  115. for line in lines:
  116. t=line[2].split()
  117. for k in t:
  118. k = k.replace(" ", "_")
  119. if "SDL-" in k:
  120. s=line[-2]
  121. p=line[-1]
  122. # info: b x h + x + y
  123. out = [1,k, s[0],s[1],p[0],p[1] ]
  124. out_lines.append(out)
  125. return out_lines
  126. def load_all_sdl(title="X"):
  127. fname ="/home/user/gui-sdl.txt"
  128. fname = show_path2+ _read_init_txt()[0]+ "/gui-sdl.txt"
  129. if os.path.isfile(fname):
  130. f=open(fname,"r")
  131. lines = f.readlines()
  132. f.close()
  133. print(" read",fname)
  134. for line in lines:
  135. if title in line:
  136. return json.loads(line)
  137. def _start_sub(cmd,name,mute=0):
  138. r = os.popen(cmd)
  139. while 1:
  140. #print(dir(r))
  141. line = r.readline()
  142. if not line:
  143. break
  144. line = line.strip()
  145. if mute == 0:
  146. cprint(name,":",[line],color="blue")
  147. cprint("EXIT:",name,cmd)
  148. #BrokenPipeError: [Errno 32] Broken pipe
  149. def start_sub(cmd,name="<PROCESS>",mute=0):
  150. thread.start_new_thread(_start_sub,(cmd,name,mute)) # SERVER
  151. def startup_all_sdl():
  152. print()
  153. print("-> def",inspect.currentframe().f_code.co_name,"-"*10)
  154. fname ="/home/user/gui-sdl.txt"
  155. fname = show_path2+ _read_init_txt()[0]+ "/gui-sdl.txt"
  156. if os.path.isfile(fname):
  157. f=open(fname,"r")
  158. xlines = f.readlines()
  159. f.close()
  160. print(" read",fname)
  161. for line in xlines:
  162. line = line.strip()
  163. if line.startswith("#-- history"):
  164. break
  165. elif line.startswith("#"):
  166. continue
  167. else:
  168. print(" line >> ",[line])
  169. try:
  170. line = json.loads(line)
  171. cmd = "python3 /opt/LibreLight/Xdesk/tksdl/{}"
  172. if line[1] == "SDL-MIDI":
  173. cmd=cmd.format("midi.py")
  174. #r=os.popen(cmd)
  175. start_sub(cmd,"SDL-MIDI",mute=1)
  176. elif line[1] == "SDL-DMX":
  177. cmd=cmd.format("dmx.py")
  178. #os.popen(cmd)
  179. start_sub(cmd,"SDL-DMX",mute=1)
  180. elif line[1] == "SDL-FIX-LIST":
  181. cmd=cmd.format("fix.py")
  182. #r=os.popen(cmd)
  183. start_sub(cmd,"SDL-FIX",mute=1)
  184. except json.decoder.JSONDecodeError as e:
  185. cprint("ERR",e,color="red")
  186. time.sleep(0.3)
  187. def _read_init_txt():#show_path):
  188. fname = show_path+"init.txt"
  189. show_name = None
  190. msg = ""
  191. if not os.path.isfile( fname ):
  192. msg = "_read_init_txt Errror: " +fname +"\n NOT FOUND !"
  193. return [None,msg]
  194. try:
  195. f = open(fname,"r")
  196. for line in f.readlines():
  197. line = line.strip()
  198. print(" init.txt:",[line])
  199. if line.startswith("#"):
  200. continue
  201. if not line:
  202. continue
  203. show_name = line
  204. show_name = show_name.replace(".","")
  205. show_name = show_name.replace("\\","")
  206. show_name = show_name.replace("/","")
  207. except Exception as e:
  208. cprint("show name exception",color="red")
  209. msg="read_init_txt Error:{}".format(e)
  210. finally:
  211. f.close()
  212. return [show_name,msg]
  213. #example test use
  214. #python3 -i -c "import tool.movewin as w;d=w.Control();d.title='SDL-DMX';d.winfo()"
  215. #w.store_all_sdl()
  216. #d.get_winfo2()
  217. #d.move(100,100)
  218. def store_all_sdl():
  219. print()
  220. print("-> def",inspect.currentframe().f_code.co_name,"-"*10)
  221. fname = show_path2+ _read_init_txt()[0]+ "/gui-sdl.txt"
  222. in_lines = []
  223. if os.path.isfile(fname):
  224. f=open(fname,"r")
  225. xlines = f.readlines()
  226. f.close()
  227. print(" read",fname)
  228. for line in xlines:
  229. line = line.strip()
  230. if not line.startswith("#") and line:
  231. in_lines.append(line)
  232. #in_lines.append('[0,"xx aa",0,0,0,0]')
  233. for line in in_lines:
  234. print(" R:",[line])
  235. lines = get_store_sdl_line()
  236. ap_line = []
  237. pop = []
  238. for line in lines:
  239. ok = 0
  240. iline = ""
  241. for j,iline in enumerate(in_lines):
  242. if line[1] in iline:
  243. if j not in pop:
  244. pop.append(j)
  245. print(" del ",j,line)
  246. for i in pop[::-1]:
  247. try:
  248. in_lines.pop(i)
  249. except Exception as e:
  250. print("ERR:",e)
  251. temp = {}
  252. for i in in_lines:
  253. k = json.loads(i)[1]
  254. if k not in temp:
  255. temp[k] = i
  256. f=open(fname,"w")
  257. f.write("#"+json.dumps(["on","title","w","h","x","y"])+"\n")
  258. for line in lines:
  259. f.write(json.dumps(line)+"\n")
  260. f.write("\n")
  261. f.write("#-- history \n")
  262. for k,line in temp.items(): #in_lines:
  263. print("+++>",line)
  264. f.write(line+"\n")
  265. f.write("\n")
  266. f.close()
  267. def movewin(_id="0xWinId",x=None,y=None):
  268. print()
  269. print("-> def",inspect.currentframe().f_code.co_name,"-"*10)
  270. cmd="xdotool windowmove {} {} {}".format(_id,x,y)
  271. return cmd
  272. def sizewin(_id="0xWinId",x=None,y=None):
  273. print()
  274. print("-> def",inspect.currentframe().f_code.co_name,"-"*10)
  275. cmd="xdotool windowsize {} {} {}".format(_id,x,y)
  276. return cmd
  277. def activate(_id="0xWinId"):
  278. cmd="xdotool windowactivate {}".format(_id)
  279. return cmd
  280. def system(cmd):
  281. print(cmd)
  282. os.system(cmd)
  283. def search_process(_file_path,exact=1):
  284. print("search_process",_file_path)
  285. pids = psutil.pids()
  286. count = 0
  287. out = []
  288. for pid in pids:
  289. try:
  290. p = psutil.Process(pid)
  291. except psutil.NoSuchProcess:
  292. break
  293. ps = p.cmdline()
  294. if len(ps) < 2:
  295. continue
  296. if "python" not in ps[0]:
  297. continue
  298. print(" ",[ps[1]])
  299. print("exact_search",exact)
  300. if exact:
  301. if str(_file_path) == str(ps[1]):
  302. print(ps)
  303. count += 1
  304. out.append(pid)
  305. else:
  306. if str(_file_path) in str(ps[1]):
  307. print(ps)
  308. count += 1
  309. out.append(pid)
  310. print("search_process",count)
  311. return out
  312. def process_kill(path):
  313. pids = search_process(path,exact=0)
  314. for pid in pids:
  315. print("process_kill:",pid)
  316. p = psutil.Process(pid)
  317. #p.name()
  318. #p.cmdline()
  319. p.terminate()
  320. p.wait()
  321. def get_lineno():
  322. callerframerecord = inspect.stack()[1] # 0 represents this line
  323. # 1 represents line at caller
  324. frame = callerframerecord[0]
  325. info = inspect.getframeinfo(frame)
  326. #print(info.filename) # __FILE__ -> Test.py
  327. #print(info.function) # __FUNCTION__ -> Main
  328. #print(info.lineno) # __LINE__ -> 13
  329. return info.lineno
  330. if __name__ == "__main__":
  331. print("# python3 movewin.py window-title x y")
  332. print("# python3 movewin.py COMMA 723 943")
  333. import random
  334. a=random.randint(100,400)
  335. b=random.randint(100,400)
  336. search = "ASD"
  337. try:
  338. search = sys.argv[1]
  339. search = search.replace("'","")
  340. except:pass
  341. try:
  342. a = sys.argv[2]
  343. except:pass
  344. try:
  345. b = sys.argv[3]
  346. except:pass
  347. _ids = winfo(search)
  348. for _id in _ids:
  349. c1 = sizewin(_id,a,b)
  350. c2 = movewin(_id,a,b)
  351. c3 = activate(_id)
  352. system(c1)
  353. time.sleep(0.1)
  354. system(c2)
  355. time.sleep(0.1)
  356. system(c3)
  357. def check_is_started(CAPTION,_file_path,sleep=0):
  358. if sleep:
  359. time.sleep(sleep)
  360. pids = search_process(_file_path)
  361. if len(pids) >= 2:
  362. search = CAPTION[:]
  363. _ids = winfo(search)
  364. for _id in _ids:
  365. c3 = activate(_id)
  366. print("check_is_started CMD:",c3)
  367. os.system(c3)
  368. time.sleep(1)
  369. sys.exit()