def _schtasks(self, args, elevated=False, echo=False): if elevated: try: p = run_as_admin("schtasks.exe", args, close_process=False, show=False) except pywintypes.error as exception: if exception.args[0] == winerror.ERROR_CANCELLED: self.lastreturncode = winerror.ERROR_CANCELLED else: raise else: self.lastreturncode = int(p["hProcess"].handle == 0) p["hProcess"].Close() finally: self.stdout = "" else: args.insert(0, "schtasks.exe") startupinfo = sp.STARTUPINFO() startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOW startupinfo.wShowWindow = sp.SW_HIDE p = sp.Popen([safe_str(arg) for arg in args], stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.STDOUT, startupinfo=startupinfo) self.stdout, stderr = p.communicate() if echo: safe_print(safe_unicode(self.stdout, enc)) self.lastreturncode = p.returncode return self.lastreturncode == 0
def lock(self): lockdir = os.path.dirname(self._lockfilename) try: if not os.path.isdir(lockdir): os.makedirs(lockdir) # Create lockfile self._lockfile = open(self._lockfilename, self._mode) except EnvironmentError as exception: # This shouldn't happen safe_print( "Error - could not open lockfile %s:" % self._lockfilename, exception) else: try: self._lock = FileLock(self._lockfile, self._exclusive, self._blocking) except FileLock.LockingError as exception: pass except EnvironmentError as exception: # This shouldn't happen safe_print( "Error - could not lock lockfile %s:" % self._lockfile.name, exception) else: return True return False
def init(set_wx_locale=False): """ Populate translation dict with found language strings and set locale. If set_wx_locale is True, set locale also for wxPython. """ langdirs = [] for dir_ in data_dirs: langdirs.append(os.path.join(dir_, "lang")) for langdir in langdirs: if os.path.exists(langdir) and os.path.isdir(langdir): try: langfiles = os.listdir(langdir) except Exception as exception: safe_print("Warning - directory '%s' listing failed: %s" % tuple(safe_unicode(s) for s in (langdir, exception))) else: for filename in langfiles: name, ext = os.path.splitext(filename) if ext.lower() == ".yaml" and name.lower() not in ldict: path = os.path.join(langdir, filename) ldict[name.lower()] = LazyDict_YAML_UltraLite(path) if len(ldict) == 0: handle_error(UserWarning("Warning: No language files found. The " "following places have been searched:\n%s" % "\n".join(langdirs)))
def get_data_path(relpath, rex=None): """ Search data_dirs for relpath and return the path or a file list. If relpath is a file, return the full path, if relpath is a directory, return a list of files in the intersection of searched directories. """ if (not relpath or relpath.endswith(os.path.sep) or (isinstance(os.path.altsep, basestring) and relpath.endswith(os.path.altsep))): return None intersection = [] paths = [] for dir_ in data_dirs: curpath = os.path.join(dir_, relpath) if os.path.exists(curpath): if os.path.isdir(curpath): try: filelist = listdir_re(curpath, rex) except Exception, exception: from log import safe_print safe_print(u"Error - directory '%s' listing failed: %s" % tuple(safe_unicode(s) for s in (curpath, exception))) else: for filename in filelist: if not filename in intersection: intersection += [filename] paths += [os.path.join(curpath, filename)] else: return curpath
def wait(self): self.listening = True if self.logfile: try: host = get_network_addr() except error: host = gethostname() self.logfile.write( lang.getstr("webserver.waiting") + (" %s:%s\n" % (host, self.port))) self.socket.settimeout(1) while self.listening: try: self.conn, addr = self.get_request() except timeout: continue self.conn.settimeout(1) break self.socket.settimeout(None) if self.listening: try: self.process_request(self.conn, addr) except: self.handle_error(self.conn, addr) self.disconnect_client() else: self._thread = threading.Thread( target=self.serve_forever, name="WebWinHTTPPatternGeneratorServerThread") self._thread.start() safe_print(lang.getstr("connection.established"))
def wait(self): self.listening = True if self.logfile: self.logfile.write( lang.getstr("connecting.to", ("Chromecast", " " + self.name)) + "\n") if not hasattr(self, "_cc"): # Find our ChromeCast try: self._cc = next(cc for cc in get_chromecasts() if safe_unicode( cc.device.friendly_name, "UTF-8") == self.name) except StopIteration: self.listening = False raise self._cc.register_handler(self._controller) # Wait for ChromeCast device to be ready while self.listening: self._cc.wait(0.05) if self._cc.status: break if self.listening: # Launch pattern generator app self._controller.launch() # Wait for it while (self.listening and self._cc.app_id != self._controller.supporting_app_id): sleep(0.05) self.conn = True safe_print(lang.getstr("connection.established"))
def get_argyll_version_string(name, paths=None): argyll_version_string = "0.0.0" cmd = get_argyll_util(name, paths) if sys.platform == "win32": startupinfo = sp.STARTUPINFO() startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOW startupinfo.wShowWindow = sp.SW_HIDE else: startupinfo = None try: p = sp.Popen([cmd.encode(fs_enc), "-?"], stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.STDOUT, startupinfo=startupinfo) except Exception as exception: safe_print(exception) return argyll_version_string for i, line in enumerate((p.communicate()[0] or "").splitlines()): if isinstance(line, str): line = line.strip() if "version" in line.lower(): argyll_version_string = line[line.lower().find("version") + 8:] break return argyll_version_string
def focus_lost_handler(self, e): e.Skip() if debug: safe_print("KILL_FOCUS", e.EventObject.Name) if e.EventObject is not self: self.last_focused = e.EventObject if debug and self.last_focused: safe_print("last_focused", self.last_focused.Name)
def Destroy(self): if self.subMenu: self.subMenu.Destroy() if debug or verbose > 1: safe_print('Destroy', self.__class__.__name__, self.Id, _get_kind_str(self.Kind), self.ItemLabel) if self.Id in IdFactory.ReservedIds: IdFactory.UnreserveId(self.Id)
def send(self, data): try: self.socket.sendall(data + "\n") except socket.error as exception: # Connection lost? safe_print("Warning - could not send data %r:" % data, exception) return False return True
def connect(self, host, port): try: self.socket.connect((host, port)) except socket.error as exception: # Other instance probably died safe_print("Connection to %s:%s failed:" % (host, port), exception) return False return True
def __call__(self, idata): if not isinstance(idata, str): verbose = self.verbose if self.convert_video_rgb_to_clut65: devi_devip = self.devi_devip else: devi_devip = lambda v: v scale = float(self.scale) idata = list(idata) # Make a copy for i, v in enumerate(idata): if isinstance(v, (float, int)): self([idata]) return if not isinstance(v, str): if verbose: for n in v: if not isinstance(n, (float, int)): raise TypeError("xicclu: Expecting list of " "strings or n-tuples with " "floats") idata[i] = " ".join( str(devi_devip(n / scale) * scale) for n in v) else: idata = idata.splitlines() numrows = len(idata) chunklen = 1000 i = 0 p = self.subprocess prevperc = -1 while True: # Process in chunks to prevent broken pipe if input data is too # large if getattr(sys, "_sigbreak", False) and not self.subprocess_abort: self.subprocess_abort = True safe_print("Got SIGBREAK, aborting subprocess...") if self.subprocess_abort or self.thread_abort: if p.poll() is None: p.stdin.write("\n") p.stdin.close() p.wait() raise Info(lang.getstr("aborted")) if p.poll() is None: # We don't use communicate() because it will end the # process p.stdin.write("\n".join(idata[chunklen * i:chunklen * (i + 1)]) + "\n") p.stdin.flush() else: # Error break perc = round(chunklen * (i + 1) / float(numrows) * 100) if perc > prevperc and self.logfile: self.logfile.write("\r%i%%" % min(perc, 100)) prevperc = perc if chunklen * (i + 1) > numrows - 1: break i += 1
def disconnect(self): try: # Will fail if the socket isn't connected, i.e. if there was an # error during the call to connect() self.shutdown(socket.SHUT_RDWR) except socket.error as exception: if exception.errno != errno.ENOTCONN: safe_print(exception) self.close()
def focus_handler(self, e): e.Skip() if debug: safe_print("SET_FOCUS", e.EventObject.Name) if e.EventObject is self and getattr(self, "last_focused", None) not in (None, self): self.last_focused.SetFocus() if debug: safe_print(self.last_focused.Name + ".SetFocus()")
def print_callstack(): """ Print call stack """ import inspect stack = inspect.stack() indent = "" for frame, filename, linenum, funcname, line, exc in reversed(stack[1:]): safe_print(indent, funcname, filename, linenum, repr("".join(line).strip())) indent += " "
def write(self, contents): if self._lockfile: try: self._lockfile.write("%s\n" % contents) except EnvironmentError as exception: # This shouldn't happen safe_print( "Error - could not write to lockfile %s:" % self._lockfile.name, exception)
def OnDestroy(self, event): self.stop_timer() del self.timer if hasattr(wx.Window, "UnreserveControlId"): for id in self.id_to_keycode.keys(): if id < 0: try: wx.Window.UnreserveControlId(id) except wx.wxAssertionError as exception: safe_print(exception)
def process_config_file(path, fn): try: with open(path, "r") as f: for key, value in XDG.config_file_parser(f): fn(key, value) except EnvironmentError as exception: from log import safe_print safe_print("XDG: Couldn't read '%s':" % path, exception) return False return True
def load_default_dirs(self): paths = XDG.get_config_files("user-dirs.defaults") if not paths: from log import safe_print safe_print("XDG.UserDirs: No default user directories") return False def fn(name, path): self.default_dirs[name] = self.localize_path_name(path) return XDG.process_config_file(paths[0], fn)
def Destroy(self): for menuitem in self.MenuItems: menuitem.Destroy() if not self.Parent: if debug or verbose > 1: safe_print('DestroyMenu HMENU', self.hmenu) win32gui.DestroyMenu(self.hmenu) if debug or verbose > 1: safe_print('Destroy', self.__class__.__name__, self) self._destroyed = True wx.EvtHandler.Destroy(self)
def _shutdown(sock, addr): try: # Will fail if the socket isn't connected, i.e. if there # was an error during the call to connect() sock.shutdown(SHUT_RDWR) except error as exception: if exception.errno != errno.ENOTCONN: safe_print( "PatternGenerator: SHUT_RDWR for %s:%i failed:" % addr[:2], exception) sock.close()
def exit(self, raise_exception=True): self.close(raise_exception) if self.temp and os.path.isfile(self.profile_path): os.remove(self.profile_path) if self.tempdir and not os.listdir(self.tempdir): try: shutil.rmtree(self.tempdir, True) except Exception as exception: safe_print("Warning - temporary directory '%s' could " "not be removed: %s" % tuple( safe_unicode(s) for s in (self.tempdir, exception)))
def zoomin_handler(self, event): if debug: safe_print("[D] measureframe_zoomin_handler") # We can't use self.get_dimensions() here because if we are near # fullscreen, next magnification step will be larger than normal display_size = self.get_display()[1][2:] default_measureframe_size = get_default_size() size = floatlist(self.GetSize()) x, y = None, None self.place_n_zoom(x, y, scale=(display_size[0] / default_measureframe_size) / (display_size[0] / size[0]) + .125)
def safe_send(self, bytes): if self.has_worker_subprocess() and not self.worker.subprocess_abort: if not self.worker.instrument_on_screen: if not getattr(self, "wait_for_instrument_on_screen", False): self.wait_for_instrument_on_screen = True safe_print( "%s: Waiting for instrument to be placed on screen" % appname) wx.CallLater(200, self.safe_send, bytes) else: self.wait_for_instrument_on_screen = False self.worker.safe_send(bytes)
def zoomout_handler(self, event): if debug: safe_print("[D] measureframe_zoomout_handler") # We can't use self.get_dimensions() here because if we are # fullscreen, scale will be 50, thus changes won't be visible quickly display_size = self.get_display()[1][2:] default_measureframe_size = get_default_size() size = floatlist(self.GetSize()) x, y = None, None self.place_n_zoom(x, y, scale=(display_size[0] / default_measureframe_size) / (display_size[0] / size[0]) - .125)
def disconnect_client(self): self.listening = False if hasattr(self, "conn"): try: self.conn.shutdown(SHUT_RDWR) except error as exception: if exception.errno != errno.ENOTCONN: safe_print( "Warning - could not shutdown pattern generator " "connection:", exception) self.conn.close() del self.conn
def announce(self): """ Anounce ourselves """ port = self.broadcast_request_port sock = socket(AF_INET, SOCK_DGRAM) sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) sock.settimeout(1) sock.connect((self.broadcast_ip, port)) addr = sock.getsockname() if self.debug: safe_print( "PrismaPatternGeneratorClient: Sending broadcast from %s:%s to port %i" % (addr[0], addr[1], port)) sock.sendall(self.prod_oem) sock.close()
def _mp_xicclu(chunk, thread_abort_event, progress_queue, profile_filename, intent="r", direction="f", order="n", pcs=None, scale=1, cwd=None, startupinfo=None, use_icclu=False, use_cam_clipping=False, logfile=None, show_actual_if_clipped=False, input_encoding=None, output_encoding=None, abortmessage="Aborted", output_format=None, reverse=False, convert_video_rgb_to_clut65=False, verbose=1): if not config.cfg.items(config.ConfigParser.DEFAULTSECT): config.initcfg() profile = ICCP.ICCProfile(profile_filename) xicclu = Xicclu(profile, intent, direction, order, pcs, scale, cwd, startupinfo, use_icclu, use_cam_clipping, logfile, None, show_actual_if_clipped, input_encoding, output_encoding, convert_video_rgb_to_clut65, verbose) prevperc = 0 start = 0 num_subchunks = 50 subchunksize = float(len(chunk)) / num_subchunks for i in range(num_subchunks): if (thread_abort_event is not None and getattr(sys, "_sigbreak", False) and not thread_abort_event.is_set()): thread_abort_event.set() safe_print("Got SIGBREAK, aborting thread...") if thread_abort_event is not None and thread_abort_event.is_set(): xicclu.exit(raise_exception=False) return Info(abortmessage) end = int(math.ceil(subchunksize * (i + 1))) xicclu(chunk[start:end]) start = end perc = round((i + 1.0) / num_subchunks * 100) if progress_queue and perc > prevperc: progress_queue.put(perc - prevperc) prevperc = perc xicclu.exit() return xicclu.get(output_format=output_format, reverse=reverse)
def initcfg(): """ Initialize the configuration. Read in settings if the configuration file exists, else create the settings directory if nonexistent. """ # read pre-v0.2.2b configuration if present if sys.platform == "darwin": oldcfg = os.path.join(expanduseru("~"), "Library", "Preferences", appname + " Preferences") else: oldcfg = os.path.join(expanduseru("~"), "." + appname) makecfgdir() if os.path.exists(confighome) and \ not os.path.exists(os.path.join(confighome, appname + ".ini")): try: if os.path.isfile(oldcfg): oldcfg_file = open(oldcfg, "rb") oldcfg_contents = oldcfg_file.read() oldcfg_file.close() cfg_file = open(os.path.join(confighome, appname + ".ini"), "wb") cfg_file.write("[Default]\n" + oldcfg_contents) cfg_file.close() elif sys.platform == "win32": key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software\\" + appname) numsubkeys, numvalues, mtime = _winreg.QueryInfoKey(key) cfg_file = open(os.path.join(confighome, appname + ".ini"), "wb") cfg_file.write("[Default]\n") for i in range(numvalues): name, value, type_ = _winreg.EnumValue(key, i) if type_ == 1: cfg_file.write((u"%s = %s\n" % (name, value)).encode("UTF-8")) cfg_file.close() except Exception, exception: # WindowsError 2 means registry key does not exist, do not show # warning in that case if sys.platform != "win32" or not hasattr(exception, "errno") or \ exception.errno != 2: from log import safe_print safe_print("Warning - could not process old configuration:", safe_unicode(exception)) # Set a few defaults which have None as possible value and thus cannot # be set in the 'defaults' collection setcfg("gamap_src_viewcond", "mt") setcfg("gamap_out_viewcond", "mt")
def read(self): incoming = "" while not "\4" in incoming: try: data = self.socket.recv(1024) except socket.error as exception: if exception.errno == errno.EWOULDBLOCK: sleep(.05) continue safe_print("Warning - could not receive data:", exception) break if not data: break incoming += data return incoming
def Sound(filename, loop=False, raise_exceptions=False): """ Sound caching mechanism """ if (filename, loop) in _sounds: # Cache hit return _sounds[(filename, loop)] else: try: sound = _Sound(filename, loop) except Exception as exception: if raise_exceptions: raise safe_print(exception) sound = _Sound(None, loop) _sounds[(filename, loop)] = sound return sound
def init(self): self._initialized = True XDG.set_translation(self) self.load_all_configs() try: codecs.lookup(self.filename_encoding) except LookupError: from log import safe_print safe_print("XDG.UserDirs: Can't convert from UTF-8 to", self.filename_encoding) return False self.load_default_dirs() self.load_user_dirs()
def get_display_number(display_no): """ Translate from Argyll display index to wx display index """ from wxaddons import wx try: display = getcfg("displays").split(os.pathsep)[display_no] except IndexError: pass else: if display == "Web @ localhost": return 0 for i in xrange(wx.Display.GetCount()): geometry = "%i, %i, %ix%i" % tuple(wx.Display(i).Geometry) if display.find("@ " + geometry) > -1: if debug: from log import safe_print safe_print("[D] Found display %s at index %i" % (geometry, i)) display_no = i break return display_no
def get_edid(display_no=0, display_name=None): """ Get and parse EDID. Return dict. On Mac OS X, you need to specify a display name. On all other platforms, you need to specify a display number (zero-based). """ edid = None if sys.platform == "win32": # The ordering will work as long as Argyll continues using # EnumDisplayMonitors monitors = util_win.get_real_display_devices_info() moninfo = monitors[display_no] device = util_win.get_active_display_device(moninfo["Device"]) if not device: return {} id = device.DeviceID.split("\\")[1] if wmi_connection: # Use WMI for Vista/Win7 # http://msdn.microsoft.com/en-us/library/Aa392707 try: msmonitors = wmi_connection.WmiMonitorDescriptorMethods() except Exception, exception: raise WMIError(exception) for msmonitor in msmonitors: if msmonitor.InstanceName.split("\\")[1] == id: try: edid = msmonitor.WmiGetMonitorRawEEdidV1Block(0) except: # No EDID entry pass else: edid = "".join(chr(i) for i in edid[0]) break else: # Use registry as fallback for Win2k/XP/2003 # http://msdn.microsoft.com/en-us/library/ff546173%28VS.85%29.aspx # "The Enum tree is reserved for use by operating system components, # and its layout is subject to change. (...) Drivers and Windows # applications must not access the Enum tree directly." # But do we care? Probably not, as older Windows' API isn't likely # gonna change. driver = "\\".join(device.DeviceID.split("\\")[-2:]) subkey = "\\".join(["SYSTEM", "CurrentControlSet", "Enum", "DISPLAY", id]) try: key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, subkey) except WindowsError: # Registry error safe_print("Windows registry error: Key", "\\".join(["HKEY_LOCAL_MACHINE", subkey]), "does not exist.") return {} numsubkeys, numvalues, mtime = _winreg.QueryInfoKey(key) for i in range(numsubkeys): hkname = _winreg.EnumKey(key, i) hk = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "\\".join([subkey, hkname])) try: test = _winreg.QueryValueEx(hk, "Driver")[0] except WindowsError: # No Driver entry continue if test == driver: # Found our display device try: devparms = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "\\".join([subkey, hkname, "Device Parameters"])) except WindowsError: # No Device Parameters (registry error?) safe_print("Windows registry error: Key", "\\".join(["HKEY_LOCAL_MACHINE", subkey, hkname, "Device Parameters"]), "does not exist.") continue try: edid = _winreg.QueryValueEx(devparms, "EDID")[0] except WindowsError: # No EDID entry pass
from log import safe_print safe_print("Warning - could not process old configuration:", safe_unicode(exception)) # Set a few defaults which have None as possible value and thus cannot # be set in the 'defaults' collection setcfg("gamap_src_viewcond", "mt") setcfg("gamap_out_viewcond", "mt") # Read cfg try: cfg.read([os.path.join(config_sys, appname + ".ini")]) cfg.read([os.path.join(confighome, appname + ".ini")]) # This won't raise an exception if the file does not exist, only if it # can't be parsed except Exception, exception: from log import safe_print safe_print("Warning - could not parse configuration file '%s'" % appname + ".ini") def setcfg(name, value): """ Set an option value in the configuration. """ if value is None: cfg.remove_option(ConfigParser.DEFAULTSECT, name) else: cfg.set(ConfigParser.DEFAULTSECT, name, unicode(value).encode("UTF-8")) def writecfg(which="user", worker=None): """ Write configuration file. which: 'user' or 'system'
def runtimeconfig(pyfile): """ Configure remaining runtime options and return runtype. You need to pass in a path to the calling script (e.g. use the __file__ attribute). """ from log import setup_logging setup_logging() if debug or verbose >= 1: from log import safe_print if debug: safe_print("[D] pydir:", pydir) if isapp: runtype = ".app" elif isexe: if debug: safe_print("[D] _MEIPASS2 or pydir:", getenvu("_MEIPASS2", exedir)) if getenvu("_MEIPASS2", exedir) not in data_dirs: data_dirs.insert(1, getenvu("_MEIPASS2", exedir)) runtype = exe_ext else: pydir_parent = os.path.dirname(pydir) if debug: safe_print("[D] dirname(os.path.abspath(sys.argv[0])):", os.path.dirname(os.path.abspath(sys.argv[0]))) safe_print("[D] pydir parent:", pydir_parent) if os.path.dirname(os.path.abspath(sys.argv[0])) == pydir_parent and \ pydir_parent not in data_dirs: # Add the parent directory of the package directory to our list # of data directories if it is the directory containing the # currently run script (e.g. when running from source) data_dirs.insert(1, pydir_parent) runtype = pyext for dir_ in sys.path: if not isinstance(dir_, unicode): dir_ = unicode(dir_, fs_enc) dir_ = os.path.abspath(os.path.join(dir_, appname)) if dir_ not in data_dirs and os.path.isdir(dir_): data_dirs.append(dir_) if debug: safe_print("[D] from sys.path:", dir_) if sys.platform not in ("darwin", "win32"): data_dirs.extend([os.path.join(dir_, "doc", appname + "-" + version) for dir_ in xdg_data_dirs + [xdg_data_home]]) data_dirs.extend([os.path.join(dir_, "doc", "packages", appname) for dir_ in xdg_data_dirs + [xdg_data_home]]) data_dirs.extend([os.path.join(dir_, "doc", appname) for dir_ in xdg_data_dirs + [xdg_data_home]]) data_dirs.extend([os.path.join(dir_, "doc", appname.lower()) # Debian for dir_ in xdg_data_dirs + [xdg_data_home]]) data_dirs.extend([os.path.join(dir_, "icons", "hicolor") for dir_ in xdg_data_dirs + [xdg_data_home]]) if debug: safe_print("[D] Data files search paths:\n[D]", "\n[D] ".join(data_dirs)) defaults["3dlut.input.profile"] = get_data_path(os.path.join("ref", "Rec709.icm")) or "" defaultmmode = defaults["measurement_mode"] defaultptype = defaults["profile.type"] defaultchart = testchart_defaults.get(defaultptype, testchart_defaults["s"])[None] defaults["testchart.file"] = get_data_path(os.path.join("ti1", defaultchart)) or "" defaults["testchart.file.backup"] = defaults["testchart.file"] defaults["profile_verification_chart"] = get_data_path(os.path.join("ref", "verify.ti1")) or "" defaults["gamap_profile"] = get_data_path(os.path.join("ref", "sRGB.icm")) or "" return runtype