def OnInit(self): print wx.version() frame = ExplorerFrame(None) self.SetTopWindow(frame) frame.Show() return True
def CreatePopupMenu(self): """ Overrides method in parent class to provide a Popup Menu when the user clicks on MyData's system tray (or menubar) icon. """ self.menu = wx.Menu() self.myTardisSyncMenuItem = wx.MenuItem( self.menu, wx.NewId(), "MyTardis Sync") if wx.version().startswith("3.0.3.dev"): self.menu.Append(self.myTardisSyncMenuItem) else: self.menu.AppendItem(self.myTardisSyncMenuItem) self.Bind(wx.EVT_MENU, self.OnMyTardisSync, self.myTardisSyncMenuItem, self.myTardisSyncMenuItem.GetId()) self.menu.AppendSeparator() self.myTardisMainWindowMenuItem = wx.MenuItem( self.menu, wx.NewId(), "MyData Main Window") if wx.version().startswith("3.0.3.dev"): self.menu.Append(self.myTardisMainWindowMenuItem) else: self.menu.AppendItem(self.myTardisMainWindowMenuItem) self.Bind(wx.EVT_MENU, self.OnMyDataMainWindow, self.myTardisMainWindowMenuItem) self.myTardisSettingsMenuItem = wx.MenuItem( self.menu, wx.NewId(), "MyData Settings") if wx.version().startswith("3.0.3.dev"): self.menu.Append(self.myTardisSettingsMenuItem) else: self.menu.AppendItem(self.myTardisSettingsMenuItem) self.Bind(wx.EVT_MENU, self.OnMyDataSettings, self.myTardisSettingsMenuItem) self.menu.AppendSeparator() self.myTardisHelpMenuItem = wx.MenuItem( self.menu, wx.NewId(), "MyData Help") if wx.version().startswith("3.0.3.dev"): self.menu.Append(self.myTardisHelpMenuItem) else: self.menu.AppendItem(self.myTardisHelpMenuItem) self.Bind(wx.EVT_MENU, self.OnMyDataHelp, self.myTardisHelpMenuItem) self.menu.AppendSeparator() self.exitMyDataMenuItem = wx.MenuItem( self.menu, wx.NewId(), "Exit MyData") if wx.version().startswith("3.0.3.dev"): self.menu.Append(self.exitMyDataMenuItem) else: self.menu.AppendItem(self.exitMyDataMenuItem) self.Bind(wx.EVT_MENU, self.OnExit, self.exitMyDataMenuItem) return self.menu
def __init__(self): wx.Frame.__init__(self, parent=None, id=wx.ID_ANY, title='wxPython example', size=(WIDTH, HEIGHT)) self.browser = None # Must ignore X11 errors like 'BadWindow' and others by # installing X11 error handlers. This must be done after # wx was intialized. if LINUX: WindowUtils.InstallX11ErrorHandlers() global g_count_windows g_count_windows += 1 self.setup_icon() self.create_menu() self.Bind(wx.EVT_CLOSE, self.OnClose) # Set wx.WANTS_CHARS style for the keyboard to work. # This style also needs to be set for all parent controls. self.browser_panel = wx.Panel(self, style=wx.WANTS_CHARS) self.browser_panel.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus) self.browser_panel.Bind(wx.EVT_SIZE, self.OnSize) if MAC: try: # noinspection PyUnresolvedReferences from AppKit import NSApp # Make the content view for the window have a layer. # This will make all sub-views have layers. This is # necessary to ensure correct layer ordering of all # child views and their layers. This fixes Window # glitchiness during initial loading on Mac (Issue #371). NSApp.windows()[0].contentView().setWantsLayer_(True) except ImportError: print("[wxpython.py] Warning: PyObjC package is missing, " "cannot fix Issue #371") print("[wxpython.py] To install PyObjC type: " "pip install -U pyobjc") if LINUX: # On Linux must show before embedding browser, so that handle # is available (Issue #347). self.Show() # In wxPython 3.0 and wxPython 4.0 on Linux handle is # still not yet available, so must delay embedding browser # (Issue #349). if wx.version().startswith("3.") or wx.version().startswith("4."): wx.CallLater(1000, self.embed_browser) else: # This works fine in wxPython 2.8 on Linux self.embed_browser() else: self.embed_browser() self.Show()
def GetEnvironmentInfo(self): """Get the environmental info / Header of error report @return: string """ info = list() info.append("#---- Notes ----#") info.append("Please provide additional information about the crash here") info.extend(["", ""]) info.append("#---- System Information ----#") info.append(self.GetProgramName()) info.append("Operating System: %s" % wx.GetOsDescription()) if sys.platform == 'darwin': info.append("Mac OSX: %s" % platform.mac_ver()[0]) info.append("Python Version: %s" % sys.version) info.append("wxPython Version: %s" % wx.version()) info.append("wxPython Info: (%s)" % ", ".join(wx.PlatformInfo)) info.append("Python Encoding: Default=%s File=%s" % \ (sys.getdefaultencoding(), sys.getfilesystemencoding())) info.append("wxPython Encoding: %s" % wx.GetDefaultPyEncoding()) info.append("System Architecture: %s %s" % (platform.architecture()[0], \ platform.machine())) info.append("Byte order: %s" % sys.byteorder) info.append("Frozen: %s" % str(getattr(sys, 'frozen', 'False'))) info.append("#---- End System Information ----#") info.append("") return os.linesep.join(info)
def __populate_versions(self, control): imageType = 'Pillow' try: imageVer = Image.PILLOW_VERSION except AttributeError: imageType = 'PIL' imageVer = Image.VERSION versions = ('Hardware:\n' '\tProcessor: {}, {} cores\n\n' 'Software:\n' '\tOS: {}, {}\n' '\tPython: {}\n' '\tmatplotlib: {}\n' '\tNumPy: {}\n' '\t{}: {}\n' '\tpySerial: {}\n' '\twxPython: {}\n' ).format(platform.processor(), multiprocessing.cpu_count(), platform.platform(), platform.machine(), platform.python_version(), matplotlib.__version__, numpy.version.version, imageType, imageVer, serial.VERSION, wx.version()) control.SetValue(versions) dc = wx.WindowDC(control) extent = list(dc.GetMultiLineTextExtent(versions, control.GetFont())) extent[0] += wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X) * 2 extent[1] += wx.SystemSettings.GetMetric(wx.SYS_HSCROLL_Y) * 2 control.SetMinSize((extent[0], extent[1])) self.Layout()
def __init__(self, parent, frame): self.frame=frame self.lastkey=None self.previewkey=self.previewbmp=self.previewimg=self.previewsize=None self.sashsize=4 wx.SplitterWindow.__init__(self, parent, wx.ID_ANY, style=wx.SP_3DSASH|wx.SP_NOBORDER|wx.SP_LIVE_UPDATE) panel=wx.Panel(self) sizer=wx.BoxSizer(wx.VERTICAL) self.sb=wx.SearchCtrl(panel) self.sb.ShowCancelButton(True) sizer.Add(self.sb, 0, flag=wx.EXPAND|(platform=='darwin' and wx.ALL or wx.BOTTOM), border=3) if platform=='darwin' and wx.VERSION<(2,9): sizer.AddSpacer(6) # layout on OSX sucks self.cb=PaletteChoicebook(panel, frame, self) sizer.Add(self.cb, 1, wx.EXPAND) panel.SetSizerAndFit(sizer) self.preview=wx.Panel(self, wx.ID_ANY, style=wx.FULL_REPAINT_ON_RESIZE) if platform=='darwin': self.preview.ClearBackground = self.ClearPreviewBackground self.SetMinimumPaneSize(1) self.SplitHorizontally(panel, self.preview, -ClutterDef.PREVIEWSIZE) self.lastheight=self.GetSize().y wx.EVT_SIZE(self, self.OnSize) wx.EVT_KEY_DOWN(self, self.OnKeyDown) wx.EVT_SET_FOCUS(self, self.OnSetFocus) wx.EVT_KEY_DOWN(self.preview, self.OnKeyDown) wx.EVT_SET_FOCUS(self.preview, self.OnSetFocus) wx.EVT_SPLITTER_SASH_POS_CHANGING(self, self.GetId(), self.OnSashPositionChanging) wx.EVT_PAINT(self.preview, self.OnPaint) wx.EVT_TEXT(self.sb, self.sb.GetId(), self.OnSearch) wx.EVT_MOUSEWHEEL(self, self.OnMouseWheel) # stop these events propagating to main window under wx2.9 if wx.version()<'2.9.4.1': # cancel button doesn't send EVT_SEARCHCTRL_CANCEL_BTN under 2.9.4.0 - http://trac.wxwidgets.org/ticket/14799 # event not needed under 2.9.4.1 wx.EVT_SEARCHCTRL_CANCEL_BTN(self.sb, self.sb.GetId(), self.OnCancelSearch)
def GetWebViewer(*args, **kwargs): """ Create WebViewer """ if wx.version().startswith('2.9'): # WebView class don't support subclass return HtmlViewer.New(*args, **kwargs) else: return WebViewer(*args, **kwargs)
def clone_key_event(self, event): if wx.version().split('.')[:2] > ['2', '8']: evt = MyKeyEvent() evt.altDown = event.altDown evt.controlDown = event.controlDown evt.KeyCode = event.KeyCode evt.metaDown = event.metaDown if wx.Platform == '__WXMSW__': evt.RawKeyCode = event.RawKeyCode evt.RawKeyFlags = event.RawKeyFlags #evt.m_scanCode = event.m_scanCode evt.shiftDown = event.shiftDown evt.X = event.X evt.Y = event.Y else: evt = wx.KeyEvent() evt.m_altDown = event.m_altDown evt.m_controlDown = event.m_controlDown evt.m_keyCode = event.m_keyCode evt.m_metaDown = event.m_metaDown if wx.Platform == '__WXMSW__': evt.m_rawCode = event.m_rawCode evt.m_rawFlags = event.m_rawFlags #evt.m_scanCode = event.m_scanCode evt.m_shiftDown = event.m_shiftDown evt.m_x = event.m_x evt.m_y = event.m_y evt.SetEventType(event.GetEventType()) evt.SetId(event.GetId()) return evt
def __init__(self, version): wx.Dialog.__init__(self, None, -1, _('About'), size=(200, 150)) titleLabel = wx.StaticText(self, -1, "BitMeter OS") titleLabel.SetFont(wx.Font(16, wx.SWISS, wx.NORMAL, wx.NORMAL)) self.gridSizer = wx.FlexGridSizer(cols=5, hgap=6, vgap=6) self.AddVersion(_("BitMeter Version"), version) self.AddVersion(_("Python Version"), platform.python_version()) self.AddVersion(_("wx Version"), wx.version()) linkLabel = wx.StaticText(self, -1, CODEBOX_URL) linkFont = wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL) linkFont.SetUnderlined(True) linkLabel.SetForegroundColour('blue') linkLabel.SetCursor(wx.StockCursor(wx.CURSOR_HAND)) linkLabel.SetFont(linkFont) linkLabel.Bind(wx.EVT_LEFT_UP, self.OnCodeboxLinkClick) licenceText = wx.TextCtrl(self, -1, _("BitMeterOS is free software: you can redistribute it and/or modify " "it under the terms of the GNU General Public License as published by " "the Free Software Foundation, either version 3 of the License, or " "(at your option) any later version.\n\n" "BitMeterOS is distributed in the hope that it will be useful, " "but WITHOUT ANY WARRANTY; without even the implied warranty of " "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the " "GNU General Public License for more details."), size=(-1, 75), style=wx.TE_MULTILINE|wx.TE_READONLY) licenceBox = wx.BoxSizer(wx.HORIZONTAL) licenceBox.Add((10,0), 0) licenceBox.Add(licenceText, 1) licenceBox.Add((10,0), 0) donateLabel = wx.StaticText(self, -1, _("Donate")) donateLabel.SetForegroundColour('blue') donateLabel.SetCursor(wx.StockCursor(wx.CURSOR_HAND)) donateLabel.SetFont(linkFont) donateLabel.Bind(wx.EVT_LEFT_UP, self.OnDonateLinkClick) okBtn = wx.Button(self, -1, _("OK"), size=(50,25)) okBtn.Bind(wx.EVT_BUTTON, self.OnOkClick) box = wx.BoxSizer(wx.VERTICAL) box.Add((0,10), 0) box.Add(titleLabel, 0, flag=wx.ALIGN_CENTER) box.Add((0,10), 0) box.Add(linkLabel, 0, flag=wx.ALIGN_CENTER) box.Add((0,10), 0) box.Add(self.gridSizer, 0, flag=wx.ALIGN_CENTER) box.Add((0,10), 0) box.Add(licenceBox, 1, flag=wx.ALIGN_CENTER|wx.EXPAND) box.Add((0,5), 0) box.Add(donateLabel, 0, flag=wx.ALIGN_CENTER) box.Add((0,10), 0) box.Add(okBtn, 0, flag=wx.ALIGN_CENTER) box.Add((0,5), 0) self.SetSizer(box) self.Fit()
def FormatErrorMessage(task, err): """Returns a string of the systems information @return: System information string """ info = list() info.append("#---- System Information ----#") info.append("%s Version: %s" % (task.about_title, task.about_version)) info.append("Operating System: %s" % wx.GetOsDescription()) if sys.platform == 'darwin': info.append("Mac OSX: %s" % platform.mac_ver()[0]) info.append("Python Version: %s" % sys.version) info.append("wxPython Version: %s" % wx.version()) info.append("wxPython Info: (%s)" % ", ".join(wx.PlatformInfo)) info.append("Python Encoding: Default=%s File=%s" % \ (sys.getdefaultencoding(), sys.getfilesystemencoding())) info.append("wxPython Encoding: %s" % wx.GetDefaultPyEncoding()) info.append("System Architecture: %s %s" % (platform.architecture()[0], \ platform.machine())) info.append("Byte order: %s" % sys.byteorder) info.append("Frozen: %s" % str(getattr(sys, 'frozen', 'False'))) info.append("#---- End System Information ----#") info.extend(["", ""]) info.append("#---- Traceback Info ----#") info.append(err) info.append("#---- End Traceback Info ----#") info.extend(["", ""]) info.append("#---- Notes ----#") info.append("Please provide additional information about the crash here:") info.append("") return os.linesep.join(info)
def CheckForWx(): """Try to import wx module and check its version""" if 'wx' in sys.modules.keys(): return minVersion = [2, 8, 10, 1] try: try: import wxversion except ImportError as e: raise ImportError(e) # wxversion.select(str(minVersion[0]) + '.' + str(minVersion[1])) wxversion.ensureMinimal(str(minVersion[0]) + '.' + str(minVersion[1])) import wx version = wx.version().split(' ')[0] if map(int, version.split('.')) < minVersion: raise ValueError('Your wxPython version is %s.%s.%s.%s' % tuple(version.split('.'))) except ImportError as e: print >> sys.stderr, 'ERROR: wxGUI requires wxPython. %s' % str(e) sys.exit(1) except (ValueError, wxversion.VersionError) as e: print >> sys.stderr, 'ERROR: wxGUI requires wxPython >= %d.%d.%d.%d. ' % tuple(minVersion) + \ '%s.' % (str(e)) sys.exit(1) except locale.Error as e: print >> sys.stderr, "Unable to set locale:", e os.environ['LC_ALL'] = ''
def __init__(self, parent, exception=''): wx.Dialog.__init__(self, parent, -1, 'Application Error', style=wx.DEFAULT_DIALOG_STYLE|wx.STAY_ON_TOP) # get system information self.exception = '' self.exception += exception self.exception += '\n-------------------------' self.exception += '\nmMass: %s' % (config.version) self.exception += '\nPython: %s' % str(platform.python_version_tuple()) self.exception += '\nwxPython: %s' % str(wx.version()) self.exception += '\nNumPy: %s' % str(numpy.version.version) self.exception += '\n-------------------------' self.exception += '\nArchitecture: %s' % str(platform.architecture()) self.exception += '\nMachine: %s' % str(platform.machine()) self.exception += '\nPlatform: %s' % str(platform.platform()) self.exception += '\nProcessor: %s' % str(platform.processor()) self.exception += '\nSystem: %s' % str(platform.system()) self.exception += '\nMac: %s' % str(platform.mac_ver()) self.exception += '\nMSW: %s' % str(platform.win32_ver()) self.exception += '\nLinux: %s' % str(platform.dist()) self.exception += '\n-------------------------\n' self.exception += 'Add your comments:\n' # make GUI sizer = self.makeGUI() # fit layout self.Layout() sizer.Fit(self) self.SetSizer(sizer) self.SetMinSize(self.GetSize()) self.Centre()
def __init__(self, WindowUtils, OS_PLATFORM, WIDTH=1400, HEIGHT=800): wx.Frame.__init__(self, parent=None, id=wx.ID_ANY, title="wxPython example", size=(WIDTH, HEIGHT)) self.browser = None self.WindowUtils = WindowUtils self.OS_PLATFORM = OS_PLATFORM if OS_PLATFORM == "LINUX": self.WindowUtils.InstallX11ErrorHandlers() global g_count_windows g_count_windows += 1 self.setup_icon() self.create_menu() self.Bind(wx.EVT_CLOSE, self.OnClose) self.browser_panel = wx.Panel(self, style=wx.WANTS_CHARS) self.browser_panel.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus) self.browser_panel.Bind(wx.EVT_SIZE, self.OnSize) if OS_PLATFORM == "LINUX": self.Show() if wx.version.startswith("3.") or wx.version().startswith("4."): wx.CallLater(20, self.embed_browser) else: self.embed_browser() else: self.embed_browser() self.Show()
def GetEnvironmentInfo(self): """Get the enviromental info / Header of error report @return: string """ system_language = wx.Locale.GetLanguageName(wx.Locale.GetSystemLanguage()) running_language = wx.Locale.GetLanguageName(wx.GetLocale().GetLanguage()) res = wx.Display().GetGeometry() info = list() info.append(self.GetProgramName()) info.append(u"Operating System: %s" % wx.GetOsDescription()) if sys.platform == 'darwin': info.append(u"Mac OSX: %s" % platform.mac_ver()[0]) info.append(u"System Lanauge: %s" % system_language) info.append(u"Running Lanauge: %s" % running_language) info.append(u"Screen Resolution: %ix%i" % (res[2], res[3])) info.append(u"Python Version: %s" % sys.version) info.append(u"wxPython Version: %s" % wx.version()) info.append(u"wxPython Info: (%s)" % ", ".join(wx.PlatformInfo)) info.append(u"Python Encoding: Default=%s File=%s" % \ (sys.getdefaultencoding(), sys.getfilesystemencoding())) info.append(u"wxPython Encoding: %s" % wx.GetDefaultPyEncoding()) info.append(u"System Architecture: %s %s" % (platform.architecture()[0], \ platform.machine())) info.append(u"Frozen: %s" % str(getattr(sys, 'frozen', 'False'))) info.append(u"") info.append(u"") return info#os.linesep.join(info)
def layout_all(self,dc=None): #settingbackgroundcolors #background = wx.NamedColour(self.background_color) #if self.GetBackgroundColour() != background: # self.SetBackgroundColour(background) #self.Clear() # print 'refreshing' if not dc: dc = wx.ClientDC(self) if wx.version().startswith('3'): self.client_size = self.GetClientSizeTuple()#seb An array doesn't make sense as a truth value: array(self.GetClientSizeTuple()) else: self.client_size = self.GetClientSize() # set the device context for all titles so they can # calculate their size for text_obj in self.all_titles: text_obj.set_dc(dc) graph_area = box_object((0,0),self.client_size) graph_area.inflate(.95) # shrink box slightly # shrink graph area to make room for titles graph_area = self.layout_border_text(graph_area) # layout axis and graph data graph_area = self.layout_graph(graph_area,dc) # center titles around graph area. self.finalize_border_text(graph_area,dc) self.graph_box = graph_area # clear the dc for all titles # ? neccessary ? for text_obj in self.all_titles: text_obj.clear_dc() self.layout_data()
def format_popup(self,pos): menu = wx.Menu() menu.Append(505, 'previous zoom', 'previous zoom') menu.Enable(505, len(self.zoom_hist) and self.zoom_hist_i>0) menu.Append(500, 'Auto Zoom', 'Auto Zoom') menu.Append(506, 'next zoom', 'next zoom') menu.Enable(506, len(self.zoom_hist) and self.zoom_hist_i<len(self.zoom_hist)-1) menu.Append(507, 'clear zoom history', 'clear zoom history') menu.Append(501, 'X-Y equal aspect ratio', 'X-Y equal - set aspect ratio to 1') menu.Append(502, 'X-Y any aspect ratio', 'X-Y equal - set aspect ratio to "normal"') menu.Append(503, 'make X-Y axes a tight fit', 'fit X-Y axes to a fraction of the grid spacing"') menu.Append(504, 'freeze X-Y axes bounds', 'freeze X-Y axes grid"') self.Bind(wx.EVT_MENU, self.on_prev_zoom, id=505) self.Bind(wx.EVT_MENU, self.on_next_zoom, id=506) self.Bind(wx.EVT_MENU, self.on_zoom_forget, id=507) self.Bind(wx.EVT_MENU, self.on_auto_zoom, id=500) self.Bind(wx.EVT_MENU, self.on_equal_aspect_ratio, id=501) self.Bind(wx.EVT_MENU, self.on_any_aspect_ratio, id=502) self.Bind(wx.EVT_MENU, self.on_axis_tight, id=503) self.Bind(wx.EVT_MENU, self.on_axis_freeze, id=504) #20090603 (called by default) menu.UpdateUI() if wx.version().startswith('3'): self.PopupMenuXY(menu) #20090603 (default mouse cursor pos) ,pos[0],pos[1]) else: self.PopupMenu(menu)
def check_versions(): print("[wxpython.py] CEF Python {ver}".format(ver=cef.__version__)) print("[wxpython.py] Python {ver} {arch}".format( ver=platform.python_version(), arch=platform.architecture()[0])) print("[wxpython.py] wxPython {ver}".format(ver=wx.version())) # CEF Python version requirement assert cef.__version__ >= "55.3", "CEF Python v55.3+ required to run this"
def main(): load_plugins() global app print "(2) wxPython version %s" % wx.version() #create the mandatory wx application object if config.isMac(): import tc_mac app = tc_mac.App(redirect=False) else: app = wx.App(redirect=False) #test for availability of our listening port interface = config.get("client", "listen_interface") port = config.getint("client", "listen_port") print "(1) opening TorChat listener on %s:%s" % (interface, port) listen_socket = tc_client.tryBindPort(interface, port) if not listen_socket: print "(1) opening TorChat listener on %s, any port" % interface listen_socket = tc_client.tryBindPort(interface, 0) if not listen_socket: print "(1) %s:%s is already in use" % (interface, port) wx.MessageBox(tc_gui.lang.D_WARN_USED_PORT_MESSAGE % (interface, port), tc_gui.lang.D_WARN_USED_PORT_TITLE) return else: print "(1) TorChat is listening on %s:%s" % (interface, port) #now continue with normal program startup print "(1) start initializing main window" app.mw = tc_gui.MainWindow(listen_socket) app.SetTopWindow(app.mw) print "(1) main window initialized" print "(1) entering main loop" app.MainLoop()
def EnvironmentInfo(): """ Returns a string of the systems information. **Returns:** * System information string **Note:** * from Editra.dev_tool """ info = list() info.append("---- Notes ----") info.append("Please provide additional information about the crash here") info.extend(["", "", ""]) info.append("---- System Information ----") info.append("Operating System: %s" % wx.GetOsDescription()) if sys.platform == 'darwin': info.append("Mac OSX: %s" % platform.mac_ver()[0]) info.append("Python Version: %s" % sys.version) info.append("wxPython Version: %s" % wx.version()) info.append("wxPython Info: (%s)" % ", ".join(wx.PlatformInfo)) info.append("Python Encoding: Default = %s File = %s" % \ (sys.getdefaultencoding(), sys.getfilesystemencoding())) info.append("wxPython Encoding: %s" % wx.GetDefaultPyEncoding()) info.append("System Architecture: %s %s" % (platform.architecture()[0], \ platform.machine())) info.append("Byte order: %s" % sys.byteorder) info.append("Frozen: %s" % str(getattr(sys, 'frozen', 'False'))) info.append("---- End System Information ----") return os.linesep.join(info)
def _CreateHtmlContent(self): """Create content for this About Dialog.""" try: self._content_string = open(self._CONTENT_FILENAME).read() except IOError: raise AboutBoxException('Cannot open or read about box content') # Grab SDK version information sdk_version = '???' # default sdk_dir = self._preferences[launcher.Preferences.PREF_APPENGINE] if sdk_dir: sdk_version_file = os.path.join(sdk_dir, 'VERSION') try: sdk_version = '<br>'.join(open(sdk_version_file).readlines()) except IOError: pass # By default, wx.html windows have a white background. We'd # prefer a standard window background color. Although there is # a wx.html.HtmlWindow.SetBackgroundColour() method, it doesn't # help us. The best we can do is set the background from within # the html itself. bgcolor = '#%02x%02x%02x' % self._background_color[0:3] # Replace some strings with dynamically determined information. text = self._content_string text = text.replace('{background-color}', bgcolor) text = text.replace('{launcher-version}', '???') # TODO(jrg): add a version text = text.replace('{python-version}', sys.version.split()[0]) text = text.replace('{wxpython-version}', wx.version()) text = text.replace('{sdk-version}', sdk_version) self._content_string = text
def ChopText(dc, text, max_size): """ Chops the input `text` if its size does not fit in `max_size`, by cutting the text and adding ellipsis at the end. :param `dc`: a :class:`DC` device context; :param string `text`: the text to chop; :param integer `max_size`: the maximum size in which the text should fit. """ # first check if the text fits with no problems if wx.version() > ("4.0.0"): x, y, dummy = dc.GetFullMultiLineTextExtent(text) else: x, y, dummy = dc.GetMultiLineTextExtent(text) if x <= max_size: return text textLen = len(text) last_good_length = 0 for i in xrange(textLen, -1, -1): s = text[0:i] s += "..." x, y = dc.GetTextExtent(s) last_good_length = i if x < max_size: break ret = text[0:last_good_length] + "..." return ret
def __init__(self, parentwin, winclass, classname, *args, **kwargs): wx.xrc.XmlResourceHandler.__init__(self) self.parentwin = parentwin self.winclass = winclass self.classname = classname self.args = args self.kwargs = kwargs self.ids = [] self.obj = None # Specify the styles recognized by objects of this type self.AddStyle("wxDEFAULT_DIALOG_STYLE", wx.DEFAULT_DIALOG_STYLE) self.AddStyle("wxSTAY_ON_TOP", wx.STAY_ON_TOP) if wx.version().split('.')[:2] <= ['2', '8']: self.AddStyle("wxDIALOG_MODAL", wx.DIALOG_MODAL) self.AddStyle("wxDIALOG_MODELESS", wx.DIALOG_MODELESS) self.AddStyle("wxNO_3D", wx.NO_3D) self.AddStyle("wxCAPTION", wx.CAPTION) self.AddStyle("wxSYSTEM_MENU", wx.SYSTEM_MENU) self.AddStyle("wxRESIZE_BORDER", wx.RESIZE_BORDER) self.AddStyle("wxRESIZE_BOX", wx.RESIZE_BOX) self.AddStyle("wxTHICK_FRAME", wx.THICK_FRAME) self.AddStyle("wxTAB_TRAVERSAL", wx.TAB_TRAVERSAL) self.AddStyle("wxCLIP_CHILDREN", wx.CLIP_CHILDREN) self.AddStyle("wxSIMPLE_BORDER", wx.SIMPLE_BORDER) self.AddStyle("wxDOUBLE_BORDER", wx.DOUBLE_BORDER) self.AddStyle("wxSUNKEN_BORDER", wx.SUNKEN_BORDER) self.AddStyle("wxRAISED_BORDER", wx.RAISED_BORDER) self.AddStyle("wxSTATIC_BORDER", wx.STATIC_BORDER) self.AddStyle("wxNO_BORDER", wx.NO_BORDER) self.AddStyle("wxTRANSPARENT_WINDOW", wx.TRANSPARENT_WINDOW) self.AddStyle("wxWANTS_CHARS", wx.WANTS_CHARS) self.AddStyle("wxNO_FULL_REPAINT_ON_RESIZE",wx.NO_FULL_REPAINT_ON_RESIZE)
def wxVerCheck(self,VerbosityLevel=0): """VerbosityLevel (0=OFF) (!0=ON)""" try: import wx minVer = [2,8,9] ver = wx.version() p = re.compile(r'[.]+') m = p.split( ver ) n = [int(m[0]),int(m[1]),int(m[2])] if n < minVer: generate_except except: # use TK for questions response = askquestion('Error', 'wxPython upgrade required. \nDo you want to install now?') if response == "yes": folder = _os.path.abspath("..\..\..\utilities\python") cmd = "%s\checkAndinstall.py --wxPython --path=%s" %(folder,folder) stat = _os.system(cmd) response = showwarning('Restart', "You must now restart script") else: print" wxPython must be installed/upgraded in order to use run this script" print" See www.wxPython.org" print return _FAIL return _SUCCESS
def create_versions_message(): return "\n".join([ "Timeline version: %s" % get_full_version(), "System version: %s" % ", ".join(platform.uname()), "Python version: %s" % python_version.replace("\n", ""), "wxPython version: %s" % wx.version(), ])
def software_stack(): """ Import all the hard dependencies. Returns a dict with the version. """ # Mandatory import numpy, scipy d = dict( numpy=numpy.version.version, scipy=scipy.version.version, ) # Optional but strongly suggested. try: import netCDF4, matplotlib d.update(dict( netCDF4=netCDF4.getlibversion(), matplotlib="Version: %s, backend: %s" % (matplotlib.__version__, matplotlib.get_backend()), )) except ImportError: pass # Optional (GUIs). try: import wx d["wx"] = wx.version() except ImportError: pass return d
def after_show(self): from . import signal from .. import cli sys.excepthook = excepthook # Process options cli.BumpsOpts.FLAGS |= set(('inspect','syspath')) opts = cli.getopts() # For wx debugging, load the wxPython Widget Inspection Tool if requested. # It will cause a separate interactive debugger window to be displayed. if opts.inspect: inspect() if opts.syspath: print("*** Resource directory: "+resource_dir()) print("*** Python path is:") for i, p in enumerate(sys.path): print("%5d %s" %(i, p)) # Put up the initial model model,output = initial_model(opts) if not model: model = plugin.new_model() signal.log_message(message=output) #self.frame.panel.show_view('log') self.frame.panel.set_model(model=model) # When setting initial aui panel split: # mac layout fails if frame is already shown # windows/unix layout fails if frame is not shown isMac = "cocoa" in wx.version() if not isMac: self.frame.Show() self.frame.panel.Layout() self.frame.panel.aui.Split(0, wx.TOP) if isMac: self.frame.Show()
def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) # There needs to be an "Images" directory with one or more jpegs in it in the # current working directory for this to work. self.jpgs = GetJpgList("./Images") # Get all the jpegs in the Images directory. self.CurrentJpg = 0 self.MaxImageSize = 200 b = wx.Button(self, -1, "Display next") b.Bind(wx.EVT_BUTTON, self.DisplayNext) # Starting with an EmptyBitmap, the real one will get put there # by the call to .DisplayNext(). if 'phoenix' in wx.version(): bmp = wx.Bitmap(self.MaxImageSize, self.MaxImageSize) else: bmp = wx.EmptyBitmap(self.MaxImageSize, self.MaxImageSize) self.Image = wx.StaticBitmap(self, -1, bmp) self.DisplayNext() # Using a Sizer to handle the layout: I never use absolute positioning. box = wx.BoxSizer(wx.VERTICAL) box.Add(b, 0, wx.CENTER | wx.ALL, 10) # Adding stretchable space before and after centers the image. box.Add((1, 1), 1) box.Add(self.Image, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALL | wx.ADJUST_MINSIZE, 10) box.Add((1, 1), 1) self.SetSizerAndFit(box) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
def showAbout(self, event): logging.debug('PsychoPyApp: Showing about dlg') license = open(os.path.join(self.prefs.paths['psychopy'],'LICENSE.txt'), 'rU').read() msg = _translate("""For stimulus generation and experimental control in python. PsychoPy depends on your feedback. If something doesn't work then let us know at [email protected]""").replace(' ', '') info = wx.AboutDialogInfo() if wx.version() >= '3.': icon = os.path.join(self.prefs.paths['resources'], 'psychopy.png') info.SetIcon(wx.Icon(icon, wx.BITMAP_TYPE_PNG, 128, 128)) info.SetName('PsychoPy') info.SetVersion('v'+psychopy.__version__) info.SetDescription(msg) info.SetCopyright('(C) 2002-2015 Jonathan Peirce') info.SetWebSite('http://www.psychopy.org') info.SetLicence(license) info.AddDeveloper('Jonathan Peirce') info.AddDeveloper('Jeremy Gray') info.AddDeveloper('Sol Simpson') info.AddDeveloper(u'Jonas Lindel\xF8v') info.AddDeveloper('Yaroslav Halchenko') info.AddDeveloper('Erik Kastman') info.AddDeveloper('Michael MacAskill') info.AddDeveloper('Hiroyuki Sogo') info.AddDocWriter('Jonathan Peirce') info.AddDocWriter('Jeremy Gray') info.AddDocWriter('Rebecca Sharman') info.AddTranslator('Hiroyuki Sogo') if not self.testMode: wx.AboutBox(info)
def OnPaint(self, evt): dc = wx.PaintDC(self) if self.permRect: dc.SetBrush(wx.BLACK_BRUSH) if 'phoenix' in wx.version(): dc.DrawRectangle(self.permRect) else: dc.DrawRectangleRect(self.permRect)
def CreateContextMenu(self): self.menu = wx.Menu() copy_menu_item = wx.MenuItem(self.menu, wx.NewId(), '&Copy text') self.menu.Bind(wx.EVT_MENU, self.CopySelection, copy_menu_item) if wx.version() > ("4.0.0"): self.menu.Append(copy_menu_item) else: self.menu.AppendItem(copy_menu_item)
from Resources.constants import * from Resources.audio import * from Resources.Modules import * from pyo.lib._wxwidgets import Grapher, BACKGROUND_COLOUR from Resources.Trajectory import Trajectory from Resources.MidiSettings import MidiSettings from Resources.CommandFrame import CommandFrame from Resources.DrawingSurface import DrawingSurface from Resources.ControlPanel import ControlPanel if sys.version_info[0] < 3: import xmlrpclib else: import xmlrpc.client as xmlrpclib if "phoenix" in wx.version(): from wx.adv import AboutDialogInfo, AboutBox else: from wx import AboutDialogInfo, AboutBox class EnvelopeFrame(wx.Frame): def __init__(self, parent, size=(600, 300)): wx.Frame.__init__(self, parent, -1, "Envelope Shape", size=size) self.parent = parent self.env = None menuBar = wx.MenuBar() self.menu = wx.Menu() self.menu.Append(200, 'Close\tCtrl+W', "") menuBar.Append(self.menu, "&File") self.SetMenuBar(menuBar)
def onInit(self, showSplash=True, testMode=False): """ :Parameters: testMode: bool If set to True then startup wizard won't appear and stdout/stderr won't be redirected to the Coder """ self.version = psychopy.__version__ self.SetAppName('PsychoPy2') # import localization after wx: from psychopy.app import localization # needed by splash screen self.localization = localization self.locale = localization.wxlocale self.locale.AddCatalog(self.GetAppName()) # set default paths and prefs self.prefs = psychopy.prefs if self.prefs.app['debugMode']: logging.console.setLevel(logging.DEBUG) # indicates whether we're running for testing purposes self.testMode = testMode self.osf_session = None if showSplash: # show splash screen splashFile = os.path.join( self.prefs.paths['resources'], 'psychopySplash.png') splashBitmap = wx.Image(name=splashFile).ConvertToBitmap() splash = AS.AdvancedSplash(None, bitmap=splashBitmap, timeout=3000, style=AS.AS_TIMEOUT | wx.FRAME_SHAPED, shadowcolour=wx.RED) # transparency? splash.SetTextPosition((10, 240)) splash.SetText(_translate(" Loading libraries...")) else: splash = None # SLOW IMPORTS - these need to be imported after splash screen starts # but then that they end up being local so keep track in self if splash: splash.SetText(_translate(" Loading PsychoPy2...")) from psychopy.compatibility import checkCompatibility # import coder and builder here but only use them later from psychopy.app import coder, builder, dialogs, urls self.keys = self.prefs.keys self.prefs.pageCurrent = 0 # track last-viewed page, can return there self.IDs = IDStore() self.urls = urls.urls self.quitting = False # check compatibility with last run version (before opening windows) self.firstRun = False if '--firstrun' in sys.argv: del sys.argv[sys.argv.index('--firstrun')] self.firstRun = True if 'lastVersion' not in self.prefs.appData: # must be before 1.74.00 last = self.prefs.appData['lastVersion'] = '1.73.04' self.firstRun = True else: last = self.prefs.appData['lastVersion'] if self.firstRun and not self.testMode: self.firstrunWizard() # setup links for URLs # on a mac, don't exit when the last frame is deleted, just show menu if sys.platform == 'darwin': self.menuFrame = MenuFrame(parent=None, app=self) # get preferred view(s) from prefs and previous view if self.prefs.app['defaultView'] == 'last': mainFrame = self.prefs.appData['lastFrame'] else: # configobjValidate should take care of this situation allowed = ['last', 'coder', 'builder', 'both'] if self.prefs.app['defaultView'] in allowed: mainFrame = self.prefs.app['defaultView'] else: self.prefs.app['defaultView'] = 'both' mainFrame = 'both' # fetch prev files if that's the preference if self.prefs.coder['reloadPrevFiles']: scripts = self.prefs.appData['coder']['prevFiles'] else: scripts = [] appKeys = list(self.prefs.appData['builder'].keys()) if self.prefs.builder['reloadPrevExp'] and ('prevFiles' in appKeys): exps = self.prefs.appData['builder']['prevFiles'] else: exps = [] # then override the prev files by command options and passed files if len(sys.argv) > 1: if sys.argv[1] == __name__: # program was executed as "python.exe PsychoPyIDE.py %1' args = sys.argv[2:] else: # program was executed as "PsychoPyIDE.py %1' args = sys.argv[1:] # choose which frame to start with if args[0] in ['builder', '--builder', '-b']: mainFrame = 'builder' args = args[1:] # can remove that argument elif args[0] in ['coder', '--coder', '-c']: mainFrame = 'coder' args = args[1:] # can remove that argument # did we get .py or .psyexp files? elif args[0][-7:] == '.psyexp': mainFrame = 'builder' exps = [args[0]] elif args[0][-3:] == '.py': mainFrame = 'coder' scripts = [args[0]] else: args = [] self.dpi = int(wx.GetDisplaySize()[0] / float(wx.GetDisplaySizeMM()[0]) * 25.4) if not (50 < self.dpi < 120): self.dpi = 80 # dpi was unreasonable, make one up if sys.platform == 'win32': # wx.SYS_DEFAULT_GUI_FONT is default GUI font in Win32 self._mainFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) else: self._mainFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT) if hasattr(self._mainFont, 'Larger'): # Font.Larger is available since wyPython version 2.9.1 # PsychoPy still supports 2.8 (see ensureMinimal above) self._mainFont = self._mainFont.Larger() self._codeFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT) self._codeFont.SetFaceName(self.prefs.coder['codeFont']) self._codeFont.SetPointSize( self._mainFont.GetPointSize()) # unify font size # create both frame for coder/builder as necess if splash: splash.SetText(_translate(" Creating frames...")) self.coder = None self.copiedRoutine = None self.copiedCompon = None self._allFrames = [] # ordered; order updated with self.onNewTopWindow if mainFrame in ['both', 'coder']: self.showCoder(fileList=scripts) if mainFrame in ['both', 'builder']: self.showBuilder(fileList=exps) # send anonymous info to www.psychopy.org/usage.php # please don't disable this, it's important for PsychoPy's development self._latestAvailableVersion = None self.updater = None prefsConn = self.prefs.connections if prefsConn['checkForUpdates'] or prefsConn['allowUsageStats']: connectThread = threading.Thread( target=connections.makeConnections, args=(self,)) connectThread.start() # query github in the background to populate a local cache about # what versions are available for download: from psychopy.tools import versionchooser as vc versionsThread = threading.Thread(target=vc._remoteVersions, args=(True,)) versionsThread.start() ok, msg = checkCompatibility(last, self.version, self.prefs, fix=True) # tell the user what has changed if not ok and not self.firstRun and not self.testMode: title = _translate("Compatibility information") dlg = dialogs.MessageDialog(parent=None, message=msg, type='Info', title=title) dlg.ShowModal() if self.prefs.app['showStartupTips'] and not self.testMode: tipFile = os.path.join( self.prefs.paths['resources'], _translate("tips.txt")) tipIndex = self.prefs.appData['tipIndex'] tp = wx.CreateFileTipProvider(tipFile, tipIndex) showTip = wx.ShowTip(None, tp) self.prefs.appData['tipIndex'] = tp.GetCurrentTip() self.prefs.saveAppData() self.prefs.app['showStartupTips'] = showTip self.prefs.saveUserPrefs() if self.prefs.connections['checkForUpdates']: self.Bind(wx.EVT_IDLE, self.checkUpdates) else: self.Bind(wx.EVT_IDLE, self.onIdle) # doing this once subsequently enables the app to open & switch among # wx-windows on some platforms (Mac 10.9.4) with wx-3.0: if wx.version() >= '3.0' and sys.platform == 'darwin': _Showgui_Hack() # returns ~immediately, no display # focus stays in never-land, so bring back to the app: if mainFrame in ['both', 'builder']: self.showBuilder() else: self.showCoder() return True
# Part of the PsychoPy library # Copyright (C) 2015 Jonathan Peirce # Distributed under the terms of the GNU General Public License (GPL). # Author: Jeremy Gray, Oct 2012; localization 2014 from pyglet.gl import gl_info import os, sys, time import wx import numpy as np import platform import tempfile, pickle import codecs if wx.version() < '2.9': tmpApp = wx.PySimpleApp() else: tmpApp = wx.App(False) from psychopy.app import localization from psychopy import info, data, visual, gui, core, __version__, web, prefs, event _localized = { #Benchmark 'Benchmark': _translate('Benchmark'), 'benchmark version': _translate('benchmark version'), 'full-screen': _translate('full-screen'), 'dots_circle': _translate('dots_circle'), 'dots_square': _translate('square'), 'available memory': _translate('available memory'), #PsychoPy
def main(): """NVDA's core main loop. This initializes all modules such as audio, IAccessible, keyboard, mouse, and GUI. Then it initialises the wx application object and sets up the core pump, which checks the queues and executes functions when requested. Finally, it starts the wx main loop. """ log.debug("Core starting") ctypes.windll.user32.SetProcessDPIAware() import config if not globalVars.appArgs.configPath: globalVars.appArgs.configPath = config.getUserDefaultConfigPath( useInstalledPathIfExists=globalVars.appArgs.launcher) #Initialize the config path (make sure it exists) config.initConfigPath() log.info("Config dir: %s" % os.path.abspath(globalVars.appArgs.configPath)) log.debug("loading config") import config config.initialize() if not globalVars.appArgs.minimal and config.conf["general"][ "playStartAndExitSounds"]: try: nvwave.playWaveFile("waves\\start.wav") except: pass logHandler.setLogLevelFromConfig() try: lang = config.conf["general"]["language"] import languageHandler log.debug("setting language to %s" % lang) languageHandler.setLanguage(lang) except: log.warning("Could not set language to %s" % lang) import versionInfo log.info("NVDA version %s" % versionInfo.version) log.info("Using Windows version %s" % winVersion.winVersionText) log.info("Using Python version %s" % sys.version) log.info("Using comtypes version %s" % comtypes.__version__) import configobj log.info("Using configobj version %s with validate version %s" % (configobj.__version__, configobj.validate.__version__)) # Set a reasonable timeout for any socket connections NVDA makes. import socket socket.setdefaulttimeout(10) log.debug("Initializing add-ons system") addonHandler.initialize() if globalVars.appArgs.disableAddons: log.info("Add-ons are disabled. Restart NVDA to enable them.") import appModuleHandler log.debug("Initializing appModule Handler") appModuleHandler.initialize() import NVDAHelper log.debug("Initializing NVDAHelper") NVDAHelper.initialize() import speechDictHandler log.debug("Speech Dictionary processing") speechDictHandler.initialize() import speech log.debug("Initializing speech") speech.initialize() if not globalVars.appArgs.minimal and (time.time() - globalVars.startTime) > 5: log.debugWarning("Slow starting core (%.2f sec)" % (time.time() - globalVars.startTime)) # Translators: This is spoken when NVDA is starting. speech.speakMessage(_("Loading NVDA. Please wait...")) import wx # wxPython 4 no longer has either of these constants (despite the documentation saying so), some add-ons may rely on # them so we add it back into wx. https://wxpython.org/Phoenix/docs/html/wx.Window.html#wx.Window.Centre wx.CENTER_ON_SCREEN = wx.CENTRE_ON_SCREEN = 0x2 log.info("Using wx version %s" % wx.version()) class App(wx.App): def OnAssert(self, file, line, cond, msg): message = "{file}, line {line}:\nassert {cond}: {msg}".format( file=file, line=line, cond=cond, msg=msg) log.debugWarning(message, codepath="WX Widgets", stack_info=True) app = App(redirect=False) # We support queryEndSession events, but in general don't do anything for them. # However, when running as a Windows Store application, we do want to request to be restarted for updates def onQueryEndSession(evt): if config.isAppX: # Automatically restart NVDA on Windows Store update ctypes.windll.kernel32.RegisterApplicationRestart(None, 0) app.Bind(wx.EVT_QUERY_END_SESSION, onQueryEndSession) def onEndSession(evt): # NVDA will be terminated as soon as this function returns, so save configuration if appropriate. config.saveOnExit() speech.cancelSpeech() if not globalVars.appArgs.minimal and config.conf["general"][ "playStartAndExitSounds"]: try: nvwave.playWaveFile("waves\\exit.wav", async=False) except: pass log.info("Windows session ending") app.Bind(wx.EVT_END_SESSION, onEndSession) log.debug("Initializing braille input") import brailleInput brailleInput.initialize() import braille log.debug("Initializing braille") braille.initialize() import displayModel log.debug("Initializing displayModel") displayModel.initialize() log.debug("Initializing GUI") import gui gui.initialize() import audioDucking if audioDucking.isAudioDuckingSupported(): # the GUI mainloop must be running for this to work so delay it wx.CallAfter(audioDucking.initialize) # #3763: In wxPython 3, the class name of frame windows changed from wxWindowClassNR to wxWindowNR. # NVDA uses the main frame to check for and quit another instance of NVDA. # To remain compatible with older versions of NVDA, create our own wxWindowClassNR. # We don't need to do anything else because wx handles WM_QUIT for all windows. import windowUtils class MessageWindow(windowUtils.CustomWindow): className = u"wxWindowClassNR" #Just define these constants here, so we don't have to import win32con WM_POWERBROADCAST = 0x218 WM_DISPLAYCHANGE = 0x7e PBT_APMPOWERSTATUSCHANGE = 0xA UNKNOWN_BATTERY_STATUS = 0xFF AC_ONLINE = 0X1 NO_SYSTEM_BATTERY = 0X80 #States for screen orientation ORIENTATION_NOT_INITIALIZED = 0 ORIENTATION_PORTRAIT = 1 ORIENTATION_LANDSCAPE = 2 def __init__(self, windowName=None): super(MessageWindow, self).__init__(windowName) self.oldBatteryStatus = None self.orientationStateCache = self.ORIENTATION_NOT_INITIALIZED self.orientationCoordsCache = (0, 0) self.handlePowerStatusChange() def windowProc(self, hwnd, msg, wParam, lParam): post_windowMessageReceipt.notify(msg=msg, wParam=wParam, lParam=lParam) if msg == self.WM_POWERBROADCAST and wParam == self.PBT_APMPOWERSTATUSCHANGE: self.handlePowerStatusChange() elif msg == self.WM_DISPLAYCHANGE: self.handleScreenOrientationChange(lParam) def handleScreenOrientationChange(self, lParam): import ui import winUser # Resolution detection comes from an article found at https://msdn.microsoft.com/en-us/library/ms812142.aspx. #The low word is the width and hiword is height. width = winUser.LOWORD(lParam) height = winUser.HIWORD(lParam) self.orientationCoordsCache = (width, height) if width > height: # If the height and width are the same, it's actually a screen flip, and we do want to alert of those! if self.orientationStateCache == self.ORIENTATION_LANDSCAPE and self.orientationCoordsCache != ( width, height): return #Translators: The screen is oriented so that it is wider than it is tall. ui.message(_("Landscape")) self.orientationStateCache = self.ORIENTATION_LANDSCAPE else: if self.orientationStateCache == self.ORIENTATION_PORTRAIT and self.orientationCoordsCache != ( width, height): return #Translators: The screen is oriented in such a way that the height is taller than it is wide. ui.message(_("Portrait")) self.orientationStateCache = self.ORIENTATION_PORTRAIT def handlePowerStatusChange(self): #Mostly taken from script_say_battery_status, but modified. import ui import winKernel sps = winKernel.SYSTEM_POWER_STATUS() if not winKernel.GetSystemPowerStatus( sps) or sps.BatteryFlag is self.UNKNOWN_BATTERY_STATUS: return if sps.BatteryFlag & self.NO_SYSTEM_BATTERY: return if self.oldBatteryStatus is None: #Just initializing the cache, do not report anything. self.oldBatteryStatus = sps.ACLineStatus return if sps.ACLineStatus == self.oldBatteryStatus: #Sometimes, this double fires. This also fires when the battery level decreases by 3%. return self.oldBatteryStatus = sps.ACLineStatus if sps.ACLineStatus & self.AC_ONLINE: #Translators: Reported when the battery is plugged in, and now is charging. ui.message( _("Charging battery. %d percent") % sps.BatteryLifePercent) else: #Translators: Reported when the battery is no longer plugged in, and now is not charging. ui.message( _("Not charging battery. %d percent") % sps.BatteryLifePercent) messageWindow = MessageWindow(unicode(versionInfo.name)) # initialize wxpython localization support locale = wx.Locale() lang = languageHandler.getLanguage() wxLang = locale.FindLanguageInfo(lang) if not wxLang and '_' in lang: wxLang = locale.FindLanguageInfo(lang.split('_')[0]) if hasattr(sys, 'frozen'): locale.AddCatalogLookupPathPrefix(os.path.join(os.getcwdu(), "locale")) # #8064: Wx might know the language, but may not actually contain a translation database for that language. # If we try to initialize this language, wx will show a warning dialog. # #9089: some languages (such as Aragonese) do not have language info, causing language getter to fail. # In this case, wxLang is already set to None. # Therefore treat these situations like wx not knowing the language at all. if wxLang and not locale.IsAvailable(wxLang.Language): wxLang = None if wxLang: try: locale.Init(wxLang.Language) except: log.error("Failed to initialize wx locale", exc_info=True) else: log.debugWarning("wx does not support language %s" % lang) import api import winUser import NVDAObjects.window desktopObject = NVDAObjects.window.Window( windowHandle=winUser.getDesktopWindow()) api.setDesktopObject(desktopObject) api.setFocusObject(desktopObject) api.setNavigatorObject(desktopObject) api.setMouseObject(desktopObject) import JABHandler log.debug("initializing Java Access Bridge support") try: JABHandler.initialize() except NotImplementedError: log.warning("Java Access Bridge not available") except: log.error("Error initializing Java Access Bridge support", exc_info=True) import winConsoleHandler log.debug("Initializing winConsole support") winConsoleHandler.initialize() import UIAHandler log.debug("Initializing UIA support") try: UIAHandler.initialize() except NotImplementedError: log.warning("UIA not available") except: log.error("Error initializing UIA support", exc_info=True) import IAccessibleHandler log.debug("Initializing IAccessible support") IAccessibleHandler.initialize() log.debug("Initializing input core") import inputCore inputCore.initialize() import keyboardHandler log.debug("Initializing keyboard handler") keyboardHandler.initialize() import mouseHandler log.debug("initializing mouse handler") mouseHandler.initialize() import touchHandler log.debug("Initializing touchHandler") try: touchHandler.initialize() except NotImplementedError: pass import globalPluginHandler log.debug("Initializing global plugin handler") globalPluginHandler.initialize() if globalVars.appArgs.install or globalVars.appArgs.installSilent: import gui.installerGui wx.CallAfter(gui.installerGui.doSilentInstall, startAfterInstall=not globalVars.appArgs.installSilent) elif globalVars.appArgs.portablePath and ( globalVars.appArgs.createPortable or globalVars.appArgs.createPortableSilent): import gui.installerGui wx.CallAfter( gui.installerGui.doCreatePortable, portableDirectory=globalVars.appArgs.portablePath, silent=globalVars.appArgs.createPortableSilent, startAfterCreate=not globalVars.appArgs.createPortableSilent) elif not globalVars.appArgs.minimal: try: # Translators: This is shown on a braille display (if one is connected) when NVDA starts. braille.handler.message(_("NVDA started")) except: log.error("", exc_info=True) if globalVars.appArgs.launcher: gui.LauncherDialog.run() # LauncherDialog will call doStartupDialogs() afterwards if required. else: wx.CallAfter(doStartupDialogs) import queueHandler # Queue the handling of initial focus, # as API handlers might need to be pumped to get the first focus event. queueHandler.queueFunction(queueHandler.eventQueue, _setInitialFocus) import watchdog import baseObject # Doing this here is a bit ugly, but we don't want these modules imported # at module level, including wx. log.debug("Initializing core pump") class CorePump(gui.NonReEntrantTimer): "Checks the queues and executes functions." def run(self): global _isPumpPending _isPumpPending = False watchdog.alive() try: if touchHandler.handler: touchHandler.handler.pump() JABHandler.pumpAll() IAccessibleHandler.pumpAll() queueHandler.pumpAll() mouseHandler.pumpAll() braille.pumpAll() except: log.exception("errors in this core pump cycle") baseObject.AutoPropertyObject.invalidateCaches() watchdog.asleep() if _isPumpPending and not _pump.IsRunning(): # #3803: Another pump was requested during this pump execution. # As our pump is not re-entrant, schedule another pump. _pump.Start(PUMP_MAX_DELAY, True) global _pump _pump = CorePump() requestPump() log.debug("Initializing watchdog") watchdog.initialize() try: import updateCheck except RuntimeError: updateCheck = None log.debug("Update checking not supported") else: log.debug("initializing updateCheck") updateCheck.initialize() log.info("NVDA initialized") postNvdaStartup.notify() log.debug("entering wx application main loop") app.MainLoop() log.info("Exiting") if updateCheck: _terminate(updateCheck) _terminate(watchdog) _terminate(globalPluginHandler, name="global plugin handler") _terminate(gui) config.saveOnExit() try: if globalVars.focusObject and hasattr(globalVars.focusObject, "event_loseFocus"): log.debug("calling lose focus on object with focus") globalVars.focusObject.event_loseFocus() except: log.exception("Lose focus error") try: speech.cancelSpeech() except: pass import treeInterceptorHandler _terminate(treeInterceptorHandler) _terminate(IAccessibleHandler, name="IAccessible support") _terminate(UIAHandler, name="UIA support") _terminate(winConsoleHandler, name="winConsole support") _terminate(JABHandler, name="Java Access Bridge support") _terminate(appModuleHandler, name="app module handler") _terminate(NVDAHelper) _terminate(touchHandler) _terminate(keyboardHandler, name="keyboard handler") _terminate(mouseHandler) _terminate(inputCore) _terminate(brailleInput) _terminate(braille) _terminate(speech) _terminate(addonHandler) if not globalVars.appArgs.minimal and config.conf["general"][ "playStartAndExitSounds"]: try: nvwave.playWaveFile("waves\\exit.wav", async=False) except: pass # #5189: Destroy the message window as late as possible # so new instances of NVDA can find this one even if it freezes during exit. messageWindow.destroy() log.debug("core done")
import uuid import wx import wx.grid from wx.lib.mixins.listctrl import CheckListCtrlMixin, ListCtrlAutoWidthMixin import wx.lib.agw.aui as aui from wx.lib.scrolledpanel import ScrolledPanel import connector import images DEBUG = False ID_CREATE, ID_CHANGE, ID_DELETE, ID_SYNC, ID_TASK_LABEL, ID_CONTEXT = \ [wx.NewId() for i in range(6)] WX_VERSION = tuple([int(v) for v in wx.version().split()[0].split(".")]) class TaskMixin(object): "ide2py extension for integrated task-focused interface support" def __init__(self): cfg = wx.GetApp().get_config("TASK") self.task_id = None self.task_suspended = True # create the structure for the task-based database: self.db = wx.GetApp().get_db() self.db.create("task", task_id=int,
from . import StringOps from .StringOps import utf8Enc, utf8Dec, pathEnc, urlFromPathname, \ urlQuote, pathnameFromUrl, flexibleUrlUnquote from .Configuration import MIDDLE_MOUSE_CONFIG_TO_TABMODE from . import OsAbstract from . import DocPages from .TempFileSet import TempFileSet from . import PluginManager # Try and load the html2 webview renderer try: WikiHtmlViewWK = None if wx.version().startswith("2.9") or wx.version() >= "3": from . import WikiHtmlView2 else: WikiHtmlView2 = None try: from . import WikiHtmlViewWK except: WikiHtmlViewWK = None import ExceptionLogger ExceptionLogger.logOptionalComponentException( "Initialize webkit HTML renderer") except: # traceback.print_exc() WikiHtmlView2 = None
ongridselectcell = EventSpec('grid_select_cell', binding=gridlib.EVT_GRID_SELECT_CELL, kind=GridEvent) ongrideditornshown = EventSpec('grid_editor_shown', binding=gridlib.EVT_GRID_EDITOR_SHOWN, kind=GridEvent) ongrideditorhidden = EventSpec('grid_editor_hidden', binding=gridlib.EVT_GRID_EDITOR_HIDDEN, kind=GridEvent) ongrideditorcreated = EventSpec('grid_editor_created', binding=gridlib.EVT_GRID_EDITOR_CREATED, kind=GridEvent) # Avoid deprecation warning (and TypeError) in WX Phoenix if wx.VERSION < (2, 9, 5) or 'classic' in wx.version(): GridTableBase = gridlib.PyGridTableBase else: GridTableBase = gridlib.GridTableBase class GridTable(GridTableBase): "A custom wx.Grid Table using user supplied data" def __init__(self, wx_grid, plugins): "data is a list of the form {row_index: {col_name: value}" # The base class must be initialized *first* GridTableBase.__init__(self) self.wx_grid = wx_grid self.plugins = plugins or {} # we need to store the row length and column length to
class PyoGuiSndView: def __init__(self, *args, **kwargs): raise Exception(NO_WX_MESSAGE) class PyoGuiKeyboard: def __init__(self, *args, **kwargs): raise Exception(NO_WX_MESSAGE) else: import wx import wx.lib.newevent from ._wxwidgets import ControlSlider, VuMeter, Grapher, DataMultiSlider, HRangeSlider from ._wxwidgets import SpectrumPanel, ScopePanel, SndViewTablePanel, Keyboard if "phoenix" not in wx.version(): wx.QueueEvent = wx.PostEvent # Custom events PyoGuiControlSliderEvent, EVT_PYO_GUI_CONTROL_SLIDER = wx.lib.newevent.NewEvent() PyoGuiGrapherEvent, EVT_PYO_GUI_GRAPHER = wx.lib.newevent.NewEvent() PyoGuiMultiSliderEvent, EVT_PYO_GUI_MULTI_SLIDER = wx.lib.newevent.NewEvent() PyoGuiSndViewMousePositionEvent, EVT_PYO_GUI_SNDVIEW_MOUSE_POSITION = wx.lib.newevent.NewEvent() PyoGuiSndViewSelectionEvent, EVT_PYO_GUI_SNDVIEW_SELECTION = wx.lib.newevent.NewEvent() PyoGuiKeyboardEvent, EVT_PYO_GUI_KEYBOARD = wx.lib.newevent.NewEvent() class PyoGuiControlSlider(ControlSlider): """ Floating-point control slider. :Parent: wx.Panel
log = printLog() panel = TestPanel(self, log) self.Bind(wx.EVT_CLOSE, self.OnDestroy) def OnDestroy(self, event): self.Destroy() class TestApp(wx.App): def OnInit(self): gMainWin = TestFrame(None) gMainWin.SetTitle('Test Demo') gMainWin.Show() return True #- __main__ ------------------------------------------------------------------- if __name__ == '__main__': import sys print('Python %s.%s.%s %s' % sys.version_info[0:4]) print('wxPython %s' % wx.version()) gApp = TestApp(redirect=False, filename=None, useBestVisual=False, clearSigInt=True) gApp.MainLoop()
KEY_NUMPAD_DOWN = wx.WXK_NUMPAD_DOWN KEY_NUMPAD_LEFT = wx.WXK_NUMPAD_LEFT KEY_NUMPAD_RIGHT = wx.WXK_NUMPAD_RIGHT KEY_NUMPAD_HOME = wx.WXK_NUMPAD_HOME KEY_NUMPAD_END = wx.WXK_NUMPAD_END KEY_NUMPAD_ENTER = wx.WXK_NUMPAD_ENTER KEY_U = 85 # Editable preference list CFG = [True, ] MSW = '__WXMSW__' GTK = '__WXGTK__' MAC = '__WXMAC__' VERSION = wx.version() IS_MAC = wx.Platform == MAC IS_MSW = wx.Platform == MSW IS_WINXP = IS_MSW and platform.release() == 'XP' IS_WIN7 = IS_MSW and platform.release() == '7' IS_WIN10 = IS_MSW and platform.release() == '10' IS_GTK = wx.Platform == GTK IS_GTK2 = IS_GTK and 'gtk2' in VERSION IS_GTK3 = IS_GTK and 'gtk3' in VERSION IS_WX2 = wx.VERSION[0] == 2 IS_WX3 = wx.VERSION[0] == 3 def _get_desktop_name(): if IS_GTK and 'XDG_CURRENT_DESKTOP' in os.environ: return os.environ['XDG_CURRENT_DESKTOP']
def __init__(self, wnd=None, locals=None, config=None, app=None, title="wxPython Widget Inspection Tool", *args, **kw): kw['title'] = title wx.Frame.__init__(self, *args, **kw) self.SetExtraStyle(wx.WS_EX_BLOCK_EVENTS) self.includeSizers = False self.started = False self.SetIcon(Icon.GetIcon()) self.MakeToolBar() panel = wx.Panel(self, size=self.GetClientSize()) # tell FrameManager to manage this frame self.mgr = wx.aui.AuiManager( panel, wx.aui.AUI_MGR_DEFAULT | wx.aui.AUI_MGR_TRANSPARENT_DRAG | wx.aui.AUI_MGR_ALLOW_ACTIVE_PANE) # make the child tools self.tree = InspectionTree(panel, size=(100, 300)) self.info = InspectionInfoPanel( panel, style=wx.NO_BORDER, ) if not locals: locals = {} myIntroText = ( "Python %s on %s, wxPython %s\n" "NOTE: The 'obj' variable refers to the object selected in the tree." % (sys.version.split()[0], sys.platform, wx.version())) self.crust = wx.py.crust.Crust( panel, locals=locals, intro=myIntroText, showInterpIntro=False, style=wx.NO_BORDER, ) self.locals = self.crust.shell.interp.locals self.crust.shell.interp.introText = '' self.locals['obj'] = self.obj = wnd self.locals['app'] = app self.locals['wx'] = wx wx.CallAfter(self._postStartup) # put the chlid tools in AUI panes self.mgr.AddPane( self.info, wx.aui.AuiPaneInfo().Name("info").Caption( "Object Info").CenterPane().CaptionVisible(True).CloseButton( False).MaximizeButton(True)) self.mgr.AddPane( self.tree, wx.aui.AuiPaneInfo().Name("tree").Caption( "Widget Tree").CaptionVisible(True).Left().Dockable( True).Floatable(True).BestSize( (280, 200)).CloseButton(False).MaximizeButton(True)) self.mgr.AddPane( self.crust, wx.aui.AuiPaneInfo().Name("crust").Caption( "PyCrust").CaptionVisible(True).Bottom().Dockable( True).Floatable(True).BestSize( (400, 200)).CloseButton(False).MaximizeButton(True)) self.mgr.Update() if config is None: config = wx.Config('wxpyinspector') self.config = config self.Bind(wx.EVT_CLOSE, self.OnClose) self.LoadSettings(self.config) self.crust.shell.lineNumbers = False self.crust.shell.setDisplayLineNumbers(False) self.crust.shell.SetMarginWidth(1, 0)
def onInit(self, showSplash=True, testMode=False): """This is launched immediately *after* the app initialises with wx :Parameters: testMode: bool """ self.SetAppName('PsychoPy3') if showSplash: #showSplash: # show splash screen splashFile = os.path.join( self.prefs.paths['resources'], 'psychopySplash.png') splashImage = wx.Image(name=splashFile) splashImage.ConvertAlphaToMask() splash = AS.AdvancedSplash(None, bitmap=splashImage.ConvertToBitmap(), timeout=3000, agwStyle=AS.AS_TIMEOUT | AS.AS_CENTER_ON_SCREEN, ) # transparency? w, h = splashImage.GetSize() splash.SetTextPosition((int(340), h-30)) splash.SetText(_translate("Copyright (C) 2020 OpenScienceTools.org")) else: splash = None # SLOW IMPORTS - these need to be imported after splash screen starts # but then that they end up being local so keep track in self from psychopy.compatibility import checkCompatibility # import coder and builder here but only use them later from psychopy.app import coder, builder, runner, dialogs if '--firstrun' in sys.argv: del sys.argv[sys.argv.index('--firstrun')] self.firstRun = True if 'lastVersion' not in self.prefs.appData: # must be before 1.74.00 last = self.prefs.appData['lastVersion'] = '1.73.04' self.firstRun = True else: last = self.prefs.appData['lastVersion'] if self.firstRun and not self.testMode: pass # setup links for URLs # on a mac, don't exit when the last frame is deleted, just show menu if sys.platform == 'darwin': self.menuFrame = MenuFrame(parent=None, app=self) # fetch prev files if that's the preference if self.prefs.coder['reloadPrevFiles']: scripts = self.prefs.appData['coder']['prevFiles'] else: scripts = [] appKeys = list(self.prefs.appData['builder'].keys()) if self.prefs.builder['reloadPrevExp'] and ('prevFiles' in appKeys): exps = self.prefs.appData['builder']['prevFiles'] else: exps = [] runlist = [] self.dpi = int(wx.GetDisplaySize()[0] / float(wx.GetDisplaySizeMM()[0]) * 25.4) if not (50 < self.dpi < 120): self.dpi = 80 # dpi was unreasonable, make one up if sys.platform == 'win32': # wx.SYS_DEFAULT_GUI_FONT is default GUI font in Win32 self._mainFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) else: self._mainFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT) try: self._codeFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT) except wx._core.wxAssertionError: # if no SYS_ANSI_FIXED_FONT then try generic FONTFAMILY_MODERN self._codeFont = wx.Font(self._mainFont.GetPointSize(), wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) # that gets most of the properties of _codeFont but the FaceName # FaceName is set in the setting of the theme: self.theme = self.prefs.app['theme'] # removed Aug 2017: on newer versions of wx (at least on mac) # this looks too big # if hasattr(self._mainFont, 'Larger'): # # Font.Larger is available since wyPython version 2.9.1 # # PsychoPy still supports 2.8 (see ensureMinimal above) # self._mainFont = self._mainFont.Larger() # self._codeFont.SetPointSize( # self._mainFont.GetPointSize()) # unify font size # create both frame for coder/builder as necess if splash: splash.SetText(_translate(" Creating frames...")) # Parse incoming call parser = argparse.ArgumentParser(prog=self) parser.add_argument('--builder', dest='builder', action="store_true") parser.add_argument('-b', dest='builder', action="store_true") parser.add_argument('--coder', dest='coder', action="store_true") parser.add_argument('-c', dest='coder', action="store_true") parser.add_argument('--runner', dest='runner', action="store_true") parser.add_argument('-r', dest='runner', action="store_true") parser.add_argument('-x', dest='direct', action='store_true') view, args = parser.parse_known_args(sys.argv) # Check from filetype if any windows need to be open if any(arg.endswith('.psyexp') for arg in args): view.builder = True exps = [file for file in args if file.endswith('.psyexp')] if any(arg.endswith('.psyrun') for arg in args): view.runner = True runlist = [file for file in args if file.endswith('.psyrun')] # If still no window specified, use default from prefs if not any(getattr(view, key) for key in ['builder', 'coder', 'runner']): if self.prefs.app['defaultView'] in view: setattr(view, self.prefs.app['defaultView'], True) elif self.prefs.app['defaultView'] == 'all': view.builder = True view.coder = True view.runner = True # Create windows if view.runner: self.showRunner(fileList=runlist) if view.coder: self.showCoder(fileList=scripts) if view.builder: self.showBuilder(fileList=exps) if view.direct: self.showRunner() for exp in [file for file in args if file.endswith('.psyexp') or file.endswith('.py')]: self.runner.panel.runFile(exp) # send anonymous info to www.psychopy.org/usage.php # please don't disable this, it's important for PsychoPy's development self._latestAvailableVersion = None self.updater = None self.news = None self.tasks = None prefsConn = self.prefs.connections ok, msg = checkCompatibility(last, self.version, self.prefs, fix=True) # tell the user what has changed if not ok and not self.firstRun and not self.testMode: title = _translate("Compatibility information") dlg = dialogs.MessageDialog(parent=None, message=msg, type='Info', title=title) dlg.ShowModal() if (self.prefs.app['showStartupTips'] and not self.testMode and not blockTips): tipFile = os.path.join( self.prefs.paths['resources'], _translate("tips.txt")) tipIndex = self.prefs.appData['tipIndex'] if parse_version(wx.__version__) >= parse_version('4.0.0a1'): tp = wx.adv.CreateFileTipProvider(tipFile, tipIndex) showTip = wx.adv.ShowTip(None, tp) else: tp = wx.CreateFileTipProvider(tipFile, tipIndex) showTip = wx.ShowTip(None, tp) self.prefs.appData['tipIndex'] = tp.GetCurrentTip() self.prefs.saveAppData() self.prefs.app['showStartupTips'] = showTip self.prefs.saveUserPrefs() self.Bind(wx.EVT_IDLE, self.onIdle) # doing this once subsequently enables the app to open & switch among # wx-windows on some platforms (Mac 10.9.4) with wx-3.0: v = parse_version if sys.platform == 'darwin': if v('3.0') <= v(wx.version()) <v('4.0'): _Showgui_Hack() # returns ~immediately, no display # focus stays in never-land, so bring back to the app: if prefs.app['defaultView'] in ['all', 'builder', 'coder', 'runner']: self.showBuilder() else: self.showCoder() # after all windows are created (so errors flushed) create output self._appLoaded = True if self.coder: self.coder.setOutputWindow() # takes control of sys.stdout # flush any errors to the last run log file logging.flush() sys.stdout.flush() # we wanted debug mode while loading but safe to go back to info mode if not self.prefs.app['debugMode']: logging.console.setLevel(logging.INFO) # Runner captures standard streams until program closed if self.runner and not self.testMode: sys.stdout = self.runner.stdOut sys.stderr = self.runner.stdOut return True
return "%s.%s" % ("#" * integer_width, "#" * fraction_width) else: return "#" * integer_width def SetValue(self, new_value): # to avoid formatting issues, values should not be passed as string! try: masked.NumCtrl.SetValue(self, new_value) except Exception, e: # TODO: better exception handling print e # WORKAROUND as Phoenix moved datetime picker # (could be useful for WXMAC or similar): if wx.VERSION < (2, 9, 5) or not 'phoenix' in wx.version(): DatePickerCtrl = wx.DatePickerCtrl DP_STYLE = wx.DP_DROPDOWN | wx.DP_SHOWCENTURY | wx.DP_ALLOWNONE | wx.DP_DEFAULT else: import wx.adv DatePickerCtrl = wx.adv.DatePickerCtrl DP_STYLE = wx.adv.DP_DROPDOWN | wx.adv.DP_SHOWCENTURY | wx.adv.DP_ALLOWNONE | wx.adv.DP_DEFAULT if DatePickerCtrl: class wx_DatePickerCtrl(DatePickerCtrl): def __init__(self, *args, **kwargs): del kwargs['mask'] kwargs['style'] = style = DP_STYLE DatePickerCtrl.__init__(self, *args, **kwargs)
self.wx_obj.SetLabel(new_text) label = InitSpec(_get_label, _set_label, doc="Title", type='string') # update metadata for the add context menu at the designer: Panel._meta.valid_children = [ctr for ctr in registry.CONTROLS.values() if ctr._image] # TODO: better filter Panel._meta.container = True if __name__ == "__main__": import sys # basic test until unit_test import gui app = wx.App(redirect=False) w = gui.Window(title="hello world", name="frmTest", tool_window=False, resizable=True, visible=False, pos=(180, 0)) p = gui.Panel(w, name="panel", label="hello!") b = gui.Button(p, name="test", label="click me!") w.show() from gui.tools.inspector import InspectorTool InspectorTool().show(w) print wx.version() app.MainLoop()
def get_dependencies(): """Returns list of dicts which indicate installed dependencies""" dependencies = [] # Numpy dep_attrs = { "name": "numpy", "min_version": "1.1.0", "description": "required", } try: import numpy dep_attrs["version"] = numpy.version.version except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) # wxPython dep_attrs = { "name": "wxPython", "min_version": "2.8.10.1", "description": "required", } try: import wx dep_attrs["version"] = wx.version() except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) # Matplotlib dep_attrs = { "name": "matplotlib", "min_version": "1.1.1", "description": "required", } try: import matplotlib dep_attrs["version"] = matplotlib._version.get_versions()["version"] except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) # Pycairo dep_attrs = { "name": "pycairo", "min_version": "1.8.8", "description": "required", } try: import cairo dep_attrs["version"] = cairo.version except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) # Python GnuPG dep_attrs = { "name": "python-gnupg", "min_version": "0.3.0", "description": "for opening own files without approval", } try: import gnupg dep_attrs["version"] = gnupg.__version__ except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) # xlrd dep_attrs = { "name": "xlrd", "min_version": "0.9.2", "description": "for loading Excel files", } try: import xlrd dep_attrs["version"] = xlrd.__VERSION__ except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) # xlwt dep_attrs = { "name": "xlwt", "min_version": "0.7.2", "description": "for saving Excel files", } try: import xlwt dep_attrs["version"] = xlwt.__VERSION__ except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) # Jedi dep_attrs = { "name": "jedi", "min_version": "0.8.0", "description": "for tab completion and context help in the entry line", } try: import jedi dep_attrs["version"] = jedi.__version__ except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) # pyrsvg dep_attrs = { "name": "pyrsvg", "min_version": "2.32", "description": "for displaying SVG files in cells", } try: import rsvg dep_attrs["version"] = True except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) # pyenchant dep_attrs = { "name": "pyenchant", "min_version": "1.6.6", "description": "for spell checking", } try: import enchant dep_attrs["version"] = enchant.__version__ except ImportError: dep_attrs["version"] = None dependencies.append(dep_attrs) return dependencies
# These are Quisk widgets from __future__ import print_function from __future__ import absolute_import from __future__ import division import sys, re import wx, wx.lib.buttons, wx.lib.stattext # The main script will alter quisk_conf_defaults to include the user's config file. import quisk_conf_defaults as conf import _quisk as QS wxVersion = wx.version()[0] def EmptyBitmap(width, height): if wxVersion in ('2', '3'): return wx.EmptyBitmap(width, height) else: return wx.Bitmap(width, height) def MakeWidgetGlobals(): global button_font, button_uline_font, button_bezel, button_width, button_height, button_text_width, button_text_height global _bitmap_menupop, _bitmap_sliderpop, _bitmap_cyclepop button_bezel = 3 # size of button bezel in pixels button_font = wx.Font(conf.button_font_size, wx.FONTFAMILY_SWISS, wx.NORMAL, wx.FONTWEIGHT_NORMAL, False, conf.quisk_typeface) button_uline_font = wx.Font(conf.button_font_size, wx.FONTFAMILY_SWISS, wx.NORMAL, wx.FONTWEIGHT_NORMAL, True, conf.quisk_typeface) dc = wx.MemoryDC() dc.SetFont(button_font) tmp_bm = EmptyBitmap(1, 1) # Thanks to NS4Y
def __init__(self): self.browser = None # Must ignore X11 errors like 'BadWindow' and others by # installing X11 error handlers. This must be done after # wx was intialized. if LINUX: cef.WindowUtils.InstallX11ErrorHandlers() global g_count_windows g_count_windows += 1 if WINDOWS: # noinspection PyUnresolvedReferences, PyArgumentList print("[wxpython.py] System DPI settings: %s" % str(cef.DpiAware.GetSystemDpi())) if hasattr(wx, "GetDisplayPPI"): print("[wxpython.py] wx.GetDisplayPPI = %s" % wx.GetDisplayPPI()) print("[wxpython.py] wx.GetDisplaySize = %s" % wx.GetDisplaySize()) print("[wxpython.py] MainFrame declared size: %s" % str( (WIDTH, HEIGHT))) size = scale_window_size_for_high_dpi(WIDTH, HEIGHT) print("[wxpython.py] MainFrame DPI scaled size: %s" % str(size)) wx.Frame.__init__(self, parent=None, id=wx.ID_ANY, title='wxPython example', size=size) # wxPython will set a smaller size when it is bigger # than desktop size. print("[wxpython.py] MainFrame actual size: %s" % self.GetSize()) self.setup_icon() self.create_menu() self.Bind(wx.EVT_CLOSE, self.OnClose) # Set wx.WANTS_CHARS style for the keyboard to work. # This style also needs to be set for all parent controls. self.browser_panel = wx.Panel(self, style=wx.WANTS_CHARS) self.browser_panel.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus) self.browser_panel.Bind(wx.EVT_SIZE, self.OnSize) if MAC: # Make the content view for the window have a layer. # This will make all sub-views have layers. This is # necessary to ensure correct layer ordering of all # child views and their layers. This fixes Window # glitchiness during initial loading on Mac (Issue #371). NSApp.windows()[0].contentView().setWantsLayer_(True) if LINUX: # On Linux must show before embedding browser, so that handle # is available (Issue #347). self.Show() # In wxPython 3.0 and wxPython 4.0 on Linux handle is # still not yet available, so must delay embedding browser # (Issue #349). if wx.version().startswith("3.") or wx.version().startswith("4."): wx.CallLater(100, self.embed_browser) else: # This works fine in wxPython 2.8 on Linux self.embed_browser() else: self.embed_browser() self.Show()
License: GNU GPL 3.x, GNU AFFERO GPL 3 Copyright: (c) 2020 Jorj X. McKie """ import os import sys import fitz import wx print("Python:", sys.version) print("wxPython:", wx.version()) print(fitz.__doc__) try: from PageFormat import FindFit except ImportError: def FindFit(*args): return "not implemented" try: from icons import ico_pdf # PDF icon in upper left screen corner do_icon = True except ImportError: do_icon = False
for classTuple in classes: className = classTuple[0] classObject = classTuple[1] methods = inspect.getmembers(classObject) for methodTuple in methods: try: sources[methodTuple[0]] = inspect.getsource(\ methodTuple[1]) except: pass return sources if __name__ == '__main__': print('[wxpython.py] architecture=%s-bit' % (8 * struct.calcsize("P"))) print('[wxpython.py] wx.version=%s' % wx.version()) # Intercept python exceptions. Exit app immediately when exception # happens on any of the threads. sys.excepthook = ExceptHook # Application settings g_applicationSettings = { # Disk cache # "cache_path": "webcache/", # CEF Python debug messages in console and in log_file "debug": True, # Set it to LOGSEVERITY_VERBOSE for more details "log_severity": cefpython.LOGSEVERITY_INFO, # Set to "" to disable logging to a file
def onInit(self, showSplash=True, testMode=False): """This is launched immediately *after* the app initialises with wx :Parameters: testMode: bool """ self.SetAppName('PsychoPy3') if False: # show splash screen splashFile = os.path.join(self.prefs.paths['resources'], 'psychopySplash.png') splashImage = wx.Image(name=splashFile) splashImage.ConvertAlphaToMask() splash = AS.AdvancedSplash( None, bitmap=splashImage.ConvertToBitmap(), timeout=3000, agwStyle=AS.AS_TIMEOUT | AS.AS_CENTER_ON_SCREEN, ) # transparency? w, h = splashImage.GetSize() splash.SetTextPosition((int(w - 130), h - 20)) splash.SetText(_translate("Loading libraries...")) wx.Yield() else: splash = None # SLOW IMPORTS - these need to be imported after splash screen starts # but then that they end up being local so keep track in self if splash: splash.SetText(_translate("Loading PsychoPy3...")) wx.Yield() from psychopy.compatibility import checkCompatibility # import coder and builder here but only use them later from psychopy.app import coder, builder, dialogs if '--firstrun' in sys.argv: del sys.argv[sys.argv.index('--firstrun')] self.firstRun = True if 'lastVersion' not in self.prefs.appData: # must be before 1.74.00 last = self.prefs.appData['lastVersion'] = '1.73.04' self.firstRun = True else: last = self.prefs.appData['lastVersion'] if self.firstRun and not self.testMode: pass # setup links for URLs # on a mac, don't exit when the last frame is deleted, just show menu if sys.platform == 'darwin': self.menuFrame = MenuFrame(parent=None, app=self) # get preferred view(s) from prefs and previous view if self.prefs.app['defaultView'] == 'last': mainFrame = self.prefs.appData['lastFrame'] else: # configobjValidate should take care of this situation allowed = ['last', 'coder', 'builder', 'both'] if self.prefs.app['defaultView'] in allowed: mainFrame = self.prefs.app['defaultView'] else: self.prefs.app['defaultView'] = 'both' mainFrame = 'both' # fetch prev files if that's the preference if self.prefs.coder['reloadPrevFiles']: scripts = self.prefs.appData['coder']['prevFiles'] else: scripts = [] appKeys = list(self.prefs.appData['builder'].keys()) if self.prefs.builder['reloadPrevExp'] and ('prevFiles' in appKeys): exps = self.prefs.appData['builder']['prevFiles'] else: exps = [] # then override the prev files by command options and passed files if len(sys.argv) > 1: if sys.argv[1] == __name__: # program was executed as "python.exe psychopyApp.py %1' args = sys.argv[2:] else: # program was executed as "psychopyApp.py %1' args = sys.argv[1:] # choose which frame to start with if args[0] in ['builder', '--builder', '-b']: mainFrame = 'builder' args = args[1:] # can remove that argument elif args[0] in ['coder', '--coder', '-c']: mainFrame = 'coder' args = args[1:] # can remove that argument # did we get .py or .psyexp files? elif args[0][-7:] == '.psyexp': mainFrame = 'builder' exps = [args[0]] elif args[0][-3:] == '.py': mainFrame = 'coder' scripts = [args[0]] else: args = [] self.dpi = int(wx.GetDisplaySize()[0] / float(wx.GetDisplaySizeMM()[0]) * 25.4) if not (50 < self.dpi < 120): self.dpi = 80 # dpi was unreasonable, make one up if sys.platform == 'win32': # wx.SYS_DEFAULT_GUI_FONT is default GUI font in Win32 self._mainFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) else: self._mainFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT) try: self._codeFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT) except wx._core.wxAssertionError: # if no SYS_ANSI_FIXED_FONT then try generic FONTFAMILY_MODERN self._codeFont = wx.Font(self._mainFont.GetPointSize(), wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) self._codeFont.SetFaceName(self.prefs.coder['codeFont']) # removed Aug 2017: on newer versions of wx (at least on mac) # this looks too big # if hasattr(self._mainFont, 'Larger'): # # Font.Larger is available since wyPython version 2.9.1 # # PsychoPy still supports 2.8 (see ensureMinimal above) # self._mainFont = self._mainFont.Larger() # self._codeFont.SetPointSize( # self._mainFont.GetPointSize()) # unify font size # create both frame for coder/builder as necess if splash: splash.SetText(_translate(" Creating frames...")) if mainFrame in ['both', 'coder']: self.showCoder(fileList=scripts) if mainFrame in ['both', 'builder']: self.showBuilder(fileList=exps) # send anonymous info to www.psychopy.org/usage.php # please don't disable this, it's important for PsychoPy's development self._latestAvailableVersion = None self.updater = None self.news = None self.tasks = None prefsConn = self.prefs.connections ok, msg = checkCompatibility(last, self.version, self.prefs, fix=True) # tell the user what has changed if not ok and not self.firstRun and not self.testMode: title = _translate("Compatibility information") dlg = dialogs.MessageDialog(parent=None, message=msg, type='Info', title=title) dlg.ShowModal() if (self.prefs.app['showStartupTips'] and not self.testMode and not blockTips): tipFile = os.path.join(self.prefs.paths['resources'], _translate("tips.txt")) tipIndex = self.prefs.appData['tipIndex'] if parse_version(wx.__version__) >= parse_version('4.0.0a1'): tp = wx.adv.CreateFileTipProvider(tipFile, tipIndex) showTip = wx.adv.ShowTip(None, tp) else: tp = wx.CreateFileTipProvider(tipFile, tipIndex) showTip = wx.ShowTip(None, tp) self.prefs.appData['tipIndex'] = tp.GetCurrentTip() self.prefs.saveAppData() self.prefs.app['showStartupTips'] = showTip self.prefs.saveUserPrefs() self.Bind(wx.EVT_IDLE, self.onIdle) # doing this once subsequently enables the app to open & switch among # wx-windows on some platforms (Mac 10.9.4) with wx-3.0: v = parse_version if sys.platform == 'darwin': if v('3.0') <= v(wx.version()) < v('4.0'): _Showgui_Hack() # returns ~immediately, no display # focus stays in never-land, so bring back to the app: if mainFrame in ['both', 'builder']: self.showBuilder() else: self.showCoder() # after all windows are created (so errors flushed) create output self._appLoaded = True if self.coder: self.coder.setOutputWindow() # takes control of sys.stdout return True
#!/usr/bin/env python # -*- coding: utf-8 -*- #-Imports---------------------------------------------------------------------- #--wxPython Imports. import wx import wx.adv if __name__ == '__main__': app = wx.App() frame = wx.Frame(None, -1, 'Minimal DatePickerCtrl Demo') panel = wx.Panel(frame) dpc = wx.adv.DatePickerCtrl(panel, size=(120, -1), pos=(10, 10), style=wx.adv.DP_DROPDOWN | wx.adv.DP_SHOWCENTURY | wx.adv.DP_ALLOWNONE) frame.CreateStatusBar().SetStatusText('wxPython %s' % wx.version()) frame.Show() app.MainLoop()
# Copyright: (c) 2000 by Total Control Software # Licence: wxWindows license #---------------------------------------------------------------------------- """ This program will load and run one of the individual demos in this directory within its own frame window. Just specify the module name on the command line. """ import wx import wx.lib.inspection import wx.lib.mixins.inspection import sys, os # stuff for debugging print "wx.version:", wx.version() print "pid:", os.getpid() ##raw_input("Press Enter...") assertMode = wx.PYAPP_ASSERT_DIALOG ##assertMode = wx.PYAPP_ASSERT_EXCEPTION #---------------------------------------------------------------------------- class Log: def WriteText(self, text): if text[-1:] == '\n': text = text[:-1] wx.LogMessage(text)
while len(sys.argv) > 1: arg = sys.argv.pop(1) if arg.lower() in ('-v', '--version'): # show all versions, sample output on macOS: # % python3 ./wxvlc.py -v # wxvlc.py: 19.07.28 (wx 4.0.6 osx-cocoa (phoenix) wxWidgets 3.0.5 _core.cpython-37m-darwin.so) # vlc.py: 3.0.6109 (Sun Mar 31 20:14:16 2019 3.0.6) # LibVLC version: 3.0.6 Vetinari (0x3000600) # LibVLC compiler: clang: warning: argument unused during compilation: '-mmacosx-version-min=10.7' [-Wunused-command-line-argument] # Plugin path: /Applications/VLC3.0.6.app/Contents/MacOS/plugins # Python: 3.7.4 (64bit) macOS 10.13.6 # Print version of this vlc.py and of the libvlc c = basename(str(wx._core).split()[-1].rstrip('>').strip("'").strip('"')) print('%s: %s (%s %s %s)' % (basename(__file__), __version__, wx.__name__, wx.version(), c)) try: vlc.print_version() vlc.print_python() except AttributeError: pass sys.exit(0) elif arg.startswith('-'): print('usage: %s [-v | --version] [<video_file_name>]' % (sys.argv[0],)) sys.exit(1) elif arg: # video file _video = expanduser(arg) if not isfile(_video): print('%s error: no such file: %r' % (sys.argv[0], arg))
import sys try: import wx WX_VERSION = int(wx.version()[0]) hasWx = True except Exception as e: hasWx = False WX_VERSION = 0 if hasWx: import wx.xrc from wx.lib.buttons import GenBitmapTextButton from pubsub import pub import wx.adv import os import time import math import random import numpy import scipy.stats import datetime from pytransit.analysis import base import pytransit.transit_tools as transit_tools import pytransit.tnseq_tools as tnseq_tools import pytransit.norm_tools as norm_tools
def create_timer(self): self.timer = wx.Timer(self, self.timer_id) self.Bind(wx.EVT_TIMER, self.on_timer, self.timer) self.timer.Start(10) # 10ms timer def on_timer(self, event): cef.MessageLoopWork() def OnExit(self): self.timer.Stop() return 0 def main(): sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error settings = {} cef.DpiAware.EnableHighDpiSupport() cef.Initialize(settings=settings) app = CefApp(False) app.MainLoop() del app # Must destroy before calling Shutdown cef.Shutdown() if __name__ == '__main__': print("CEF Python {ver}".format(ver=cef.__version__)) print("Python {ver} {arch}".format(ver=platform.python_version(), arch=platform.architecture()[0])) print("wxPython {ver}".format(ver=wx.version())) main()
def __init__(self,parent, storeClient, storeAddons): StoreDialog._instance = self # Translators: The title of the Addons Dialog profile = storeClient.getUserProfile() title = _("NVDAStore") if profile is not None: title = _("NVDASTORE ({firstName} {lastName})".format(firstName=profile[u'fname'], lastName=profile[u'lname'])) super(StoreDialog,self).__init__(parent,title=title, pos=(100,200), size=(800, 600)) StoreDialog._instance.storeAddons = storeAddons StoreDialog._instance.storeClient = storeClient mainSizer = wx.BoxSizer(wx.VERTICAL) panelSizer = wx.BoxSizer(wx.HORIZONTAL) settingsSizer = wx.BoxSizer(wx.VERTICAL) categoriesSizer = wx.BoxSizer(wx.VERTICAL) entriesSizer = wx.BoxSizer(wx.VERTICAL) if globalVars.appArgs.disableAddons: # Translators: A message in the add-ons manager shown when all add-ons are disabled. addonsDisabledLabel=wx.StaticText(self,-1,label=_("All add-ons are currently disabled. To enable add-ons you must restart NVDA.")) mainSizer.Add(addonsDisabledLabel) # Translators: the label for the installed addons list in the addons manager. categoriesLabel = wx.StaticText(self, -1, label=_("Categories")) categoriesSizer.Add(categoriesLabel) self.categories = wx.ListBox(self, -1, style = wx.LC_REPORT | wx.LC_SINGLE_SEL, size=(300, 350)) self.categories.Bind(wx.EVT_LISTBOX, self.onCategoryItemSelected) categoriesSizer.Add(self.categories) panelSizer.Add(categoriesSizer) # Modules list. entriesLabel=wx.StaticText(self,-1,label=_("Modules")) entriesSizer.Add(entriesLabel) self.addonsList=wx.ListCtrl(self,-1,style=wx.LC_REPORT|wx.LC_SINGLE_SEL,size=(550,350)) # Translators: The label for a column in add-ons list used to identify add-on package name (example: package is OCR). self.addonsList.InsertColumn(0,_("Package"),width=150) # Translators: The label for a column in add-ons list used to identify add-on's running status (example: status is running). self.addonsList.InsertColumn(1,_("Status"),width=50) # Translators: The label for a column in add-ons list used to identify add-on's version (example: version is 0.3). self.addonsList.InsertColumn(2,_("Version"),width=50) # Translators: The label for a column in add-ons list used to identify add-on's author (example: author is NV Access). self.addonsList.InsertColumn(3,_("Author"),width=300) self.addonsList.Bind(wx.EVT_LIST_ITEM_FOCUSED, self.onListItemSelected) entriesSizer.Add(self.addonsList) panelSizer.Add(entriesSizer) # Text control to show version information. descSizer = wx.BoxSizer(wx.VERTICAL) descLabel = wx.StaticText(self, -1, label=_("Description")) descSizer.Add(descLabel) self.descCtrl = wx.TextCtrl(self, wx.ID_ANY, size=(400, 350), style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_RICH) descSizer.Add(self.descCtrl) panelSizer.Add(descSizer, proportion=3) entryButtonsSizer=wx.BoxSizer(wx.HORIZONTAL) # Translators: The label for a button in Add-ons Manager dialog to show information about the selected add-on. self.aboutButton=wx.Button(self,label=_("&About add-on...")) self.aboutButton.Disable() self.aboutButton.Bind(wx.EVT_BUTTON,self.onAbout) entryButtonsSizer.Add(self.aboutButton) # Translators: The label for a button in Add-ons Manager dialog to show the help for the selected add-on. self.helpButton=wx.Button(self,label=_("Add-on &help")) self.helpButton.Disable() self.helpButton.Bind(wx.EVT_BUTTON,self.onHelp) entryButtonsSizer.Add(self.helpButton) # Translators: The label for a button in Add-ons Manager dialog to enable or disable the selected add-on. self.enableDisableButton=wx.Button(self,label=_("&Disable add-on")) self.enableDisableButton.Disable() self.enableDisableButton.Bind(wx.EVT_BUTTON,self.onEnableDisable) entryButtonsSizer.Add(self.enableDisableButton) # Translators: The label for a button in Add-ons Manager dialog to install an add-on. self.addButton=wx.Button(self,label=_("&Install")) self.addButton.Bind(wx.EVT_BUTTON,self.onAddClick) entryButtonsSizer.Add(self.addButton) # Translators: The label for a button to remove either: # Remove the selected add-on in Add-ons Manager dialog. # Remove a speech dictionary entry. self.removeButton=wx.Button(self,label=_("&Remove")) self.removeButton.Disable() self.removeButton.Bind(wx.EVT_BUTTON,self.onRemoveClick) entryButtonsSizer.Add(self.removeButton) # Translators: The label of a button in Add-ons Manager to open the Add-ons website and get more add-ons. self.getAddonsButton=wx.Button(self,label=_("Store")) self.getAddonsButton.Bind(wx.EVT_BUTTON,self.onGetAddonsClick) entryButtonsSizer.Add(self.getAddonsButton) settingsSizer.Add(panelSizer) settingsSizer.Add(entryButtonsSizer) mainSizer.Add(settingsSizer,border=20,flag=wx.LEFT|wx.RIGHT|wx.TOP) # Translators: The label of a button to close the Addons dialog. closeButton = wx.Button(self, label=_("&Close"), id=wx.ID_CLOSE) closeButton.Bind(wx.EVT_BUTTON, lambda evt: self.Close()) mainSizer.Add(closeButton,border=20,flag=wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.CENTER|wx.ALIGN_RIGHT) self.Bind(wx.EVT_CLOSE, self.onClose) self.EscapeId = wx.ID_CLOSE mainSizer.Fit(self) self.SetSizer(mainSizer) self.selfUpdateCheck = True self.refreshCategoriesList() self.refreshAddonsList() self.addonsList.SetFocus() self.Center(wx.BOTH | wx.CENTER if "4.0" in wx.version() else wx.BOTH | wx.CENTER_ON_SCREEN)
# On Mac the code after app.MainLoop() never executes, so # need to call CEF shutdown here. if platform.system() == "Darwin": chrome.Shutdown() wx.GetApp().Exit() class MyApp(wx.App): def OnInit(self): frame = MainFrame() self.SetTopWindow(frame) frame.Show() return True if __name__ == '__main__': chrome.Initialize({ "debug": True, "log_file": "debug.log", "log_severity": chrome.cefpython.LOGSEVERITY_INFO, # "cache_path": "webcache/", }) print('[sample1.py] wx.version=%s' % wx.version()) app = MyApp(False) app.MainLoop() # Important: do the wx cleanup before calling Shutdown del app # On Mac Shutdown is called in OnClose if platform.system() in ["Linux", "Windows"]: chrome.Shutdown()
def __init__(self, parent, ID=-1, title="About " + APP_NAME): AboutDialog.__init__(self, parent, ID, title) self.set_program_name(APP_NAME + " - a wxPython port of Synfig Studio") self.set_version("Python: " + sys.version[0:6] + ", wx: " + wx.version()) self.set_comment("2D vector animation studio") self.set_website("http://synfig.org/") self.set_copyright( "Copyright 2001-2013\nRobert B. Quattlebaum Jr.,\nAdrian Bentley and Synfig contributors" ) license = wordwrap( "This program is free software; you can redistribute it and/or modify " "it under the terms of the GNU General Public License as published by " "the Free Software Foundation; either version 2 of the License, or " "(at your option) any later version.\n\n" "This program is distributed in the hope that it will be useful, " "but WITHOUT ANY WARRANTY; without even the implied warranty of " "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the " "GNU General Public License for more details.\n\n" "You should have received a copy of the GNU General Public License along " "with this program; if not, write to the Free Software Foundation, Inc., " "51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or visit: http://www.gnu.org/", 550, wx.ClientDC(self)) self.set_license(license) authors = [] authors.append("wxSynfig Developer:") authors.append("") authors.append("Austin Aigbe") authors.append("") authors.append("Original developers of Synfig:") authors.append("") authors.append("Robert B. Quattlebaum Jr (darco)") authors.append("Adrian Bentley") authors.append("") authors.append("Contributors:") authors.append("") authors.append("Adrian Winchell (SnapSilverlight)") authors.append("Andreas Jochens") authors.append("Brendon Higgins") authors.append("Carlos López González (genete)") authors.append("Carlos A. Sosa Navarro") authors.append("Chris Moore (dooglus)") authors.append("Chris Norman (pixelgeek)") authors.append("Cyril Brulebois (KiBi)") authors.append("Daniel Fort") authors.append("Daniel Hornung (rubikcube)") authors.append("David Roden (Bombe)") authors.append("Denis Zdorovtsov (trizer)") authors.append("Dmitriy Pomerantsev (Atrus)") authors.append("Douglas Lau") authors.append("Evgenij Katunov") authors.append("Gerald Young (Yoyobuae)") authors.append("Gerco Ballintijn") authors.append("IL'dar AKHmetgaleev (AkhIL)") authors.append("Ivan Mahonin") authors.append("Jerome Blanchi (d.j.a.y.)") authors.append("Konstantin Dmitriev (zelgadis)") authors.append("Luka Pravica") authors.append("Nikita Kitaev (nikitakit)") authors.append("Martin Michlmayr (tbm)") authors.append("Max May (Permutatrix)") authors.append("Miguel Gea Milvaques (xerakko)") authors.append("Paul Wise (pabs)") authors.append("Ralf Corsepius") authors.append("Ramon Miranda") authors.append("Ray Frederikson") authors.append("Timo Paulssen (timonator)") authors.append("Yu Chen (jcome)") authors.append("Yue Shi Lai") self.set_authors(authors) artists = [] artists.append("Aurore D (rore)") artists.append("Bertrand Grégoire (berteh)") artists.append("Carl-Christian Gehl (Razputin)") artists.append("Carlos López González (genete)") artists.append("Chris Norman (pixelgeek)") artists.append("Daniel Hornung (rubikcube)") artists.append("David Rylander (rylleman)") artists.append("Franco Iacomella (Yaco)") artists.append("Gerald Young (Yoyobuae)") artists.append("Henrique Lopes Barone") artists.append("Konstantin Dmitriev (zelgadis)") artists.append("Madeleine Crubellier (mad0)") artists.append("Nikolai Mamashev (solkap)") artists.append("Robert B. Quattlebaum Jr. (darco)") artists.append("Thimotee Guiet (satrip)") artists.append("Yu Chen (jcome)") self.set_artists(artists) self.CenterOnScreen()
def runTest(frame, nb, log): win = TestPanel(nb, log) return win #--DocUtils Imports. try: from docutils.core import publish_string overview = publish_string(SBB.__doc__.replace(':class:', ''), writer_name='html') except ImportError: overview = SBB.__doc__ #- __main__ -------------------------------------------------------------------- if __name__ == '__main__': import os import sys try: # Try running with wxPythonDemo run.py first. import run run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:]) except ImportError: # run.py not found, try running normally. print(wx.version()) gApp = ShapedBitmapButtonApp(redirect=False, filename=None, useBestVisual=False, clearSigInt=True) gApp.MainLoop()
self.timer.Stop() if __name__ == '__main__': sys.excepthook = ExceptHook cefpython.g_debug = False cefpython.g_debugFile = GetApplicationPath("debug.log") settings = { "log_severity": cefpython.LOGSEVERITY_INFO, # LOGSEVERITY_VERBOSE "log_file": GetApplicationPath("debug.log"), # Set to "" to disable. "release_dcheck_enabled": True, # Enable only when debugging. # This directories must be set on Linux "locales_dir_path": cefpython.GetModuleDirectory() + "/locales", "resources_dir_path": cefpython.GetModuleDirectory(), "browser_subprocess_path": "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess") } # print("browser_subprocess_path="+settings["browser_subprocess_path"]) cefpython.Initialize(settings) print('wx.version=%s' % wx.version()) app = MyApp(False) app.MainLoop() # Let wx.App destructor do the cleanup before calling cefpython.Shutdown(). del app cefpython.Shutdown()