def convert(self, input, dstdir, filename, profilenum=20): if self._writing: return file = os.path.splitext(filename)[0] + '.wmv' output = os.path.join(dstdir, file) self._writer = self.createWMWriter(profilenum) self._writer.SetOutputFilename(output) self.findPins(self._writer) self._videopeer = dshow.CreatePyRenderingListener(self) self._audiofilter = Filter(self, self._writer, self._audiopinix, self._audiopinprops) self._audiopeer = dshow.CreatePyRenderingListener(self._audiofilter) # this call will set indirectly self._writer format fg = self.createFilterGraph(input) if not fg: return None mc = fg.QueryIMediaControl() mc.Run() import win32ui while fg.WaitForCompletion(0) == 0: win32ui.PumpWaitingMessages() mc.Stop() win32ui.PumpWaitingMessages() return output
def QueueFlush(self, max=sys.maxint): # Returns true if the queue is empty after the flush # debug("Queueflush - %d, %d\n" % (max, self.outputQueue.qsize())) if self.bCreating: return 1 items = [] rc = 0 while max > 0: try: item = self.outputQueue.get_nowait() if is_platform_unicode: # Note is_platform_unicode is never true any more! if not isinstance(item, UnicodeType): item = unicode(item, default_platform_encoding) item = item.encode( default_scintilla_encoding) # What scintilla uses. else: # try and display using mbcs encoding if isinstance(item, UnicodeType): item = item.encode("mbcs") items.append(item) except Queue.Empty: rc = 1 break max = max - 1 if len(items) != 0: if not self.CheckRecreateWindow(): debug(":Recreate failed!\n") return 1 # In trouble - so say we have nothing to do. win32ui.PumpWaitingMessages() # Pump paint messages self.currentView.dowrite(string.join(items, '')) return rc
def calcDur(self): self._player.Begin() repeat = 0 while not self.dur and repeat < 40: win32ui.PumpWaitingMessages(0, 0) win32api.Sleep(50) repeat = repeat + 1 self._player.Stop()
def iMessageBox(sMsg, sTitle, iType, iIcon): """ A frivolity that demonstrates that Mark Hammond's win32 code is all callable by Python under Mt4. """ i = win32ui.MessageBox(sMsg, sTitle, iType | iIcon) # while != 0 ? win32ui.PumpWaitingMessages() return i
def ThreadedStatusProgressDialog(title, msg="", maxticks=100): t = ProgressThread(title, msg, maxticks) t.CreateThread() # Need to run a basic "PumpWaitingMessages" loop just incase we are # running inside Pythonwin. # Basic timeout incase things go terribly wrong. Ideally we should use # win32event.MsgWaitForMultipleObjects(), but we use a threading module # event - so use a dumb strategy end_time = time.time() + 10 while time.time() < end_time: if t.createdEvent.isSet(): break win32ui.PumpWaitingMessages() time.sleep(0.1) return t.dialog
def ThreadedDemo(): rect = win32ui.GetMainFrame().GetMDIClient().GetClientRect() rect = rect[0], int(rect[3] * 3 / 4), int(rect[2] / 4), rect[3] incr = rect[2] for i in range(4): if i == 0: f = FontFrame() title = "Not threaded" else: f = ThreadedFontFrame() title = "Threaded GUI Demo" f.Create(title, rect) rect = rect[0] + incr, rect[1], rect[2] + incr, rect[3] # Givem a chance to start win32api.Sleep(100) win32ui.PumpWaitingMessages()
def start(self): #запуск сервера server = dde.CreateServer() server.AddTopic(QuikTopic(self)) server.Create(self.topic_name) event = win32event.CreateEvent(None, 0, 0, None) while 1: win32ui.PumpWaitingMessages(0, -1) rc = win32event.MsgWaitForMultipleObjects((event, ), 0, 100, win32event.QS_ALLEVENTS) if rc == win32event.WAIT_OBJECT_0: break #elif rc==win32event.WAIT_OBJECT_0+1: # print "OK1" #if win32ui.PumpWaitingMessages(0,-1): # raise RuntimeError("We got an unexpected WM_QUIT message!") elif rc == win32event.WAIT_TIMEOUT: pass
def write_bin(string_param): global __debug2 global __count_print_statements if __debug_write == True: print 'write_bin', string_param index = 0 for char_in_str in string_param: #print 'write_bin[%02d]:%02X,<%c>' % (index, ord(char_in_str), ord(char_in_str)) index = index + 1 __count_print_statements = __count_print_statements + 1 if (__count_print_statements & 0x07) == 1: #print 'pumping messages bin', __count_print_statements win32ui.PumpWaitingMessages(0, -1) __obj_com_port.write(string_param) if "outWaiting" in dir(__obj_com_port): while __obj_com_port.outWaiting(): time.sleep(0.001) else: __obj_com_port.flush()
def QueueFlush(self, max=None): # Returns true if the queue is empty after the flush # debug("Queueflush - %d, %d\n" % (max, self.outputQueue.qsize())) if self.bCreating: return 1 items = [] rc = 0 while max is None or max > 0: try: item = self.outputQueue.get_nowait() items.append(item) except Queue.Empty: rc = 1 break if max is not None: max = max - 1 if len(items) != 0: if not self.CheckRecreateWindow(): debug(":Recreate failed!\n") return 1 # In trouble - so say we have nothing to do. win32ui.PumpWaitingMessages() # Pump paint messages self.currentView.dowrite(''.join(items)) return rc
def serve_events(): import win32ui, win32con win32ui.PumpWaitingMessages(win32con.WM_MOUSEFIRST, win32con.WM_MOUSELAST) from __main__ import toplevel toplevel.serve_events()
def Log_Capture(SecondsWait, expected_frame_size=0, filename=None, kick_logger=None): global __LogTotalBytesCapture global __LogFrames global __LogTimestamp global __LogExpectedFrameSize global __LogTotalFramesSaved global __Logfilehandle global __Total_frames_received if (filename != None): __Logfilehandle = open(filename, 'w') else: __Logfilehandle = None __LogExpectedFrameSize = expected_frame_size str_to_send = '' #total_loops = 0 #__Total_frames_received = 0 #__Total_star_lines_received = 0 #__LogCurrentFrame = '' __LogTotalFramesSaved = 0 __LogTotalBytesCapture = 0 last_frames_received = 0 __LogFrames = [] __LogTimestamp = [] start_time = time.time() kick_time = start_time update_screen_time = start_time while ((start_time + SecondsWait) > time.time()): #total_loops = total_loops + 1 #print 'Loop to capture logger frames:', total_loops time_time = time.time() picasso_talk_get_answer_rs232(str_to_send) if ((kick_time + 2.0) > time_time): kick_time = time_time kick_logger(5) if ((update_screen_time + 15.0) > time_time): update_screen_time = time_time if (last_frames_received != __LogTotalFramesSaved): last_frames_received = __LogTotalFramesSaved print 'Frames received:', __LogTotalFramesSaved win32ui.PumpWaitingMessages(0, -1) #if(__Total_frames_received != 0): # print 'lines starting by <*>', __Total_star_lines_received # print 'lines starting by <&> (frames)', __Total_frames_received # print 'average lines per frame:', (float(__Total_star_lines_received) / float(__Total_frames_received)) Parse_Logger_finish() if (__LogTotalBytesCapture == 0): print 'No data from logger, make sure to enable logging with <t.logger.mask(1)> or <l.mask(1)> if <l = t.logger()>' if (filename != None): return (__LogTotalBytesCapture, __LogTotalFramesSaved) else: return (__LogFrames, __LogTimestamp) else: if (filename != None): print 'Logger total frames:', __LogTotalFramesSaved, ', total size:', __LogTotalBytesCapture return (__LogTotalBytesCapture, __LogTotalFramesSaved) else: print 'Logger total frames:', __LogTotalFramesSaved, ', total size:', __LogTotalBytesCapture return (__LogFrames, __LogTimestamp)
sys.argv = ParseArgs(args) sys.argv.insert(0, script) # sys.path[0] is the path of the script oldPath0 = sys.path[0] newPath0 = os.path.split(script)[0] if not oldPath0: # if sys.path[0] is empty sys.path[0] = newPath0 insertedPath0 = 0 else: sys.path.insert(0, newPath0) insertedPath0 = 1 bWorked = 0 win32ui.DoWaitCursor(1) base = os.path.split(script)[1] # Allow windows to repaint before starting. win32ui.PumpWaitingMessages() win32ui.SetStatusText('Running script %s...' % base,1 ) exitCode = 0 from pywin.framework import interact # Check the debugger flags if debugger is None and (debuggingType != RS_DEBUGGER_NONE): win32ui.MessageBox("No debugger is installed. Debugging options have been ignored!") debuggingType = RS_DEBUGGER_NONE # Get a code object - ignore the debugger for this, as it is probably a syntax error # at this point try: codeObject = compile(f.read()+"\n", script, "exec") except: # Almost certainly a syntax error! _HandlePythonFailure("run script", script)
def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None): global lastScript, lastArgs, lastDebuggingType _debugger_stop_frame_ = 1 # Magic variable so the debugger will hide me! # Get the debugger - may be None! debugger = GetDebugger() if defName is None: try: pathName = GetActiveFileName() except KeyboardInterrupt: return # User cancelled save. else: pathName = defName if not pathName: pathName = lastScript if defArgs is None: args = "" if pathName == lastScript: args = lastArgs else: args = defArgs if debuggingType is None: debuggingType = lastDebuggingType if not pathName or bShowDialog: dlg = DlgRunScript(debugger is not None) dlg["script"] = pathName dlg["args"] = args dlg["debuggingType"] = debuggingType if dlg.DoModal() != win32con.IDOK: return script = dlg["script"] args = dlg["args"] debuggingType = dlg["debuggingType"] if not script: return if debuggingType == RS_DEBUGGER_GO and debugger is not None: # This may surprise users - they select "Run under debugger", but # it appears not to! Only warn when they pick from the dialog! # First - ensure the debugger is activated to pickup any break-points # set in the editor. try: # Create the debugger, but _dont_ init the debugger GUI. rd = debugger._GetCurrentDebugger() except AttributeError: rd = None if rd is not None and len(rd.breaks) == 0: msg = "There are no active break-points.\r\n\r\nSelecting this debug option without any\r\nbreak-points is unlikely to have the desired effect\r\nas the debugger is unlikely to be invoked..\r\n\r\nWould you like to step-through in the debugger instead?" rc = win32ui.MessageBox( msg, win32ui.LoadString(win32ui.IDR_DEBUGGER), win32con.MB_YESNOCANCEL | win32con.MB_ICONINFORMATION, ) if rc == win32con.IDCANCEL: return if rc == win32con.IDYES: debuggingType = RS_DEBUGGER_STEP lastDebuggingType = debuggingType lastScript = script lastArgs = args else: script = pathName # try and open the script. if (len(os.path.splitext(script)[1]) == 0 ): # check if no extension supplied, and give one. script = script + ".py" # If no path specified, try and locate the file path, fnameonly = os.path.split(script) if len(path) == 0: try: os.stat(fnameonly) # See if it is OK as is... script = fnameonly except os.error: fullScript = LocatePythonFile(script) if fullScript is None: win32ui.MessageBox("The file '%s' can not be located" % script) return script = fullScript else: path = win32ui.FullPath(path) if not IsOnPythonPath(path): sys.path.append(path) # py3k fun: If we use text mode to open the file, we get \r\n # translated so Python allows the syntax (good!), but we get back # text already decoded from the default encoding (bad!) and Python # ignores any encoding decls (bad!). If we use binary mode we get # the raw bytes and Python looks at the encoding (good!) but \r\n # chars stay in place so Python throws a syntax error (bad!). # So: so the binary thing and manually normalize \r\n. try: f = open(script, "rb") except IOError as exc: win32ui.MessageBox("The file could not be opened - %s (%d)" % (exc.strerror, exc.errno)) return # Get the source-code - as above, normalize \r\n code = f.read().replace(byte_crlf, byte_lf).replace(byte_cr, byte_lf) + byte_lf # Remember and hack sys.argv for the script. oldArgv = sys.argv sys.argv = ParseArgs(args) sys.argv.insert(0, script) # sys.path[0] is the path of the script oldPath0 = sys.path[0] newPath0 = os.path.split(script)[0] if not oldPath0: # if sys.path[0] is empty sys.path[0] = newPath0 insertedPath0 = 0 else: sys.path.insert(0, newPath0) insertedPath0 = 1 bWorked = 0 win32ui.DoWaitCursor(1) base = os.path.split(script)[1] # Allow windows to repaint before starting. win32ui.PumpWaitingMessages() win32ui.SetStatusText("Running script %s..." % base, 1) exitCode = 0 from pywin.framework import interact # Check the debugger flags if debugger is None and (debuggingType != RS_DEBUGGER_NONE): win32ui.MessageBox( "No debugger is installed. Debugging options have been ignored!") debuggingType = RS_DEBUGGER_NONE # Get a code object - ignore the debugger for this, as it is probably a syntax error # at this point try: codeObject = compile(code, script, "exec") except: # Almost certainly a syntax error! _HandlePythonFailure("run script", script) # No code object which to run/debug. return __main__.__file__ = script try: if debuggingType == RS_DEBUGGER_STEP: debugger.run(codeObject, __main__.__dict__, start_stepping=1) elif debuggingType == RS_DEBUGGER_GO: debugger.run(codeObject, __main__.__dict__, start_stepping=0) else: # Post mortem or no debugging exec(codeObject, __main__.__dict__) bWorked = 1 except bdb.BdbQuit: # Dont print tracebacks when the debugger quit, but do print a message. print("Debugging session cancelled.") exitCode = 1 bWorked = 1 except SystemExit as code: exitCode = code bWorked = 1 except KeyboardInterrupt: # Consider this successful, as we dont want the debugger. # (but we do want a traceback!) if interact.edit and interact.edit.currentView: interact.edit.currentView.EnsureNoPrompt() traceback.print_exc() if interact.edit and interact.edit.currentView: interact.edit.currentView.AppendToPrompt([]) bWorked = 1 except: if interact.edit and interact.edit.currentView: interact.edit.currentView.EnsureNoPrompt() traceback.print_exc() if interact.edit and interact.edit.currentView: interact.edit.currentView.AppendToPrompt([]) if debuggingType == RS_DEBUGGER_PM: debugger.pm() del __main__.__file__ sys.argv = oldArgv if insertedPath0: del sys.path[0] else: sys.path[0] = oldPath0 f.close() if bWorked: win32ui.SetStatusText("Script '%s' returned exit code %s" % (script, exitCode)) else: win32ui.SetStatusText("Exception raised while running script %s" % base) try: sys.stdout.flush() except AttributeError: pass win32ui.DoWaitCursor(0)
def convertvideofile(url, dstdir, file, node): import producer global engine # ignore suggested extension and make our own file = os.path.splitext(file)[0] + '.rm' fullpath = os.path.join(dstdir, file) if engine is None: engine = producer.CreateRMBuildEngine() for pin in engine.GetPins(): if pin.GetOutputMimeType() == producer.MIME_REALVIDEO: videopin = pin elif pin.GetOutputMimeType() == producer.MIME_REALAUDIO: audiopin = pin engine.SetDoOutputMimeType(producer.MIME_REALAUDIO, 0) engine.SetDoOutputMimeType(producer.MIME_REALVIDEO, 1) engine.SetDoOutputMimeType(producer.MIME_REALEVENT, 0) engine.SetDoOutputMimeType(producer.MIME_REALIMAGEMAP, 0) engine.SetDoOutputMimeType(producer.MIME_REALPIX, 0) engine.SetRealTimeEncoding(0) engine.SetDoMultiRateEncoding(1) cp = engine.GetClipProperties() ts = engine.GetTargetSettings() if node is not None: cp.SetTitle(MMAttrdefs.getattr(node, 'title')) cp.SetAuthor(MMAttrdefs.getattr(node, 'author')) cp.SetCopyright(MMAttrdefs.getattr(node, 'copyright')) ts.SetVideoQuality(MMAttrdefs.getattr(node, 'project_videotype')) ts.RemoveAllTargetAudiences() target = MMAttrdefs.getattr(node, 'project_targets') for i in range(5): if (1 << i) & target: ts.AddTargetAudience(i) if not target: ts.AddTargetAudience(producer.ENC_TARGET_28_MODEM) else: # we don't know nothin' about the node so use some defaults cp.SetTitle('') cp.SetAuthor('') cp.SetCopyright('') # XXX: for testing incr caps #ts.AddTargetAudience(producer.ENC_TARGET_28_MODEM) ts.AddTargetAudience(producer.ENC_TARGET_DUAL_ISDN) #ts.SetVideoQuality(producer.ENC_VIDEO_QUALITY_NORMAL) ts.SetVideoQuality(producer.ENC_VIDEO_QUALITY_SMOOTH_MOTION) cp.SetPerfectPlay(1) cp.SetMobilePlay(0) cp.SetSelectiveRecord(0) cp.SetDoOutputServer(0) cp.SetDoOutputFile(1) cp.SetOutputFilename(fullpath) import dshow, MMurl b = dshow.CreateGraphBuilder() url = MMurl.canonURL(url) url = MMurl.unquote(url) b.RenderFile(url) renderer = b.FindFilterByName('Video Renderer') enumpins = renderer.EnumPins() pin = enumpins.Next() lastpin = pin.ConnectedTo() b.RemoveFilter(renderer) try: vf = dshow.CreateFilter('Video Real Media Converter') except: print 'Video real media converter filter is not installed' return b.AddFilter(vf, 'VRMC') b.Render(lastpin) try: aurenderer = b.FindFilterByName('Default DirectSound Device') except: aurenderer = None if not aurenderer: try: aurenderer = b.FindFilterByName('Default WaveOut Device') except: aurenderer = None if aurenderer: enumpins = aurenderer.EnumPins() pin = enumpins.Next() lastpin = pin.ConnectedTo() b.RemoveFilter(aurenderer) try: af = dshow.CreateFilter('Audio Real Media Converter') except: aurenderer = None else: b.AddFilter(af, 'ARMC') b.Render(lastpin) try: vrconv = vf.QueryIRealConverter() except: print 'Filter does not support interface IRealConverter' return try: ukeng = engine.QueryInterfaceUnknown() except: print 'RMABuildEngine QueryInterfaceUnknown failed' return vrconv.SetInterface(ukeng, 'IRMABuildEngine') try: ukpin = videopin.QueryInterfaceUnknown() except: print 'RMAInputPin QueryInterfaceUnknown failed' return vrconv.SetInterface(ukpin, 'IRMAInputPin') if aurenderer: try: arconv = af.QueryIRealConverter() except: aurenderer = None else: arconv.SetInterface(ukeng, 'IRMABuildEngine') if aurenderer: try: ukpin = audiopin.QueryInterfaceUnknown() except: aurenderer = None else: arconv.SetInterface(ukpin, 'IRMAInputPin') if aurenderer: engine.SetDoOutputMimeType(producer.MIME_REALAUDIO, 1) ts.SetAudioContent(producer.ENC_AUDIO_CONTENT_VOICE) # PinProperties,MediaSample,PrepareToEncode,Encode, DoneEncoding # are all managed by our dshow filter mc = b.QueryIMediaControl() mc.Run() import sys if sys.platform == 'win32': # remove messages in queue # dispatch only paint message import win32ui while b.WaitForCompletion(0) == 0: win32ui.PumpWaitingMessages() mc.Stop() win32ui.PumpWaitingMessages() else: b.WaitForCompletion() mc.Stop() del b
def wait(self): while self.sas.Busy: win32ui.PumpWaitingMessages(0, -1)
def convertaudiofile(url, dstdir, file, node): # ignore suggested extension and make our own file = os.path.splitext(file)[0] + '.wma' fullpath = os.path.join(dstdir, file) profman = wmfapi.CreateProfileManager() # set an apropriate system profile # or a create a new one profile = profman.LoadSystemProfile(10) # find audio pin writer = wmfapi.CreateWriter() writer.SetProfile(profile) npins = writer.GetInputCount() audiopinix = -1 audiopinmt = None audiopinprops = None print 'profile pins:' for i in range(npins): pinprop = writer.GetInputProps(i) pintype = pinprop.GetType() if pintype == wmfapi.WMMEDIATYPE_Audio: audiopinix = i audiopinprops = pinprop audiopinmt = pinprop.GetMediaType() if audiopinix >= 0: print 'audiopin is pin ', audiopinix else: print 'no audio pin' return None writer.SetOutputFilename(fullpath) b = dshow.CreateGraphBuilder() import MMurl url = MMurl.canonURL(url) url = MMurl.unquote(url) b.RenderFile(url) # find renderer try: aurenderer = b.FindFilterByName('Default DirectSound Device') except: aurenderer = None if not aurenderer: try: aurenderer = b.FindFilterByName('Default WaveOut Device') except: aurenderer = None if not aurenderer: return None enumpins = aurenderer.EnumPins() pin = enumpins.Next() aulastpin = pin.ConnectedTo() b.RemoveFilter(aurenderer) try: f = dshow.CreateFilter('Audio Windows Media Converter') except: print 'Audio windows media converter filter is not installed' return None b.AddFilter(f, 'AWMC') b.Render(aulastpin) try: wmconv = f.QueryIWMConverter() except: print 'Filter does not support interface IWMConverter' return try: uk = writer.QueryIUnknown() except: print 'WMWriter QueryIUnknown failed' return wmconv.SetWMWriter(uk) try: uk = audiopinprops.QueryIUnknown() except: print 'WMInputMediaProps QueryIUnknown failed' return wmconv.SetAudioInputProps(audiopinix, uk) # media properties and converting is # managed by our dshow filter mc = b.QueryIMediaControl() mc.Run() import sys if sys.platform == 'win32': # remove messages in queue import win32ui while b.WaitForCompletion(0) == 0: win32ui.PumpWaitingMessages() mc.Stop() win32ui.PumpWaitingMessages() else: b.WaitForCompletion() mc.Stop()