def __LocalInit(self): try: self.ROM = self.Current_Ctrl.Get_ROM( self.Current_Ctrl.GetFocusedItem()) except: self.Close() self.Orig_Encoding = wx.GetDefaultPyEncoding() wx.SetDefaultPyEncoding("cp437") self.SetSize(Config.Config["NFO_Size"]) if Config.Config["NFO_Position"][0] == -1: self.CentreOnScreen() else: self.SetPosition(Config.Config["NFO_Position"]) self.Bind(wx.EVT_SIZE, self.On_Window_Size) self.Bind(wx.EVT_MOVE, self.On_Window_Move) # font = wx.Font( Config.Config ["NFO_Zoom"], wx.DEFAULT, wx.NORMAL, wx.NORMAL, False, "Lucida Console", wx.FONTENCODING_CP437 ) font = wx.Font(Config.Config["NFO_Zoom"], Config.Config["NFO_Family"], Config.Config["NFO_Style"], Config.Config["NFO_Weight"], False, Config.Config["NFO_Face"], wx.FONTENCODING_CP437) self.NFO_Text.SetFont(font) Data = Utils.Get_NFO(self.ROM) if Data != "": self.NFO_Text.AppendText(Data) else: self.NFO_Text.AppendText("None Available\n") self.NFO_Text.ShowPosition(0) self.Zoom_Size_Text.SetLabel(" Zoom Size : %d" % Config.Config["NFO_Zoom"])
def LoadPreferences(): global app global prefs, prefsfile, AppDataDir, AppDir global PLATFORM_IS_WIN, PLATFORM_IS_GTK, PLATFORM_IS_MAC global pythexec, pythexecw #check for preferences file in user userpreferencesdirectory if os.path.exists(prefsfile): try: drPrefsFile.ReadPreferences(prefs, prefsfile) except: self.ShowMessage(("Error with: " + prefsfile + "\nEasyPython will load the program defaults."), "Preferences Error") prefs.reset() drPrefsFile.WritePreferences(prefs, prefsfile) else: drPrefsFile.WritePreferences(prefs, prefsfile) wx.GetApp().debugmodus = prefs.debugmodus # already restted if prefs.defaultencoding: reload(sys) #this is needed because of wine and linux sys.setdefaultencoding(prefs.defaultencoding) wx.SetDefaultPyEncoding(prefs.defaultencoding) #*******************************************************************************************************
def __init__(self,parent,id,title): wx.SetDefaultPyEncoding('utf8') self.presLan_en = gettext.translation('Transana', 'locale', languages=['en']) self.presLan_en.install() lang = wx.LANGUAGE_ENGLISH self.locale = wx.Locale(lang) self.locale.AddCatalog("Transana") # Define the Configuration Data TransanaGlobal.configData = ConfigData.ConfigData() # Create the global transana graphics colors, once the ConfigData object exists. TransanaGlobal.transana_graphicsColorList = TransanaGlobal.getColorDefs(TransanaGlobal.configData.colorConfigFilename) # Set essential global color manipulation data structures once the ConfigData object exists. (TransanaGlobal.transana_colorNameList, TransanaGlobal.transana_colorLookup, TransanaGlobal.keywordMapColourSet) = TransanaGlobal.SetColorVariables() TransanaGlobal.configData.videoPath = 'C:\\Users\\DavidWoods\\Videos' TransanaGlobal.menuWindow = MenuWindow.MenuWindow(None, -1, title) self.ControlObject = ControlObjectClass.ControlObject() self.ControlObject.Register(Menu = TransanaGlobal.menuWindow) TransanaGlobal.menuWindow.Register(ControlObject = self.ControlObject) wx.Frame.__init__(self,parent,-1, title, size = (800,600), style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE) self.testsRun = 0 self.testsSuccessful = 0 self.testsFailed = 0 mainSizer = wx.BoxSizer(wx.VERTICAL) self.txtCtrl = wx.TextCtrl(self, -1, "Unit Test: SSL\n\n", style=wx.TE_LEFT | wx.TE_MULTILINE) self.txtCtrl.AppendText("Transana Version: %s\nsingleUserVersion: %s\n" % (TransanaConstants.versionNumber, TransanaConstants.singleUserVersion)) mainSizer.Add(self.txtCtrl, 1, wx.EXPAND | wx.ALL, 5) self.SetSizer(mainSizer) self.SetAutoLayout(True) self.Layout() self.CenterOnScreen() # Status Bar self.CreateStatusBar() self.SetStatusText("") self.Show(True) try: self.RunTests() except: print print print sys.exc_info()[0] print sys.exc_info()[1] traceback.print_exc(file=sys.stdout) if TransanaConstants.DBInstalled in ['MySQLdb-embedded']: DBInterface.EndSingleUserDatabase() TransanaGlobal.menuWindow.Destroy()
def OnInit(self): try: progPath = os.path.dirname(sys.argv[0]) os.chdir(progPath) except: pass wx.SetDefaultPyEncoding('utf-8') opts = options.Options() mtexts.setLang(opts.langid) frame = morin.MFrame(None, -1, mtexts.txts['Morinus'], opts) frame.Show(True) return True
def OnInit (self): """ App initialiser """ wx.SetDefaultPyEncoding("utf-8") self.SetAppName(u'pykpc') config = wx.Config() lang = config.Read('lang', 'LANGUAGE_DEFAULT') self.locale = wx.Locale(getattr(wx, lang)) self.localePath = os.path.abspath('./locale') + os.path.sep self.locale.AddCatalogLookupPathPrefix(self.localePath) self.locale.AddCatalog(self.AppName) self.frame = MainFrame.MainFrame(None, title=_("Pump")) self.frame.Show() return True
def __init__(self, parent, id, title): wx.SetDefaultPyEncoding('utf8') wx.Frame.__init__(self, parent, -1, title, size=(800, 600), style=wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE) self.testsRun = 0 self.testsSuccessful = 0 self.testsFailed = 0 mainSizer = wx.BoxSizer(wx.VERTICAL) self.txtCtrl = wx.TextCtrl(self, -1, "Unit Test: Miscellaneous Functions\n\n", style=wx.TE_LEFT | wx.TE_MULTILINE) self.txtCtrl.AppendText( "Transana Version: %s singleUserVersion: %s\n\n" % (TransanaConstants.versionNumber, TransanaConstants.singleUserVersion)) mainSizer.Add(self.txtCtrl, 1, wx.EXPAND | wx.ALL, 5) self.SetSizer(mainSizer) self.SetAutoLayout(True) self.Layout() self.CenterOnScreen() # Status Bar self.CreateStatusBar() self.SetStatusText("") self.Show(True) self.RunTests()
def SetFilename(self, filename, offset=0): """ Load a file in a media player. If an offset is passed, the video will be positioned to that offset. """ # If a file name is specified if filename != '': # Show the media player control self.movie.Show(True) # If we're including check boxes ... if self.includeCheckBoxes: # ... show the check boxes! self.includeInClip.Show(True) self.playAudio.Show(True) # If we're on Windows, we may need to change media player back ends! if ('wxMSW' in wx.PlatformInfo): # Break out the file extension (videoFilename, videoExtension) = os.path.splitext(filename) # If the extension is one that requires the QuickTime Player ... if videoExtension.lower() in ['.mov', '.mp4', '.m4v', '.aac']: # ... indicate we need the QuickTime back end backendNeeded = wx.media.MEDIABACKEND_QUICKTIME # If the extension is one that requires the Windows Media Player ... elif videoExtension.lower() in ['.wmv', '.wma']: # ... indicate we need the WMP10 back end backendNeeded = wx.media.MEDIABACKEND_WMP10 # If we have MPEG and are on Windows XP or earlier ... elif (videoExtension.lower() in ['.mpg', '.mpeg']) and ((sys.getwindowsversion()[0] < 6)): # ... indicate we need the DirectShow back end backendNeeded = wx.media.MEDIABACKEND_DIRECTSHOW # If not QuickTime or Windows Media or MPEG on XP ... else: # ... Check the Configuration data to see which wxMediaPlayer back end we need. if TransanaGlobal.configData.mediaPlayer == 1: backendNeeded = wx.media.MEDIABACKEND_DIRECTSHOW else: backendNeeded = wx.media.MEDIABACKEND_WMP10 # Override default MP4 Media Player, if configured to do so if (videoExtension.lower() == '.mp4') and (TransanaGlobal.configData.mp4MediaPlayer == 1): # ... Check the Configuration data to see which wxMediaPlayer back end we need. if TransanaGlobal.configData.mediaPlayer == 1: backendNeeded = wx.media.MEDIABACKEND_DIRECTSHOW else: backendNeeded = wx.media.MEDIABACKEND_WMP10 # If the current back end is different from the needed back end ... if self.backend != backendNeeded: # ... signal the back end that we need ... self.backend = backendNeeded # ... and recreate the Media Player using the new back end type. self.CreateMediaPlayer(filename) # We need to have a flag that indicates that the video is in the process of loading self.isLoading = True # We don't know the media length in some back ends until the load is complete. self.mediaLengthKnown = False # QuickTime on Windows cannot correctly load files if the PATH contains non-CP1252 characters! # A chinese file name in a CP1252 path is OK, but an english file name in a chinese path won't load. # This code fixes that problem. # First, detect Windows and QuickTime if ('wxMSW' in wx.PlatformInfo) and (self.backend == wx.media.MEDIABACKEND_QUICKTIME): # Change the Python Encoding to cp1252 wx.SetDefaultPyEncoding('cp1252') # Replace backslashes with forward slashes filename = filename.replace('\\', '/') # Get the Current Working Directory originalCWD = os.getcwd() # Divide the path and the file name from each other (currentPath, currentFileName) = os.path.split(filename) # Change the Current Directory to the file's location os.chdir(currentPath) if DEBUG: print "video_player.SetFileName(1):" print "Path changed to ", currentPath.encode('utf8'), currentPath.encode(sys.getfilesystemencoding()) == os.getcwd(), type(currentPath), type(os.getcwd()) # Encode just the File Name portion of the path tmpfilename = currentFileName.encode(sys.getfilesystemencoding()) if DEBUG: print "tmpfilename =", tmpfilename, os.path.exists(tmpfilename), os.path.exists(currentFileName) # If we're not on Windows OR we aren't using QuickTime ... else: if DEBUG: print "video_player.SetFileName(2):" print "filename.encode('utf8') =", filename.encode('utf8') # ... then the unencoded file name including the full path works just fine! tmpfilename = filename # Try to load the file in the media player. If successful ... if self.movie.Load(tmpfilename): # ... remember the file name self.FileName = filename # Initialize the start and end points if offset <= 0: self.VideoStartPoint = 0 else: self.VideoStartPoint = offset self.VideoEndPoint = 0 # If the file load FAILS ... else: # Display an error message msg = _('Transana was unable to load media file "%s".') if 'unicode' in wx.PlatformInfo: msg = unicode(msg, 'utf8') dlg = Dialogs.ErrorDialog(self, msg % filename) dlg.ShowModal() dlg.Destroy() # Signal that the media file did not load self.isLoading = False self.FileName = "" # Again, detect Windows and QuickTime if ('wxMSW' in wx.PlatformInfo) and (self.backend == wx.media.MEDIABACKEND_QUICKTIME): # Reset the Default Python encoding back to UTF8 wx.SetDefaultPyEncoding('utf8') # Reset the Current Working Directory to what it used to be os.chdir(originalCWD) # If no filename is specified ... else: # "unload" what might be in the Media Player self.movie.Load('') # Hide the Media Player self.movie.Show(False) # If there are checkboxes (multiple videos) ... if self.includeCheckBoxes: # ... hide them too. self.includeInClip.Show(False) self.playAudio.Show(False) # If the graphic has been hidden, it may be the wrong size. This fixes that. self.OnSize(None) # Update the Panel on screen self.Update() # If on Windows Vista, Windows 7, or later and we are using DirectShow ... if ('wxMSW' in wx.PlatformInfo) and (sys.getwindowsversion()[0] >= 6) and (self.backend == wx.media.MEDIABACKEND_DIRECTSHOW): # ... there's a bug in wxPython that prevents DirectShow from triggering wx.EVT_MEDIA_LOADED, so we'll call it # manually here. wx.CallAfter is not sufficient, as the video needs time to load and CallAfter doesn't wait # long enough. wx.CallLater(2000, self.OnMediaLoaded, None)
def OnInit(self): """ Initialize the application """ # If we have a Workshop Version, see if the version is still valid, report to the user and exit if not. # NOTE: This code just provides a user message and clean exit. Transana will still be disabled if this # code is removed. (This code is user-accessible on OS X!) if TransanaConstants.workshopVersion: import datetime t1 = TransanaConstants.startdate t2 = TransanaConstants.expirationdate t3 = time.localtime() t4 = datetime.datetime(t3[0], t3[1], t3[2], t3[3], t3[4]) if (t1 > t4) or (t2 < t4): dlg = Dialogs.ErrorDialog( None, "This copy of Transana is no longer valid.") dlg.ShowModal() dlg.Destroy return False # In wxPython, you used to be able to initialize the ConfigData object in the TransanaGlobal module, even though the # wx.App() hadn't been initialized yet. Moving from wxPython 2.8.1 to wxPython 2.8.9, this stopped being true # at least on the Mac. Therefore, we moved creation of the ConfigData object to here in the code. # However, there are MANY references to ConfigData being in the TransanaGlobal module, so that's where we'll keep it. TransanaGlobal.configData = ConfigData.ConfigData() # If we are running from a BUILD instead of source code ... if hasattr(sys, "frozen"): # or ('wxMac' in wx.PlatformInfo): # See if the Default Profile Path exists. If not ... if not os.path.exists( TransanaGlobal.configData.GetDefaultProfilePath()): # ... then create it (recursively). os.makedirs(TransanaGlobal.configData.GetDefaultProfilePath()) # Build the path for the error log path = os.path.join( TransanaGlobal.configData.GetDefaultProfilePath(), 'Transana_Error.log') # redirect output to the error log self.RedirectStdio(filename=path) # Put a startup indicator in the Error Log print "Transana started:", time.asctime() # If no Language is defined ... if TransanaGlobal.configData.language == '': # ... then we know this is the first startup for this user profile. Remember that! firstStartup = True # If language is known ... else: # ... then it's NOT first time startup. firstStartup = False # Now that we've loaded the Configuration Data, we can see if we need to alter the default encoding # If we're on Windows, single-user, using Russian, use KOI8r encoding instead of Latin-1, # Chinese uses big5, Japanese uses cp932, and Korean uses cp949 ## if ('wxMSW' in wx.PlatformInfo) and (TransanaConstants.singleUserVersion): ## if (TransanaGlobal.configData.language == 'ru'): ## TransanaGlobal.encoding = 'koi8_r' ## elif (TransanaGlobal.configData.language == 'zh'): ## TransanaGlobal.encoding = TransanaConstants.chineseEncoding ## elif (TransanaGlobal.configData.language == 'el'): ## TransanaGlobal.encoding = 'iso8859_7' ## elif (TransanaGlobal.configData.language == 'ja'): ## TransanaGlobal.encoding = 'cp932' ## elif (TransanaGlobal.configData.language == 'ko'): ## TransanaGlobal.encoding = 'cp949' # Use UTF-8 Encoding throughout Transana to allow maximum internationalization if ('unicode' in wx.PlatformInfo) and (wx.VERSION_STRING >= '2.6'): wx.SetDefaultPyEncoding('utf_8') # On OS/X, change the working directory to the directory the script is # running from, this is necessary for running from a bundle. if "__WXMAC__" in wx.PlatformInfo: if TransanaGlobal.programDir != '': os.chdir(TransanaGlobal.programDir) import MenuWindow # import Menu Window Object sys.excepthook = transana_excepthook # Define the system exception handler # First, determine the program name that should be displayed, single or multi-user if TransanaConstants.singleUserVersion: if TransanaConstants.proVersion: programTitle = _("Transana - Professional") else: programTitle = _("Transana - Standard") else: programTitle = _("Transana - Multiuser") # Ammend the program title for the Demo version if appropriate if TransanaConstants.demoVersion: programTitle += _(" - Demonstration") # Create the Menu Window TransanaGlobal.menuWindow = MenuWindow.MenuWindow( None, -1, programTitle) # Create the global transana graphics colors, once the ConfigData object exists. TransanaGlobal.transana_graphicsColorList = TransanaGlobal.getColorDefs( TransanaGlobal.configData.colorConfigFilename) # Set essential global color manipulation data structures once the ConfigData object exists. (TransanaGlobal.transana_colorNameList, TransanaGlobal.transana_colorLookup, TransanaGlobal.keywordMapColourSet ) = TransanaGlobal.SetColorVariables() # Add the RTF modules to the Python module search path. This allows # us to import from a directory other than the standard search paths # and the current directory/subdirectories. sys.path.append("rtf") # Load the Splash Screen graphic bitmap = TransanaImages.splash.GetBitmap() # We need to draw the Version Number onto the Splash Screen Graphic. # First, create a Memory DC memoryDC = wx.MemoryDC() # Select the bitmap into the Memory DC memoryDC.SelectObject(bitmap) # Build the Version label if TransanaConstants.singleUserVersion: if TransanaConstants.labVersion: versionLbl = _("Computer Lab Version") elif TransanaConstants.demoVersion: versionLbl = _("Demonstration Version") elif TransanaConstants.workshopVersion: versionLbl = _("Workshop Version") else: if TransanaConstants.proVersion: versionLbl = _("Professional Version") else: versionLbl = _("Standard Version") else: versionLbl = _("Multi-user Version") versionLbl += " %s" # Determine the size of the version text (verWidth, verHeight) = memoryDC.GetTextExtent( versionLbl % TransanaConstants.versionNumber) # Add the Version Number text to the Memory DC (and therefore the bitmap) memoryDC.DrawText(versionLbl % TransanaConstants.versionNumber, 370 - verWidth, 156) # Clear the bitmap from the Memory DC, thus freeing it to be displayed! memoryDC.SelectObject(wx.EmptyBitmap(10, 10)) # If the Splash Screen Graphic exists, display the Splash Screen for 4 seconds. # If not, raise an exception. if bitmap: # Mac requires a different style, as "STAY_ON_TOP" adds a header to the Splash Screen if "__WXMAC__" in wx.PlatformInfo: splashStyle = wx.SIMPLE_BORDER else: splashStyle = wx.SIMPLE_BORDER | wx.STAY_ON_TOP # If we have a Right-To-Left language ... if TransanaGlobal.configData.LayoutDirection == wx.Layout_RightToLeft: # ... we need to reverse the image direcion bitmap = bitmap.ConvertToImage().Mirror().ConvertToBitmap() splashPosition = wx.DefaultPosition ## This doesn't work. I have not been able to put the Splash Screen anywhere but on the Center of ## Monitor 0 (with wx.SPASH_CENTER_ON_SCREEN) or the upper left corner of Monitor 0 (without it). Bummer. ## # Get the Size and Position for the PRIMARY screen ## (x1, y1, w1, h1) = wx.Display(TransanaGlobal.configData.primaryScreen).GetClientArea() ## (x2, y2) = bitmap.GetSize() ## ## splashPosition = (int(float(w1) / 2.0) + x1 - int(float(x2) / 2.0), ## int(float(h1) / 2.0) + y1 - int(float(y2) / 2.0)) ## ## print "Splash Screen Position:" ## print TransanaGlobal.configData.primaryScreen ## print x1, y1, w1, h1 ## print x2, y2 ## print splashPosition ## print # Create the SplashScreen object splash = wx.SplashScreen( bitmap, wx.SPLASH_CENTER_ON_SCREEN | wx.SPLASH_TIMEOUT, 4000, None, -1, splashPosition, wx.DefaultSize, splashStyle) else: raise ImageLoadError, \ _("Unable to load Transana's splash screen image. Installation error?") wx.Yield() if DEBUG: print "Number of Monitors:", wx.Display.GetCount() for x in range(wx.Display.GetCount()): print " ", x, wx.Display(x).IsPrimary(), wx.Display( x).GetGeometry(), wx.Display(x).GetClientArea() print import DataWindow # import Data Window Object import VideoWindow # import Video Window Object # import Transcript Window Object if TransanaConstants.USESRTC: import TranscriptionUI_RTC as TranscriptionUI else: import TranscriptionUI import VisualizationWindow # import Visualization Window Object import exceptions # import exception handler (Python) # if we're running the multi-user version of Transana ... if not TransanaConstants.singleUserVersion: # ... import the Transana ChatWindow module import ChatWindow # Initialize all main application Window Objects # If we're running the Lab version OR we're on the Mac ... if TransanaConstants.labVersion or ('wxMac' in wx.PlatformInfo): # ... then pausing for 4 seconds delays the appearance of the Lab initial configuration dialog # or the Mac version login / database dialog until the Splash screen closes. time.sleep(4) # If we are running the Lab version ... if TransanaConstants.labVersion: # ... we want an initial configuration screen. Start by importing Transana's Option Settings dialog import OptionsSettings # Initialize all paths to BLANK for the lab version TransanaGlobal.configData.videoPath = '' TransanaGlobal.configData.visualizationPath = '' TransanaGlobal.configData.databaseDir = '' # Create the config dialog for the Lab initial configuration options = OptionsSettings.OptionsSettings( TransanaGlobal.menuWindow, lab=True) options.Destroy() wx.Yield() # If the databaseDir is blank, user pressed CANCEL ... if (TransanaGlobal.configData.databaseDir == ''): # ... and we should quit immediately, signalling failure return False # initialze a variable indicating database connection to False (assume the worst.) connectionEstablished = False # Let's trap the situation where the database folder is not available. try: # Start MySQL if using the embedded version if TransanaConstants.singleUserVersion: DBInterface.InitializeSingleUserDatabase() # If we get here, we've been successful! (NOTE that MU merely changes our default from False to True!) connectionEstablished = True except: if DEBUG: import traceback print sys.exc_info()[0], sys.exc_info()[1] traceback.print_exc(file=sys.stdout) msg = _( 'Transana is unable to access any Database at "%s".\nPlease check to see if this path is available.' ) if not TransanaConstants.labVersion: msg += '\n' + _( 'Would you like to restore the default Database path?') if ('unicode' in wx.PlatformInfo) and isinstance(msg, str): msg = unicode(msg, 'utf8') msg = msg % TransanaGlobal.configData.databaseDir if TransanaConstants.labVersion: dlg = Dialogs.ErrorDialog(None, msg) dlg.ShowModal() dlg.Destroy() return False # If we're on the Single-user version for Windows ... if TransanaConstants.singleUserVersion: # ... determine the file name for the data conversion information pickle file fs = os.path.join(TransanaGlobal.configData.databaseDir, '260_300_Convert.pkl') # If there is data in mid-conversion ... if os.path.exists(fs): # ... get the conversion data from the Pickle File f = file(fs, 'r') # exportedDBs is a dictionary containing the Transana-XML file name and the encoding of each DB to be imported self.exportedDBs = pickle.load(f) # Close the pickle file f.close() # Prompt the user about importing the converted data prompt = unicode( _("Transana has detected one or more databases ready for conversion.\nDo you want to convert those databases now?" ), 'utf8') tmpDlg = Dialogs.QuestionDialog(TransanaGlobal.menuWindow, prompt, _("Database Conversion")) result = tmpDlg.LocalShowModal() tmpDlg.Destroy() # If the user wants to do the conversion now ... if result == wx.ID_YES: # ... import Transana's XML Import code import XMLImport # Before we go further, let's make sure none of the conversion files have ALREADY been imported! # The 2.42 to 2.50 Data Conversion Utility shouldn't allow this, but it doesn't hurt to check. # Iterate through the conversion data for key in self.exportedDBs: # Determine the file path for the converted database newDBPath = os.path.join( TransanaGlobal.configData.databaseDir, key + '.db') # If the converted database ALREADY EXISTS ... if os.path.exists(newDBPath): # ... create an error message prompt = unicode( _('Database "%s" already exists.\nDatabase "%s" cannot be converted at this time.' ), 'utf8') # ... display an error message tmpDlg = Dialogs.ErrorDialog( None, prompt % (key, key)) tmpDlg.ShowModal() tmpDlg.Destroy() # If the converted database does NOT exist ... else: if 'wxMac' in wx.PlatformInfo: prompt = _( 'Converting "%s"\nThis process may take a long time, depending on how much data this database contains.\nWe cannot provide progress feedback on OS X. Please be patient.' ) progWarn = Dialogs.PopupDialog( None, _("Converting Databases"), prompt % key) # Create the Import Database, passing the database name so the user won't be prompted for one. DBInterface.establish_db_exists(dbToOpen=key, usePrompt=False) # Import the database. # First, create an Import Database dialog, but don't SHOW it. temp = XMLImport.XMLImport( TransanaGlobal.menuWindow, -1, _('Transana XML Import'), importData=self.exportedDBs[key]) # ... Import the requested data! temp.Import() # Close the Import Database dialog temp.Close() if 'wxMac' in wx.PlatformInfo: progWarn.Destroy() progWarn = None # Close the database that was just imported DBInterface.close_db() # Clear the current database name from the Config data TransanaGlobal.configData.database = '' # If we do NOT have a localhost key (which Lab version does not!) ... if not TransanaGlobal.configData.databaseList.has_key( 'localhost'): # ... let's create one so we can pass the converted database name! TransanaGlobal.configData.databaseList[ 'localhost'] = {} TransanaGlobal.configData.databaseList[ 'localhost']['dbList'] = [] # Update the database name TransanaGlobal.configData.database = key # Add the new (converted) database name to the database list TransanaGlobal.configData.databaseList[ 'localhost']['dbList'].append( key.encode('utf8')) # Start exception handling try: # If we're NOT in the lab version of Transana ... if not TransanaConstants.labVersion: # This is harder than it should be because of a combination of encoding and case-changing issues. # Let's iterate through the Version 2.5 "paths by database" config data for key2 in TransanaGlobal.configData.pathsByDB2.keys( ): # If we have a LOCAL database with a matching key to the database being imported ... if (key2[0] == '') and ( key2[1] == 'localhost' ) and (key2[2].decode('utf8').lower() == key): # Add the unconverted database's PATH values to the CONVERTED database's configuration! TransanaGlobal.configData.pathsByDB[('', 'localhost', key.encode('utf8'))] = \ {'visualizationPath' : TransanaGlobal.configData.pathsByDB2[key2]['visualizationPath'], 'videoPath' : TransanaGlobal.configData.pathsByDB2[key2]['videoPath']} # ... and we can stop looking break # Save the altered configuration data TransanaGlobal.configData.SaveConfiguration() # The Computer Lab version sometimes throws a KeyError except exceptions.KeyError: # If this comes up, we can ignore it. pass # Delete the Import File Information os.remove(fs) if DEBUG: print "Done importing Files" # We can only continue if we initialized the database OR are running MU. if connectionEstablished: # If a new database login fails three times, we need to close the program. # Initialize a counter to track that. logonCount = 1 # Flag if Logon succeeds loggedOn = False # Keep trying for three tries or until successful while (logonCount <= 3) and (not loggedOn): logonCount += 1 # Confirm the existence of the DB Tables, creating them if needed. # This method also calls the Username and Password Dialog if needed. # NOTE: The Menu Window must be created first to server as a parent for the Username and Password Dialog # called up by DBInterface. if DBInterface.establish_db_exists(): if DEBUG: print "Creating Data Window", # Create the Data Window # Data Window creation causes Username and Password Dialog to be displayed, # so it should be created before the Video Window self.dataWindow = DataWindow.DataWindow( TransanaGlobal.menuWindow) if DEBUG: print self.dataWindow.GetSize() print "Creating Video Window", # Create the Video Window self.videoWindow = VideoWindow.VideoWindow( TransanaGlobal.menuWindow) # Create the Transcript Window. If on the Mac, include the Close button. if DEBUG: print self.videoWindow.GetSize() print "Creating Transcript Window", self.transcriptWindow = TranscriptionUI.TranscriptionUI( TransanaGlobal.menuWindow, includeClose=('wxMac' in wx.PlatformInfo)) if DEBUG: print self.transcriptWindow.dlg.GetSize() print "Creating Visualization Window", # Create the Visualization Window self.visualizationWindow = VisualizationWindow.VisualizationWindow( TransanaGlobal.menuWindow) if DEBUG: print self.visualizationWindow.GetSize() print "Creating Control Object" # Create the Control Object and register all objects to be controlled with it self.ControlObject = ControlObject() self.ControlObject.Register( Menu=TransanaGlobal.menuWindow, Video=self.videoWindow, Transcript=self.transcriptWindow, Data=self.dataWindow, Visualization=self.visualizationWindow) # Set the active transcript self.ControlObject.activeTranscript = 0 # Register the ControlObject with all other objects to be controlled TransanaGlobal.menuWindow.Register( ControlObject=self.ControlObject) self.dataWindow.Register(ControlObject=self.ControlObject) self.videoWindow.Register(ControlObject=self.ControlObject) self.transcriptWindow.Register( ControlObject=self.ControlObject) self.visualizationWindow.Register( ControlObject=self.ControlObject) # Set the Application Top Window to the Menu Window (wxPython) self.SetTopWindow(TransanaGlobal.menuWindow) TransanaGlobal.resizingAll = True if DEBUG: print print "Before Showing Windows:" print " menu:\t\t", TransanaGlobal.menuWindow.GetRect( ) print " visual:\t", self.visualizationWindow.GetRect() print " video:\t", self.videoWindow.GetRect() print " trans:\t", self.transcriptWindow.dlg.GetRect() print " data:\t\t", self.dataWindow.GetRect() print print 'Heights:', self.transcriptWindow.dlg.GetRect( )[1] + self.transcriptWindow.dlg.GetRect( )[3], self.dataWindow.GetRect( )[1] + self.dataWindow.GetRect()[3] print if self.transcriptWindow.dlg.GetRect( )[1] + self.transcriptWindow.dlg.GetRect( )[3] > self.dataWindow.GetRect( )[1] + self.dataWindow.GetRect()[3]: self.dataWindow.SetRect((self.dataWindow.GetRect()[0], self.dataWindow.GetRect()[1], self.dataWindow.GetRect()[2], self.dataWindow.GetRect()[3] + \ (self.transcriptWindow.dlg.GetRect()[1] + self.transcriptWindow.dlg.GetRect()[3] - (self.dataWindow.GetRect()[1] + self.dataWindow.GetRect()[3])))) print "DataWindow Height Adjusted!" print " data:\t\t", self.dataWindow.GetRect() print # Show all Windows. TransanaGlobal.menuWindow.Show(True) if DEBUG: print "Showing Windows:" print " menu:", TransanaGlobal.menuWindow.GetRect() self.visualizationWindow.Show() if DEBUG: print " visualization:", self.visualizationWindow.GetRect( ) self.videoWindow.Show() if DEBUG: print " video:", self.videoWindow.GetRect( ), self.transcriptWindow.dlg.GetRect() self.transcriptWindow.Show() if DEBUG: print " transcript:", self.transcriptWindow.dlg.GetRect( ), self.dataWindow.GetRect() self.dataWindow.Show() if DEBUG: print " data:", self.dataWindow.GetRect( ), self.visualizationWindow.GetRect() # Get the size and position of the Visualization Window (x, y, w, h) = self.visualizationWindow.GetRect() if DEBUG: print print "Call 3", 'Visualization', w + x # Adjust the positions of all other windows to match the Visualization Window's initial position self.ControlObject.UpdateWindowPositions('Visualization', w + x + 1, YUpper=h + y + 1) TransanaGlobal.resizingAll = False loggedOn = True # If logon fails, inform user and offer to try again twice. elif logonCount <= 3: # Check to see if we have an SSL failure caused by insufficient data if (not TransanaConstants.singleUserVersion) and TransanaGlobal.configData.ssl and \ (TransanaGlobal.configData.sslClientCert == '' or TransanaGlobal.configData.sslClientKey == ''): # If so, inform the user prompt = _( "The information on the SSL tab is required to establish an SSL connection to the database.\nWould you like to try again?" ) # Otherwise ... else: # ... give a generic message about logon failure. prompt = _( 'Transana was unable to connect to the database.\nWould you like to try again?' ) dlg = Dialogs.QuestionDialog( TransanaGlobal.menuWindow, prompt, _('Transana Database Connection')) # If the user does not want to try again, set the counter to 4, which will cause the program to exit if dlg.LocalShowModal() == wx.ID_NO: logonCount = 4 # Clean up the Dialog Box dlg.Destroy() # If we successfully logged in ... if loggedOn: # ... save the configuration data that got us in TransanaGlobal.configData.SaveConfiguration() # if we're running the multi-user version of Transana and successfully connected to a database ... if not TransanaConstants.singleUserVersion and loggedOn: if DEBUG: print "Need to connect to MessageServer" # ... connect to the Message Server Here TransanaGlobal.socketConnection = ChatWindow.ConnectToMessageServer( ) # If the connections fails ... if TransanaGlobal.socketConnection == None: # ... signal that Transana should NOT start up! loggedOn = False else: # If Transana MU sits idle too long (30 - 60 minutes), people would sometimes get a # "Connection to Database Lost" error message even though MySQL was set to maintain the # connection for 8 hours. To try to address this, we will set up a Timer that will run # a simple query every 10 minutes to maintain the connection to the database. # Create the Connection Timer TransanaGlobal.connectionTimer = wx.Timer(self) # Bind the timer to its event self.Bind(wx.EVT_TIMER, self.OnTimer) # Tell the timer to fire every 10 minutes. # NOTE: If changing this value, it also needs to be changed in the ControlObjectClass.GetNewDatabase() method. TransanaGlobal.connectionTimer.Start(600000) if DEBUG: print "MessageServer connected!" # Check if the Database and Message Server are both using SSL and select the appropriate graphic self.dataWindow.UpdateSSLStatus(TransanaGlobal.configData.ssl and TransanaGlobal.chatIsSSL) # if this is the first time this user profile has used Transana ... if firstStartup and loggedOn: # ... create a prompt about looking at the Tutorial prompt = _( 'If this is your first time using Transana, the Transana Tutorial can help you learn how to use the program.' ) prompt += '\n\n' + _( 'Would you like to see the Transana Tutorial now?') # Display the Tutorial prompt in a Yes / No dialog tmpDlg = Dialogs.QuestionDialog(TransanaGlobal.menuWindow, prompt) # If the user says Yes ... if tmpDlg.LocalShowModal() == wx.ID_YES: # ... start the Tutorial self.ControlObject.Help('Welcome to the Transana Tutorial') if DEBUG: print print "Final Windows:" print " menu:\t\t", TransanaGlobal.menuWindow.GetRect() print " visual:\t", self.visualizationWindow.GetRect() print " video:\t", self.videoWindow.GetRect() print " trans:\t", self.transcriptWindow.dlg.GetRect() print " data:\t\t", self.dataWindow.GetRect() print else: loggedOn = False dlg = Dialogs.QuestionDialog(TransanaGlobal.menuWindow, msg, _('Transana Database Connection')) if dlg.LocalShowModal() == wx.ID_YES: TransanaGlobal.configData.databaseDir = os.path.join( TransanaGlobal.configData.GetDefaultProfilePath(), 'databases') TransanaGlobal.configData.SaveConfiguration() # Clean up the Dialog Box dlg.Destroy() return loggedOn
# constants and common memmory storage import sys import os import datetime import threading import time # Make the file folder the cwd os.chdir(sys.path[0]) # import wxPython: import wx import wx.html # fix windows weird characters in menus wx.SetDefaultPyEncoding("utf-8") # wx auto if __name ... code def action(url): gui.action(url) def configure_event_handlers(): config.event_handlers = { "__rbac": { "requires": [], }, "handlers": {} }
def Extract(self, inputFile, outputFile, mode='AudioExtraction'): """ Perform Audio Extraction, or Media Conversion with the new version. """ # Remember the mode being used self.mode = mode # If we're messing with wxProcess, we need to define a function to clean up if we shut down! def __del__(self): if self.process is not None: self.process.Detach() self.process.CloseOutput() self.process = None # Be prepared to capture the wxProcess' EVT_END_PROCESS self.Bind(wx.EVT_END_PROCESS, self.OnEndProcess) # Windows requires that we change the default encoding for Python for the audio extraction code to work # properly with Unicode files (!!!) This isn't needed on OS X, as its default file system encoding is utf-8. # See python's documentation for sys.getfilesystemencoding() if 'wxMSW' in wx.PlatformInfo: wx.SetDefaultPyEncoding('mbcs') # Build the command line for the appropriate media conversion call if mode == 'AudioExtraction': # -i input file # -vn disable video # -ar 2756 Audio Sampling rate 2756 Hz # -ab 8k Audio Bitrate 8kb/s # -ac 1 Audio Channels 1 (mono) # -acodec pcm_u8 8-bit PCM audio codec # -y overwrite existing destination file programStr = os.path.join(TransanaGlobal.programDir, 'ffmpeg_Transana') if 'wxMSW' in wx.PlatformInfo: programStr += '.exe' process = '"' + programStr + '" "-embedded" "1" "-i" "%s" "-vn" "-ar" "2756" "-ab" "8k" "-ac" "1" "-acodec" "pcm_u8" "-y" "%s"' tempMediaFilename = inputFile tempWaveFilename = outputFile elif mode == 'AudioExtraction-OLD': programStr = os.path.join(TransanaGlobal.programDir, 'audioextract') if 'wxMSW' in wx.PlatformInfo: programStr += '.exe' process = '"' + programStr + '" "%s" "%s"' tempMediaFilename = inputFile.encode('utf8') tempWaveFilename = outputFile.encode('utf8') elif mode == 'CustomConvert': process = self.processCommand if DEBUG: print "WaveformProgress.Extract():", sys.getfilesystemencoding( ) print process % (inputFile, outputFile) print tempMediaFilename = inputFile.encode(sys.getfilesystemencoding()) tempWaveFilename = outputFile.encode(sys.getfilesystemencoding()) else: import TransanaExceptions raise TransanaExceptions.NotImplementedError self.destFile = outputFile # Create a wxProcess object self.process = wx.Process(self) # Call the wxProcess Object's Redirect method. This allows us to capture the process's output! self.process.Redirect() # Encode the filenames to UTF8 so that unicode files are handled properly process = process.encode('utf8') if DEBUG: print "WaveformProgress.Extract():" st = process % (tempMediaFilename, tempWaveFilename) if isinstance(st, unicode): print st.encode('utf8') else: print st print # Call the Audio Extraction program using wxExecute, capturing the output via wxProcess. This call MUST be asynchronous. self.pid = wx.Execute(process % (tempMediaFilename, tempWaveFilename), wx.EXEC_ASYNC, self.process) # On Windows ... if 'wxMSW' in wx.PlatformInfo: # ... reset the default Python encoding to UTF-8 wx.SetDefaultPyEncoding('utf_8') # Note the time when the progress bar started self.progressStartTime = time.time() # Start the timer to get feedback and post progress self.timer.Start(500) # If we're processing Modally ... if self.showModally: # ... show the Progress Dialog modally self.ShowModal() # If we're allowing multiple threads ... else: # ... show the Progress Dialog non-modally self.Show()
def __init__(self, parent, fileName=u'Demö.mpg'): """ Initialize the MediaConvert Dialog Box. """ wx.SetDefaultPyEncoding('utf_8') self.locale = wx.Locale(parent.locale.Language) # Remember the File Name passed in self.fileName = fileName # Initialize the process variable self.process = None # Create the Dialog wx.Dialog.__init__(self, parent, -1, _('Media File Conversion'), size=wx.Size(600, 700), style=wx.DEFAULT_DIALOG_STYLE | wx.THICK_FRAME) # To look right, the Mac needs the Small Window Variant. if "__WXMAC__" in wx.PlatformInfo: self.SetWindowVariant(wx.WINDOW_VARIANT_SMALL) # Create the main Sizer, which will hold the box1, box2, etc. and boxButton sizers box = wx.BoxSizer(wx.VERTICAL) # Add the Source File label lblSource = wx.StaticText(self, -1, _("Source Media File:")) box.Add(lblSource, 0, wx.TOP | wx.LEFT | wx.RIGHT, 10) # Create the box1 sizer, which will hold the source file and its browse button box1 = wx.BoxSizer(wx.HORIZONTAL) # Create the Source File text box self.txtSrcFileName = wx.TextCtrl(self, -1, fileName) self.txtSrcFileName.SetValue(self.fileName) box1.Add(self.txtSrcFileName, 1, wx.EXPAND) # Spacer box1.Add((4, 0)) # Add the Source Sizer to the Main Sizer box.Add(box1, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) # Add the Information label lblMemo = wx.StaticText(self, -1, _("Information:")) box.Add(lblMemo, 0, wx.LEFT | wx.RIGHT, 10) # Add the Information text control self.memo = wx.TextCtrl(self, -1, style=wx.TE_MULTILINE) box.Add(self.memo, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) # Create the boxButtons sizer, which will hold the dialog box's buttons boxButtons = wx.BoxSizer(wx.HORIZONTAL) # Create a Close button btnClose = wx.Button(self, wx.ID_CANCEL, _("Close")) boxButtons.Add(btnClose, 0, wx.ALIGN_RIGHT | wx.ALIGN_BOTTOM | wx.RIGHT, 10) # Add the boxButtons sizer to the main box sizer box.Add( boxButtons, 0, wx.ALIGN_RIGHT | wx.ALIGN_BOTTOM | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) # Define box as the form's main sizer self.SetSizer(box) # Set this as the minimum size for the form. self.SetSizeHints(minW=self.GetSize()[0], minH=int(self.GetSize()[1] * 0.75)) # Tell the form to maintain the layout and have it set the intitial Layout self.SetAutoLayout(True) self.Layout() # Position the form in the center of the screen self.CentreOnScreen() # If a file name was passed in as a parameter ... if (self.fileName != ''): # ... process that file to prepare for conversion self.ProcessMediaFile(self.fileName)
# Time-stamp: "2010-06-16 16:36:48 jantman" # $LastChangedRevision$ # $HeadURL$ # # Copyright 2008 Jason Antman. Licensed under GNU GPLv3 or latest version (at author's discretion). # Jason Antman - [email protected] - http://www.jasonantman.com # Project web site at http://www.jasonantman.com/tuxtruck/ import wx # import wx for the GUI import SpeedMeter as SM from math import pi, sqrt # SpeedMeter from http://xoomer.virgilio.it/infinity77/main/SpeedMeter.html and referenced at http://wiki.wxpython.org/SpeedMeter # This Is For Latin/Greek Symbols I Used In The Demo Only wx.SetDefaultPyEncoding('iso8859-1') #import pyOBD_Meters_RPM as Meter_RPM from pyOBD_Meters_RPM import * class pyOBD_Main(wx.Frame): """ This is the top-level frame. It's the root of everything, and what is run by the executable. """ def __init__(self, parent, id): """ Init the GUI and set everything up, Create and init all of the meters. """ wx.Frame.__init__(self, parent, id, '', style=wx.NO_BORDER) # init the main frame
print( u'Warning: Could not find legacy version of wx on system. Reverting to default settings.' ) # Ensure that "legacy" version isn't already in use if not wxversion._selected: wxversion.select([u'3.0', u'2.8']) import commands, gettext, wx # Python & wx.Python encoding to UTF-8 if (sys.getdefaultencoding() != u'utf-8'): reload(sys) # FIXME: Recommended not to use sys.setdefaultencoding(u'utf-8') wx.SetDefaultPyEncoding('UTF-8') from dbr.app import DebreateApp # Initialize app before importing local modules debreate_app = DebreateApp() from dbr.config import ConfCode from dbr.config import GetAllConfigKeys from dbr.config import GetDefaultConfigValue from dbr.language import GetLocaleDir from dbr.language import GT from dbr.language import SetLocaleDir from dbr.language import TRANSLATION_DOMAIN from dbr.log import Logger from dbr.workingdir import ChangeWorkingDirectory
def On_OK(self, event): # wxGlade: cNFODialog.<event_handler> wx.SetDefaultPyEncoding(self.Orig_Encoding) event.Skip()
def ProcessMediaFile(self, inputFile): """ Process a Media File to see what it's made of, a pre-requisite to converting it. This process also populates the form's options. """ # If we're messing with wxProcess, we need to define a function to clean up if we shut down! def __del__(self): # If a process has been defined ... if self.process is not None: # ... detach it self.process.Detach() # ... Close its output self.process.CloseOutput() # ... and de-reference it self.process = None # Reset (re-initialize) all media file variables self.process = None # Clear the Information box self.memo.Clear() # Be prepared to capture the wxProcess' EVT_END_PROCESS self.Bind(wx.EVT_END_PROCESS, self.OnEndProcess) # Windows requires that we change the default encoding for Python for the audio extraction code to work # properly with Unicode files (!!!) This isn't needed on OS X, as its default file system encoding is utf-8. # See python's documentation for sys.getfilesystemencoding() if 'wxMSW' in wx.PlatformInfo: # Set the Python Encoding to match the File System Encoding wx.SetDefaultPyEncoding(sys.getfilesystemencoding()) # Just use the File Name, no encoding needed tempMediaFilename = inputFile self.memo.AppendText("wx version: %s\n" % wx.VERSION_STRING) self.memo.AppendText( "Encoding Information:\n defaultPyEncoding: %s, filesystemencoding: %s\n\n" % (wx.GetDefaultPyEncoding(), sys.getfilesystemencoding())) self.memo.AppendText( "Locale: %s %s %s\n\n" % (self.locale.Locale, self.locale.Name, self.locale.Language)) process = '"echo" "%s"' # Create a wxProcess object self.process = wx.Process(self) # Call the wxProcess Object's Redirect method. This allows us to capture the process's output! self.process.Redirect() # Encode the filenames to UTF8 so that unicode files are handled properly process = process.encode('utf8') self.memo.AppendText("Media Filename:\n") self.memo.AppendText("%s (%s)\n" % (tempMediaFilename, type(tempMediaFilename))) self.memo.AppendText("Process call:\n") self.memo.AppendText("%s (%s - %s)\n\n" % (process % tempMediaFilename, type(process), type(process % tempMediaFilename))) line = tempMediaFilename.encode('utf8') for tmpX in range(len(line)): self.memo.AppendText("%02d\t%03d" % (tmpX, ord(line[tmpX]))) if ord(line[tmpX]) < 255: self.memo.AppendText(u"\t'%s'" % (unichr(ord(line[tmpX])))) self.memo.AppendText("\n") try: self.memo.AppendText("%02d %s (%s)\n\n" % (len(line), line, type(line))) except: self.memo.AppendText("EXCEPTION RAISED:\n%s\n%s\n\n" % (sys.exc_info()[0], sys.exc_info()[1])) # Call the Audio Extraction program using wxExecute, capturing the output via wxProcess. This call MUST be asynchronous. self.pid = wx.Execute(process % tempMediaFilename.encode('utf8'), wx.EXEC_ASYNC, self.process) # On Windows, we need to reset the encoding to UTF-8 if 'wxMSW' in wx.PlatformInfo: wx.SetDefaultPyEncoding('utf_8')
class MainWindow(wx.Frame): """ Main window of the app. """ # ensure consistent encoding wx.SetDefaultPyEncoding('utf-8') app_name = 'Демо' def __init__(self, window_size=(400, 200)): super(MainWindow, self).__init__(None, size=window_size) self.create_on_window_components() self.create_off_window_components() # Helper methods def create_on_window_components(self): """ Create components meant to be located in the window. """ # window panel self.panel = wx.Panel(self, wx.ID_ANY) # add choose color button self.choose_color_btn = wx.Button(self.panel, label="Выбор цвета") # bind it to an event handler self.Bind(wx.EVT_BUTTON, self.on_choose_color, self.choose_color_btn) # put the button in a sizer and center it sizer = wx.BoxSizer(wx.VERTICAL) sizer.AddStretchSpacer() sizer.Add(self.choose_color_btn, 0, wx.CENTER) sizer.AddStretchSpacer() self.panel.SetSizer(sizer) def create_off_window_components(self): """ Create window components, such as menu and status bar. """ self.create_menu() self.CreateStatusBar() if platform.system() == 'Windows': self.set_title('Палитра') else: self.set_title() def create_menu(self): """ Create menu of the app. """ file_menu = wx.Menu() for menu_id, label, help_text, handler in \ [ ( wx.ID_ABOUT, '&О приложении', 'Информация о приложении', self.on_about ), ( wx.ID_OPEN, '&Палитра', 'Палитра', self.on_open_palette ), (None, None, None, None), ( wx.ID_EXIT, '&Выход', 'Выход из приложения', self.on_exit ) ]: if menu_id is None: file_menu.AppendSeparator() else: item = file_menu.Append(menu_id, label, help_text) self.Bind(wx.EVT_MENU, handler, item) menu_bar = wx.MenuBar() menu_bar.Append(file_menu, '&Файл') # Add the fileMenu to the MenuBar self.SetMenuBar(menu_bar) # Add the menuBar to the Frame def set_title(self, title=None): """ Set title of the app """ app_title = '' if title is not None: app_title = "%s - %s" % (self.app_name, title) else: app_title = self.app_name super(MainWindow, self).SetTitle(app_title) def show_color_code(self, code): """ Show color code in message dialog. """ text = 'Вы выбрали цвет - %s' % ('#%02x%02x%02x' % code).upper() title = 'Выбранный цвет' dialog = wx.MessageDialog(self, text, title, wx.OK) dialog.ShowModal() dialog.Destroy() # Event handlers: def on_about(self, event): """ Open about dialog. """ title = "Демо приложение на \"wxPython\"" caption = 'О приложении' dialog = wx.MessageDialog(self, title, caption, wx.OK) dialog.ShowModal() dialog.Destroy() def on_exit(self, event): """ Exit the app. """ self.Close() # Close the main window. def on_open_palette(self, event): """ Open palette window. """ self.set_title('Палитра') if platform.system() != 'Windows': self.Show() def on_choose_color(self, event): """ Handle 'choose' color button press. """ dialog = wx.ColourDialog(self) # Ensure the full colour dialog is displayed, # not the abbreviated version. dialog.GetColourData().SetChooseFull(True) if dialog.ShowModal() == wx.ID_OK: color_code = dialog.GetColourData().GetColour().Get() self.show_color_code(color_code) dialog.Destroy()
if not os.path.isdir(TMP_PATH): os.mkdir(TMP_PATH) if not os.path.isfile(os.path.join(TMP_PATH,'.recent.txt')): f = open(os.path.join(TMP_PATH,'.recent.txt'), "w") f.close() if not os.path.isdir(AUTOMATION_SAVE_PATH): os.mkdir(AUTOMATION_SAVE_PATH) file = None if len(sys.argv) >= 2: file = sys.argv[1] csound = CsoundLib.Csound() CeciliaLib.setCsound(csound) app = CeciliaApp() wx.SetDefaultPyEncoding('utf-8') X,Y = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X), wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y) if CeciliaLib.getPlatform() == 'linux2': bmp = wx.Bitmap(os.path.join(RESOURCES_PATH, "Cecilia_splash.png"), wx.BITMAP_TYPE_PNG) sp = wx.SplashScreen(bitmap=bmp, splashStyle=wx.SPLASH_TIMEOUT, milliseconds=3000, parent=None) sp.Center() else: sp_y = Y/4 sp = CeciliaSplashScreen(None, sp_y) display = wx.Display() numDisp = display.GetCount() CeciliaLib.setNumDisplays(numDisp) print 'Numbers of displays:', numDisp displays = [] displayOffset = [] displaySize = []
def main(): U"""构造主程序app_gPY2IPA并运行""" wx.SetDefaultPyEncoding('utf8') app_gPY2IPA = App() app_gPY2IPA.MainLoop()
def __init__(self, parent, id): """ Init the GUI and set everything up, Create and init all of the meters. """ wx.Frame.__init__(self, parent, id, '', style=wx.NO_BORDER) # init the main frame wx.SetDefaultPyEncoding('iso8859-1') # setup the main frame positioning self.SetPosition((100, 200)) self.SetSize((800, 480)) self.CenterOnScreen() self.SetWindowStyle(wx.NO_BORDER) panel = wx.Panel(self, -1) sizer = wx.FlexGridSizer(2, 3, 2, 5) panel1 = wx.Panel(panel, -1, style=wx.SUNKEN_BORDER) panel2 = wx.Panel(panel, -1, style=wx.RAISED_BORDER) panel3 = wx.Panel(panel, -1, style=wx.SUNKEN_BORDER) panel4 = wx.Panel(panel, -1, style=wx.RAISED_BORDER) panel5 = wx.Panel(panel, -1, style=wx.SUNKEN_BORDER) panel6 = wx.Panel(panel, -1, style=wx.RAISED_BORDER) # First SpeedMeter: We Use The Following Styles: # # SM_DRAW_HAND: We Want To Draw The Hand (Arrow) Indicator # SM_DRAW_SECTORS: Full Sectors Will Be Drawn, To Indicate Different Intervals # SM_DRAW_MIDDLE_TEXT: We Draw Some Text In The Center Of SpeedMeter # SM_DRAW_SECONDARY_TICKS: We Draw Secondary (Intermediate) Ticks Between # The Main Ticks (Intervals) self.SpeedWindow1 = SM.SpeedMeter( panel1, extrastyle=SM.SM_DRAW_HAND | SM.SM_DRAW_SECTORS | SM.SM_DRAW_MIDDLE_TEXT | SM.SM_DRAW_SECONDARY_TICKS) # Set The Region Of Existence Of SpeedMeter (Always In Radians!!!!) self.SpeedWindow1.SetAngleRange(-pi / 6, 7 * pi / 6) # Create The Intervals That Will Divide Our SpeedMeter In Sectors intervals = range(0, 201, 20) self.SpeedWindow1.SetIntervals(intervals) # Assign The Same Colours To All Sectors (We Simulate A Car Control For Speed) # Usually This Is Black colours = [wx.BLACK] * 10 self.SpeedWindow1.SetIntervalColours(colours) # Assign The Ticks: Here They Are Simply The String Equivalent Of The Intervals ticks = [str(interval) for interval in intervals] self.SpeedWindow1.SetTicks(ticks) # Set The Ticks/Tick Markers Colour self.SpeedWindow1.SetTicksColour(wx.WHITE) # We Want To Draw 5 Secondary Ticks Between The Principal Ticks self.SpeedWindow1.SetNumberOfSecondaryTicks(5) # Set The Font For The Ticks Markers self.SpeedWindow1.SetTicksFont( wx.Font(7, wx.SWISS, wx.NORMAL, wx.NORMAL)) # Set The Text In The Center Of SpeedMeter self.SpeedWindow1.SetMiddleText("Km/h") # Assign The Colour To The Center Text self.SpeedWindow1.SetMiddleTextColour(wx.WHITE) # Assign A Font To The Center Text self.SpeedWindow1.SetMiddleTextFont( wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD)) # Set The Colour For The Hand Indicator self.SpeedWindow1.SetHandColour(wx.Colour(255, 50, 0)) # Do Not Draw The External (Container) Arc. Drawing The External Arc May # Sometimes Create Uglier Controls. Try To Comment This Line And See It # For Yourself! self.SpeedWindow1.DrawExternalArc(False) # Set The Current Value For The SpeedMeter self.SpeedWindow1.SetSpeedValue(44) # jantman - this is my test self.SpeedWindow2 = pyOBD_Meters_RPM(panel2) # Third SpeedMeter: We Use The Following Styles: # # SM_DRAW_HAND: We Want To Draw The Hand (Arrow) Indicator # SM_DRAW_PARTIAL_SECTORS: Partial Sectors Will Be Drawn, To Indicate Different Intervals # SM_DRAW_MIDDLE_ICON: We Draw An Icon In The Center Of SpeedMeter self.SpeedWindow3 = SM.SpeedMeter(panel3, extrastyle=SM.SM_DRAW_HAND | SM.SM_DRAW_PARTIAL_SECTORS | SM.SM_DRAW_MIDDLE_ICON) # We Want To Simulate A Car Gas-Control self.SpeedWindow3.SetAngleRange(-pi / 3, pi / 3) intervals = range(0, 5) self.SpeedWindow3.SetIntervals(intervals) colours = [wx.BLACK] * 3 colours.append(wx.RED) self.SpeedWindow3.SetIntervalColours(colours) ticks = ["F", "", "", "", "E"] self.SpeedWindow3.SetTicks(ticks) self.SpeedWindow3.SetTicksColour(wx.WHITE) self.SpeedWindow3.SetHandColour(wx.Colour(255, 255, 0)) # Define The Icon We Want icon = wx.Icon("images/fuel.ico", wx.BITMAP_TYPE_ICO) icon.SetWidth(24) icon.SetHeight(24) # Draw The Icon In The Center Of SpeedMeter self.SpeedWindow3.SetMiddleIcon(icon) self.SpeedWindow3.SetSpeedBackground(wx.BLACK) self.SpeedWindow3.SetArcColour(wx.WHITE) self.SpeedWindow3.SetSpeedValue(0.7) # Fourth SpeedMeter: We Use The Following Styles: # # SM_DRAW_HAND: We Want To Draw The Hand (Arrow) Indicator # SM_DRAW_SECTORS: Full Sectors Will Be Drawn, To Indicate Different Intervals # SM_DRAW_SHADOW: A Shadow For The Hand Indicator Is Drawn # SM_DRAW_MIDDLE_ICON: We Draw An Icon In The Center Of SpeedMeter # # NOTE: We Use The Mouse Style mousestyle=SM_MOUSE_TRACK. In This Way, Mouse # Events Are Catched (Mainly Left Clicks/Drags) And You Can Change The Speed # Value Using The Mouse self.SpeedWindow4 = SM.SpeedMeter( panel4, extrastyle=SM.SM_DRAW_HAND | SM.SM_DRAW_SECTORS | SM.SM_DRAW_SHADOW | SM.SM_DRAW_MIDDLE_ICON, mousestyle=SM.SM_MOUSE_TRACK) # We Want To Simulate Some Kind Of Thermometer (In Celsius Degrees!!!) self.SpeedWindow4.SetAngleRange(pi, 2 * pi) intervals = range(35, 44) self.SpeedWindow4.SetIntervals(intervals) colours = [wx.BLUE] * 5 colours.extend([wx.Colour(255, 255, 0)] * 2) colours.append(wx.RED) self.SpeedWindow4.SetIntervalColours(colours) # in the quotes should be the char for \xb0 ticks = [str(interval) + "\xb0" for interval in intervals] self.SpeedWindow4.SetTicks(ticks) self.SpeedWindow4.SetTicksColour(wx.BLACK) self.SpeedWindow4.SetTicksFont( wx.Font(7, wx.TELETYPE, wx.NORMAL, wx.BOLD)) self.SpeedWindow4.SetHandColour(wx.Colour(0, 0, 255)) self.SpeedWindow4.SetSpeedBackground(wx.SystemSettings_GetColour(0)) self.SpeedWindow4.DrawExternalArc(False) self.SpeedWindow4.SetHandColour(wx.GREEN) self.SpeedWindow4.SetShadowColour(wx.Colour(50, 50, 50)) # We Want A Simple Arrow As Indicator, Not The More Scenic Hand ;-) self.SpeedWindow4.SetHandStyle("Arrow") # Define The Icon We Want icon = wx.Icon("images/temp.ico", wx.BITMAP_TYPE_ICO) icon.SetWidth(16) icon.SetHeight(16) # Draw The Icon In The Center Of SpeedMeter self.SpeedWindow4.SetMiddleIcon(icon) # Quite An High Fever!!! self.SpeedWindow4.SetSpeedValue(41.4) # Fifth SpeedMeter: We Use The Following Styles: # # SM_DRAW_HAND: We Want To Draw The Hand (Arrow) Indicator # SM_DRAW_PARTIAL_SECTORS: Partial Sectors Will Be Drawn, To Indicate Different Intervals # SM_DRAW_SECONDARY_TICKS: We Draw Secondary (Intermediate) Ticks Between # The Main Ticks (Intervals) # SM_DRAW_MIDDLE_TEXT: We Draw Some Text In The Center Of SpeedMeter # SM_ROTATE_TEXT: The Ticks Texts Are Rotated Accordingly To Their Angle self.SpeedWindow5 = SM.SpeedMeter( panel5, extrastyle=SM.SM_DRAW_HAND | SM.SM_DRAW_PARTIAL_SECTORS | SM.SM_DRAW_SECONDARY_TICKS | SM.SM_DRAW_MIDDLE_TEXT | SM.SM_ROTATE_TEXT) # We Want To Simulate The Round Per Meter Control In A Car self.SpeedWindow5.SetAngleRange(-pi / 6, 7 * pi / 6) intervals = range(0, 9) self.SpeedWindow5.SetIntervals(intervals) colours = [wx.BLACK] * 6 colours.append(wx.Colour(255, 255, 0)) colours.append(wx.RED) self.SpeedWindow5.SetIntervalColours(colours) ticks = [str(interval) for interval in intervals] self.SpeedWindow5.SetTicks(ticks) self.SpeedWindow5.SetTicksColour(wx.WHITE) self.SpeedWindow5.SetTicksFont( wx.Font(7, wx.SWISS, wx.NORMAL, wx.NORMAL)) self.SpeedWindow5.SetHandColour(wx.Colour(255, 50, 0)) self.SpeedWindow5.SetSpeedBackground(wx.SystemSettings_GetColour(0)) self.SpeedWindow5.DrawExternalArc(False) self.SpeedWindow5.SetShadowColour(wx.Colour(50, 50, 50)) self.SpeedWindow5.SetMiddleText("rpm") self.SpeedWindow5.SetMiddleTextColour(wx.WHITE) self.SpeedWindow5.SetMiddleTextFont( wx.Font(8, wx.SWISS, wx.NORMAL, wx.BOLD)) self.SpeedWindow5.SetSpeedBackground(wx.Colour(160, 160, 160)) self.SpeedWindow5.SetSpeedValue(5.6) # Sixth SpeedMeter: That Is Complete And Complex Example. # We Use The Following Styles: # # SM_DRAW_HAND: We Want To Draw The Hand (Arrow) Indicator # SM_DRAW_PARTIAL_FILLER: The Region Passed By The Hand Indicator Is Highlighted # With A Different Filling Colour # SM_DRAW_MIDDLE_ICON: We Draw An Icon In The Center Of SpeedMeter # SM_DRAW_GRADIENT: A Circular Colour Gradient Is Drawn Inside The SpeedMeter, To # Give Some Kind Of Scenic Effect # SM_DRAW_FANCY_TICKS: We Use wx.lib. # SM_DRAW_SHADOW: A Shadow For The Hand Indicator Is Drawn self.SpeedWindow6 = SM.SpeedMeter( panel6, extrastyle=SM.SM_DRAW_HAND | SM.SM_DRAW_PARTIAL_FILLER | SM.SM_DRAW_MIDDLE_ICON | SM.SM_DRAW_GRADIENT | SM.SM_DRAW_FANCY_TICKS | SM.SM_DRAW_SHADOW) self.SpeedWindow6.SetAngleRange(0, 4 * pi / 3) intervals = [ 0, pi / 6, sqrt(pi), 2. / 3. * pi, pi**2 / 4, pi, 7. / 6. * pi, 4 * pi / 3 ] self.SpeedWindow6.SetIntervals(intervals) # If You Use The Style SM_DRAW_FANCY_TICKS, Refer To wx.lib.fancytext To Create # Correct XML Strings To Put Here ticks = [ "0", "<pi/>/6", "sq(<pi/>)", "2<pi/>/3", "<pi/><sup>2</sup>/4", "<pi/>", "7<pi/>/6", "4<pi/>/3" ] self.SpeedWindow6.SetTicks(ticks) self.SpeedWindow6.SetTicksColour(wx.Colour(0, 90, 0)) self.SpeedWindow6.SetTicksFont(wx.Font(6, wx.ROMAN, wx.NORMAL, wx.BOLD)) self.SpeedWindow6.SetHandColour(wx.Colour(60, 60, 60)) self.SpeedWindow6.DrawExternalArc(False) self.SpeedWindow6.SetFillerColour(wx.Colour(145, 220, 200)) self.SpeedWindow6.SetShadowColour(wx.BLACK) self.SpeedWindow6.SetDirection("Reverse") self.SpeedWindow6.SetSpeedBackground(wx.SystemSettings_GetColour(0)) # Set The First Gradient Colour, Which Is The Colour Near The External Arc self.SpeedWindow6.SetFirstGradientColour(wx.RED) # Set The Second Gradient Colour, Which Is The Colour Near The Center Of The SpeedMeter self.SpeedWindow6.SetSecondGradientColour(wx.WHITE) icon = wx.Icon("images/pi.ico", wx.BITMAP_TYPE_ICO) icon.SetHeight(12) icon.SetWidth(12) self.SpeedWindow6.SetMiddleIcon(icon) self.SpeedWindow6.SetSpeedValue(pi / 3) # End Of SpeedMeter Controls Construction. Add Some Functionality self.helpbuttons = [] self.isalive = 0 icononselected = wx.Icon("images/help.ico", wx.BITMAP_TYPE_ICO, 16, 16) icoselected = wx.Icon("images/pressed.ico", wx.BITMAP_TYPE_ICO, 16, 16) bmp1 = wx.EmptyBitmap(16, 16) bmp1.CopyFromIcon(icononselected) bmp2 = wx.EmptyBitmap(16, 16) bmp2.CopyFromIcon(icoselected) # These Are Cosmetics For The First SpeedMeter Control bsizer1 = wx.BoxSizer(wx.VERTICAL) hsizer1 = wx.BoxSizer(wx.HORIZONTAL) slider = wx.Slider(panel1, -1, 44, 0, 200, size=(-1, 40), style=wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS) slider.SetTickFreq(5, 1) slider.Bind(wx.EVT_SCROLL, self.OnSliderScroll) slider.SetToolTip(wx.ToolTip("Drag The Slider To Change The Speed!")) hsizer1.Add(slider, 1, wx.EXPAND) bsizer1.Add(self.SpeedWindow1, 1, wx.EXPAND) bsizer1.Add(hsizer1, 0, wx.EXPAND) panel1.SetSizer(bsizer1) # These Are Cosmetics For The Second SpeedMeter Control # Create The Timer For The Clock self.timer = wx.PyTimer(self.ClockTimer) self.currvalue = 0 bsizer2 = wx.BoxSizer(wx.VERTICAL) hsizer2 = wx.BoxSizer(wx.HORIZONTAL) stattext2 = wx.StaticText(panel2, -1, "A Simple Clock", style=wx.ALIGN_CENTER) button2 = wx.Button(panel2, -1, "Stop") self.stopped = 0 button2.Bind(wx.EVT_BUTTON, self.OnStopClock) button2.SetToolTip(wx.ToolTip("Click To Stop/Resume The Clock")) hsizer2.Add(button2, 0, wx.LEFT, 5) hsizer2.Add(stattext2, 1, wx.EXPAND) bsizer2.Add(self.SpeedWindow2.getSpeedWindow(), 1, wx.EXPAND) bsizer2.Add(hsizer2, 0, wx.EXPAND) panel2.SetSizer(bsizer2) # These Are Cosmetics For The Third SpeedMeter Control self.timer3 = wx.PyTimer(self.OilTimer) bsizer3 = wx.BoxSizer(wx.VERTICAL) hsizer3 = wx.BoxSizer(wx.HORIZONTAL) sc = wx.SpinCtrl(panel3, -1, size=(60, 20)) sc.SetRange(1, 250) sc.SetValue(50) self.spinctrl = sc strs = "Change The Speed And See How Much Fuel You Loose" self.spinctrl.SetToolTip(wx.ToolTip(strs)) button3 = wx.Button(panel3, -1, "Refill!", size=(60, 20)) button3.SetToolTip(wx.ToolTip("Click Here To Refill!")) button3.Bind(wx.EVT_BUTTON, self.OnRefill) hsizer3.Add(self.spinctrl, 0, wx.EXPAND | wx.LEFT, 5) hsizer3.Add(button3, 0, wx.EXPAND | wx.LEFT, 5) hsizer3.Add((1, 0), 2, wx.EXPAND) bsizer3.Add(self.SpeedWindow3, 1, wx.EXPAND) bsizer3.Add(hsizer3, 0, wx.EXPAND) panel3.SetSizer(bsizer3) # These Are Cosmetics For The Fourth SpeedMeter Control bsizer4 = wx.BoxSizer(wx.VERTICAL) hsizer4 = wx.BoxSizer(wx.HORIZONTAL) stattext4 = wx.StaticText(panel4, -1, "Use The Mouse ;-)") hsizer4.Add(stattext4, 1, wx.EXPAND | wx.LEFT, 5) bsizer4.Add(self.SpeedWindow4, 1, wx.EXPAND) bsizer4.Add(hsizer4, 0, wx.EXPAND) panel4.SetSizer(bsizer4) # These Are Cosmetics For The Fifth SpeedMeter Control bsizer5 = wx.BoxSizer(wx.VERTICAL) hsizer5 = wx.BoxSizer(wx.HORIZONTAL) button5 = wx.Button(panel5, -1, "Simulate") button5.SetToolTip(wx.ToolTip("Start A Car Acceleration Simulation")) button5.Bind(wx.EVT_BUTTON, self.OnSimulate) hsizer5.Add(button5, 0, wx.EXPAND | wx.LEFT, 5) hsizer5.Add((1, 0), 1, wx.EXPAND) bsizer5.Add(self.SpeedWindow5, 1, wx.EXPAND) bsizer5.Add(hsizer5, 0, wx.EXPAND) panel5.SetSizer(bsizer5) # These Are Cosmetics For The Sixth SpeedMeter Control bsizer6 = wx.BoxSizer(wx.VERTICAL) hsizer6 = wx.BoxSizer(wx.HORIZONTAL) txtctrl6 = wx.TextCtrl(panel6, -1, "60", size=(60, 20)) txtctrl6.SetToolTip(wx.ToolTip("Insert An Angle In DEGREES")) self.txtctrl = txtctrl6 button6 = wx.Button(panel6, -1, "Go!") button6.SetToolTip( wx.ToolTip("Calculate The Equivalent In Radians And Display It")) hsizer6.Add(txtctrl6, 0, wx.EXPAND | wx.LEFT, 5) hsizer6.Add(button6, 0, wx.EXPAND | wx.LEFT, 5) hsizer6.Add((1, 0), 1, wx.EXPAND) button6.Bind(wx.EVT_BUTTON, self.OnCalculate) bsizer6.Add(self.SpeedWindow6, 1, wx.EXPAND) bsizer6.Add(hsizer6, 0, wx.EXPAND) panel6.SetSizer(bsizer6) bsizer1.Layout() bsizer2.Layout() bsizer3.Layout() bsizer4.Layout() bsizer5.Layout() bsizer6.Layout() sizer.Add(panel1, 1, wx.EXPAND) sizer.Add(panel2, 1, wx.EXPAND) sizer.Add(panel3, 1, wx.EXPAND) sizer.Add(panel4, 1, wx.EXPAND) sizer.Add(panel5, 1, wx.EXPAND) sizer.Add(panel6, 1, wx.EXPAND) sizer.AddGrowableRow(0) sizer.AddGrowableRow(1) sizer.AddGrowableCol(0) sizer.AddGrowableCol(1) sizer.AddGrowableCol(2) panel.SetSizer(sizer) sizer.Layout() self.timer.Start(1000) self.timer3.Start(500)
def main(): wx.SetDefaultPyEncoding('latin-1') wx.Log.EnableLogging(False) app = PyggyBank(True, "log.txt") app.MainLoop()