def __init__(self, aParent, aResource): self._bitmap = graphic.Bitmap(aResource.file, aResource.size) self._file = aResource.file self._size = tuple(aResource.size) w = aResource.size[0] if w == -2: w = self._bitmap.getWidth() h = aResource.size[1] if h == -2: h = self._bitmap.getHeight() size = (w, h) #size = wx.Size( self._bitmap.GetWidth(), self._bitmap.GetHeight() ) ##if aResource.border == 'transparent': ## mask = wx.MaskColour(self._bitmap, wxBLACK) ## self._bitmap.SetMask(mask) StaticBitmap.__init__(self, aParent, widget.makeNewId(aResource.id), self._bitmap.getBits(), aResource.position, size, style=wx.NO_FULL_REPAINT_ON_RESIZE | wx.CLIP_SIBLINGS, name=aResource.name) widget.Widget.__init__(self, aParent, aResource) wx.EVT_WINDOW_DESTROY(self, self._OnDestroy) self._bindEvents(event.WIDGET_EVENTS)
def __init__(self, parent, pos, getPicFn, clickFn): self.getPic = getPicFn self.click = clickFn StaticBitmap.__init__(self, parent, -1, self.getPic(), pos) self.tickSnap = wx.Timer(self, -1) self.frames = 10 self.currentSleep = 1000. / self.frames self.Bind(wx.EVT_TIMER, self.OnTimer, self.tickSnap) self.Bind(wx.EVT_LEFT_UP, self.OnClick) self.tickSnap.Start(self.currentSleep, False)
class wxgTagImageEAPnl(wx.ScrolledWindow): def __init__(self, *args, **kwds): # begin wxGlade: wxgTagImageEAPnl.__init__ kwds["style"] = kwds.get("style", 0) | wx.BORDER_NONE | wx.TAB_TRAVERSAL wx.ScrolledWindow.__init__(self, *args, **kwds) self._TCTRL_description = wx.TextCtrl(self, wx.ID_ANY, "") self._TCTRL_filename = wx.TextCtrl(self, wx.ID_ANY, "") from wx.lib.statbmp import GenStaticBitmap self._BMP_image = GenStaticBitmap(self, wx.ID_ANY, wx.Bitmap(100, 100), style=wx.BORDER_SIMPLE) self._BTN_pick_image = wx.Button(self, wx.ID_ANY, _("&Pick"), style=wx.BU_EXACTFIT) self.__set_properties() self.__do_layout() self.Bind(wx.EVT_BUTTON, self._on_pick_image_button_pressed, self._BTN_pick_image) # end wxGlade def __set_properties(self): # begin wxGlade: wxgTagImageEAPnl.__set_properties self.SetScrollRate(10, 10) self._TCTRL_description.SetToolTip(_("A name for the tag.\n\nNote that there cannot be two tags with the same name.")) self._TCTRL_filename.SetToolTip(_("An example file name for this image. Mainly used for deriving a suitable file extension.")) self._BMP_image.SetMinSize((100, 100)) self._BMP_image.SetToolTip(_("The image to use for the tag.\n\nDo not use a big image because the tag will be downscaled anyway.")) self._BTN_pick_image.SetToolTip(_("Pick the file from which to load the tag image.")) # end wxGlade def __do_layout(self): # begin wxGlade: wxgTagImageEAPnl.__do_layout _gszr_main = wx.FlexGridSizer(3, 2, 1, 3) __szr_image = wx.BoxSizer(wx.HORIZONTAL) __lbl_name = wx.StaticText(self, wx.ID_ANY, _("Tag name")) __lbl_name.SetForegroundColour(wx.Colour(255, 0, 0)) _gszr_main.Add(__lbl_name, 0, wx.ALIGN_CENTER_VERTICAL, 0) _gszr_main.Add(self._TCTRL_description, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 0) __lbl_fname = wx.StaticText(self, wx.ID_ANY, _("File name")) _gszr_main.Add(__lbl_fname, 0, wx.ALIGN_CENTER_VERTICAL, 0) _gszr_main.Add(self._TCTRL_filename, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, 0) __lbl_image = wx.StaticText(self, wx.ID_ANY, _("Image")) __lbl_image.SetForegroundColour(wx.Colour(255, 0, 0)) _gszr_main.Add(__lbl_image, 0, wx.ALIGN_CENTER_VERTICAL, 0) __szr_image.Add(self._BMP_image, 0, wx.ALIGN_CENTER | wx.ALL, 3) __szr_image.Add(self._BTN_pick_image, 0, wx.ALIGN_CENTER_VERTICAL, 0) _gszr_main.Add(__szr_image, 1, wx.EXPAND, 0) self.SetSizer(_gszr_main) _gszr_main.Fit(self) _gszr_main.AddGrowableCol(1) self.Layout() # end wxGlade def _on_pick_image_button_pressed(self, event): # wxGlade: wxgTagImageEAPnl.<event_handler> print("Event handler '_on_pick_image_button_pressed' not implemented!") event.Skip()
def __init__(self, *args, **kwds): # begin wxGlade: wxgTagImageEAPnl.__init__ kwds["style"] = kwds.get("style", 0) | wx.BORDER_NONE | wx.TAB_TRAVERSAL wx.ScrolledWindow.__init__(self, *args, **kwds) self._TCTRL_description = wx.TextCtrl(self, wx.ID_ANY, "") self._TCTRL_filename = wx.TextCtrl(self, wx.ID_ANY, "") from wx.lib.statbmp import GenStaticBitmap self._BMP_image = GenStaticBitmap(self, wx.ID_ANY, wx.Bitmap(100, 100), style=wx.BORDER_SIMPLE) self._BTN_pick_image = wx.Button(self, wx.ID_ANY, _("&Pick"), style=wx.BU_EXACTFIT) self.__set_properties() self.__do_layout() self.Bind(wx.EVT_BUTTON, self._on_pick_image_button_pressed, self._BTN_pick_image)
def addDragDropItem(self, newid, icon, dragCallback, toolTip): """ Add an item to the toolbar """ bmp = wx.Image(os.path.join(self.iconpath, icon), wx.BITMAP_TYPE_ANY).ConvertToBitmap() bmp2 = wx.EmptyBitmap(38, 32) dc = wx.MemoryDC() dc.SelectObject(bmp2) #dc.SetPen(wx.Pen(self.GetBackgroundColour(),1)) #dc.SetBrush(wx.Brush(self.GetBackgroundColour())) dc.SetPen(wx.Pen(wx.Colour(0, 0, 0), 1)) dc.SetBrush(wx.Brush(wx.Colour(0, 0, 0))) dc.DrawRectangle(0, 0, 38, 32) x = 1 y = 0 dc.DrawBitmap(bmp, 7, 0) for i in range(0, 10): dc.SetPen(wx.Pen(wx.Colour(135, 135, 135), 1)) dc.DrawLine(x, y, x + 6, y) y += 1 dc.SetPen(wx.Pen(wx.Colour(100, 100, 100), 1)) dc.DrawLine(x, y, x + 6, y) y += 1 y += 2 dc.SelectObject(wx.NullBitmap) self.icons[newid] = bmp2 sbmp = StaticBitmap(self, newid, bmp, style=wx.RAISED_BORDER, size=(40, 40)) self.sbmps[newid] = sbmp sbmp.Bind(wx.EVT_MOTION, dragCallback) #p.Bind(wx.EVT_MOTION,dragCallback) #self.sizer.Add(p,flag=wx.RIGHT,border=2) #p.Bind( wx.EVT_LEFT_UP,self.onToolClick) self.sizer.Add(sbmp, flag=wx.RIGHT, border=2) sbmp.Bind(wx.EVT_LEFT_UP, self.onToolClick) sbmp.SetHelpText(toolTip.GetTip()) sbmp.SetToolTip(toolTip)
def SetPopupBitmap(self, bitmap): """ Sets The ToasterBox Background Image. Use It Only For ToasterBoxes Created With TB_SIMPLE Style. """ bitmap = bitmap.ConvertToImage() xsize, ysize = self.GetSize() bitmap = bitmap.Scale(xsize, ysize) bitmap = bitmap.ConvertToBitmap() self._staticbitmap = StaticBitmap(self, -1, bitmap, pos=(0, 0)) if self._closingstyle & TB_ONCLICK and self._windowstyle != TB_CAPTION: self._staticbitmap.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
def __init__(self, *args, **kwds): if 'stateValues' in kwds: self.stateValues = kwds['stateValues'] del kwds['stateValues'] else: self.stateValues = [] if 'tooltips' in kwds: self.tooltips = kwds['tooltips'] del kwds['tooltips'] else: self.tooltips = [] if 'state' in kwds: self.currState = kwds['state'] del kwds['state'] else: self.currState = -1 GenStaticBitmap.__init__(self, *args, bitmap=wx.NullBitmap, **kwds) self.SetState(self.currState) self.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseIn, self) self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseOut, self) self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp, self) self.Bind(wx.EVT_RIGHT_UP, self.OnRightUp, self)
def SetPopupBitmap(self, bitmap): """ Sets the L{ToasterBox} background image. :param `bitmap`: a valid `wx.Bitmap` object. If defaulted to ``None``, then no background bitmap is used. :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style. """ bitmap = bitmap.ConvertToImage() xsize, ysize = self.GetSize() bitmap = bitmap.Scale(xsize, ysize) bitmap = bitmap.ConvertToBitmap() self._staticbitmap = StaticBitmap(self, -1, bitmap, pos=(0, 0)) if self._closingstyle & TB_ONCLICK and self._windowstyle != TB_CAPTION: self._staticbitmap.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
def __init__(self, parent): num_icon, icons, handler = self._get_params() self.mem = 0 self.icon = [] self.nproc = 0 super(StatusBar, self).__init__(parent, -1) # This status bar has three fields self.SetFieldsCount(num_icon + 2) # Sets the three fields to be relative widths to each other. self.SetStatusWidths([-1] + [20] * num_icon + [140]) # Field 0 ... just text self.SetStatusText("welcome...", 0) # This will fall into field 1 (the second field) self.icon = [None] * num_icon from ifigure.ifigure_config import icondir for i in range(num_icon): path = os.path.join(icondir, '16x16', icons[i]) self.icon[i] = GenStaticBitmap(self, wx.ID_ANY, bitmap=wx.Bitmap(path)) self.icon[i].Bind(wx.EVT_LEFT_DOWN, handler[i]) # hint does not work for staticbitmap?? # self.icon[i].SetToolTip(wx.ToolTip(icons[i][:-4])) # set the initial position of the checkbox self.Reposition() # timer for what...? self.timer = wx.PyTimer(self.notify) self.timer.Start(2000) self.notify()
class ToasterBoxWindow(wx.Frame): def __init__(self, parent, parent2, tbstyle, windowstyle, closingstyle, scrollType=TB_SCR_TYPE_DU): """ Default class constructor. Used internally. Do not call directly this class in your application! """ wx.Frame.__init__(self, parent, wx.ID_ANY, "window", wx.DefaultPosition, wx.DefaultSize, style=windowstyle | wx.CLIP_CHILDREN) self._starttime = wx.DateTime.Now().GetTicks() self._parent2 = parent2 self._parent = parent self._sleeptime = 10 self._step = 4 self._pausetime = 1700 self._textcolour = wx.BLACK self._popuptext = "Change Me!" # the size we want the dialog to be framesize = wx.Size(150, 170) self._count = 1 self._tbstyle = tbstyle self._windowstyle = windowstyle self._closingstyle = closingstyle self._scrollType = scrollType if tbstyle == TB_COMPLEX: self.sizer = wx.BoxSizer(wx.VERTICAL) else: self._staticbitmap = None if self._windowstyle == TB_CAPTION: self.Bind(wx.EVT_CLOSE, self.OnClose) self.SetTitle("") if self._closingstyle & TB_ONCLICK and self._windowstyle != TB_CAPTION: self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown) self._bottomright = wx.Point(wx.GetDisplaySize().GetWidth(), wx.GetDisplaySize().GetHeight()) self.SetDimensions(self._bottomright.x, self._bottomright.y, framesize.GetWidth(), framesize.GetHeight()) def OnClose(self, event): self.NotifyTimer(None) event.Skip() def OnMouseDown(self, event): self.NotifyTimer(None) event.Skip() def SetPopupBitmap(self, bitmap): """ Sets the ToasterBox background image. Use it only for ToasterBoxes created with TB_SIMPLE style. """ bitmap = bitmap.ConvertToImage() xsize, ysize = self.GetSize() bitmap = bitmap.Scale(xsize, ysize) bitmap = bitmap.ConvertToBitmap() self._staticbitmap = StaticBitmap(self, -1, bitmap, pos=(0, 0)) if self._closingstyle & TB_ONCLICK and self._windowstyle != TB_CAPTION: self._staticbitmap.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown) def SetPopupSize(self, size): """ Sets the ToasterBox size. """ self.SetDimensions(self._bottomright.x, self._bottomright.y, size[0], size[1]) def SetPopupPosition(self, pos): """ Sets the ToasterBox position on screen. """ self._bottomright = wx.Point(pos[0] + self.GetSize().GetWidth(), pos[1] + self.GetSize().GetHeight()) self._dialogtop = pos def SetPopupPositionByInt(self, pos): """ Sets the ToasterBox position on screen, at one of the screen corners. """ w, h = wx.GetDisplaySize() self._bottomright = wx.Point(w, h) # top left if pos == 0: popupposition = wx.Point(0, 0) # top right elif pos == 1: popupposition = wx.Point(w - self._popupsize[0], 0) # bottom left elif pos == 2: popupposition = wx.Point(0, h - self._popupsize[1]) # bottom right elif pos == 3: popupposition = wx.Point(self._bottomright.x - self._popupsize[0], self._bottomright.y - self._popupsize[1]) self._bottomright = wx.Point(popupposition.x + self._popupsize[0], popupposition.y + self._popupsize[1]) self._dialogtop = popupposition def SetPopupPauseTime(self, pausetime): """ Sets the time after which the ToasterBox is destroyed (linger). """ self._pausetime = pausetime def SetPopupScrollSpeed(self, speed): """ Sets the ToasterBox scroll speed. The speed parameter is the pause time (in ms) for every step in the ScrollUp() method. """ self._sleeptime = speed def AddPanel(self, panel): """ Adds a panel to the ToasterBox. Use it only for ToasterBoxes created with TB_COMPLEX style. """ if not self._tbstyle & TB_COMPLEX: raise Exception( "\nERROR: Panel Can Not Be Added When Using TB_SIMPLE ToasterBox Style" ) self.sizer.Add(panel, 1, wx.EXPAND) self.sizer.Layout() self.SetSizer(self.sizer) if self._closingstyle & TB_ONCLICK and self._windowstyle != TB_CAPTION: panel.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown) def SetPopupText(self, text): """ Sets the ToasterBox text. Use it only for ToasterBoxes created with TB_SIMPLE style. """ self._popuptext = text def SetPopupTextFont(self, font): """ Sets the ToasterBox text font. Use it only for ToasterBoxes created with TB_SIMPLE style. """ self._textfont = font def GetPopupText(self): """ Returns the ToasterBox text. Use it only for ToasterBoxes created with TB_SIMPLE style. """ return self._popuptext def Play(self): """ Creates the ToasterBoxWindow, that does all the job. """ # do some checks to make sure this window is valid if self._bottomright.x < 1 or self._bottomright.y < 1: return False if self.GetSize().GetWidth() < 50 or self.GetSize().GetWidth() < 50: # toasterbox launches into a endless loop for some reason # when you try to make the window too small. return False self.ScrollUp() timerid = wx.NewId() self.showtime = wx.Timer(self, timerid) self.showtime.Start(self._pausetime) self.Bind(wx.EVT_TIMER, self.NotifyTimer, id=timerid) return True def NotifyTimer(self, event): """ Hides gradually the ToasterBoxWindow. """ self.showtime.Stop() del self.showtime self.ScrollDown() def SetPopupBackgroundColor(self, colour): """ Sets the ToasterBox background colour. Use it only for ToasterBoxes created with TB_SIMPLE style. """ self.SetBackgroundColour(colour) def SetPopupTextColor(self, colour): """ Sets the ToasterBox foreground colour. Use it only for ToasterBoxes created with TB_SIMPLE style. """ self._textcolour = colour def ScrollUp(self): """ Scrolls the ToasterBox up, which means gradually showing the ToasterBox. """ self.Show(True) # walk the Y value up in a raise motion xpos = self.GetPosition().x ypos = self._bottomright[1] windowsize = 0 # checking the type of the scroll (from up to down or from down to up) if self._scrollType == TB_SCR_TYPE_UD: start = self._dialogtop[1] stop = ypos step = self._step elif self._scrollType == TB_SCR_TYPE_DU: start = ypos stop = self._dialogtop[1] step = -self._step else: errMsg = ( "scrollType not supported (in ToasterBoxWindow.ScrollUp): %s" % self._scrollType) raise ValueError(errMsg) for i in xrange(start, stop, step): if i < self._dialogtop[1]: i = self._dialogtop[1] windowsize = windowsize + self._step # checking the type of the scroll (from up to down or from down to up) if self._scrollType == TB_SCR_TYPE_UD: dimY = self._dialogtop[1] elif self._scrollType == TB_SCR_TYPE_DU: dimY = i else: errMsg = ( "scrollType not supported (in ToasterBoxWindow.ScrollUp): %s" % self._scrollType) raise ValueError(errMsg) self.SetDimensions(self._dialogtop[0], dimY, self.GetSize().GetWidth(), windowsize) if self._tbstyle == TB_SIMPLE: self.DrawText() wx.MilliSleep(self._sleeptime) self.Update() self.Refresh() self.Update() if self._tbstyle == TB_SIMPLE: self.DrawText() self.SetFocus() def ScrollDown(self): """ Scrolls the ToasterBox down, which means gradually hiding the ToasterBox. """ # walk down the Y value windowsize = self.GetSize().GetHeight() # checking the type of the scroll (from up to down or from down to up) if self._scrollType == TB_SCR_TYPE_UD: start = self._bottomright.y stop = self._dialogtop[1] step = -self._step elif self._scrollType == TB_SCR_TYPE_DU: start = self._dialogtop[1] stop = self._bottomright.y step = self._step else: errMsg = ( "scrollType not supported (in ToasterBoxWindow.ScrollUp): %s" % self._scrollType) raise ValueError(errMsg) for i in xrange(start, stop, step): if i > self._bottomright.y: i = self._bottomright.y windowsize = windowsize - self._step if windowsize <= 0: break # checking the type of the scroll (from up to down or from down to up) if self._scrollType == TB_SCR_TYPE_UD: dimY = self._dialogtop[1] elif self._scrollType == TB_SCR_TYPE_DU: dimY = i else: errMsg = ( "scrollType not supported (in ToasterBoxWindow.ScrollUp): %s" % self._scrollType) raise ValueError(errMsg) self.SetDimensions(self._dialogtop[0], dimY, self.GetSize().GetWidth(), windowsize) wx.MilliSleep(self._sleeptime) self.Refresh() self.Hide() if self._parent2: self._parent2.Notify() def DrawText(self): if self._staticbitmap is not None: dc = wx.ClientDC(self._staticbitmap) else: dc = wx.ClientDC(self) dc.SetFont(self._textfont) if not hasattr(self, "text_coords"): self._getTextCoords(dc) fg = dc.GetTextForeground() dc.SetTextForeground(self._textcolour) dc.DrawTextList(*self.text_coords) dc.SetTextForeground(fg) def _getTextCoords(self, dc): """ Draw the user specified text using the wx.DC. Use it only for ToasterBoxes created with TB_SIMPLE style. """ # border from sides and top to text (in pixels) border = 7 # how much space between text lines textPadding = 2 pText = self.GetPopupText() max_len = len(pText) tw, th = self._parent2._popupsize if self._windowstyle == TB_CAPTION: th = th - 20 while 1: lines = textwrap.wrap(pText, max_len) for line in lines: w, h = dc.GetTextExtent(line) if w > tw - border * 2: max_len -= 1 break else: break fh = 0 for line in lines: w, h = dc.GetTextExtent(line) fh += h + textPadding y = (th - fh) / 2 coords = [] for line in lines: w, h = dc.GetTextExtent(line) x = (tw - w) / 2 coords.append((x, y)) y += h + textPadding self.text_coords = (lines, coords)
def __init__(self, *args, **kwargs): if "pngs" in kwargs: self.pngs = kwargs["pngs"] del kwargs["pngs"] if "codes" in kwargs: self.codes = kwargs["codes"] del kwargs["codes"] if "imflag" in kwargs: self.imflag = kwargs["imflag"] del kwargs["imflag"] else: self.imflag = 0 super(TwitterWindow, self).__init__(*args, **kwargs) self.previewsize = 400 self.SetSize((420, 550)) self.SetTitle( "Twitter Extension - Bringing Mass Spectrometry to the Masses") self.APP_KEY = "tQoLvTjNPbeqZGl95ea8rqfvO" self.APP_SECRET = "6knaUv912Db37ZWMMSODuxZvmhjNOcxpHRV6YAyVNSvSfQHVz5" if self.imflag == 0: choices = [ "None", "Data and Fit", "Zero-Charge Mass", "m/z Grid", "Individual Peaks", "Mass Grid", "Bar Chart" ] else: choices = [p[1] for p in self.pngs] choices = ["None"] + choices self.pnl = wx.Panel(self) self.vbox = wx.BoxSizer(wx.VERTICAL) self.sb = wx.StaticBox(self.pnl, label='Tweet a spectrum!') self.sbs = wx.StaticBoxSizer(self.sb, orient=wx.VERTICAL) self.hbox1 = wx.BoxSizer(wx.HORIZONTAL) self.loginbutton = wx.Button(self.pnl, label="Twitter Log In") self.hbox1.Add(wx.StaticText(self.pnl, label=''), 0, wx.ALIGN_CENTER_VERTICAL) self.hbox1.Add(self.loginbutton, flag=wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border=5) self.hbox1.Add(wx.StaticText(self.pnl, label=' User: '******'Tweet: '), 0, wx.ALIGN_CENTER_VERTICAL) self.hbox2.Add(self.inputbox2, flag=wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border=5) self.countbox = wx.TextCtrl(self.pnl, value="7", style=wx.TE_READONLY | wx.TE_RIGHT, size=(30, 25)) self.hbox2.Add(wx.StaticText(self.pnl, label=' '), 0, wx.ALIGN_CENTER_VERTICAL) self.hbox2.Add(self.countbox, 0, wx.ALIGN_CENTER_VERTICAL) self.hbox2.Add(wx.StaticText(self.pnl, label=' Characters'), 0, wx.ALIGN_CENTER_VERTICAL) self.sbs.Add(self.hbox2, 0, wx.ALIGN_CENTER_HORIZONTAL) self.sbs.AddSpacer(10) self.hbox3 = wx.BoxSizer(wx.HORIZONTAL) self.hbox3.Add(wx.StaticText(self.pnl, label='Image: '), 0, wx.ALIGN_CENTER_VERTICAL) self.imagechoice = wx.Choice(self.pnl, -1, (115, 50), choices=choices) self.imagechoice.SetSelection(0) self.previewbutton = wx.Button(self.pnl, label="Preview") self.hbox3.Add(self.imagechoice, 0, wx.ALIGN_CENTER_VERTICAL) self.hbox3.Add(self.previewbutton, 0, wx.ALIGN_CENTER_VERTICAL) self.sbs.Add(self.hbox3, 0, wx.ALIGN_CENTER_HORIZONTAL) self.hbox4 = wx.BoxSizer(wx.HORIZONTAL) self.emptyimg = wx.EmptyImage(self.previewsize, self.previewsize) self.emptyimg.Replace(0, 0, 0, 255, 255, 255) self.imageCtrl = StaticBitmap(self.pnl, wx.ID_ANY, wx.Bitmap(self.emptyimg)) self.hbox4.Add(self.imageCtrl, 0) self.sbs.Add(self.hbox4, 1, wx.ALIGN_CENTER_HORIZONTAL) self.hbox5 = wx.BoxSizer(wx.HORIZONTAL) self.hbox5.Add(wx.StaticText(self.pnl, label=''), 0, wx.ALIGN_CENTER_VERTICAL) self.tweetbutton = wx.Button(self.pnl, label="Tweet it!") self.hbox5.Add(self.tweetbutton, 0, wx.ALIGN_CENTER_VERTICAL) self.sbs.Add(self.hbox5, 0, wx.ALIGN_CENTER_HORIZONTAL) self.pnl.SetSizer(self.sbs) self.pnl.SetBackgroundColour("WHITE") self.vbox.Add(self.pnl, proportion=1, flag=wx.ALL | wx.EXPAND, border=5) ''' hboxend = wx.BoxSizer(wx.HORIZONTAL) okButton = wx.Button(self, label='Ok') closeButton = wx.Button(self, label='Cancel') hboxend.Add(okButton) hboxend.Add(closeButton, flag=wx.LEFT, border=5) okButton.Bind(wx.EVT_BUTTON, self.on_close) closeButton.Bind(wx.EVT_BUTTON, self.on_close_cancel) self.vbox.Add(hboxend, flag=wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, border=10) ''' self.SetSizer(self.vbox) self.loginbutton.Bind(wx.EVT_BUTTON, self.OnLaunchWeb) self.inputbox2.Bind(wx.EVT_TEXT, self.OnCharacterCount) self.previewbutton.Bind(wx.EVT_BUTTON, self.OnPreview) self.tweetbutton.Bind(wx.EVT_BUTTON, self.Tweet) self.Center() if self.codes is not None: self.LoadScreenName()
class TwitterWindow(wx.Dialog): def __init__(self, *args, **kwargs): if "pngs" in kwargs: self.pngs = kwargs["pngs"] del kwargs["pngs"] if "codes" in kwargs: self.codes = kwargs["codes"] del kwargs["codes"] if "imflag" in kwargs: self.imflag = kwargs["imflag"] del kwargs["imflag"] else: self.imflag = 0 super(TwitterWindow, self).__init__(*args, **kwargs) self.previewsize = 400 self.SetSize((420, 550)) self.SetTitle( "Twitter Extension - Bringing Mass Spectrometry to the Masses") self.APP_KEY = "tQoLvTjNPbeqZGl95ea8rqfvO" self.APP_SECRET = "6knaUv912Db37ZWMMSODuxZvmhjNOcxpHRV6YAyVNSvSfQHVz5" if self.imflag == 0: choices = [ "None", "Data and Fit", "Zero-Charge Mass", "m/z Grid", "Individual Peaks", "Mass Grid", "Bar Chart" ] else: choices = [p[1] for p in self.pngs] choices = ["None"] + choices self.pnl = wx.Panel(self) self.vbox = wx.BoxSizer(wx.VERTICAL) self.sb = wx.StaticBox(self.pnl, label='Tweet a spectrum!') self.sbs = wx.StaticBoxSizer(self.sb, orient=wx.VERTICAL) self.hbox1 = wx.BoxSizer(wx.HORIZONTAL) self.loginbutton = wx.Button(self.pnl, label="Twitter Log In") self.hbox1.Add(wx.StaticText(self.pnl, label=''), 0, wx.ALIGN_CENTER_VERTICAL) self.hbox1.Add(self.loginbutton, flag=wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border=5) self.hbox1.Add(wx.StaticText(self.pnl, label=' User: '******'Tweet: '), 0, wx.ALIGN_CENTER_VERTICAL) self.hbox2.Add(self.inputbox2, flag=wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border=5) self.countbox = wx.TextCtrl(self.pnl, value="7", style=wx.TE_READONLY | wx.TE_RIGHT, size=(30, 25)) self.hbox2.Add(wx.StaticText(self.pnl, label=' '), 0, wx.ALIGN_CENTER_VERTICAL) self.hbox2.Add(self.countbox, 0, wx.ALIGN_CENTER_VERTICAL) self.hbox2.Add(wx.StaticText(self.pnl, label=' Characters'), 0, wx.ALIGN_CENTER_VERTICAL) self.sbs.Add(self.hbox2, 0, wx.ALIGN_CENTER_HORIZONTAL) self.sbs.AddSpacer(10) self.hbox3 = wx.BoxSizer(wx.HORIZONTAL) self.hbox3.Add(wx.StaticText(self.pnl, label='Image: '), 0, wx.ALIGN_CENTER_VERTICAL) self.imagechoice = wx.Choice(self.pnl, -1, (115, 50), choices=choices) self.imagechoice.SetSelection(0) self.previewbutton = wx.Button(self.pnl, label="Preview") self.hbox3.Add(self.imagechoice, 0, wx.ALIGN_CENTER_VERTICAL) self.hbox3.Add(self.previewbutton, 0, wx.ALIGN_CENTER_VERTICAL) self.sbs.Add(self.hbox3, 0, wx.ALIGN_CENTER_HORIZONTAL) self.hbox4 = wx.BoxSizer(wx.HORIZONTAL) self.emptyimg = wx.EmptyImage(self.previewsize, self.previewsize) self.emptyimg.Replace(0, 0, 0, 255, 255, 255) self.imageCtrl = StaticBitmap(self.pnl, wx.ID_ANY, wx.Bitmap(self.emptyimg)) self.hbox4.Add(self.imageCtrl, 0) self.sbs.Add(self.hbox4, 1, wx.ALIGN_CENTER_HORIZONTAL) self.hbox5 = wx.BoxSizer(wx.HORIZONTAL) self.hbox5.Add(wx.StaticText(self.pnl, label=''), 0, wx.ALIGN_CENTER_VERTICAL) self.tweetbutton = wx.Button(self.pnl, label="Tweet it!") self.hbox5.Add(self.tweetbutton, 0, wx.ALIGN_CENTER_VERTICAL) self.sbs.Add(self.hbox5, 0, wx.ALIGN_CENTER_HORIZONTAL) self.pnl.SetSizer(self.sbs) self.pnl.SetBackgroundColour("WHITE") self.vbox.Add(self.pnl, proportion=1, flag=wx.ALL | wx.EXPAND, border=5) ''' hboxend = wx.BoxSizer(wx.HORIZONTAL) okButton = wx.Button(self, label='Ok') closeButton = wx.Button(self, label='Cancel') hboxend.Add(okButton) hboxend.Add(closeButton, flag=wx.LEFT, border=5) okButton.Bind(wx.EVT_BUTTON, self.on_close) closeButton.Bind(wx.EVT_BUTTON, self.on_close_cancel) self.vbox.Add(hboxend, flag=wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, border=10) ''' self.SetSizer(self.vbox) self.loginbutton.Bind(wx.EVT_BUTTON, self.OnLaunchWeb) self.inputbox2.Bind(wx.EVT_TEXT, self.OnCharacterCount) self.previewbutton.Bind(wx.EVT_BUTTON, self.OnPreview) self.tweetbutton.Bind(wx.EVT_BUTTON, self.Tweet) self.Center() if self.codes is not None: self.LoadScreenName() def LoadScreenName(self): self.OAUTH_TOKEN = self.codes[0] self.OAUTH_TOKEN_SECRET = self.codes[1] twitter = Twython(self.APP_KEY, self.APP_SECRET, self.OAUTH_TOKEN, self.OAUTH_TOKEN_SECRET) self.screen_name = twitter.verify_credentials()["screen_name"] print("Logged in successfully as: ", self.screen_name) self.userbox.SetValue("@" + self.screen_name) def OnClose(self, e): self.Destroy() self.EndModal(0) def OnCloseCancel(self, e): self.Destroy() self.EndModal(1) def OnPreview(self, e): choice = self.imagechoice.GetSelection() print(choice) self.imageFile = None self.imageCtrl.SetBitmap(wx.Bitmap(self.emptyimg)) if choice is not 0: for i in self.pngs: if i[0] == choice: self.imageFile = i[1] print(self.imageFile) if self.imageFile is not None: image = wx.Image(self.imageFile, wx.BITMAP_TYPE_ANY) W = image.GetWidth() H = image.GetHeight() if W > H: NewW = self.previewsize NewH = self.previewsize * H / W else: NewH = self.previewsize NewW = self.previewsize * W / H image = image.Scale(NewW, NewH) btm = wx.Bitmap(image) self.imageCtrl.SetBitmap(btm) pass def OnCharacterCount(self, e): string = self.inputbox2.GetValue() count = len(string) self.countbox.SetValue(str(count)) def OnLaunchWeb(self, e): twitter = Twython(self.APP_KEY, self.APP_SECRET) auth = twitter.get_authentication_tokens() self.OAUTH_TOKEN = auth['oauth_token'] self.OAUTH_TOKEN_SECRET = auth['oauth_token_secret'] self.url = auth["auth_url"] webbrowser.open(self.url, new=2) self.pinwindow = PinWindow(self) self.pinwindow.ShowModal() self.pin = self.pinwindow.pin if self.pin is not None: oauth_verifier = self.pin twitter = Twython(self.APP_KEY, self.APP_SECRET, self.OAUTH_TOKEN, self.OAUTH_TOKEN_SECRET) final_step = twitter.get_authorized_tokens(oauth_verifier) self.OAUTH_TOKEN = final_step['oauth_token'] self.OAUTH_TOKEN_SECRET = final_step['oauth_token_secret'] self.codes = [self.OAUTH_TOKEN, self.OAUTH_TOKEN_SECRET] self.LoadScreenName() else: print("No pin provided") def Tweet(self, e): if self.codes is not None: self.OAUTH_TOKEN = self.codes[0] self.OAUTH_TOKEN_SECRET = self.codes[1] twitter = Twython(self.APP_KEY, self.APP_SECRET, self.OAUTH_TOKEN, self.OAUTH_TOKEN_SECRET) tweet = self.inputbox2.GetValue() print("Tweeting: ", tweet) choice = self.imagechoice.GetSelection() self.imageFile = None if choice is not 0: self.OnPreview(e) # self.imageFile=os.path.join(os.getcwd(),self.imageFile) print("\twith image: ", self.imageFile) photo = open(self.imageFile, "rb") # result=twitter.upload_media(media=photo) # id=result['media_id'] # twitter.update_status(status=tweet,media_ids=id) twitter.update_status_with_media(status=tweet, media=photo) else: twitter.update_status(status=tweet) pass else: print("Need to log in to Twitter") self.OnClose(e)
class ToasterBoxWindow(wx.Frame): """ This class does all the job, by handling background images, text properties and panel adding. Depending on the style you choose, L{ToasterBoxWindow} will behave differently in order to handle widgets inside it. """ def __init__(self, parent, parent2, tbstyle, windowstyle, closingstyle, scrollType=TB_SCR_TYPE_DU): """ Default class constructor. Used internally. Do not call directly this class in your application! :param `parent`: the window parent; :param `parent2`: the L{ToasterBox} calling this window; :param `tbstyle`: the L{ToasterBoxWindow} main style. Can be one of the following bits: ====================== ======= ================================ `ToasterBox` Style Value Description ====================== ======= ================================ ``TB_SIMPLE`` 0x1 A simple `ToasterBox`, with background image and text customization can be created ``TB_COMPLEX`` 0x2 `ToasterBoxes` with different degree of complexity can be created. You can add as many controls as you want, provided that you call the L{AddPanel} method and pass to it a dummy frame and a `wx.Panel`. ====================== ======= ================================ :param `windowstyle`: this parameter influences the visual appearance of L{ToasterBoxWindow}, and can be one of the following styles: ====================== ========== ================================ Window Style Hex Value Description ====================== ========== ================================ ``TB_DEFAULT_STYLE`` 0x2008002 Default window style for `ToasterBox`, with no caption nor close box. ``TB_CAPTION`` 0x22009806 `ToasterBox` will have a caption, with the possibility to set a title for the `ToasterBox` frame, and a close box. ====================== ========== ================================ :param `closingstyle`: the closing style for L{ToasterBoxWindow}. Can be one of the following bits: ==================== =========== ================================================== Closing Styles Hex Value Description ==================== =========== ================================================== ``TB_ONTIME`` 0x1 `ToasterBox` will close after a specified amount of time. ``TB_ONCLICK`` 0x2 `ToasterBox` can be closed by clicking anywhere on the `ToasterBox` frame. ==================== =========== ================================================== :param `scrollType`: the scrolling direction for L{ToasterBoxWindow}. Can be one of the following bits: ==================== =========== ================================================== Scroll Styles Hex Value Description ==================== =========== ================================================== ``TB_SCR_TYPE_UD`` 0x1 `ToasterBox` will scroll from up to down ``TB_SCR_TYPE_DU`` 0x2 `ToasterBox` will scroll from down to up ==================== =========== ================================================== """ wx.Frame.__init__(self, parent, wx.ID_ANY, "window", wx.DefaultPosition, wx.DefaultSize, style=windowstyle | wx.CLIP_CHILDREN) self._starttime = wx.GetLocalTime() self._parent2 = parent2 self._parent = parent self._sleeptime = 10 self._step = 4 self._pausetime = 1700 self._textcolour = wx.BLACK self._popuptext = "Change Me!" # the size we want the dialog to be framesize = wx.Size(150, 170) self._count = 1 self._tbstyle = tbstyle self._windowstyle = windowstyle self._closingstyle = closingstyle self._scrollType = scrollType if tbstyle == TB_COMPLEX: self.sizer = wx.BoxSizer(wx.VERTICAL) else: self._staticbitmap = None if self._windowstyle == TB_CAPTION: self.Bind(wx.EVT_CLOSE, self.OnClose) self.SetTitle("") if self._closingstyle & TB_ONCLICK and self._windowstyle != TB_CAPTION: self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown) self._bottomright = wx.Point(wx.GetDisplaySize().GetWidth(), wx.GetDisplaySize().GetHeight()) self.SetDimensions(self._bottomright.x, self._bottomright.y, framesize.GetWidth(), framesize.GetHeight()) def OnClose(self, event): """ Handles the ``wx.EVT_CLOSE`` event for L{ToasterBoxWindow}. :param `event`: a `wx.CloseEvent` event to be processed. """ self.NotifyTimer(None) event.Skip() def OnMouseDown(self, event): """ Handles the ``wx.EVT_LEFT_DOWN`` event for L{ToasterBoxWindow}. :param `event`: a `wx.MouseEvent` event to be processed. """ self.NotifyTimer(None) event.Skip() def SetPopupBitmap(self, bitmap): """ Sets the L{ToasterBox} background image. :param `bitmap`: a valid `wx.Bitmap` object. If defaulted to ``None``, then no background bitmap is used. :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style. """ bitmap = bitmap.ConvertToImage() xsize, ysize = self.GetSize() bitmap = bitmap.Scale(xsize, ysize) bitmap = bitmap.ConvertToBitmap() self._staticbitmap = StaticBitmap(self, -1, bitmap, pos=(0, 0)) if self._closingstyle & TB_ONCLICK and self._windowstyle != TB_CAPTION: self._staticbitmap.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown) def SetPopupSize(self, size): """ Sets the L{ToasterBox} size. :param `size`: the new control size, an instance of `wx.Size`. """ self.SetDimensions(self._bottomright.x, self._bottomright.y, size[0], size[1]) def SetPopupPosition(self, pos): """ Sets the L{ToasterBox} position on screen. :param `pos`: the widget position, an instance of `wx.Point`. """ self._bottomright = wx.Point(pos[0] + self.GetSize().GetWidth(), pos[1] + self.GetSize().GetHeight()) self._dialogtop = pos def SetPopupPositionByInt(self, pos): """ Sets the L{ToasterBox} position on screen, at one of the screen corners. :param `pos`: an integer specifying the screen corner, namely: ============= ======================================== Corner Number Position ============= ======================================== 0 Top left screen corner 1 Top right screen corner 2 Bottom left screen corner 3 Bottom right screen corner ============= ======================================== """ w, h = wx.GetDisplaySize() self._bottomright = wx.Point(w, h) # top left if pos == 0: popupposition = wx.Point(0, 0) # top right elif pos == 1: popupposition = wx.Point(w - self._popupsize[0], 0) # bottom left elif pos == 2: popupposition = wx.Point(0, h - self._popupsize[1]) # bottom right elif pos == 3: popupposition = wx.Point(self._bottomright.x - self._popupsize[0], self._bottomright.y - self._popupsize[1]) self._bottomright = wx.Point(popupposition.x + self._popupsize[0], popupposition.y + self._popupsize[1]) self._dialogtop = popupposition def SetPopupPauseTime(self, pausetime): """ Sets the time after which the L{ToasterBox} is destroyed (linger). :param `pausetime`: the delay after which the control is destroyed, in seconds. """ self._pausetime = pausetime def SetPopupScrollSpeed(self, speed): """ Sets the L{ToasterBox} scroll speed. :param `speed`: it is the pause time (in milliseconds) for every step in the L{ScrollUp} method. """ self._sleeptime = speed def AddPanel(self, panel): """ Adds a panel to the L{ToasterBox}. :param `panel`: an instance of `wx.Window`. :note: Use this method only for a L{ToasterBox} created with the ``TB_COMPLEX`` style. """ if not self._tbstyle & TB_COMPLEX: raise Exception( "\nERROR: Panel Can Not Be Added When Using TB_SIMPLE ToasterBox Style" ) self.sizer.Add(panel, 1, wx.EXPAND) self.sizer.Layout() self.SetSizer(self.sizer) if self._closingstyle & TB_ONCLICK and self._windowstyle != TB_CAPTION: panel.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown) def SetPopupText(self, text): """ Sets the L{ToasterBox} text label. :param `text`: the widget label. :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style. """ self._popuptext = text def SetPopupTextFont(self, font): """ Sets the L{ToasterBox} text font. :param `colour`: a valid `wx.Colour` object. If defaulted to ``None``, then a simple generic font will be generated. :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style. """ self._textfont = font def GetPopupText(self): """ Returns the L{ToasterBox} text. :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style. """ return self._popuptext def Play(self): """ Creates the L{ToasterBoxWindow}, that does all the job. """ # do some checks to make sure this window is valid if self._bottomright.x < 1 or self._bottomright.y < 1: return False if self.GetSize().GetWidth() < 50 or self.GetSize().GetWidth() < 50: # toasterbox launches into a endless loop for some reason # when you try to make the window too small. return False self.ScrollUp() timerid = wx.NewId() self.showtime = wx.Timer(self, timerid) self.showtime.Start(self._pausetime) self.Bind(wx.EVT_TIMER, self.NotifyTimer, id=timerid) return True def NotifyTimer(self, event): """ Hides gradually the L{ToasterBoxWindow}. """ self.showtime.Stop() del self.showtime self.ScrollDown() def SetPopupBackgroundColour(self, colour): """ Sets the L{ToasterBox} background colour. :param `colour`: a valid `wx.Colour` object. If defaulted to ``None``, then the background colour will be white. :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style. """ self.SetBackgroundColour(colour) def SetPopupTextColour(self, colour): """ Sets the L{ToasterBox} foreground colour. :param `colour`: a valid `wx.Colour` object. If defaulted to ``None``, then the background colour will be black. :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style. """ self._textcolour = colour def ScrollUp(self): """ Scrolls the L{ToasterBox} up, which means gradually showing it. """ self.Show(True) # walk the Y value up in a raise motion xpos = self.GetPosition().x ypos = self._bottomright[1] windowsize = 0 # checking the type of the scroll (from up to down or from down to up) if self._scrollType == TB_SCR_TYPE_UD: start = self._dialogtop[1] stop = ypos step = self._step elif self._scrollType == TB_SCR_TYPE_DU: start = ypos stop = self._dialogtop[1] step = -self._step else: errMsg = ( "scrollType not supported (in ToasterBoxWindow.ScrollUp): %s" % self._scrollType) raise ValueError(errMsg) for i in xrange(start, stop, step): if i < self._dialogtop[1]: i = self._dialogtop[1] windowsize = windowsize + self._step # checking the type of the scroll (from up to down or from down to up) if self._scrollType == TB_SCR_TYPE_UD: dimY = self._dialogtop[1] elif self._scrollType == TB_SCR_TYPE_DU: dimY = i else: errMsg = ( "scrollType not supported (in ToasterBoxWindow.ScrollUp): %s" % self._scrollType) raise ValueError(errMsg) self.SetDimensions(self._dialogtop[0], dimY, self.GetSize().GetWidth(), windowsize) if self._tbstyle == TB_SIMPLE: self.DrawText() wx.Usleep(self._sleeptime) self.Update() self.Refresh() self.Update() if self._tbstyle == TB_SIMPLE: self.DrawText() self.SetFocus() def ScrollDown(self): """ Scrolls the L{ToasterBox} down, which means gradually hiding it. """ # walk down the Y value windowsize = self.GetSize().GetHeight() # checking the type of the scroll (from up to down or from down to up) if self._scrollType == TB_SCR_TYPE_UD: start = self._bottomright.y stop = self._dialogtop[1] step = -self._step elif self._scrollType == TB_SCR_TYPE_DU: start = self._dialogtop[1] stop = self._bottomright.y step = self._step else: errMsg = ( "scrollType not supported (in ToasterBoxWindow.ScrollUp): %s" % self._scrollType) raise ValueError(errMsg) for i in xrange(start, stop, step): if i > self._bottomright.y: i = self._bottomright.y windowsize = windowsize - self._step if windowsize <= 0: break # checking the type of the scroll (from up to down or from down to up) if self._scrollType == TB_SCR_TYPE_UD: dimY = self._dialogtop[1] elif self._scrollType == TB_SCR_TYPE_DU: dimY = i else: errMsg = ( "scrollType not supported (in ToasterBoxWindow.ScrollUp): %s" % self._scrollType) raise ValueError(errMsg) self.SetDimensions(self._dialogtop[0], dimY, self.GetSize().GetWidth(), windowsize) wx.Usleep(self._sleeptime) self.Refresh() self.Hide() if self._parent2: self._parent2.Notify() def DrawText(self): """ Draws the text label for a L{ToasterBox} with ``TB_SIMPLE`` style set. """ if self._staticbitmap is not None: dc = wx.ClientDC(self._staticbitmap) else: dc = wx.ClientDC(self) dc.SetFont(self._textfont) if not hasattr(self, "text_coords"): self._getTextCoords(dc) fg = dc.GetTextForeground() dc.SetTextForeground(self._textcolour) dc.DrawTextList(*self.text_coords) dc.SetTextForeground(fg) def _getTextCoords(self, dc): """ Draw the user specified text. :param `dc`: an instance of `wx.DC`. :note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style. """ # border from sides and top to text (in pixels) border = 7 # how much space between text lines textPadding = 2 pText = self.GetPopupText() max_len = len(pText) tw, th = self._parent2._popupsize if self._windowstyle == TB_CAPTION: th = th - 20 while 1: lines = textwrap.wrap(pText, max_len) for line in lines: w, h = dc.GetTextExtent(line) if w > tw - border * 2: max_len -= 1 break else: break fh = 0 for line in lines: w, h = dc.GetTextExtent(line) fh += h + textPadding y = (th - fh) / 2 coords = [] for line in lines: w, h = dc.GetTextExtent(line) x = (tw - w) / 2 coords.append((x, y)) y += h + textPadding self.text_coords = (lines, coords)