def GetContentWidth(self): bmp = self._getBitmap() if bmp is not None: bw = bmp.GetWidth() else: # no bitmap -> size is zero bw = 0 label = self.GetLabel() dc = wx.WindowDC(self) dc.SetFont(self.GetFont()) # size of text tw, th = dc.GetTextExtent(label) contentWidth = bw + tw + self.marginImage return contentWidth
def addText(self, text, color=''): # the horizontal extent can depend on the locale and font in use: font = self.GetFont() dc = wx.WindowDC(self) dc.SetFont(font) textWidth, textHeight = dc.GetTextExtent(text) textLength = wx.Size(textWidth + 50, textHeight) _style = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL myTxt = wx.StaticText(self, -1, label=text, style=_style, size=textLength) if len(color): myTxt.SetForegroundColour(color) self.sizer.Add(myTxt, 1, wx.ALIGN_CENTER)
def __populate_versions(self, control): imageType = 'Pillow' try: imageVer = Image.PILLOW_VERSION except AttributeError: imageType = 'PIL' imageVer = Image.VERSION visvisVer = 'Not installed' if not hasattr(sys, 'frozen'): try: import visvis as vv visvisVer = vv.__version__ except ImportError: pass versions = ('Hardware:\n' '\tProcessor: {}, {} cores\n\n' 'Software:\n' '\tOS: {}, {}\n' '\tPython: {}\n' '\tmatplotlib: {}\n' '\tNumPy: {}\n' '\t{}: {}\n' '\tpySerial: {}\n' '\tvisvis: {}\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, visvisVer, wx.version()) control.SetValue(versions) dc = wx.WindowDC(control) extent = list(dc.GetFullMultiLineTextExtent(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 __set_dev_grid(self): self.gridDev.Unbind(grid.EVT_GRID_EDITOR_CREATED) self.Unbind(grid.EVT_GRID_CELL_LEFT_CLICK) self.Unbind(grid.EVT_GRID_CELL_CHANGE) self.gridDev.ClearGrid() i = 0 for device in self.devices: self.gridDev.SetReadOnly(i, self.COL_SEL, True) self.gridDev.SetCellRenderer(i, self.COL_SEL, TickCellRenderer()) self.gridDev.SetCellValue(i, self.COL_NAME, device.name) cell = grid.GridCellChoiceEditor(sorted(DeviceGPS.TYPE), allowOthers=False) self.gridDev.SetCellValue(i, self.COL_TYPE, DeviceGPS.TYPE[device.type]) self.gridDev.SetCellEditor(i, self.COL_TYPE, cell) if device.type == DeviceGPS.NMEA_SERIAL: self.gridDev.SetCellValue(i, self.COL_HOST, device.get_serial_desc()) self.gridDev.SetReadOnly(i, self.COL_HOST, True) else: self.gridDev.SetCellValue(i, self.COL_HOST, device.resource) self.gridDev.SetReadOnly(i, self.COL_HOST, False) self.gridDev.SetCellValue(i, self.COL_TEST, '...') self.gridDev.SetCellAlignment(i, self.COL_SEL, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE) i += 1 self.index = limit(self.index, 0, len(self.devices) - 1) self.__select_row(self.index) self.index = self.index self.gridDev.AutoSize() font = self.gridDev.GetFont() dc = wx.WindowDC(self.gridDev) dc.SetFont(font) width, _height = dc.GetTextExtent(max(DeviceGPS.TYPE, key=len)) self.gridDev.SetColSize(self.COL_TYPE, width * 1.5) self.gridDev.Bind(grid.EVT_GRID_EDITOR_CREATED, self.__on_create) self.Bind(grid.EVT_GRID_CELL_LEFT_CLICK, self.__on_click) self.Bind(grid.EVT_GRID_CELL_CHANGE, self.__on_change)
def __init__(self, parent, id, value=None, action_kw={}, *args, **kwargs): global PHONECTRL_WIDTH self.__digits = '0123456789' # this_sty = wx.TAB_TRAVERSAL| wx.TE_PROCESS_ENTER kw = kwargs wx.TextCtrl.__init__(self, parent.GetWindow(), id, size=(-1, -1), *args, **kw) self.SetMaxLength(14) if PHONECTRL_WIDTH == 0: dc = wx.WindowDC(self) PHONECTRL_WIDTH = dc.GetMultiLineTextExtent("00 00 00 00 00", self.GetFont())[0] self.SetMinSize((PHONECTRL_WIDTH + 15, -1)) wx.EVT_CHAR(self, self.onChar) wx.EVT_TEXT(self, -1, self.checkSyntax) wx.EVT_LEFT_DOWN(self, self.OnLeftDown)
def __init__(self, parent): super(servicesPanel, self).__init__(parent) mainSizer = wx.BoxSizer(wx.VERTICAL) apiKeyLabel = wx.StaticText( self, -1, _(u"If you have a SndUp account, enter your API Key here. If your API Key is invalid, {0} will fail to upload. If there is no API Key here, {0} will upload annonymously." ).format(application.name, )) self.apiKey = wx.TextCtrl(self, -1) dc = wx.WindowDC(self.apiKey) dc.SetFont(self.apiKey.GetFont()) self.apiKey.SetSize(dc.GetTextExtent("0" * 100)) apiKeyBox = wx.BoxSizer(wx.HORIZONTAL) apiKeyBox.Add(apiKeyLabel, 0, wx.ALL, 5) apiKeyBox.Add(self.apiKey, 0, wx.ALL, 5) mainSizer.Add(apiKeyBox, 0, wx.ALL, 5) self.pocketBtn = wx.Button(self, -1) mainSizer.Add(self.pocketBtn, 0, wx.ALL, 5) self.SetSizer(mainSizer)
def DoHighlight(self, tlw, rect, colour, useWinDC, penWidth=2): if useWinDC: dc = wx.WindowDC(tlw) else: dc = wx.ScreenDC() dc.SetPen(wx.Pen(colour, penWidth)) dc.SetBrush(wx.TRANSPARENT_BRUSH) drawRect = wx.Rect(*rect) dc.DrawRectangleRect(drawRect) drawRect.Inflate(2, 2) if not useWinDC: pos = tlw.ScreenToClient(drawRect.GetPosition()) drawRect.SetPosition(pos) wx.CallLater(self.highlightTime, tlw.RefreshRect, drawRect) return dc
def screenshot(self, title=None, destdir=OUTPUT_DIR, window=None): try: from PIL import Image except ImportError: self._logger.error("Could not load PIL: not making screenshots") return if window is None: app = wx.GetApp() window = app.GetTopWindow() if not window: self._logger.error("Couldn't obtain top window and no window was passed as argument, bailing out") return rect = window.GetClientRect() size = window.GetSize() rect = wx.Rect(rect.x, rect.y, size.x, size.y) screen = wx.WindowDC(window) bmp = wx.EmptyBitmap(rect.GetWidth(), rect.GetHeight() + 30) mem = wx.MemoryDC(bmp) mem.Blit(0, 30, rect.GetWidth(), rect.GetHeight(), screen, rect.GetX(), rect.GetY()) titlerect = wx.Rect(0, 0, rect.GetWidth(), 30) mem.DrawRectangleRect(titlerect) if title: mem.DrawLabel(title, titlerect, wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL) del mem myWxImage = wx.ImageFromBitmap(bmp) im = Image.new('RGB', (myWxImage.GetWidth(), myWxImage.GetHeight())) im.frombytes(myWxImage.GetData()) if not os.path.exists(destdir): os.makedirs(destdir) index = 1 filename = os.path.join(destdir, 'Screenshot-%.2d.png' % index) while os.path.exists(filename): index += 1 filename = os.path.join(destdir, 'Screenshot-%.2d.png' % index) im.save(filename) del bmp
def GetBMP(self, method): w = self.widget maskClr = wx.Colour(12, 34, 56) sz = w.GetSize() bmp = wx.EmptyBitmap(sz.width, sz.height) dc = wx.MemoryDC() dc.SelectObject(bmp) dc.SetBackground(wx.Brush(maskClr)) dc.Clear() if method == 0: wdc = wx.WindowDC(w) dc.Blit(0,0, sz.width, sz.height, wdc, 0, 0) else: ##wx.DrawWindowOnDC(w, dc, method) wx.DrawWindowOnDC(w, dc) dc.SelectObject(wx.NullBitmap) bmp.SetMaskColour(maskClr) self.right.SetBMP(bmp, method)
def OnBtnLog(self, event): button = event.GetEventObject() label = button.GetLabel() if label == 'Show Log': button.SetLabel('Close Log') # Compute size of the Log Dialog. # Size it to provide a TextCtrl with 80x20 chars dc = wx.WindowDC(self) dc.SetFont(self.GetFont()) sz = dc.GetTextExtent('X') # Size of 'X' sz = wx.Size(sz.x * 80, sz.y * 20) print(sz) self.logFrame = LogFrame(parent=self, title='LogFrame', size=sz) self.logFrame.Show() else: button.SetLabel('Show Log') self.logFrame.Destroy() self.logFrame = None
def _hitTest(self, point): """ Given a point in device coordinates, return a handle to the display key that contains the point, or None if no corresponding display key is found """ point = self.CalcUnscrolledPosition(point) if self._displayMode == DISPLAY_MODE_DYNAMIC_RESIZE: dc = wx.WindowDC(self) displayRect = self._getDisplayRect() scale = self._getScale(displayRect) dc.SetMapMode(wx.MM_TEXT) dc.SetUserScale(scale, scale) (point.x, point.y) = (dc.DeviceToLogicalX(point.x), dc.DeviceToLogicalY(point.y)) for displayKey in self._displayKeys.values(): if displayKey.scaled.Contains(point): return displayKey.handle return None
def __init__(self, parent, id=-1, style=wx.EXPAND): wx.Panel.__init__(self, parent, id=id, style=style) title = wx.StaticText(self, -1, stdlines.SLOGAN) title.SetFont(bigfont) icon = wx.StaticBitmap( self, -1, wx.Bitmap(os.path.join(IMGDIR, 'pie_48.png'))) desc = wx.StaticText(self, -1, '') dc = wx.WindowDC(desc) desc.SetLabel(wordwrap.wordwrap(stdlines.DESCRIPTION, 300, dc)) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add((20,20), 1) sizer.Add(title, 0, wx.ALL|wx.ALIGN_CENTER, 5) sizer.Add(icon, 0, wx.ALL|wx.ALIGN_CENTRE, 5) sizer.Add(desc, 0, wx.ALL|wx.ALIGN_CENTRE, 5) sizer.Add((20,20), 3) self.SetSizer(sizer) self.Layout()
def GetLabelGrid(parent, bigFont=False, colnames=[], leftAlignCols=[]): font = wx.Font(fontSize + (fontSize // 3 if bigFont else 0), wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) dc = wx.WindowDC(parent) dc.SetFont(font) w, h = dc.GetTextExtent('999') label = wx.StaticText(parent, label=u'{}:'.format(_('Recorded'))) grid = ColGrid.ColGrid(parent, colnames=colnames) grid.SetLeftAlignCols(leftAlignCols) grid.SetRowLabelSize(0) grid.SetRightAlign(True) grid.AutoSizeColumns(True) grid.DisableDragColSize() grid.DisableDragRowSize() grid.SetDefaultCellFont(font) grid.SetDefaultRowSize(int(h * 1.15), True) return label, grid
def GetLabelGrid(parent, bigFont=False): font = wx.Font(fontSize + (fontSize // 3 if bigFont else 0), wx.DEFAULT, wx.NORMAL, wx.NORMAL) dc = wx.WindowDC(parent) dc.SetFont(font) w, h = dc.GetTextExtent('999') label = wx.StaticText(parent, label=u'{}:'.format(_('Recorded'))) grid = ColGrid.ColGrid(parent, colnames=colnames) grid.SetLeftAlignCols([iNameCol, iWaveCol]) grid.SetRowLabelSize(0) grid.SetRightAlign(True) grid.AutoSizeColumns(True) grid.DisableDragColSize() grid.DisableDragRowSize() grid.SetDoubleBuffered(True) grid.SetDefaultCellFont(font) grid.SetDefaultRowSize(int(h * 1.15), True) return label, grid
def OnPaint(self, evt=None): """ """ t = time.clock() self.old_time = t dc = wx.WindowDC(self) dc.SetBrush(self.bgrBrush) # Если параменты индикатора не менялись, то перерисовываем только картинку if not self.isParChanged(): self.DrawPic(self.NextState(), dc, True) self.OnCheckClose() return dc.BeginDrawing() pen = wx.Pen(wx.Colour(100, 100, 100)) dc.SetPen(pen) sx, sy = self.GetSize() px, py = self._pic_size dc.SetBrush(self.bgrBrush) # Чистим dc.DrawRectangle(0, 0, sx, sy) # Отрисовываем сообщение self.DrawLabel(dc) # Отрисовываем индикатор процесса self.DrawIndicator(dc) # Отрисовываем картинку self.DrawPic(self.NextState(), dc) dc.EndDrawing() if evt: evt.Skip self.OnCheckClose()
def __init__(self, value=""): super(findDialog, self).__init__(None, -1) panel = wx.Panel(self) sizer = wx.BoxSizer(wx.VERTICAL) self.SetTitle(_(u"Find in current buffer")) label = wx.StaticText(panel, -1, _(u"String")) self.string = wx.TextCtrl(panel, -1, value) dc = wx.WindowDC(self.string) dc.SetFont(self.string.GetFont()) self.string.SetSize(dc.GetTextExtent("0" * 40)) sizer.Add(label, 0, wx.ALL, 5) sizer.Add(self.string, 0, wx.ALL, 5) ok = wx.Button(panel, wx.ID_OK, _(u"OK")) ok.SetDefault() cancel = wx.Button(panel, wx.ID_CANCEL, _(u"Cancel")) btnsizer = wx.BoxSizer() btnsizer.Add(ok, 0, wx.ALL, 5) btnsizer.Add(cancel, 0, wx.ALL, 5) sizer.Add(btnsizer, 0, wx.ALL, 5) panel.SetSizer(sizer) self.SetClientSize(sizer.CalcMin())
def capture_image(panel, labels): # Need to be at a top level window in order to force a redraw frame = panel while not frame.IsTopLevel(): frame = frame.parent frame.Show() wx.Yield() # Grab the bitmap; if it is the top level, then include WindowDC so we # can grab the window decorations. This only works on Windows! if panel.IsTopLevel(): graphdc = wx.WindowDC(panel) else: graphdc = wx.ClientDC(panel) w, h = graphdc.GetSize() bmp = wx.EmptyBitmap(w, h) memdc = wx.MemoryDC() memdc.SelectObject(bmp) memdc.Blit(0, 0, w, h, graphdc, 0, 0) # Add annotations using a GCDC so we get antialiased corners gcdc = wx.GCDC(memdc) for widget, label, position in labels: annotate(gcdc, widget=widget, label=label, position=position, panelsize=(w, h)) # Release the bitmap from the DC memdc.SelectObject(wx.NullBitmap) # Copy bitmap to a numpy array img = numpy.empty((w, h, 3), 'uint8') bmp.CopyToBuffer(buffer(img), format=wx.BitmapBufferFormat_RGB) # Destroy the frame frame.Destroy() wx.Yield() return img
def __init__(self, tweet): super(viewNonTweet, self).__init__(None, size=(850,850)) self.SetTitle(_(u"View")) panel = wx.Panel(self) label = wx.StaticText(panel, -1, _(u"Item")) self.text = wx.TextCtrl(parent=panel, id=-1, value=tweet, style=wx.TE_READONLY|wx.TE_MULTILINE, size=(250, 180)) dc = wx.WindowDC(self.text) dc.SetFont(self.text.GetFont()) (x, y, z) = dc.GetMultiLineTextExtent("0"*140) self.text.SetSize((x, y)) self.text.SetFocus() textBox = wx.BoxSizer(wx.HORIZONTAL) textBox.Add(label, 0, wx.ALL, 5) textBox.Add(self.text, 1, wx.EXPAND, 5) mainBox = wx.BoxSizer(wx.VERTICAL) mainBox.Add(textBox, 0, wx.ALL, 5) spellcheck = wx.Button(panel, -1, _("Spelling correction"), size=wx.DefaultSize) spellcheck.Bind(wx.EVT_BUTTON, self.onCheck) self.unshortenButton = wx.Button(panel, -1, _(u"Expand URL"), size=wx.DefaultSize) self.unshortenButton.Bind(wx.EVT_BUTTON, self.onUnshorten) self.unshortenButton.Disable() translateButton = wx.Button(panel, -1, _(u"Translate message"), size=wx.DefaultSize) translateButton.Bind(wx.EVT_BUTTON, self.onTranslate) cancelButton = wx.Button(panel, wx.ID_CANCEL, _(u"Close"), size=wx.DefaultSize) cancelButton.SetDefault() buttonsBox = wx.BoxSizer(wx.HORIZONTAL) buttonsBox.Add(spellcheck, 0, wx.ALL, 5) buttonsBox.Add(self.unshortenButton, 0, wx.ALL, 5) buttonsBox.Add(translateButton, 0, wx.ALL, 5) buttonsBox.Add(cancelButton, 0, wx.ALL, 5) mainBox.Add(buttonsBox, 0, wx.ALL, 5) selectId = wx.NewId() self.Bind(wx.EVT_MENU, self.onSelect, id=selectId) self.accel_tbl = wx.AcceleratorTable([ (wx.ACCEL_CTRL, ord('A'), selectId), ]) self.SetAcceleratorTable(self.accel_tbl) panel.SetSizer(mainBox) self.SetClientSize(mainBox.CalcMin()) self.check_urls()
def calcSizeIndepDimensions(self): """ Calculate the dimensions which are independent of the panel size. Call this also after an options change. """ # Calculate and set dimensions of a "cell" which is the day number # of a particular day or a weekday heading ("Mo", "Tu", ...). dc = wx.WindowDC(self) try: # Initialize dims dc.SetFont(self.boldFont) cdw, cdh = dc.GetTextExtent("00") dc.SetFont(self.stdFont) # Expand cell width if a short weekday is broader for i in range(7): wd = wx.DateTime.GetWeekDayName(i, wx.DateTime.Name_Abbr) cdw = max(cdw, dc.GetTextExtent(wd)[0]) self.cellWidth = cdw self.cellHeight = cdh self.popupShiftX = self.cellWidth // 2 self.popupShiftY = self.cellHeight - 2 finally: dc.SetFont(wx.NullFont) del dc # Calc minimal month dimensions # 7 weekdays plus minimal distance between them self.minMonthWidth = 7 * self.cellWidth + 6 * self.minCellDistHor # A month spans over 4 to 6 weeks (at least partially) ignoring the # plus one line for month name plus one line for weekday names self.minMonthHeight = 8 * self.cellHeight + 7 * self.minCellDistVert
def Draw(self, dc): #print(self.GetLabel(), "wires>>> ", self._wires) #print(self.GetNode().GetName(), self.GetLabel(), self.GetWires()) final = self.GetPosition() + self.GetNode().GetRect().GetPosition() # Set color dc.SetPen(wx.Pen(wx.Colour("#2B2B2B"), 2)) dc.SetBrush(wx.Brush(wx.Colour('#C7C729'), wx.SOLID)) # Draw the plug dc.DrawCircle(final.x, final.y, self.GetRadius()) tdc = wx.WindowDC(wx.GetApp().GetTopWindow()) w, h = tdc.GetTextExtent(self.GetLabel()) # Plug label margin if self._type == 0: x = final.x + 12 else: x = final.x - w - 18 dc.DrawText(self.GetLabel(), x, final.y - h / 2)
def refresh( self ): self.grid.AutoSizeRows( False ) dc = wx.WindowDC( self.grid ) dc.SetFont( self.font ) widthTotal = self.rowLabelSize width, height = dc.GetTextExtent(" 00:00:00.000 ") self.grid.SetColSize( 0, width ) widthTotal += width width, height = dc.GetTextExtent(" 9999 ") self.grid.SetColSize( 1, width ) widthTotal += width scrollBarWidth = 48 self.grid.SetSize( (widthTotal + scrollBarWidth, -1) ) self.GetSizer().SetMinSize( (widthTotal + scrollBarWidth, -1) ) self.grid.ForceRefresh() self.Fit() wx.CallAfter( self.recordTimeButton.SetFocus )
def __set_gain_control(self): grid = self.controlGain.GetContainingSizer() if len(self.devicesRtl) > 0: self.controlGain.Destroy() device = self.devicesRtl[self.settings.indexRtl] if device.isDevice: gains = device.get_gains_str() self.controlGain = wx.Choice(self.toolbar, choices=gains) gain = device.get_closest_gain_str(device.gain) self.controlGain.SetStringSelection(gain) else: self.controlGain = NumCtrl(self.toolbar, integerWidth=3, fractionWidth=1) font = self.controlGain.GetFont() dc = wx.WindowDC(self.controlGain) dc.SetFont(font) size = dc.GetTextExtent('####.#') self.controlGain.SetMinSize((size[0] * 1.2, -1)) self.controlGain.SetValue(device.gain) grid.Add(self.controlGain, pos=(1, 7), flag=wx.ALIGN_CENTER) grid.Layout()
def PopulateList(self, descrs): self.descrs = descrs lstctr = self.list lstctr.Freeze() font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) _text = _("Use") dc = wx.WindowDC(self) dc.SetFont(font) fc_wdth = int(dc.GetTextExtent(_text)[0] * 1.25) lstctr.InsertColumn(0, _text, width=fc_wdth, format=wx.LIST_FORMAT_CENTRE) lwdth = lstctr.GetClientSizeTuple()[0] lstctr.InsertColumn(1, _("Title"), width=lwdth - fc_wdth) for data in descrs: index = lstctr.InsertStringItem(maxint, '') lstctr.SetStringItem(index, 1, data['name']) lstctr.CheckItem(index, data['isactive']) self.nitems = index + 1 lstctr.Thaw() lstctr.Update() self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.on_item_selected, self.list)
def _OnPaint(self, evt): dc = wx.WindowDC(self) # dc = wx.BufferedPaintDC(self) dc.SetBackground(wx.Brush("black", wx.SOLID)) dc.Clear() # dc.DrawBitmap(self.bgBitmap, 0, 0) wdposx, wdposy = self.getCenterPos(False) bx, by = self.Size[0], self.Size[1] if datetime.datetime.now().minute % 2 == 0: makeDigiClockImg(dc, bx, by, self.smallFont, self.bigFont, 0) makeCalendarImg(dc, self.Size[0] / 2, self.Size[1] / 2, wdposx - self.Size[0] / 4, self.Size[1] / 2) # dc.DrawBitmap(self.digiClockBitMap, 0, 0) # dc.DrawBitmap(self.calBitMap, wdposx - self.Size[0] / 4, self.Size[1] / 2) else: makeDigiClockImg(dc, bx, by, self.smallFont, self.bigFont, 0) makeCalendarImg(dc, self.Size[0] / 2, self.Size[1] / 2, wdposx - self.Size[0] / 4, self.Size[1] / 2) # dc.DrawBitmap(self.digiClockBitMap, 0, self.Size[1] / 2) # dc.DrawBitmap(self.calBitMap, wdposx - self.Size[0] / 4, 0) if self.showClock: self.drawAnalogClock(dc, time.time())
def __init__(self): if DEBUGGING: print('EGUIFrame.__init__()') ### set up application folder if getattr(sys, 'frozen', False): ### If the application is run as a bundle, the pyInstaller bootloader # extends the sys module by a flag frozen=True and sets the app # path into variable _MEIPASS'. self.e_gui_path = sys._MEIPASS ### TO BE FIXED # After bundling with pyInstaller, running App failed, which seems to be the path issue. # The above sys._MEIPASS didn't work as expected. # When the path was stripped three times # (because e_gui.app/Contents/MacOS is where the e_gui executable is located) # using path.dirname, the e_gui.app successfully launched # Maybe this issue of pyInstaller might get fixed later for i in range(3): self.e_gui_path = path.dirname(self.e_gui_path) else: self.e_gui_path = path.dirname(path.abspath(__file__)) self.flag_img = False self.flag_snd = False self.flag_mov = False self.flag_script_visible = False self.allowed_img_ext = ['png', 'jpg', 'tif', 'tiff'] self.allowed_snd_ext = ['wav'] self.allowed_mov_ext = ['mov', 'mp4', 'avi'] w_pos = (0, 25) w_size = (wx.Display(0).GetGeometry()[2], wx.Display(0).GetGeometry()[3] - w_pos[1]) self.w_sz = w_size # initial size wx.Frame.__init__(self, None, -1, "Experimenter_GUI - %s" % __version__, pos=w_pos, size=w_size) #style=wx.DEFAULT_FRAME_STYLE^(wx.RESIZE_BORDER|wx.MAXIMIZE_BOX)) self.SetBackgroundColour('#333333') #self.ShowFullScreen(True) #self.Bind(wx.EVT_SIZE, self.onSizing) ### set window size exactly to self.w_sz without menubar/border/etc. _diff = (self.GetSize()[0] - self.GetClientSize()[0], self.GetSize()[1] - self.GetClientSize()[1]) _sz = (w_size[0] + _diff[0], w_size[1] + _diff[1]) self.SetSize(_sz) ### font setup if 'darwin' in sys.platform: _font = "Monaco" else: _font = "Courier" fontSz = 8 self.base_script_font = wx.Font(20, wx.FONTFAMILY_DEFAULT, wx.NORMAL, wx.FONTWEIGHT_NORMAL, False, "Courier", wx.FONTENCODING_SYSTEM) self.fonts = [] # 0:smll, 1:default, larger fonts as index gets larger for i in range(5): self.fonts.append( wx.Font(fontSz, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, False, faceName=_font)) fontSz += 2 dc = wx.WindowDC(self) dc.SetFont(self.fonts[1]) ### set up panels ip_sz = (270, w_size[1] - 40) ip_pos = (0, 40) sp_sz = (670, w_size[1] - 60) sp_pos = (w_size[0] - sp_sz[0], 40) mp_sz = (w_size[0] - ip_sz[0] - sp_sz[0], w_size[1] - 80) mp_pos = (ip_sz[0], 80) self.ip_sz = ip_sz self.mp_sz = mp_sz self.sp_sz = sp_sz title = wx.StaticText(self, -1, "Item list", pos=(ip_pos[0], 3)) title.SetFont(self.fonts[4]) title.SetForegroundColour('#DDDDDD') self.iPanel = ItemPanel(self, pos=ip_pos, size=ip_sz) title = wx.StaticText(self, -1, "Set up items in script", pos=(mp_pos[0], 3)) title.SetFont(self.fonts[4]) title.SetForegroundColour('#DDDDDD') sTxt = wx.StaticText(self, -1, " - Change a choice box item with mouse, or", pos=(mp_pos[0], title.GetPosition()[1] + title.GetSize()[1] + 2)) sTxt.SetFont(self.fonts[2]) sTxt.SetForegroundColour('#DDDDDD') sTxt = wx.StaticText( self, -1, " type a text in a text-box and press Return-key.", pos=(mp_pos[0], sTxt.GetPosition()[1] + sTxt.GetSize()[1] + 2)) sTxt.SetFont(self.fonts[2]) sTxt.SetForegroundColour('#DDDDDD') self.mPanel = MainPanel(self, pos=mp_pos, size=mp_sz) title = wx.StaticText(self, -1, "Result script", pos=(sp_pos[0], 3)) title.SetFont(self.fonts[4]) title.SetForegroundColour('#DDDDDD') btn = wx.Button(self, -1, "", name="show_script_btn", pos=(sp_pos[0] + title.GetSize()[0] + 5, 0), size=(25, 20)) set_img_for_btn( path.join(self.e_gui_path, "input/img_script_show.png"), btn) btn.Bind(wx.EVT_LEFT_UP, self.onShowScript) self.sPanel = ScriptPanel(self, pos=sp_pos, size=sp_sz) ### Connecting key-inputs with some functions exit_BtnID = wx.NewIdRef(count=1) #esc_BtnID = wx.NewIdRef(count=1) self.Bind(wx.EVT_MENU, self.quit, id=exit_BtnID) #self.Bind(wx.EVT_MENU, self.onESC, id = esc_BtnID) accel_tbl = wx.AcceleratorTable([(wx.ACCEL_CMD, ord('Q'), exit_BtnID)]) #(wx.ACCEL_NORMAL, wx.WXK_ESCAPE, esc_BtnID) ]) self.SetAcceleratorTable(accel_tbl) #msg = "Click OK button (or press ENTER key) to start the app.\nDialog for asking a series of questions to determine stimuli paths/correct stimulus/etc will appear.\n\nIf stimuli for trials should be specifically ordered, stimuli filenames should follow specific rules.\nIf you are not sure about it, cancel the dialog box and check the rules by pressing info(i) button next to 'setup_stimuli' in the left panel." #show_msg(msg, size=(400, 280)) wx.CallLater(1, self.mPanel.setUpStimuli, None)
def refresh(self, forceRefresh=False): self.setGpxDistanceButton.Enable(hasattr(Model.race, 'geoTrack')) if not (forceRefresh or self.isExternalChange() or self.state.changed()): return # Fix the height of the column labels. dc = wx.WindowDC(self.grid) dc.SetFont(self.grid.GetLabelFont()) textHeight = dc.GetTextExtent('Label')[1] self.colLabelHeight = textHeight * max( name.count('\n') + 1 for name in self.colnames) + textHeight // 4 self.grid.SetColLabelSize(self.colLabelHeight) with Model.LockRace() as race: self.grid.ClearGrid() if race is None: return for c in xrange(self.grid.GetNumberCols()): if self.grid.GetColLabelValue(c).startswith(_('Distance')): self.grid.SetColLabelValue( c, u'{}\n({})'.format(_('Distance'), ['km', 'miles' ][getattr(race, 'distanceUnit', 0)])) break categories = race.getAllCategories() if self.grid.GetNumberRows() > 0: self.grid.DeleteRows(0, self.grid.GetNumberRows()) self.grid.AppendRows(len(categories)) for r, cat in enumerate(categories): self._setRow( r=r, active=cat.active, name=cat.name, gender=getattr(cat, 'gender', None), catStr=cat.catStr, catType=cat.catType, startOffset=cat.startOffset, numLaps=cat._numLaps, raceMinutes=cat.raceMinutes, lappedRidersMustContinue=getattr( cat, 'lappedRidersMustContinue', False), distance=getattr(cat, 'distance', None), distanceType=getattr(cat, 'distanceType', Model.Category.DistanceByLap), firstLapDistance=getattr(cat, 'firstLapDistance', None), publishFlag=cat.publishFlag, uploadFlag=cat.uploadFlag, seriesFlag=cat.seriesFlag, ) self.doAutosize() self.fixCells() # Force the grid to the correct size. self.grid.FitInside() self.GetSizer().Layout()
def GetTextExtent(text): tdc = wx.WindowDC(wx.GetApp().GetTopWindow()) w, h = tdc.GetTextExtent(text) return w, h
def save_screenshot_to_file(filename=None, widget=None, settle_time=None): """Take screenshot of widget. <settle_time> in milliseconds """ assert (isinstance(widget, wx.Window)), '<widget> must be (sub)class of wx.Window' if filename is None: filename = gmTools.get_unique_filename( prefix='gm-screenshot-%s-' % pyDT.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'), suffix='.png' # for testing: #,tmp_dir = os.path.join(gmTools.gmPaths().home_dir, 'gnumed') ) else: filename = gmTools.fname_sanitize(filename) _log.debug('filename: %s', filename) _log.debug('widget: %s', widget) _log.debug('display size: %s', wx.DisplaySize()) # let it settle a bit for, say, tooltips if settle_time is not None: for wait_slice in range(int(settle_time // 100)): wx.SafeYield() time.sleep(0.1) widget_rect_on_screen = widget.GetScreenRect() client_area_origin_on_screen = widget.ClientToScreen((0, 0)) widget_rect_local = widget.GetRect() widget_rect_client_area = widget.GetClientRect() client_area_origin_local = widget.GetClientAreaOrigin() _log.debug('widget.GetScreenRect(): %s', widget_rect_on_screen) _log.debug('widget.ClientToScreen(0, 0): %s', client_area_origin_on_screen) _log.debug('widget.GetRect(): %s', widget_rect_local) _log.debug('widget.GetClientRect(): %s', widget_rect_client_area) _log.debug('widget.GetClientAreaOrigin(): %s', client_area_origin_local) width2snap = widget_rect_local.width height2snap = widget_rect_local.height border_x = client_area_origin_on_screen.x - widget_rect_local.x x2snap_from = 0 - border_x title_and_menu_height = client_area_origin_on_screen.y - widget_rect_on_screen.y y2snap_from = 0 - title_and_menu_height # those are the correct dimensions but we don't get to # *see* the window decorations on a WindowDC or ClientDC :-( # (and a screendc doesn't work either) _log.debug('left (x) border: %s', border_x) _log.debug('top (y) border: %s', title_and_menu_height) _log.debug('x2snap_from: %s', x2snap_from) _log.debug('y2snap_from: %s', y2snap_from) _log.debug('width2snap: %s', width2snap) _log.debug('height2snap: %s', height2snap) # WindowDC includes decorations, supposedly, but Windows only window_dc = wx.WindowDC(widget) wxbmp = __snapshot_to_bitmap(source_dc=window_dc, x2snap_from=x2snap_from, y2snap_from=y2snap_from, width2snap=width2snap, height2snap=height2snap) window_dc.Destroy() del window_dc wxbmp.SaveFile(filename, wx.BITMAP_TYPE_PNG) del wxbmp x2snap_on_screen = widget_rect_on_screen.x y2snap_on_screen = widget_rect_on_screen.y # adjust for menu/title ? sane_x2snap_on_screen = max(0, x2snap_on_screen) sane_y2snap_on_screen = max(0, y2snap_on_screen) _log.debug('x2snap_on_screen: %s', x2snap_on_screen) _log.debug('y2snap_on_screen: %s', y2snap_on_screen) _log.debug('sane x2snap_on_screen: %s', sane_x2snap_on_screen) _log.debug('sane x2snap_on_screen: %s', sane_y2snap_on_screen) screen_dc = wx.ScreenDC() # not implemented: #wxbmp = screen_dc.GetAsBitmap() # can use subrect=... wxbmp = __snapshot_to_bitmap(source_dc=screen_dc, x2snap_from=sane_x2snap_on_screen, y2snap_from=sane_y2snap_on_screen, width2snap=width2snap, height2snap=height2snap) screen_dc.Destroy() del screen_dc wxbmp.SaveFile(filename + '.screendc.png', wx.BITMAP_TYPE_PNG) del wxbmp # ClientDC does not include decorations, only client area #client_dc = wx.ClientDC(widget) #wxbmp = __snapshot_to_bitmap ( # source_dc = client_dc, # x2snap_from = x2snap_from, # y2snap_from = y2snap_from, # width2snap = width2snap, # height2snap = height2snap #) #client_dc.Destroy() #del client_dc #wxbmp.SaveFile(filename + '.clientdc.png', wx.BITMAP_TYPE_PNG) #del wxbmp # adjust for window decoration on Linux #if sys.platform == 'linux': # If the widget has a menu bar, remove that from the title bar height. #if hasattr(widget, 'GetMenuBar'): # if widget.GetMenuBar(): # title_bar_height /= 2 # print('title bar height:', title_bar_height) #width2snap += (border_width * 2) #height2snap += title_bar_height + border_width gmDispatcher.send(signal='statustext', msg=_('Saved screenshot to file [%s].') % filename) return filename
def __init__(self, graph, settings): wx.Panel.__init__(self, graph) self.spectrum = None self.graph = graph self.settings = settings self.measure = None self.checked = { Measure.MIN: None, Measure.MAX: None, Measure.AVG: None, Measure.GMEAN: None, Measure.HBW: None, Measure.OBW: None } self.selected = None self.SetBackgroundColour('white') self.grid = wxGrid.Grid(self) self.grid.CreateGrid(3, 19) self.grid.EnableEditing(True) self.grid.EnableDragGridSize(False) self.grid.SetColLabelSize(1) self.grid.SetRowLabelSize(1) self.grid.SetColMinimalAcceptableWidth(1) self.grid.SetColSize(2, 1) self.grid.SetColSize(7, 1) self.grid.SetColSize(11, 1) self.grid.SetColSize(15, 1) self.grid.SetMargins(0, wx.SystemSettings_GetMetric(wx.SYS_HSCROLL_Y)) for x in range(self.grid.GetNumberRows()): self.grid.SetRowLabelValue(x, '') for y in range(self.grid.GetNumberCols()): self.grid.SetColLabelValue(y, '') for row in range(self.grid.GetNumberRows()): for col in range(self.grid.GetNumberCols()): self.grid.SetReadOnly(row, col, True) self.locsDesc = { 'F Start': (0, 0), 'F End': (1, 0), 'F Delta': (2, 0), 'P Min': (0, 4), 'P Max': (1, 4), 'P Delta': (2, 4), 'Mean': (0, 9), 'GMean': (1, 9), 'Flatness': (2, 9), '-3dB Start': (0, 13), '-3dB End': (1, 13), '-3dB Delta': (2, 13), 'OBW Start': (0, 17), 'OBW End': (1, 17), 'OBW Delta': (2, 17) } self.__set_descs() self.locsCheck = { Measure.MIN: (0, 3), Measure.MAX: (1, 3), Measure.AVG: (0, 8), Measure.GMEAN: (1, 8), Measure.HBW: (0, 12), Measure.OBW: (0, 16) } self.__set_check_editor() self.locsFreq = [(0, 1), (1, 1)] self.__set_freq_editor() colour = self.grid.GetBackgroundColour() self.grid.SetCellTextColour(2, 3, colour) self.grid.SetCellTextColour(2, 8, colour) self.grid.SetCellTextColour(1, 12, colour) self.grid.SetCellTextColour(2, 12, colour) self.grid.SetCellTextColour(1, 16, colour) self.grid.SetCellTextColour(2, 16, colour) self.__clear_checks() self.locsMeasure = { 'start': (0, 1), 'end': (1, 1), 'deltaF': (2, 1), 'minFP': (0, 5), 'maxFP': (1, 5), 'deltaFP': (2, 5), 'minP': (0, 6), 'maxP': (1, 6), 'deltaP': (2, 6), 'avg': (0, 10), 'gmean': (1, 10), 'flat': (2, 10), 'hbwstart': (0, 14), 'hbwend': (1, 14), 'hbwdelta': (2, 14), 'obwstart': (0, 18), 'obwend': (1, 18), 'obwdelta': (2, 18) } fontCell = self.grid.GetDefaultCellFont() fontSize = fontCell.GetPointSize() fontStyle = fontCell.GetStyle() fontWeight = fontCell.GetWeight() font = wx.Font(fontSize, wx.FONTFAMILY_MODERN, fontStyle, fontWeight) dc = wx.WindowDC(self.grid) dc.SetFont(font) widthMHz = dc.GetTextExtent('###.######')[0] * 1.2 widthdB = dc.GetTextExtent('-##.##')[0] * 1.2 for _desc, (_row, col) in self.locsDesc.iteritems(): self.grid.AutoSizeColumn(col) for col in [1, 5, 14, 18]: self.grid.SetColSize(col, widthMHz) for row in xrange(self.grid.GetNumberRows()): self.grid.SetCellFont(row, col, font) for col in [6, 10]: self.grid.SetColSize(col, widthdB) for row in xrange(self.grid.GetNumberRows()): self.grid.SetCellFont(row, col, font) for _desc, (_row, col) in self.locsCheck.iteritems(): self.grid.AutoSizeColumn(col) toolTips = {} toolTips[self.locsMeasure['start']] = 'Selection start (MHz)' toolTips[self.locsMeasure['end']] = 'Selection end (MHz)' toolTips[self.locsMeasure['deltaF']] = 'Selection bandwidth (MHz)' toolTips[self.locsMeasure['minFP']] = 'Minimum power location (MHz)' toolTips[self.locsMeasure['maxFP']] = 'Maximum power location (MHz)' toolTips[ self.locsMeasure['deltaFP']] = 'Power location difference (MHz)' toolTips[self.locsMeasure['minP']] = 'Minimum power (dB)' toolTips[self.locsMeasure['maxP']] = 'Maximum power (dB)' toolTips[self.locsMeasure['deltaP']] = 'Power difference (dB)' toolTips[self.locsMeasure['avg']] = 'Mean power (dB)' toolTips[self.locsMeasure['gmean']] = 'Geometric mean power (dB)' toolTips[self.locsMeasure['flat']] = 'Spectral flatness' toolTips[self.locsMeasure['hbwstart']] = '-3db start location (MHz)' toolTips[self.locsMeasure['hbwend']] = '-3db end location (MHz)' toolTips[self.locsMeasure['hbwdelta']] = '-3db bandwidth (MHz)' toolTips[self.locsMeasure['obwstart']] = '99% start location (MHz)' toolTips[self.locsMeasure['obwend']] = '99% end location (MHz)' toolTips[self.locsMeasure['obwdelta']] = '99% bandwidth (MHz)' self.toolTips = GridToolTips(self.grid, toolTips) self.popupMenu = wx.Menu() self.popupMenuCopy = self.popupMenu.Append(wx.ID_ANY, "&Copy", "Copy entry") self.Bind(wx.EVT_MENU, self.__on_copy, self.popupMenuCopy) self.Bind(wxGrid.EVT_GRID_CELL_RIGHT_CLICK, self.__on_popup_menu) self.Bind(wxGrid.EVT_GRID_CELL_LEFT_CLICK, self.__on_cell_click) if wx.VERSION >= (3, 0, 0, 0): self.Bind(wxGrid.EVT_GRID_CELL_CHANGED, self.__on_cell_change) box = wx.BoxSizer(wx.VERTICAL) box.Add(self.grid, 0, wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=10) self.SetSizer(box)
def __init__(self, mode, lang, *args, **kwargs): super(DischargeMeasurementsPanel, self).__init__(*args, **kwargs) self.startTimeLbl = "Start Time" self.endTimeLbl = "End Time" self.airTempLbl = u"Air Temp. \n(\N{DEGREE SIGN}C)" self.waterTempLbl = u"Water Temp. \n(\N{DEGREE SIGN}C)" self.widthLbl = "Width\n(m)" self.areaLbl = u"Area\n(m\N{SUPERSCRIPT TWO})" self.meanVelLbl = "Mean Velocity (m/s)" self.mghLbl = "M.G.H. (m)" self.dischLbl = u"Discharge (m\N{SUPERSCRIPT THREE}/s)" self.uncertaintyLbl = u"Uncertainty (%)" self.mmtLbl = "Mmt Mean Time" self.shiftLbl = "Calc. Shift Base Curve (m)" self.diffLbl = "Difference Base Curve (%)" self.curveLbl = "Curve #" self.mghChoices = ["", " (HG)", " (HG2)", " (WLR1)", " (WLR2)"] # self.dischChoices = ["","E","B"] self.curveList = [""] self.controlConditionRemLbl = "Control Condition Remarks" self.dischRemarkLbl = "Discharge Activity Remarks" # self.correctMGHBtnHint = "Attention! \n\nYou must enter your SRC in the stage summary table below if:\n\n\ # 1. SRC is not 0.000\n\ # 2. You are uploading logger information\n\n\ # This field is not directly uploaded to AQUARIUS. To ensure the correct gauge correction is uploaded, Weighted M.G.H, SRC \ # and Gauge Correction must be entered in the EHSN stage summary table below." self.correctMGHBtnHint = "This field is not directly uploaded to AQUARIUS. To ensure the correct gauge correction is uploaded, the Weighted M.G.H, SRC \ and Gauge Correction must be entered in the EHSN stage summary table below." self.uncertaintyInfoMsg = """ All uncertainty values reported here are 2-sigma value - FlowTracker (2 x Uncertainty Value reported in *.dis File) - FlowTracker2 (2 x Uncertainty Value reported in *.ft File) - SxS Pro (1 x Uncertainty Value reported in *.xml File) - RSSL(2 x Uncertainty Value reported in *.dis File) - QRev (1 x Uncertainty Value reported in *.xml File) - eHSN Mid-section (IVE Value) """ self.timeFormat = "%H:%M" if lang == wx.LANGUAGE_ENGLISH: self.timeFormat = "%I:%M" self.mmtDfltValLbl = wx.DateTime.Now().Format(self.timeFormat) self.mode = mode self.manager = None self.controlLbl = "Control Condition" self.contCondLbl = "Condition" self.contCondList = [ "", "Unspecified", "No Flow", "Clear", "Altered", "Debris", "Vegetation", "Fill", "Scour", "Ice" ] # self.picturedLbl = "Site and/or control pictures were taken." #height for panels self.height = 40 f = self.GetFont() dc = wx.WindowDC(self) dc.SetFont(f) self.width, self.height = dc.GetTextExtent("Ag") self.height *= 2.2 self.ctrlHeight = self.height - 6 self.BGColour = (210, 210, 210) self.wrapLength = 80 self.lang = lang self.InitUI()