import wx import wx.lib.colourselect as csel import wx.lib.intctrl as intctrl import six import math import datetime import Model import Utils from GetResults import GetResults defaultBackgroundColours = [ wx.Colour(16, 16, 16), wx.Colour(34, 139, 34), wx.Colour(235, 155, 0), wx.Colour(147, 112, 219), wx.Colour(0, 0, 139), wx.Colour(139, 0, 0) ] def getForegroundsBackgrounds(): race = Model.race foregrounds, backgrounds = [], [] for i in range(len(defaultBackgroundColours)): try: foregrounds.append( Utils.colorFromStr(race.lapCounterForegrounds[i])) except (IndexError, AttributeError): foregrounds.append(wx.WHITE) try:
def lighterColour( c ): rgb = c.Get( False ) return wx.Colour( *[int(v + (255 - v) * 0.6) for v in rgb] )
def makeColourGradient(frequency1, frequency2, frequency3, phase1, phase2, phase3, center = 128, width = 127, len = 50 ): fp = [(frequency1,phase1), (frequency2,phase2), (frequency3,phase3)] grad = [wx.Colour(*[int(math.sin(f*i + p) * width + center) for f, p in fp]) for i in xrange(len+1)] return grad[1:]
import wx HIGH_LIGHT_COLOR1 = wx.Colour(34, 177, 76) HIGH_LIGHT_COLOR_TEST = wx.Colour(255, 0, 255)
def refresh(self): model = SeriesModel.model HeaderNames = getHeaderNames() scoreByPoints = model.scoreByPoints scoreByTime = model.scoreByTime self.postPublishCmd.SetValue(model.postPublishCmd) with wx.BusyCursor() as wait: self.raceResults = model.extractAllRaceResults( adjustForUpgrades=False, isIndividual=False) self.fixCategories() categoryName = self.categoryChoice.GetStringSelection() if not categoryName or not (scoreByPoints or scoreByTime): Utils.AdjustGridSize(self.grid, 0, 0) return self.grid.ClearGrid() pointsForRank = { r.getFileName(): r.pointStructure for r in model.races } teamPointsForRank = { r.getFileName(): r.teamPointStructure for r in model.races } results, races = GetModelInfo.GetCategoryResultsTeam( categoryName, self.raceResults, pointsForRank, teamPointsForRank, useMostEventsCompleted=model.useMostEventsCompleted, numPlacesTieBreaker=model.numPlacesTieBreaker, ) results = [rr for rr in results if toFloat(rr[1]) > 0.0] headerNames = HeaderNames + [ u'{}\n{}'.format(r[1], r[0].strftime('%Y-%m-%d') if r[0] else u'') for r in races ] Utils.AdjustGridSize(self.grid, len(results), len(headerNames)) self.setColNames(headerNames) for row, (team, points, gap, rrs) in enumerate(results): self.grid.SetCellValue(row, 0, six.text_type(row + 1)) self.grid.SetCellValue(row, 1, six.text_type(team)) self.grid.SetCellValue(row, 2, six.text_type(points)) self.grid.SetCellValue(row, 3, six.text_type(gap)) for q, rt in enumerate(rrs): self.grid.SetCellValue(row, 4 + q, formatTeamResults(scoreByPoints, rt)) for c in range(0, len(headerNames)): self.grid.SetCellBackgroundColour(row, c, wx.WHITE) self.grid.SetCellTextColour(row, c, wx.BLACK) if self.sortCol is not None: def getBracketedNumber(v): numberMax = 99999 if not v: return numberMax try: return int(reNoDigits.sub('', v.split('(')[1])) except (IndexError, ValueError): return numberMax data = [] for r in range(0, self.grid.GetNumberRows()): rowOrig = [ self.grid.GetCellValue(r, c) for c in range(0, self.grid.GetNumberCols()) ] rowCmp = rowOrig[:] rowCmp[0] = int(rowCmp[0]) rowCmp[4] = Utils.StrToSeconds(rowCmp[4]) rowCmp[5:] = [getBracketedNumber(v) for v in rowCmp[5:]] rowCmp.extend(rowOrig) data.append(rowCmp) if self.sortCol > 0: fg = wx.WHITE bg = wx.Colour(0, 100, 0) else: fg = wx.BLACK bg = wx.Colour(255, 165, 0) iCol = abs(self.sortCol) data.sort(key=lambda x: x[iCol], reverse=(self.sortCol < 0)) for r, row in enumerate(data): for c, v in enumerate(row[self.grid.GetNumberCols():]): self.grid.SetCellValue(r, c, v) if c == iCol: self.grid.SetCellTextColour(r, c, fg) self.grid.SetCellBackgroundColour(r, c, bg) if c < 4: halign = wx.ALIGN_LEFT elif c == 4 or c == 5: halign = wx.ALIGN_RIGHT else: halign = wx.ALIGN_CENTRE self.grid.SetCellAlignment(r, c, halign, wx.ALIGN_TOP) self.statsLabel.SetLabel('{} / {}'.format( self.grid.GetNumberRows(), GetModelInfo.GetTotalUniqueTeams(self.raceResults))) self.grid.AutoSizeColumns(False) self.grid.AutoSizeRows(False) self.GetSizer().Layout()
def angle_from_mouse(self, workspace, pixel_data): '''Run a UI that gets an angle from the user''' import wx if self.how_often == IO_ONCE: d = self.get_dictionary(workspace.image_set_list) if d.has_key(D_ANGLE): return d[D_ANGLE] if pixel_data.ndim == 2: # make a color matrix for consistency pixel_data = np.dstack((pixel_data, pixel_data, pixel_data)) pd_min = np.min(pixel_data) pd_max = np.max(pixel_data) if pd_min == pd_max: pixel_data[:, :, :] = 0 else: pixel_data = ((pixel_data - pd_min) * 255.0 / (pd_max - pd_min)) # # Make a 100 x 100 image so it's manageable # isize = 200 i, j, k = np.mgrid[0:isize, 0:int(isize * pixel_data.shape[1] / pixel_data.shape[0]), 0:3].astype(float) i *= float(pixel_data.shape[0]) / float(isize) j *= float(pixel_data.shape[0]) / float(isize) pixel_data = scind.map_coordinates(pixel_data, (i, j, k)) # # Make a dialog box that contains the image # dialog = wx.Dialog(workspace.frame, title="Rotate image") sizer = wx.BoxSizer(wx.VERTICAL) dialog.SetSizer(sizer) sizer.Add( wx.StaticText(dialog, label="Drag image to rotate, hit OK to continue"), 0, wx.ALIGN_CENTER_HORIZONTAL) canvas = wx.StaticBitmap(dialog) canvas.SetDoubleBuffered(True) canvas.BackgroundColour = wx.Colour(0, 0, 0, wx.ALPHA_TRANSPARENT) sizer.Add( canvas, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) angle = [0] angle_text = wx.StaticText(dialog, label="Angle: %d" % angle[0]) sizer.Add(angle_text, 0, wx.ALIGN_CENTER_HORIZONTAL) def imshow(): angle_text.Label = "Angle: %d" % int(angle[0]) angle_text.Refresh() my_angle = -angle[0] * np.pi / 180.0 transform = np.array([[np.cos(my_angle), -np.sin(my_angle)], [np.sin(my_angle), np.cos(my_angle)]]) # Make it rotate about the center offset = affine_offset(pixel_data.shape, transform) x = np.dstack((scind.affine_transform(pixel_data[:, :, 0], transform, offset, order=0), scind.affine_transform(pixel_data[:, :, 1], transform, offset, order=0), scind.affine_transform(pixel_data[:, :, 2], transform, offset, order=0))) buff = x.astype(np.uint8).tostring() bitmap = wx.BitmapFromBuffer(x.shape[1], x.shape[0], buff) canvas.SetBitmap(bitmap) imshow() # # Install handlers for mouse down, mouse move and mouse up # dragging = [False] initial_angle = [0] hand_cursor = wx.StockCursor(wx.CURSOR_HAND) arrow_cursor = wx.StockCursor(wx.CURSOR_ARROW) def get_angle(event): center = np.array(canvas.Size) / 2 point = np.array(event.GetPositionTuple()) offset = point - center return -np.arctan2(offset[1], offset[0]) * 180.0 / np.pi def on_mouse_down(event): canvas.Cursor = hand_cursor dragging[0] = True initial_angle[0] = get_angle(event) - angle[0] canvas.CaptureMouse() wx.EVT_LEFT_DOWN(canvas, on_mouse_down) def on_mouse_up(event): if dragging[0]: canvas.ReleaseMouse() dragging[0] = False canvas.Cursor = arrow_cursor wx.EVT_LEFT_UP(canvas, on_mouse_up) def on_mouse_lost(event): dragging[0] = False canvas.Cursor = arrow_cursor wx.EVT_MOUSE_CAPTURE_LOST(canvas, on_mouse_lost) def on_mouse_move(event): if dragging[0]: angle[0] = get_angle(event) - initial_angle[0] imshow() canvas.Refresh(eraseBackground=False) wx.EVT_MOTION(canvas, on_mouse_move) # # Put the OK and Cancel buttons on the bottom # btnsizer = wx.StdDialogButtonSizer() btn = wx.Button(dialog, wx.ID_OK) btn.SetDefault() btnsizer.AddButton(btn) btn = wx.Button(dialog, wx.ID_CANCEL) btnsizer.AddButton(btn) btnsizer.Realize() sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 5) dialog.Fit() result = dialog.ShowModal() dialog.Destroy() if result == wx.ID_OK: return angle[0] raise ValueError("Canceled by user in FlipAndRotate")
def __init__(self, parent): wx.Panel.__init__(self, parent) backgroud_colour = wx.Colour(255, 255, 255) self.SetBackgroundColour(backgroud_colour) self.SetAutoLayout(1) # Counter for projects loaded in current GUI # Fixed hyperlink items tooltip = wx.ToolTip(_("Export InVesalius screen to an image file")) link_export_picture = hl.HyperLinkCtrl(self, -1, _("Export picture...")) link_export_picture.SetUnderlines(False, False, False) link_export_picture.SetBold(True) link_export_picture.SetColours("BLACK", "BLACK", "BLACK") link_export_picture.SetBackgroundColour(self.GetBackgroundColour()) link_export_picture.SetToolTip(tooltip) link_export_picture.AutoBrowse(False) link_export_picture.UpdateLink() link_export_picture.Bind(hl.EVT_HYPERLINK_LEFT, self.OnLinkExportPicture) tooltip = wx.ToolTip(_("Export 3D surface")) link_export_surface = hl.HyperLinkCtrl(self, -1, _("Export 3D surface...")) link_export_surface.SetUnderlines(False, False, False) link_export_surface.SetBold(True) link_export_surface.SetColours("BLACK", "BLACK", "BLACK") link_export_surface.SetBackgroundColour(self.GetBackgroundColour()) link_export_surface.SetToolTip(tooltip) link_export_surface.AutoBrowse(False) link_export_surface.UpdateLink() link_export_surface.Bind(hl.EVT_HYPERLINK_LEFT, self.OnLinkExportSurface) #tooltip = wx.ToolTip(_("Export 3D mask (voxels)")) #link_export_mask = hl.HyperLinkCtrl(self, -1,_("Export mask...")) #link_export_mask.SetUnderlines(False, False, False) #link_export_mask.SetColours("BLACK", "BLACK", "BLACK") #link_export_mask.SetToolTip(tooltip) #link_export_mask.AutoBrowse(False) #link_export_mask.UpdateLink() #link_export_mask.Bind(hl.EVT_HYPERLINK_LEFT, # self.OnLinkExportMask) #tooltip = wx.ToolTip("Request rapid prototyping services") #link_request_rp = hl.HyperLinkCtrl(self,-1,"Request rapid prototyping...") #link_request_rp.SetUnderlines(False, False, False) #link_request_rp.SetColours("BLACK", "BLACK", "BLACK") #link_request_rp.SetToolTip(tooltip) #link_request_rp.AutoBrowse(False) #link_request_rp.UpdateLink() #link_request_rp.Bind(hl.EVT_HYPERLINK_LEFT, self.OnLinkRequestRP) #tooltip = wx.ToolTip("Open report tool...") #link_report = hl.HyperLinkCtrl(self,-1,"Open report tool...") #link_report.SetUnderlines(False, False, False) #link_report.SetColours("BLACK", "BLACK", "BLACK") #link_report.SetToolTip(tooltip) #link_report.AutoBrowse(False) #link_report.UpdateLink() #link_report.Bind(hl.EVT_HYPERLINK_LEFT, self.OnLinkReport) # Image(s) for buttons if sys.platform == 'darwin': BMP_EXPORT_SURFACE = wx.Bitmap(\ "../icons/surface_export_original.png", wx.BITMAP_TYPE_PNG).ConvertToImage()\ .Rescale(25, 25).ConvertToBitmap() BMP_TAKE_PICTURE = wx.Bitmap(\ "../icons/tool_photo_original.png", wx.BITMAP_TYPE_PNG).ConvertToImage()\ .Rescale(25, 25).ConvertToBitmap() #BMP_EXPORT_MASK = wx.Bitmap("../icons/mask.png", # wx.BITMAP_TYPE_PNG) else: BMP_EXPORT_SURFACE = wx.Bitmap("../icons/surface_export.png", wx.BITMAP_TYPE_PNG).ConvertToImage()\ .Rescale(25, 25).ConvertToBitmap() BMP_TAKE_PICTURE = wx.Bitmap("../icons/tool_photo.png", wx.BITMAP_TYPE_PNG).ConvertToImage()\ .Rescale(25, 25).ConvertToBitmap() #BMP_EXPORT_MASK = wx.Bitmap("../icons/mask_small.png", # wx.BITMAP_TYPE_PNG) # Buttons related to hyperlinks button_style = pbtn.PB_STYLE_SQUARE | pbtn.PB_STYLE_DEFAULT button_picture = pbtn.PlateButton(self, BTN_PICTURE, "", BMP_TAKE_PICTURE, style=button_style) button_picture.SetBackgroundColour(self.GetBackgroundColour()) self.button_picture = button_picture button_surface = pbtn.PlateButton(self, BTN_SURFACE, "", BMP_EXPORT_SURFACE, style=button_style) button_surface.SetBackgroundColour(self.GetBackgroundColour()) #button_mask = pbtn.PlateButton(self, BTN_MASK, "", # BMP_EXPORT_MASK, # style=button_style) #button_request_rp = pbtn.PlateButton(self, BTN_REQUEST_RP, "", # BMP_IMPORT, style=button_style) #button_report = pbtn.PlateButton(self, BTN_REPORT, "", # BMP_IMPORT, # style=button_style) # When using PlaneButton, it is necessary to bind events from parent win self.Bind(wx.EVT_BUTTON, self.OnButton) # Tags and grid sizer for fixed items flag_link = wx.EXPAND | wx.GROW | wx.LEFT | wx.TOP flag_button = wx.EXPAND | wx.GROW fixed_sizer = wx.FlexGridSizer(rows=2, cols=2, hgap=2, vgap=0) fixed_sizer.AddGrowableCol(0, 1) fixed_sizer.AddMany([ (link_export_picture, 1, flag_link, 3), (button_picture, 0, flag_button), (link_export_surface, 1, flag_link, 3), (button_surface, 0, flag_button), ]) #(link_export_mask, 1, flag_link, 3), #(button_mask, 0, flag_button)]) #(link_report, 0, flag_link, 3), #(button_report, 0, flag_button), #(link_request_rp, 1, flag_link, 3), #(button_request_rp, 0, flag_button)]) # Add line sizers into main sizer main_sizer = wx.BoxSizer(wx.VERTICAL) main_sizer.Add(fixed_sizer, 0, wx.GROW | wx.EXPAND) # Update main sizer and panel layout self.SetSizer(main_sizer) self.Fit() self.sizer = main_sizer self.__init_menu()
def __init__(self, parent=None): # wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 800,630 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL ) wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString, pos=wx.DefaultPosition, size=wx.Size(800, 630), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL) self.isOKGoogle = False self.isOKChina = False self.isOKYoutube = False print('程序正在启动...\n请稍等...'.decode()) # try: if True: self.updateObj = updatetool.UpdateTool(isDebug=ISDEBUG) # self.clientRegObj = clientRegTool.ClientRegTool(isDebug = True) clientRegTool = self.updateObj.getClientRegTool() self.clientRegObj = clientRegTool.ClientRegTool(isDebug=ISDEBUG) self.downcount = self.clientRegObj.getDownCount() self.downtool = self.clientRegObj.getDownTool() trailback = None if self.downtool == None: trailback = self.clientRegObj.trail(isGetCode=True) self.downtool = self.clientRegObj.getDownTool() else: if self.downtool.isTrailCode != self.clientRegObj.isTrail: trailback = self.clientRegObj.trail(isGetCode=True) else: trailback = self.clientRegObj.trail() self.isShowTrail = False if trailback['erro'] == 1: #目前是试用状态 self.isShowTrail = True self.savePth = self.downtool.get_desktop() self.downtool.msgtool.setUIObj(self) self.isWinSystem = self.downtool.isWinSystem # except Exception as e: # self.savePth = '' # self.isShowTrail = False print(os.getcwd()) self.count = 0 self.gaugeValueStart = 0 self.savepthconfig = 'savepth.txt' if os.path.exists(self.savepthconfig): f = open(self.savepthconfig, 'r') self.savePth = f.read() f.close() self.queue = Queue.Queue() self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize) self.SetBackgroundColour( wx.SystemSettings.GetColour(wx.SYS_COLOUR_APPWORKSPACE)) sbSizer1 = wx.StaticBoxSizer( wx.StaticBox(self, wx.ID_ANY, u"youtube下载工具,本工具来源,https://fengmm521.taobao.com/"), wx.VERTICAL) # self.m_staticText1 = wx.StaticText( self, wx.ID_ANY, u"在下边输入要下载的视频网址,每个视频一行", wx.Point( -1,-1 ), wx.DefaultSize, 0 ) # self.m_staticText1.Wrap( -1 ) # sbSizer1.Add( self.m_staticText1, 0, wx.ALL, 5 ) self.m_staticText1 = wx.StaticText( self, wx.ID_ANY, u"在下边输入要下载的视频网址,每个视频一行,试用版最多可下载五个视频,注册版没有限制。", wx.Point(-1, -1), wx.DefaultSize, 0) self.m_staticText1.Wrap(-1) sbSizer1.Add(self.m_staticText1, 0, wx.ALL, 5) self.m_textCtrl1 = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(760, 200), style=wx.TE_MULTILINE) sbSizer1.Add(self.m_textCtrl1, 0, wx.ALL, 5) self.m_staticText4 = wx.StaticText(self, wx.ID_ANY, u"下载文件保存路径:", wx.DefaultPosition, wx.DefaultSize, 0) self.m_staticText4.Wrap(-1) sbSizer1.Add(self.m_staticText4, 0, wx.ALL, 5) #------------------ gbSizer1 = wx.GridBagSizer(0, 0) gbSizer1.SetFlexibleDirection(wx.BOTH) gbSizer1.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED) self.m_textCtrl3 = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(500, -1), 0) gbSizer1.Add(self.m_textCtrl3, wx.GBPosition(0, 1), wx.GBSpan(1, 1), wx.ALL, 5) self.m_textCtrl3.SetLabel(self.savePth) #------------------ # self.m_button3 = wx.Button( self, wx.ID_ANY, u"选择保存路径", wx.DefaultPosition, wx.DefaultSize, 0 ) # sbSizer1.Add( self.m_button3, 0, wx.ALL, 5 ) self.m_button3 = wx.Button(self, wx.ID_ANY, u"选择保存路径", wx.DefaultPosition, wx.DefaultSize, 0) gbSizer1.Add(self.m_button3, wx.GBPosition(0, 0), wx.GBSpan(1, 1), wx.ALL, 5) self.Bind(wx.EVT_BUTTON, self.onSavePathSelectClick, self.m_button3) # self.m_textCtrl3 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 500,-1 ), 0 ) # sbSizer1.Add( self.m_textCtrl3, 1, wx.BOTTOM|wx.LEFT, 5 ) # self.m_textCtrl3.SetLabel(self.savePth) #--------------- sbSizer1.Add(gbSizer1, 0, 0, 5) gSizer1 = wx.GridSizer(2, 2, 0, 0) gbSizer2 = wx.GridBagSizer(0, 0) gbSizer2.SetFlexibleDirection(wx.BOTH) gbSizer2.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED) #--------------- self.m_staticText3 = wx.StaticText(self, wx.ID_ANY, u"1/100", wx.Point(-1, -1), wx.DefaultSize, 0) self.m_staticText3.Wrap(-1) gbSizer2.Add(self.m_staticText3, wx.GBPosition(1, 0), wx.GBSpan(1, 1), wx.ALL, 5) self.m_staticText3.SetLabel('请输入视频网址后,点开始下载') # self.m_button2 = wx.Button( self, wx.ID_ANY, u"开始下载", wx.DefaultPosition, wx.Size( 150,-1 ), 0 ) # sbSizer1.Add( self.m_button2, 0, wx.ALL, 5 ) self.m_button2 = wx.Button(self, wx.ID_ANY, u"开始下载", wx.DefaultPosition, wx.Size(150, -1), 0) gbSizer2.Add(self.m_button2, wx.GBPosition(0, 0), wx.GBSpan(1, 1), wx.ALL, 5) self.Bind(wx.EVT_BUTTON, self.onDownloadClick, self.m_button2) self.m_staticText2 = wx.StaticText(self, wx.ID_ANY, u"下载进度与祥情:", wx.DefaultPosition, wx.DefaultSize, 0) self.m_staticText2.Wrap(-1) gbSizer2.Add(self.m_staticText2, wx.GBPosition(2, 0), wx.GBSpan(1, 1), wx.ALL, 5) # sbSizer1.Add( self.m_staticText2, 0, wx.ALL, 5 ) # self.m_staticText3 = wx.StaticText( self, wx.ID_ANY, u"1/100", wx.Point( -1,-1 ), wx.DefaultSize, 0 ) # self.m_staticText3.Wrap( -1 ) # sbSizer1.Add( self.m_staticText3, 0, wx.ALL, 5 ) # self.m_staticText3.SetLabel('请输入视频网址后,点开始下载') #----------------- gSizer1.Add(gbSizer2, 1, wx.EXPAND, 5) gbSizer4 = wx.GridBagSizer(0, 0) gbSizer4.SetFlexibleDirection(wx.BOTH) gbSizer4.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED) # imagpth = u"data" + os.sep + "image.png" self.m_bitmap1 = wx.StaticBitmap( self, wx.ID_ANY, wx.Bitmap(u"data/image.png", wx.BITMAP_TYPE_ANY), wx.DefaultPosition, wx.DefaultSize, 0) gbSizer4.Add(self.m_bitmap1, wx.GBPosition(0, 0), wx.GBSpan(1, 1), wx.ALL, 5) bSizer1 = wx.BoxSizer(wx.VERTICAL) self.m_buyTextTitle = wx.StaticText(self, wx.ID_ANY, u"扫二维码购买注册码永久使用", wx.DefaultPosition, wx.DefaultSize, 0) self.m_buyTextTitle.Wrap(-1) bSizer1.Add(self.m_buyTextTitle, 1, wx.ALL, 5) self.m_buyTextTitle1 = wx.StaticText(self, wx.ID_ANY, u"支持微信,支付宝购买", wx.DefaultPosition, wx.Size(-1, -1), 0) self.m_buyTextTitle1.Wrap(-1) self.m_buyTextTitle1.SetForegroundColour(wx.Colour(177, 255, 221)) bSizer1.Add(self.m_buyTextTitle1, 0, wx.ALL, 5) self.m_textCtrl4 = wx.TextCtrl(self, wx.ID_ANY, u"请输入注册码", wx.DefaultPosition, wx.DefaultSize, 0) self.m_textCtrl4.SetBackgroundColour( wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)) bSizer1.Add(self.m_textCtrl4, 0, wx.ALL | wx.EXPAND, 5) self.m_regbtn = wx.Button(self, wx.ID_ANY, u"注册", wx.DefaultPosition, wx.DefaultSize, 0) bSizer1.Add(self.m_regbtn, 0, wx.ALL, 5) def regBtnFunc(evt): tmpmsg, isOK = self.clientRegObj.bind(self.m_textCtrl4.GetValue()) self.isShowTrail = bool(isOK) if not self.isShowTrail: self.hideTrailUI() self.showMsg(tmpmsg) self.Bind(wx.EVT_BUTTON, regBtnFunc, self.m_regbtn) gbSizer4.Add(bSizer1, wx.GBPosition(0, 1), wx.GBSpan(1, 1), wx.EXPAND, 5) bSizer2 = wx.BoxSizer(wx.VERTICAL) self.m_staticText7 = wx.StaticText(self, wx.ID_ANY, u"剩余试用数:", wx.DefaultPosition, wx.DefaultSize, 0) self.m_staticText7.Wrap(-1) self.m_staticText7.SetForegroundColour(wx.Colour(254, 217, 204)) bSizer2.Add(self.m_staticText7, 0, wx.ALL, 5) lcount = str(max(5 - self.downcount, 0)) self.m_tailSticTxt = wx.StaticText(self, wx.ID_ANY, lcount, wx.DefaultPosition, wx.DefaultSize, 0) self.m_tailSticTxt.Wrap(-1) self.m_tailSticTxt.SetFont( wx.Font(40, 70, 90, 90, False, wx.EmptyString)) self.m_tailSticTxt.SetForegroundColour(wx.Colour(137, 255, 128)) bSizer2.Add(self.m_tailSticTxt, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 5) gbSizer4.Add(bSizer2, wx.GBPosition(0, 3), wx.GBSpan(1, 1), wx.EXPAND, 5) gSizer1.Add(gbSizer4, 1, wx.EXPAND, 5) sbSizer1.Add(gSizer1, 1, wx.EXPAND, 5) #----------------- self.m_gauge1 = wx.Gauge(self, wx.ID_ANY, 100, wx.DefaultPosition, wx.Size(750, -1), wx.GA_HORIZONTAL) self.m_gauge1.SetValue(1) sbSizer1.Add(self.m_gauge1, 0, wx.ALL, 5) self.m_textCtrl2 = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(760, 98), style=wx.TE_MULTILINE) sbSizer1.Add(self.m_textCtrl2, 0, wx.ALL, 5) self.SetSizer(sbSizer1) self.Layout() self.Centre(wx.BOTH) self.showtimer = 0 self.showTishi = '' self.videotmppth = '' self.audiotmppth = '' # self.Bind(wx.EVT_IDLE, self.OnIdle) # 创建定时器 self.timer = wx.Timer(self) #创建定时器 self.Bind(wx.EVT_TIMER, self.onTimer, self.timer) #绑定一个定时器事件 self.startTimer(30) self.downthread = None self.isComplet = False self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) self.showMsg('程序正在加载下载模块...\n') if self.isShowTrail: self.showTrailUI() else: self.hideTrailUI() self.showMsg('所有模块加载完成!\n') self.initClient()
def __init__(self, parent): global candidateList wx.Frame.__init__(self, parent, title=u"抽奖", style=wx.MAXIMIZE | wx.DEFAULT_FRAME_STYLE) self.panel = PanelMain.PanelMain(self) self.panel.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBack) countForThisTimeStr = u"本次抽出" self.countForThisTime = wx.StaticText(self.panel, label=countForThisTimeStr, pos=(80, 1040)) self.countForThisTime.SetBackgroundColour(wx.Colour(0, 0, 0, 255)) self.countForThisTime.SetForegroundColour(wx.Colour(255, 255, 255, 255)) self.inputForCount = wx.TextCtrl(self.panel, -1, u"50", size=(40, -1), style=wx.TE_CENTRE, pos=(150, 1040)) self.inputForCount.SetInsertionPoint(0) self.CandidateCount = wx.StaticText(self.panel, label=u"/", pos=(200, 1040)) self.CandidateCount.SetBackgroundColour(wx.Colour(0, 0, 0, 255)) self.CandidateCount.SetForegroundColour(wx.Colour(255, 255, 255, 255)) self.stopRollNumber = wx.Button(self.panel, label=u"停", pos=(1200, 1040), size=(150, 30)) self.Bind(wx.EVT_BUTTON, self.OnStopRollNumber, self.stopRollNumber) btnSize = (100, 30) self.GetForthButton = wx.Button(self.panel, label=u"抽取幸运奖", pos=(300, 1040), size=btnSize) self.Bind(wx.EVT_BUTTON, self.OnGetForthButton, self.GetForthButton) self.GetThirdButton = wx.Button(self.panel, label=u"抽取三等奖", pos=(420, 1040), size=btnSize) self.Bind(wx.EVT_BUTTON, self.OnGetThirdButton, self.GetThirdButton) self.GetSecondButton = wx.Button(self.panel, label=u"抽取二等奖", pos=(540, 1040), size=btnSize) self.Bind(wx.EVT_BUTTON, self.OnGetSecondButton, self.GetSecondButton) self.GetFirstButton = wx.Button(self.panel, label=u"抽取一等奖", pos=(660, 1040), size=btnSize) self.Bind(wx.EVT_BUTTON, self.OnGetFirstButton, self.GetFirstButton) self.GetSpecialButton = wx.Button(self.panel, label=u"抽取特等奖", pos=(780, 1040), size=btnSize) self.Bind(wx.EVT_BUTTON, self.OnGetSpecialButton, self.GetSpecialButton) self.btnShowResultPanel = wx.Button(self.panel, label=u"显示上次结果", pos=(900, 1040), size=btnSize) self.Bind(wx.EVT_BUTTON, self.OnBtnShowResultPanel, self.btnShowResultPanel) self.btnHideResultPanel = wx.Button(self.panel, label=u"关闭结果显示", pos=(1020, 1040), size=btnSize) self.Bind(wx.EVT_BUTTON, self.OnBtnHideResultPanel, self.btnHideResultPanel) self.GetForthButton.Enable(True) self.GetThirdButton.Enable(True) self.GetSecondButton.Enable(True) self.GetFirstButton.Enable(True) self.GetSpecialButton.Enable(True) self.stopRollNumber.Enable(False) self.Bind(wx.EVT_CHAR_HOOK, self.OnKey) self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer) self.rollCount = 0 self.CandidateCount.SetLabel(u"/" + str(len(candidateList))) self.LoadBGMain() self.LoadBGResult() self.bmp = self.bmpMain self.Show(True) self.ShowFullScreen(True, wx.FULLSCREEN_ALL) self.HCenter(self.panel.showNumber) self.HCenter(self.panel.txtTitle)
# childFrameStyle = wx.CLIP_CHILDREN | wx.FRAME_TOOL_WINDOW childFrameStyle = wx.CLIP_CHILDREN # Style that the DataView ListCtrl is created in ## options: wx.LC_SMALL_ICON, wx.LC_LIST dataViewListStyle = wx.LC_LIST # Should the palette be a menubar or a notebook ## options: 'tabs', 'menu' paletteStyle = 'tabs' # Frame test button on the Palette toolbar showFrameTestButton = False # Style flags used by most splitters in the IDE splitterStyle = wx.SP_LIVE_UPDATE | wx.SP_3DSASH | wxNO_3D # Alternating background colours used in ListCtrls (pastel blue and yellow) pastels = True pastelMedium = wx.Colour(235, 246, 255) pastelLight = wx.Colour(255, 255, 240) # Colour (indicating danger) used to display uninitialised window space. # A control must be placed in this space before valid code can be generated undefinedWindowCol = wx.Colour(128, 0, 0) # Info that will be filled into the comment block. (Edit->Add module info) # Also used by setup.py staticInfoPrefs = { 'Purpose': '', 'Author': '<your name>', 'Copyright': '(c) 2006', 'Licence': '<your licence>', 'Email': '<your email>', }
def test_BitmapSetMaskColour(self): b5 = wx.Bitmap(pngFile) b5.SetMaskColour(wx.Colour(1, 2, 3)) b5.SetMaskColour('black')
def Append(self, plugin): """Append a plugin into the panel. :param plugin (sppasPluginParam) The plugin to append """ plugin_id = plugin.get_key() # Create the button button_id = wx.NewId() button_icon = os.path.join(plugin.get_directory(), plugin.get_icon()) button = ButtonPanel(self, button_id, self._preferences, button_icon, plugin_id, activated=True) # Create a description with the plugin name and its description. p = wx.Panel(self, -1) p.SetBackgroundColour(self._preferences.GetValue('M_BG_COLOUR')) n = plugin.get_name() if len(n) == 0: n = "Unknown plugin name" txt_name = wx.TextCtrl(p, wx.ID_ANY, value=n, style=wx.TE_READONLY | wx.NO_BORDER) self.__apply_preferences(txt_name) font = self._preferences.GetValue('M_FONT') font.SetWeight(wx.BOLD) txt_name.SetFont(font) d = plugin.get_descr() if len(d) == 0: d = "No description available." txt_descr = wx.TextCtrl(p, wx.ID_ANY, value=d, style=wx.TE_READONLY | wx.TE_MULTILINE | wx.NO_BORDER | wx.TE_WORDWRAP | wx.TE_NO_VSCROLL) self.__apply_preferences(txt_descr) txt_readme = wx.StaticText(p, -1, "About...") self.__apply_preferences(txt_readme) txt_readme.SetForegroundColour(wx.Colour(80, 100, 220)) txt_readme.Bind(wx.EVT_LEFT_UP, self.OnReadme) s = wx.BoxSizer(wx.VERTICAL) s.Add(txt_name, proportion=0, flag=wx.LEFT | wx.EXPAND, border=2) s.Add(txt_readme, proportion=0, flag=wx.LEFT | wx.BOTTOM, border=2) s.Add(txt_descr, proportion=1, flag=wx.LEFT | wx.TOP | wx.EXPAND, border=2) p.SetSizerAndFit(s) box = wx.BoxSizer(wx.HORIZONTAL) box.Add(button, proportion=0, flag=wx.ALL, border=4) box.Add(p, proportion=1, flag=wx.ALL | wx.EXPAND, border=4) # Add to the main sizer self.GetSizer().Add(box, flag=wx.ALL | wx.EXPAND, border=0) self._plugins[plugin_id] = (button_id, box, txt_readme) self.Layout() self.Refresh()
def __init__(self): wx.Frame.__init__(self, None, -1, APP_TITLE, style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER) # 默认style是下列项的组合:wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX | wx.RESIZE_BORDER | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN self.SetBackgroundColour(wx.Colour(224,224,224)) self.SetSize((800, 600)) self.Center() if hasattr(sys, "frozen") and getattr(sys, "frozen"): exeName = win32api.GetModuleFileName(win32api.GetModuleHandle(None)) icon = wx.Icon(exeName, wx.BITMAP_TYPE_ICO) else: icon = wx.Icon(APP_ICON, wx.BITMAP_TYPE_ICO) self.SetIcon(icon) # left panelLeft = wx.BoxSizer(wx.VERTICAL) gridDatas = [] self.gridTable = wx.grid.Grid(self, -1, pos=(5,5), size=(400, 400), style=wx.WANTS_CHARS) self.infoTable = FileListGridTable(gridDatas) self.gridTable.SetTable(self.infoTable, True) self.gauge = wx.Gauge(self, range = 20, size = (250, 25), style = wx.GA_HORIZONTAL) panelLeft.Add(self.gridTable, 0, wx.EXPAND|wx.ALL, 5) panelLeft.Add(self.gauge, 0, wx.EXPAND|wx.ALL, 5) # right panelRight = wx.BoxSizer(wx.VERTICAL) btnOpenFiles = wx.Button(self, -1, u'Open', size=(50, 50)) btnOpenFiles.Bind(wx.EVT_BUTTON, self.OpenFiles) btnMoveUp = wx.Button(self, -1, u'↑', size=(50, 50)) btnMoveUp.Bind(wx.EVT_BUTTON, self.MoveUp) btnMoveDown = wx.Button(self, -1, u'↓', size=(50, 50)) btnMoveDown.Bind(wx.EVT_BUTTON, self.MoveDown) btnMerge = wx.Button(self, -1, u'Merge', size=(50,50)) btnMerge.Bind(wx.EVT_BUTTON, self.MergePDFFiles) btnClear = wx.Button(self, -1, u'Clear', size=(50,50)) btnClear.Bind(wx.EVT_BUTTON, self.ClearFiles) panelRight.Add(btnOpenFiles, 0, wx.ALL, 10) panelRight.Add(btnMoveUp, 0, wx.ALL, 10) panelRight.Add(btnMoveDown, 0, wx.ALL, 10) panelRight.Add(btnMerge, 0, wx.ALL, 10) panelRight.Add(btnClear, 0, wx.ALL, 10) mainBox = wx.BoxSizer(wx.HORIZONTAL) mainBox.Add(panelLeft, 1, wx.EXPAND|wx.LEFT|wx.TOP|wx.BOTTOM, 5) mainBox.Add(panelRight, 0, wx.EXPAND|wx.ALL, 20) self.Bind(wx.EVT_CLOSE, self.OnClose) self.Bind(wx.EVT_SIZE, self.OnResize) self.SetAutoLayout(True) self.SetSizer(mainBox) self.Layout() logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s') self.logger = logging.getLogger(__name__)
def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(1000, 500)) self.MainSizer = wx.BoxSizer(wx.VERTICAL) self.TopSizer = wx.BoxSizer(wx.HORIZONTAL) self.IdeenListe = wx.ListCtrl(self, style=wx.LC_REPORT | wx.LC_SINGLE_SEL) self.IdeenListe.InsertColumn(0, "Ideen") self.TopSizer.Add(self.IdeenListe, 0, wx.ALL | wx.EXPAND, 5) self.EintragSizer = wx.BoxSizer(wx.VERTICAL) self.EintragKopfSizer = wx.GridSizer(rows=4, cols=2, vgap=5, hgap=5) self.TitleStat = wx.StaticText(self, label="Titel") self.TitleText = wx.TextCtrl(self) self.TagsStat = wx.StaticText(self, label="Tags") self.TagsText = wx.TextCtrl(self) self.BeschreibungStat = wx.StaticText(self, label="Beschreibung") self.BeschreibungText = wx.TextCtrl(self) self.FarbeStat = wx.StaticText(self, label="Farbe") self.FarbButtonSizer = wx.BoxSizer(wx.HORIZONTAL) self.WhiteButton = wx.ToggleButton(self, label="White") self.WhiteButton.SetForegroundColour(wx.WHITE) self.GrayButton = wx.ToggleButton(self, label="Gray") self.GrayButton.SetForegroundColour(wx.LIGHT_GREY) self.YellowButton = wx.ToggleButton(self, label="Yellow") self.YellowButton.SetForegroundColour(wx.YELLOW) self.PinkButton = wx.ToggleButton(self, label="Pink") self.PinkButton.SetForegroundColour(wx.Colour(255, 0, 255)) self.FarbButtonSizer.Add(self.WhiteButton, 1, wx.ALL | wx.EXPAND) self.FarbButtonSizer.Add(self.GrayButton, 1, wx.ALL | wx.EXPAND) self.FarbButtonSizer.Add(self.YellowButton, 1, wx.ALL | wx.EXPAND) self.FarbButtonSizer.Add(self.PinkButton, 1, wx.ALL | wx.EXPAND) self.FarbButtonListe = {"white": self.WhiteButton, "gray": self.GrayButton, "yellow": self.YellowButton, "pink": self.PinkButton} self.EintragKopfSizer.Add(self.TitleStat, 0, wx.ALL | wx.EXPAND) self.EintragKopfSizer.Add(self.TagsStat, 0, wx.ALL | wx.EXPAND) self.EintragKopfSizer.Add(self.TitleText, 1, wx.ALL | wx.EXPAND) self.EintragKopfSizer.Add(self.TagsText, 1, wx.ALL | wx.EXPAND) self.EintragKopfSizer.Add(self.BeschreibungStat, 0, wx.ALL | wx.EXPAND) self.EintragKopfSizer.Add(self.FarbeStat, 0, wx.ALL | wx.EXPAND) self.EintragKopfSizer.Add(self.BeschreibungText, 1, wx.ALL | wx.EXPAND) self.EintragKopfSizer.Add(self.FarbButtonSizer, 1, wx.ALL | wx.EXPAND) self.EintragSizer.Add(self.EintragKopfSizer, 0, wx.ALL | wx.EXPAND) self.EintragLangText = wx.TextCtrl(self, style=wx.TE_MULTILINE) self.EintragSizer.Add(self.EintragLangText, 1, wx.ALL | wx.EXPAND) self.TopSizer.Add(self.EintragSizer, 1, wx.ALL | wx.EXPAND, 5) self.BottomSizer = wx.BoxSizer(wx.HORIZONTAL) self.PlusButton = wx.Button(self, label="+") self.MinusButton = wx.Button(self, label="-") self.SaveButton = wx.Button(self, label="Speichern") self.BottomSizer.Add(self.PlusButton, 0, wx.ALL) self.BottomSizer.Add(self.MinusButton, 0, wx.ALL) self.BottomSizer.AddStretchSpacer() self.BottomSizer.Add(self.SaveButton, 0, wx.ALL | wx.ALIGN_RIGHT) self.MainSizer.Add(self.TopSizer, 1, wx.ALL | wx.EXPAND) self.MainSizer.Add(self.BottomSizer, 0, wx.ALL | wx.EXPAND, 5) self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.showEntry, self.IdeenListe) self.Bind(wx.EVT_BUTTON, self.writeJson, self.SaveButton) for _, button in self.FarbButtonListe.items(): self.Bind(wx.EVT_TOGGLEBUTTON, self.toggleColor, button) self.Bind(wx.EVT_BUTTON, self.newEntry, self.PlusButton) self.NewEntryFlag = False self.SetSizer(self.MainSizer) self.Show() self.readJson(None)
def to_wxcolour(self): return wx.Colour(self.r, self.g, self.b, self.a)
def refresh(self, stuff): """ Displays fitting Sends data to d.Display.refresh where the rows and columns are set up, then does a bit of post-processing (colors) """ self.Freeze() d.Display.refresh(self, stuff) sFit = Fit.getInstance() fit = sFit.getFit(self.activeFitID) slotMap = {} # test for too many modules (happens with t3s / CCP change in slot layout) for slot in [e.value for e in FittingSlot]: slotMap[slot] = fit.getSlotsFree(slot) < 0 for i, mod in enumerate(self.mods): self.SetItemBackgroundColour(i, self.GetBackgroundColour()) # only consider changing color if we're dealing with a Module if isinstance(mod, Module): hasRestrictionOverriden = False if not mod.isEmpty: fits = mod.fits(fit, False) hasRestrictionOverriden = getattr(mod, 'restrictionOverridden', None) # If module had broken fitting restrictions but now doesn't, # ensure it is now valid, and remove restrictionOverridden # variable. More in #1519 if not fit.ignoreRestrictions and hasRestrictionOverriden: clean = False if fits: if not mod.hardpoint: clean = True elif fit.getHardpointsFree(mod.hardpoint) >= 0: clean = True if clean: del mod.restrictionOverridden hasRestrictionOverriden = not hasRestrictionOverriden if slotMap[ mod. slot] or hasRestrictionOverriden: # Color too many modules as red self.SetItemBackgroundColour(i, wx.Colour(204, 51, 51)) elif sFit.serviceFittingOptions[ "colorFitBySlot"]: # Color by slot it enabled self.SetItemBackgroundColour(i, self.slotColour(mod.slot)) # Set rack face to bold if isinstance(mod, Rack) and \ sFit.serviceFittingOptions["rackSlots"] and \ sFit.serviceFittingOptions["rackLabels"]: self.font.SetWeight(wx.FONTWEIGHT_BOLD) self.SetItemFont(i, self.font) else: self.font.SetWeight(wx.FONTWEIGHT_NORMAL) self.SetItemFont(i, self.font) self.Thaw() self.itemCount = self.GetItemCount()
def _init_ctrls(self, prnt): # generated method, don't edit wx.Dialog.__init__(self, id=wxID_DLGCREATEDD, name='dlgCreateDD', parent=prnt, pos=wx.Point(500, 118), size=wx.Size(437, 529), style=wx.DEFAULT_DIALOG_STYLE, title='RawImage') self.SetClientSize(wx.Size(429, 495)) self.SetAutoLayout(True) self.SetBackgroundColour(wx.Colour(125, 152, 221)) self.SetCursor(wx.STANDARD_CURSOR) self.SetMinSize(wx.Size(-1, -1)) self.Center(wx.BOTH) self.NoteBookAssessment = wx.Notebook( id=wxID_DLGCREATEDDNOTEBOOKASSESSMENT, name='NoteBookAssessment', parent=self, pos=wx.Point(16, 48), size=wx.Size(400, 400), style=0) self.NoteBookAssessment.SetBackgroundColour(wx.Colour(125, 152, 221)) self.NoteBookAssessment.SetAutoLayout(True) self.lblProjectName = wx.StaticText( id=wxID_DLGCREATEDDLBLPROJECTNAME, label='Create Raw DD Image ', name='lblProjectName', parent=self, pos=wx.Point(0, 0), size=wx.Size(430, 32), style=wx.ALIGN_RIGHT | wx.RAISED_BORDER | wx.ST_NO_AUTORESIZE) self.lblProjectName.SetFont( wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False, 'Tahoma')) self.lblProjectName.SetForegroundColour(wx.Colour(0, 78, 155)) self.lblProjectName.SetBackgroundColour(wx.Colour(215, 235, 255)) self.panEvidence = wx.Panel(id=wxID_DLGCREATEDDPANEVIDENCE, name='panEvidence', parent=self.NoteBookAssessment, pos=wx.Point(0, 0), size=wx.Size(392, 374), style=wx.TAB_TRAVERSAL) self.panEvidence.SetBackgroundColour(wx.Colour(225, 236, 255)) self.btnOK = wx.Button(id=wxID_DLGCREATEDDBTNOK, label=u'&OK', name=u'btnOK', parent=self, pos=wx.Point(256, 456), size=wx.Size(75, 23), style=0) self.btnOK.Bind(wx.EVT_BUTTON, self.OnBtnOKButton, id=wxID_DLGCREATEDDBTNOK) self.btnCancel = wx.Button(id=wxID_DLGCREATEDDBTNCANCEL, label=u'&Cancel', name=u'btnCancel', parent=self, pos=wx.Point(336, 456), size=wx.Size(75, 23), style=0) self.btnCancel.Bind(wx.EVT_BUTTON, self.OnBtnCancelButton, id=wxID_DLGCREATEDDBTNCANCEL) self.choiceSourceType = wx.Choice(choices=[ r'Select One...', r'Physical Drive', r'Logical Drive', r'Contents of a Folder' ], id=wxID_DLGCREATEDDCHOICESOURCETYPE, name='choiceSourceType', parent=self.panEvidence, pos=wx.Point(24, 32), size=wx.Size(192, 21), style=0) self.choiceSourceType.SetSelection(0) self.choiceSourceType.Bind(wx.EVT_CHOICE, self.OnChoiceSourceTypeChoice, id=wxID_DLGCREATEDDCHOICESOURCETYPE) self.lstDestinations = wx.ListCtrl(id=wxID_DLGCREATEDDLSTDESTINATIONS, name='lstDestinations', parent=self.panEvidence, pos=wx.Point(16, 192), size=wx.Size(360, 72), style=wx.LC_LIST | wx.HSCROLL | wx.LC_SINGLE_SEL | wx.VSCROLL) self.staticBox1 = wx.StaticBox(id=wxID_DLGCREATEDDSTATICBOX1, label='Select Evidence Source Type:', name='staticBox1', parent=self.panEvidence, pos=wx.Point(8, 8), size=wx.Size(376, 64), style=0) self.staticBox2 = wx.StaticBox( id=wxID_DLGCREATEDDSTATICBOX2, label='Select from the following available source:', name='staticBox2', parent=self.panEvidence, pos=wx.Point(8, 80), size=wx.Size(376, 80), style=0) self.staticBox3 = wx.StaticBox(id=wxID_DLGCREATEDDSTATICBOX3, label='Image Destination(s)', name='staticBox3', parent=self.panEvidence, pos=wx.Point(8, 168), size=wx.Size(376, 136), style=0) self.btnAddDestination = wx.Button( id=wxID_DLGCREATEDDBTNADDDESTINATION, label='Add...', name='btnAddDestination', parent=self.panEvidence, pos=wx.Point(208, 272), size=wx.Size(75, 23), style=0) self.btnAddDestination.Bind(wx.EVT_BUTTON, self.OnBtnAddDestinationButton, id=wxID_DLGCREATEDDBTNADDDESTINATION) self.btnDeleteDestination = wx.Button( id=wxID_DLGCREATEDDBTNDELETEDESTINATION, label=u'Delete', name=u'btnDeleteDestination', parent=self.panEvidence, pos=wx.Point(296, 272), size=wx.Size(75, 23), style=0) self.btnDeleteDestination.Enable(True) self.btnDeleteDestination.Bind(wx.EVT_BUTTON, self.OnBtnDeleteDestinationButton, id=wxID_DLGCREATEDDBTNDELETEDESTINATION) self.chkVerifyImages = wx.CheckBox( id=wxID_DLGCREATEDDCHKVERIFYIMAGES, label=u'Verify images after they are created', name='chkVerifyImages', parent=self.panEvidence, pos=wx.Point(16, 328), size=wx.Size(216, 13), style=0) self.chkVerifyImages.SetValue(True) self._init_coll_NoteBookAssessment_Pages(self.NoteBookAssessment)
def __init__(self, *args, **varargs): varargs["title"] = "Regular expression editor" super(RegexpDialog, self).__init__(*args, **varargs) self.__value = "Not initialized" self.__test_text = "Not initialized" self.__guesses = RE_FILENAME_GUESSES font = wx.Font(10, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) self.font = font self.error_font = font sizer = wx.BoxSizer(wx.VERTICAL) hsizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(hsizer, 0, wx.GROW | wx.ALL, 5) hsizer.Add(wx.StaticText(self, label="Regex:"), 0, wx.ALIGN_CENTER | wx.ALL, 5) self.regexp_display = wx.stc.StyledTextCtrl(self, -1, style=wx.BORDER_SIMPLE) self.regexp_display.SetBufferedDraw(True) o = self.regexp_display.GetFullTextExtent("".join(["M"] * 50)) w, h = self.regexp_display.ClientToWindowSize(wx.Size(o[1], o[2])) self.regexp_display.SetMinSize(wx.Size(w, h)) self.regexp_display.Text = self.value self.regexp_display.SetLexer(wx.stc.STC_LEX_CONTAINER) for key in range(31): self.regexp_display.StyleSetFont(key, self.font) self.regexp_display.StyleSetForeground(TOK_ORDINARY, wx.Colour(0, 0, 0, 255)) self.regexp_display.StyleSetForeground(TOK_ESCAPE, wx.Colour(0, 64, 64, 255)) self.regexp_display.StyleSetForeground(TOK_GROUP, wx.Colour(0, 0, 255, 255)) self.regexp_display.StyleSetForeground(TOK_REPEAT, wx.Colour(0, 128, 0, 255)) self.regexp_display.StyleSetForeground(TOK_BRACKET_EXP, wx.Colour(64, 64, 64, 255)) self.regexp_display.StyleSetForeground(TOK_SPECIAL, wx.Colour(128, 64, 0, 255)) color_db = self.get_color_db() for i in range(1, 16): self.regexp_display.StyleSetForeground(TOK_DEFINITION - 1 + i, color_db[i % len(color_db)]) self.regexp_display.StyleSetForeground(STYLE_ERROR, wx.Colour(255, 64, 128, 255)) self.regexp_display.StyleSetFont(34, self.font) self.regexp_display.StyleSetForeground(34, wx.Colour(0, 0, 255, 255)) self.regexp_display.StyleSetUnderline(34, True) self.regexp_display.StyleSetFont(35, self.font) self.regexp_display.StyleSetForeground(35, wx.Colour(255, 0, 0, 255)) self.regexp_display.SetUseVerticalScrollBar(0) self.regexp_display.SetUseHorizontalScrollBar(0) self.regexp_display.SetMarginWidth(wx.stc.STC_MARGIN_NUMBER, 0) self.regexp_display.SetMarginWidth(wx.stc.STC_MARGIN_SYMBOL, 0) hsizer.Add(self.regexp_display, 1, wx.EXPAND | wx.ALL, 5) hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(wx.StaticText(self, label="Test text:"), 0, wx.ALIGN_CENTER | wx.ALL, 5) self.test_text_ctl = wx.TextCtrl(self, value=self.__test_text) self.test_text_ctl.Font = self.font hsizer.Add(self.test_text_ctl, 1, wx.ALIGN_CENTER | wx.ALL, 5) sizer.Add(hsizer, 0, wx.GROW | wx.ALL, 5) style = wx.NO_BORDER self.test_display = wx.stc.StyledTextCtrl(self, -1, style=style) self.test_display.SetLexer(wx.stc.STC_LEX_CONTAINER) self.test_display.StyleClearAll() self.test_display.StyleSetFont(STYLE_NO_MATCH, self.font) self.test_display.StyleSetForeground(STYLE_NO_MATCH, wx.Colour(128, 128, 128, 255)) color_db = self.get_color_db() for i in range(16): self.test_display.StyleSetFont(STYLE_FIRST_LABEL - 1 + i, self.font) self.test_display.StyleSetForeground(STYLE_FIRST_LABEL - 1 + i, color_db[i % len(color_db)]) self.test_display.StyleSetFont(STYLE_ERROR, self.error_font) self.test_display.StyleSetForeground(STYLE_ERROR, wx.Colour(255, 0, 0, 255)) self.test_display.Text = self.__test_text self.test_display.SetReadOnly(True) self.test_display.SetUseVerticalScrollBar(0) self.test_display.SetUseHorizontalScrollBar(0) self.test_display.SetMarginWidth(wx.stc.STC_MARGIN_NUMBER, 0) self.test_display.SetMarginWidth(wx.stc.STC_MARGIN_SYMBOL, 0) text_extent = self.test_display.GetFullTextExtent(self.__test_text) self.test_display.SetSizeHints(100, text_extent[1] + 3, maxH=text_extent[1] + 3) self.test_display.Enable(False) sizer.Add(self.test_display, 0, wx.EXPAND | wx.ALL, 5) line = wx.StaticLine(self, -1, size=(20, -1), style=wx.LI_HORIZONTAL) sizer.Add(line, 0, wx.GROW | wx.RIGHT | wx.LEFT, 5) hsizer = wx.StdDialogButtonSizer() guess_button = wx.Button(self, label="Guess") hsizer.Add(guess_button, 0) ok_button = wx.Button(self, label="Submit") ok_button.SetDefault() hsizer.Add(ok_button, 0, wx.LEFT, 5) cancel_button = wx.Button(self, label="Cancel") hsizer.Add(cancel_button, 0, wx.LEFT, 5) hsizer.Realize() sizer.Add(hsizer, 0, wx.ALIGN_RIGHT | wx.ALL, 5) self.Bind(wx.EVT_BUTTON, self.on_guess, guess_button) self.Bind(wx.EVT_BUTTON, self.on_ok_button, ok_button) self.Bind(wx.EVT_BUTTON, self.on_cancel_button, cancel_button) self.Bind(wx.EVT_TEXT, self.on_test_text_text_change, self.test_text_ctl) self.Bind(wx.stc.EVT_STC_CHANGE, self.on_editor_text_change, self.regexp_display) self.Bind(wx.stc.EVT_STC_STYLENEEDED, self.on_style_needed, self.regexp_display) self.regexp_display.Bind(wx.EVT_KEY_DOWN, self.on_regexp_key) self.SetSizer(sizer) self.Fit()
def Remplissage(self): listeChamps = [ "{SIGNATAIRE_GENRE}", "{SIGNATAIRE_NOM}", "{SIGNATAIRE_FONCTION}", "{NUM_ATTESTATION}", "{DATE_DEBUT}", "{DATE_FIN}", "{DATE_EDITION}", "{LIEU_EDITION}", "{NOMS_INDIVIDUS}", "{DESTINATAIRE_NOM}", "{DESTINATAIRE_RUE}", "{DESTINATAIRE_VILLE}", "{TOTAL_PERIODE}", "{TOTAL_REGLE}", "{SOLDE_DU}", "{ORGANISATEUR_NOM}", "{ORGANISATEUR_RUE}", "{ORGANISATEUR_CP}", "{ORGANISATEUR_VILLE}", "{ORGANISATEUR_TEL}", "{ORGANISATEUR_FAX}", "{ORGANISATEUR_MAIL}", "{ORGANISATEUR_SITE}", "{ORGANISATEUR_AGREMENT}", "{ORGANISATEUR_SIRET}", "{ORGANISATEUR_APE}", ] # Catégorie self.Append(wxpg.PropertyCategory(_(u"Modèle"))) propriete = wxpg.EnumProperty(label=_(u"Modèle de document"), name="IDmodele", value=0) propriete.SetHelpString( _(u"Sélectionnez le modèle de document à utiliser")) propriete.SetEditor("EditeurComboBoxAvecBoutons") propriete.SetAttribute("obligatoire", True) self.Append(propriete) self.MAJ_modeles() # Catégorie self.Append(wxpg.PropertyCategory(_(u"Signataire"))) propriete = wxpg.EnumProperty(label=_(u"Signataire du document"), name="signataire", value=0) propriete.SetHelpString( _(u"Sélectionnez le signataire du document (à renseigner au préalable dans le paramétrage de l'activité)" )) propriete.SetAttribute("obligatoire", True) propriete.SetAttribute("reinitialisation_interdite", True) self.Append(propriete) self.MAJ_signataires() # Catégorie self.Append(wxpg.PropertyCategory(_(u"Mémorisation"))) # Mémorisation des paramètres propriete = wxpg.BoolProperty(label=_(u"Mémoriser les paramètres"), name="memoriser_parametres", value=True) propriete.SetHelpString( _(u"Cochez cette case si vous souhaitez mémoriser les paramètres de cette liste" )) propriete.SetAttribute("UseCheckbox", True) self.Append(propriete) # Répertoire de sauvegarde if 'phoenix' in wx.PlatformInfo: propriete = wxpg.DirProperty( name=_(u"Répertoire pour copie unique"), label="repertoire_copie", value="") else: propriete = wxpg.DirProperty( label=_(u"Répertoire pour copie unique"), name="repertoire_copie", value="") propriete.SetHelpString( _(u"Enregistrer une copie unique de chaque document dans le répertoire sélectionné. Sinon laissez vide ce champ." )) self.Append(propriete) # Catégorie self.Append(wxpg.PropertyCategory(_(u"Titre"))) # Afficher le titre propriete = wxpg.BoolProperty(label=_(u"Afficher le titre"), name="afficher_titre", value=True) propriete.SetHelpString( _(u"Cochez cette case si vous souhaitez afficher le titre du le document" )) propriete.SetAttribute("UseCheckbox", True) self.Append(propriete) propriete = wxpg.StringProperty(label=_(u"Titre du document"), name="texte_titre", value=_(u"Attestation de présence")) propriete.SetHelpString( _(u"Saisissez le titre du document (Par défaut 'Attestation de présence'). Vous pouvez intégrer les mots-clés suivants : %s" ) % ", ".join(listeChamps)) propriete.SetAttribute("obligatoire", True) self.Append(propriete) propriete = wxpg.IntProperty(label=_(u"Taille de texte du titre"), name="taille_texte_titre", value=19) propriete.SetHelpString( _(u"Saisissez la taille de texte du titre (29 par défaut)")) propriete.SetAttribute("obligatoire", True) self.Append(propriete) self.SetPropertyEditor("taille_texte_titre", "SpinCtrl") propriete = wxpg.BoolProperty( label=_(u"Afficher la période de facturation"), name="afficher_periode", value=True) propriete.SetHelpString( _(u"Cochez cette case si vous souhaitez afficher la période de facturation dans le document" )) propriete.SetAttribute("UseCheckbox", True) self.Append(propriete) propriete = wxpg.IntProperty( label=_(u"Taille de texte de la période"), name="taille_texte_periode", value=8) propriete.SetHelpString( _(u"Saisissez la taille de texte de la période (8 par défaut)")) propriete.SetAttribute("obligatoire", True) self.Append(propriete) self.SetPropertyEditor("taille_texte_periode", "SpinCtrl") # Catégorie self.Append(wxpg.PropertyCategory(_(u"Tableau des prestations"))) # Affichage condensé ou détaillé propriete = wxpg.EnumProperty( label=_(u"Affichage des prestations"), name="affichage_prestations", labels=[_(u"Détaillé"), _(u"Condensé")], values=[0, 1], value=0) propriete.SetHelpString(_(u"Sélectionnez un type d'affichage")) propriete.SetAttribute("obligatoire", True) self.Append(propriete) # Intitulés des prestations labels = [ _(u"Intitulé original"), _(u"Intitulé original + état 'Absence injustifiée'"), _(u"Nom du tarif"), _(u"Nom de l'activité") ] propriete = wxpg.EnumProperty(label=_(u"Intitulés des prestations"), name="intitules", labels=labels, values=[0, 1, 2, 3], value=0) propriete.SetHelpString( _(u"Sélectionnez le type d'intitulé à afficher pour les prestations" )) propriete.SetAttribute("obligatoire", True) self.Append(propriete) # Couleur 1 propriete = wxpg.ColourProperty(label=_(u"Couleur de fond 1"), name="couleur_fond_1", value=wx.Colour(204, 204, 255)) propriete.SetHelpString(_(u"Sélectionnez la couleur 1")) propriete.SetAttribute("obligatoire", True) self.Append(propriete) # Couleur 2 propriete = wxpg.ColourProperty(label=_(u"Couleur de fond 2"), name="couleur_fond_2", value=wx.Colour(234, 234, 255)) propriete.SetHelpString(_(u"Sélectionnez la couleur 2")) propriete.SetAttribute("obligatoire", True) self.Append(propriete) # Largeur colonne Date propriete = wxpg.IntProperty( label=_(u"Largeur de la colonne Date (ou Qté)"), name="largeur_colonne_date", value=50) propriete.SetHelpString( _(u"Saisissez la largeur de la colonne Date (50 par défaut)")) propriete.SetAttribute("obligatoire", True) self.Append(propriete) self.SetPropertyEditor("largeur_colonne_date", "SpinCtrl") # Largeur colonne Montant HT propriete = wxpg.IntProperty( label=_(u"Largeur de la colonne Montant HT"), name="largeur_colonne_montant_ht", value=50) propriete.SetHelpString( _(u"Saisissez la largeur de la colonne Montant HT (50 par défaut)" )) propriete.SetAttribute("obligatoire", True) self.Append(propriete) self.SetPropertyEditor("largeur_colonne_montant_ht", "SpinCtrl") # Largeur colonne Montant TVA propriete = wxpg.IntProperty( label=_(u"Largeur de la colonne Montant TVA"), name="largeur_colonne_montant_tva", value=50) propriete.SetHelpString( _(u"Saisissez la largeur de la colonne Montant TVA (50 par défaut)" )) propriete.SetAttribute("obligatoire", True) self.Append(propriete) self.SetPropertyEditor("largeur_colonne_montant_tva", "SpinCtrl") # Largeur colonne Montant TTC propriete = wxpg.IntProperty( label=_(u"Largeur de la colonne Montant TTC"), name="largeur_colonne_montant_ttc", value=70) propriete.SetHelpString( _(u"Saisissez la largeur de la colonne Montant TTC (70 par défaut)" )) propriete.SetAttribute("obligatoire", True) self.Append(propriete) self.SetPropertyEditor("largeur_colonne_montant_ttc", "SpinCtrl") # Taille de texte du nom de l'individu propriete = wxpg.IntProperty(label=_(u"Taille de texte de l'individu"), name="taille_texte_individu", value=9) propriete.SetHelpString( _(u"Saisissez la taille de texte de l'individu (9 par défaut)")) propriete.SetAttribute("obligatoire", True) self.Append(propriete) self.SetPropertyEditor("taille_texte_individu", "SpinCtrl") # Taille de texte du nom de l'activité propriete = wxpg.IntProperty( label=_(u"Taille de texte de l'activité"), name="taille_texte_activite", value=6) propriete.SetHelpString( _(u"Saisissez la taille de texte de l'activité (6 par défaut)")) propriete.SetAttribute("obligatoire", True) self.Append(propriete) self.SetPropertyEditor("taille_texte_activite", "SpinCtrl") # Taille de texte des noms de colonnes propriete = wxpg.IntProperty( label=_(u"Taille de texte des noms de colonnes"), name="taille_texte_noms_colonnes", value=5) propriete.SetHelpString( _(u"Saisissez la taille de texte des noms de colonnes (5 par défaut)" )) propriete.SetAttribute("obligatoire", True) self.Append(propriete) self.SetPropertyEditor("taille_texte_noms_colonnes", "SpinCtrl") # Taille de texte des prestations propriete = wxpg.IntProperty( label=_(u"Taille de texte des prestations"), name="taille_texte_prestation", value=7) propriete.SetHelpString( _(u"Saisissez la taille de texte des prestations (7 par défaut)")) propriete.SetAttribute("obligatoire", True) self.Append(propriete) self.SetPropertyEditor("taille_texte_prestation", "SpinCtrl") # Taille de texte des messages propriete = wxpg.IntProperty(label=_(u"Taille de texte des messages"), name="taille_texte_messages", value=7) propriete.SetHelpString( _(u"Saisissez la taille de texte des messages (7 par défaut)")) propriete.SetAttribute("obligatoire", True) self.Append(propriete) self.SetPropertyEditor("taille_texte_messages", "SpinCtrl") # Taille de texte des labels totaux propriete = wxpg.IntProperty( label=_(u"Taille de texte des labels totaux"), name="taille_texte_labels_totaux", value=9) propriete.SetHelpString( _(u"Saisissez la taille de texte des labels totaux (9 par défaut)" )) propriete.SetAttribute("obligatoire", True) self.Append(propriete) self.SetPropertyEditor("taille_texte_labels_totaux", "SpinCtrl") # Taille de texte des totaux propriete = wxpg.IntProperty( label=_(u"Taille de texte des montants totaux"), name="taille_texte_montants_totaux", value=10) propriete.SetHelpString( _(u"Saisissez la taille de texte des montants totaux (10 par défaut)" )) propriete.SetAttribute("obligatoire", True) self.Append(propriete) self.SetPropertyEditor("taille_texte_montants_totaux", "SpinCtrl") # Catégorie self.Append(wxpg.PropertyCategory(_(u"Prestations antérieures"))) # Taille de texte propriete = wxpg.IntProperty( label=_(u"Taille de texte du commentaire"), name="taille_texte_prestations_anterieures", value=5) propriete.SetHelpString( _(u"Saisissez la taille de texte du commentaire de bas de tableaux (5 par défaut)" )) propriete.SetAttribute("obligatoire", True) self.Append(propriete) self.SetPropertyEditor("taille_texte_prestations_anterieures", "SpinCtrl") # Texte d'information propriete = wxpg.LongStringProperty( label=_(u"Texte d'information"), name="texte_prestations_anterieures", value= _(u"Des prestations antérieures ont été reportées sur cette attestation." )) propriete.SetHelpString( _(u"Saisissez un texte d'information pour les prestations antérieures" )) self.Append(propriete) # Catégorie self.Append(wxpg.PropertyCategory(_(u"Texte d'introduction"))) propriete = wxpg.LongStringProperty(label=_(u"Texte d'introduction"), name="texte_introduction", value=TEXTE_INTRO) propriete.SetHelpString( _(u"Saisissez un texte d'introduction. Vous pouvez intégrer les mots-clés suivants : %s" ) % ", ".join(listeChamps)) self.Append(propriete) propriete = wxpg.IntProperty( label=_(u"Taille de texte d'introduction"), name="taille_texte_introduction", value=9) propriete.SetHelpString( _(u"Saisissez la taille de texte d'introduction (9 par défaut)")) propriete.SetAttribute("obligatoire", True) self.Append(propriete) self.SetPropertyEditor("taille_texte_introduction", "SpinCtrl") propriete = wxpg.EnumProperty(label=_(u"Style de texte introduction"), name="style_texte_introduction", labels=[ _(u"Normal"), _(u"Italique"), "Gras", _(u"Italique + Gras") ], values=[0, 1, 2, 3], value=1) propriete.SetHelpString(_(u"Sélectionnez un style de texte")) propriete.SetAttribute("obligatoire", True) self.Append(propriete) propriete = wxpg.ColourProperty( label=_(u"Couleur de fond introduction"), name="couleur_fond_introduction", value=wx.Colour(255, 255, 255)) propriete.SetHelpString( _(u"Sélectionnez une couleur de fond pour le texte d'introduction" )) propriete.SetAttribute("obligatoire", True) self.Append(propriete) propriete = wxpg.ColourProperty( label=_(u"Couleur de bord introduction"), name="couleur_bord_introduction", value=wx.Colour(255, 255, 255)) propriete.SetHelpString( _(u"Sélectionnez une couleur de bord pour le texte d'introduction" )) propriete.SetAttribute("obligatoire", True) self.Append(propriete) propriete = wxpg.EnumProperty( label=_(u"Alignement du texte d'introduction"), name="alignement_texte_introduction", labels=[_(u"Gauche"), _(u"Centre"), _(u"Droite")], values=[0, 1, 2], value=1) propriete.SetHelpString( _(u"Sélectionnez un type d'alignement pour le texte d'introduction" )) self.Append(propriete) # Catégorie self.Append(wxpg.PropertyCategory(_(u"Texte de conclusion"))) propriete = wxpg.LongStringProperty(label=_(u"Texte de conclusion"), name="texte_conclusion", value=u"") propriete.SetHelpString( _(u"Saisissez un texte de conclusion (Aucun par défaut). Vous pouvez intégrer les mots-clés suivants : %s" ) % ", ".join(listeChamps)) self.Append(propriete) propriete = wxpg.IntProperty(label=_(u"Taille de texte de conclusion"), name="taille_texte_conclusion", value=9) propriete.SetHelpString( _(u"Saisissez la taille de texte de conclusion (9 par défaut)")) propriete.SetAttribute("obligatoire", True) self.Append(propriete) self.SetPropertyEditor("taille_texte_conclusion", "SpinCtrl") propriete = wxpg.EnumProperty(label=_(u"Style de texte conclusion"), name="style_texte_conclusion", labels=[ _(u"Normal"), _(u"Italique"), "Gras", _(u"Italique + Gras") ], values=[0, 1, 2, 3], value=0) propriete.SetHelpString(_(u"Sélectionnez un style de texte")) propriete.SetAttribute("obligatoire", True) self.Append(propriete) propriete = wxpg.ColourProperty(label=_(u"Couleur de fond conclusion"), name="couleur_fond_conclusion", value=wx.Colour(255, 255, 255)) propriete.SetHelpString( _(u"Sélectionnez une couleur de fond pour le texte de conclusion") ) propriete.SetAttribute("obligatoire", True) self.Append(propriete) propriete = wxpg.ColourProperty(label=_(u"Couleur de bord conclusion"), name="couleur_bord_conclusion", value=wx.Colour(255, 255, 255)) propriete.SetHelpString( _(u"Sélectionnez une couleur de bord pour le texte de conclusion") ) propriete.SetAttribute("obligatoire", True) self.Append(propriete) propriete = wxpg.EnumProperty( label=_(u"Alignement du texte de conclusion"), name="alignement_texte_conclusion", labels=[_(u"Gauche"), _(u"Centre"), _(u"Droite")], values=[0, 1, 2], value=0) propriete.SetHelpString( _(u"Sélectionnez un type d'alignement pour le texte de conclusion" )) self.Append(propriete) # Signature self.Append(wxpg.PropertyCategory(_(u"Signature"))) propriete = wxpg.ImageFileProperty(label=_(u"Image de signature"), name="image_signature") propriete.SetHelpString( _(u"Sélectionnez l'image d'une signature à insérer en fin de document" )) self.Append(propriete) propriete = wxpg.IntProperty(label=_(u"Taille de l'image (en %)"), name="taille_image_signature", value=100) propriete.SetHelpString( _(u"Saisissez la taille de l'image en pourcentage (100 par défaut)" )) propriete.SetAttribute("obligatoire", True) self.Append(propriete) self.SetPropertyEditor("taille_image_signature", "SpinCtrl") propriete = wxpg.EnumProperty( label=_(u"Alignement de l'image"), name="alignement_image_signature", labels=[_(u"Gauche"), _(u"Centre"), _(u"Droite")], values=[0, 1, 2], value=0) propriete.SetHelpString( _(u"Sélectionnez un type d'alignement pour l'image de signature")) self.Append(propriete)
def MakeSnapshot(self, maxColumns=1337): if self.FVsnapshot: self.FVsnapshot = None tbmp = wx.Bitmap(16, 16) tdc = wx.MemoryDC() tdc.SelectObject(tbmp) tdc.SetFont(self.font) columnsWidths = [] for i in range(len(self.DEFAULT_COLS)): columnsWidths.append(0) sFit = Fit.getInstance() try: fit = sFit.getFit(self.activeFitID) except Exception as e: pyfalog.critical("Failed to get fit") pyfalog.critical(e) return if fit is None: return slotMap = {} for slot in [e.value for e in FittingSlot]: slotMap[slot] = fit.getSlotsFree(slot) < 0 padding = 2 isize = 16 headerSize = max(isize, tdc.GetTextExtent("W")[0]) + padding * 2 maxRowHeight = isize rows = 0 for st in self.mods: for i, col in enumerate(self.activeColumns): if i > maxColumns: break name = col.getText(st) if not isinstance(name, str): name = "" nx, ny = tdc.GetTextExtent(name) imgId = col.getImageId(st) cw = 0 if imgId != -1: cw += isize + padding if name != "": cw += nx + 4 * padding if imgId == -1 and name == "": cw += isize + padding maxRowHeight = max(ny, maxRowHeight) columnsWidths[i] = max(columnsWidths[i], cw) rows += 1 render = wx.RendererNative.Get() # Fix column widths (use biggest between header or items) for i, col in enumerate(self.activeColumns): if i > maxColumns: break name = col.columnText imgId = col.imageId if not isinstance(name, str): name = "" opts = wx.HeaderButtonParams() if name != "": opts.m_labelText = name if imgId != -1: opts.m_labelBitmap = wx.Bitmap(isize, isize) width = render.DrawHeaderButton(self, tdc, (0, 0, 16, 16), sortArrow=wx.HDR_SORT_ICON_NONE, params=opts) columnsWidths[i] = max(columnsWidths[i], width) tdc.SelectObject(wx.NullBitmap) maxWidth = padding * 2 for i in range(len(self.DEFAULT_COLS)): if i > maxColumns: break maxWidth += columnsWidths[i] mdc = wx.MemoryDC() mbmp = wx.Bitmap(maxWidth, maxRowHeight * rows + padding * 4 + headerSize) mdc.SelectObject(mbmp) mdc.SetBackground(wx.Brush(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW))) mdc.Clear() mdc.SetFont(self.font) mdc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)) cx = padding for i, col in enumerate(self.activeColumns): if i > maxColumns: break name = col.columnText imgId = col.imageId if not isinstance(name, str): name = "" opts = wx.HeaderButtonParams() opts.m_labelAlignment = wx.ALIGN_LEFT if name != "": opts.m_labelText = name if imgId != -1: bmp = col.bitmap opts.m_labelBitmap = bmp render.DrawHeaderButton(self, mdc, (cx, padding, columnsWidths[i], headerSize), wx.CONTROL_CURRENT, sortArrow=wx.HDR_SORT_ICON_NONE, params=opts) cx += columnsWidths[i] brush = wx.Brush(wx.Colour(224, 51, 51)) pen = wx.Pen(wx.Colour(224, 51, 51)) mdc.SetPen(pen) mdc.SetBrush(brush) cy = padding * 2 + headerSize for st in self.mods: cx = padding if slotMap[st.slot]: mdc.DrawRectangle(cx, cy, maxWidth - cx, maxRowHeight) for i, col in enumerate(self.activeColumns): if i > maxColumns: break name = col.getText(st) if not isinstance(name, str): name = "" imgId = col.getImageId(st) tcx = cx if imgId != -1: self.imageList.Draw(imgId, mdc, cx, cy, wx.IMAGELIST_DRAW_TRANSPARENT, False) tcx += isize + padding if name != "": nx, ny = mdc.GetTextExtent(name) rect = wx.Rect() rect.top = cy rect.left = cx + 2 * padding rect.width = nx rect.height = maxRowHeight + padding mdc.DrawLabel(name, rect, wx.ALIGN_CENTER_VERTICAL) tcx += nx + padding cx += columnsWidths[i] cy += maxRowHeight mdc.SelectObject(wx.NullBitmap) self.FVsnapshot = mbmp
def cachePaint(self, size): """ Caches the widget so self.paintBuffer is up-to-date. """ def wordWrap(text, lineWidth, gc): """ Returns a list of lines from a string This is somewhat based on the wordwrap function built into wx.lib. (For some reason, GraphicsContext.GetPartialTextExtents() is returning totally wrong numbers but GetTextExtent() works fine.) This assumes that you've already set up the font you want on the GC. It gloms multiple spaces together, but for our purposes that's ok. """ words = re.finditer('\S+\s*', text.replace('\r', '')) lines = '' currentLine = '' for w in words: word = w.group(0) wordWidth = gc.GetTextExtent(currentLine + word)[0] if wordWidth < lineWidth: currentLine += word if '\n' in word: lines += currentLine currentLine = '' else: lines += currentLine + '\n' currentLine = word lines += currentLine return lines.split('\n') # Which set of colors to use flat = self.app.config.ReadBool('flatDesign') colors = PassageWidget.FLAT_COLORS if flat else PassageWidget.COLORS def dim(c, dim, flat=flat): """Lowers a color's alpha if dim is true.""" if isinstance(c, wx.Colour): c = list(c.Get(includeAlpha=True)) elif type(c) is str: c = list(ord(a) for a in c[1:].decode('hex')) else: c = list(c) if len(c) < 4: c.append(255) if dim: a = PassageWidget.FLAT_DIMMED_ALPHA if flat else PassageWidget.DIMMED_ALPHA if not self.app.config.ReadBool('fastStoryPanel'): c[3] *= a else: c[0] *= a c[1] *= a c[2] *= a return wx.Colour(*[int(i) for i in c]) # set up our buffer bitmap = wx.Bitmap(size.width, size.height) self.paintBuffer.SelectObject(bitmap) # switch to a GraphicsContext as necessary gc = self.paintBuffer if self.app.config.ReadBool( 'fastStoryPanel') else wx.GraphicsContext.Create(self.paintBuffer) # text font sizes # wxWindows works with points, so we need to doublecheck on actual pixels titleFontSize = self.parent.toPixels((metrics.size('widgetTitle'), -1), scaleOnly=True)[0] titleFontSize = sorted((metrics.size('fontMin'), titleFontSize, metrics.size('fontMax')))[1] excerptFontSize = sorted((metrics.size('fontMin'), titleFontSize * 0.9, metrics.size('fontMax')))[1] if self.app.config.ReadBool('flatDesign'): titleFont = wx.Font(titleFontSize, wx.SWISS, wx.NORMAL, wx.LIGHT, False, 'Arial') excerptFont = wx.Font(excerptFontSize, wx.SWISS, wx.NORMAL, wx.LIGHT, False, 'Arial') else: titleFont = wx.Font(titleFontSize, wx.SWISS, wx.NORMAL, wx.BOLD, False, 'Arial') excerptFont = wx.Font(excerptFontSize, wx.SWISS, wx.NORMAL, wx.NORMAL, False, 'Arial') titleFontHeight = math.fabs(titleFont.GetPixelSize()[1]) excerptFontHeight = math.fabs(excerptFont.GetPixelSize()[1]) tagBarColor = dim( tuple(i * 256 for i in colorsys.hsv_to_rgb( 0.14 + math.sin(hash("".join(self.passage.tags))) * 0.08, 0.58 if flat else 0.28, 0.88)), self.dimmed) tags = set( self.passage.tags) - (tiddlywiki.TiddlyWiki.INFO_TAGS | self.getHeader().invisiblePassageTags()) # inset for text (we need to know this for layout purposes) inset = titleFontHeight / 3 # frame if self.passage.isAnnotation(): frameColor = colors['frame'] c = wx.Colour(*colors['annotation']) frameInterior = (c, c) else: frameColor = dim(colors['frame'], self.dimmed) frameInterior = (dim(colors['bodyStart'], self.dimmed), dim(colors['bodyEnd'], self.dimmed)) if not flat: gc.SetPen(wx.Pen(frameColor, 1)) if isinstance(gc, wx.GraphicsContext): gc.SetBrush(gc.CreateLinearGradientBrush(0, 0, 0, size.height, \ frameInterior[0], frameInterior[1])) else: gc.GradientFillLinear(wx.Rect(0, 0, size.width - 1, size.height - 1), \ frameInterior[0], frameInterior[1], wx.SOUTH) gc.SetBrush(wx.TRANSPARENT_BRUSH) gc.DrawRectangle(0, 0, size.width - 1, size.height - 1) else: gc.SetPen(wx.Pen(frameInterior[0])) gc.SetBrush(wx.Brush(frameInterior[0])) gc.DrawRectangle(0, 0, size.width, size.height) greek = size.width <= PassageWidget.MIN_GREEKING_SIZE * ( 2 if self.passage.isAnnotation() else 1) # title bar titleBarHeight = PassageWidget.GREEK_HEIGHT * 3 if greek else titleFontHeight + ( 2 * inset) if self.passage.isAnnotation(): titleBarColor = frameInterior[0] else: titleBarColor = dim(self.getTitleColor(), self.dimmed) gc.SetPen(wx.Pen(titleBarColor, 1)) gc.SetBrush(wx.Brush(titleBarColor)) if flat: gc.DrawRectangle(0, 0, size.width, titleBarHeight) else: gc.DrawRectangle(1, 1, size.width - 3, titleBarHeight) if not greek: # draw title # we let clipping prevent writing over the frame if isinstance(gc, wx.GraphicsContext): gc.ResetClip() gc.Clip(inset, inset, size.width - (inset * 2), titleBarHeight - 2) else: gc.DestroyClippingRegion() gc.SetClippingRegion(inset, inset, size.width - (inset * 2), titleBarHeight - 2) titleTextColor = dim(colors['titleText'], self.dimmed) if isinstance(gc, wx.GraphicsContext): gc.SetFont(titleFont, titleTextColor) else: gc.SetFont(titleFont) gc.SetTextForeground(titleTextColor) if self.passage.title: gc.DrawText(self.passage.title, inset, inset) # draw excerpt if not self.passage.isImage(): excerptTop = inset + titleBarHeight # we split the excerpt by line, then draw them in turn # (we use a library to determine breaks, but have to draw the lines ourselves) if isinstance(gc, wx.GraphicsContext): gc.ResetClip() gc.Clip(inset, inset, size.width - (inset * 2), size.height - (inset * 2) - 1) else: gc.DestroyClippingRegion() gc.SetClippingRegion(inset, inset, size.width - (inset * 2), size.height - (inset * 2) - 1) if self.passage.isAnnotation(): excerptTextColor = wx.Colour(*colors['annotationText']) else: excerptTextColor = dim(colors['excerptText'], self.dimmed) if isinstance(gc, wx.GraphicsContext): gc.SetFont(excerptFont, excerptTextColor) else: gc.SetFont(excerptFont) gc.SetTextForeground(excerptTextColor) excerptLines = wordWrap(self.passage.text, size.width - (inset * 2), gc) for line in excerptLines: gc.DrawText(line, inset, excerptTop) excerptTop += excerptFontHeight * PassageWidget.LINE_SPACING \ * min(1.75,max(1,1.75*size.width/260 if (self.passage.isAnnotation() and line) else 1)) if excerptTop + excerptFontHeight > size.height - inset: break if (self.passage.isStoryText() or self.passage.isStylesheet()) and tags: tagBarHeight = excerptFontHeight + (2 * inset) gc.SetPen(wx.Pen(tagBarColor, 1)) gc.SetBrush(wx.Brush(tagBarColor)) gc.DrawRectangle(0, size.height - tagBarHeight - 1, size.width, tagBarHeight + 1) # draw tags tagTextColor = dim(colors['frame'], self.dimmed) if isinstance(gc, wx.GraphicsContext): gc.SetFont(excerptFont, tagTextColor) else: gc.SetFont(excerptFont) gc.SetTextForeground(tagTextColor) text = wordWrap(' '.join(tags), size.width - (inset * 2), gc)[0] gc.DrawText(text, inset * 2, (size.height - tagBarHeight)) else: # greek title gc.SetPen(wx.Pen(colors['titleText'], PassageWidget.GREEK_HEIGHT)) height = inset width = (size.width - inset) / 2 if isinstance(gc, wx.GraphicsContext): gc.StrokeLine(inset, height, width, height) else: gc.DrawLine(inset, height, width, height) height += PassageWidget.GREEK_HEIGHT * 3 # greek body text if not self.passage.isImage(): gc.SetPen(wx.Pen(colors['annotationText'] \ if self.passage.isAnnotation() else colors['greek'], PassageWidget.GREEK_HEIGHT)) chars = len(self.passage.text) while height < size.height - inset and chars > 0: width = size.height - inset if height + (PassageWidget.GREEK_HEIGHT * 2) > size.height - inset: width /= 2 elif chars < 80: width = max(4, width * chars / 80) if isinstance(gc, wx.GraphicsContext): gc.StrokeLine(inset, height, width, height) else: gc.DrawLine(inset, height, width, height) height += PassageWidget.GREEK_HEIGHT * 2 chars -= 80 # greek tags if (self.passage.isStoryText() or self.passage.isStylesheet()) and tags: tagBarHeight = PassageWidget.GREEK_HEIGHT * 3 gc.SetPen(wx.Pen(tagBarColor, 1)) gc.SetBrush(wx.Brush(tagBarColor)) height = size.height - tagBarHeight - 2 width = size.width - 4 gc.DrawRectangle(2, height, width, tagBarHeight) gc.SetPen(wx.Pen(colors['greek'], PassageWidget.GREEK_HEIGHT)) height += inset width = (width - inset * 2) / 2 if isinstance(gc, wx.GraphicsContext): gc.StrokeLine(inset, height, width, height) else: gc.DrawLine(inset, height, width, height) if self.passage.isImage(): if self.bitmap: if isinstance(gc, wx.GraphicsContext): gc.ResetClip() gc.Clip(1, titleBarHeight + 1, size.width - 3, size.height - 3) else: gc.DestroyClippingRegion() gc.SetClippingRegion(1, titleBarHeight + 1, size.width - 3, size.height - 3) width = size.width height = size.height - titleBarHeight # choose smaller of vertical and horizontal scale factor, to preserve aspect ratio scale = min(width / float(self.bitmap.GetWidth()), height / float(self.bitmap.GetHeight())) img = self.bitmap.ConvertToImage() if scale != 1: img = img.Scale(scale * self.bitmap.GetWidth(), scale * self.bitmap.GetHeight()) # offset image horizontally or vertically, to centre after scaling offsetWidth = (width - img.GetWidth()) / 2 offsetHeight = (height - img.GetHeight()) / 2 if isinstance(gc, wx.GraphicsContext): gc.DrawBitmap(img.ConvertToBitmap(self.bitmap.GetDepth()), 1 + offsetWidth, titleBarHeight + 1 + offsetHeight, img.GetWidth(), img.GetHeight()) else: gc.DrawBitmap(img.ConvertToBitmap(self.bitmap.GetDepth()), 1 + offsetWidth, titleBarHeight + 1 + offsetHeight) if isinstance(gc, wx.GraphicsContext): gc.ResetClip() else: gc.DestroyClippingRegion() # draw a broken link emblem in the bottom right if necessary # fixme: not sure how to do this with transparency def showEmblem(emblem, gc=gc, size=size, inset=inset): emblemSize = emblem.GetSize() emblemPos = [ size.width - (emblemSize[0] + inset), \ size.height - (emblemSize[1] + inset) ] if isinstance(gc, wx.GraphicsContext): gc.DrawBitmap(emblem, emblemPos[0], emblemPos[1], emblemSize[0], emblemSize[1]) else: gc.DrawBitmap(emblem, emblemPos[0], emblemPos[1]) if len(self.getBrokenLinks()): showEmblem(self.brokenEmblem) elif len(self.getIncludedLinks()) or len(self.passage.variableLinks): showEmblem(self.externalEmblem) # finally, draw a selection over ourselves if we're selected if self.selected: color = dim( titleBarColor if flat else wx.SystemSettings.GetColour( wx.SYS_COLOUR_HIGHLIGHT), self.dimmed) if self.app.config.ReadBool('fastStoryPanel'): gc.SetPen(wx.Pen(color, 2 + flat)) else: gc.SetPen(wx.TRANSPARENT_PEN) if isinstance(gc, wx.GraphicsContext): r, g, b = color.Get(False) color = wx.Colour(r, g, b, 64) gc.SetBrush(wx.Brush(color)) else: gc.SetBrush(wx.TRANSPARENT_BRUSH) gc.DrawRectangle(0, 0, size.width, size.height) self.paintBufferBounds = size
import wx import sys, os kBootSeqColor_Invalid = wx.Colour(64, 64, 64) kBootSeqColor_Optional = wx.Colour(166, 255, 255) kBootSeqColor_Active = wx.Colour(147, 255, 174) kBootSeqColor_Failed = wx.Colour(255, 0, 0) kConnectStage_Rom = 1 kConnectStage_Flashloader = 2 kConnectStage_ExternalMemory = 3 kConnectStage_Reset = 4 kMcuSeries_iMXRT = 'i.MXRT' kMcuSeries_iMXRT10yy = 'RT10yy' kMcuSeries_iMXRTxxx = 'RTxxx' kMcuSeries_iMXRT11yy = 'RT11yy' kMcuSeries_iMXRTyyyy = [kMcuSeries_iMXRT10yy, kMcuSeries_iMXRT11yy] kMcuSeries_LPC = 'LPC' kMcuSeries_Kinetis = 'Kinetis' kMcuSeries_v1_0_0 = [kMcuSeries_iMXRT] kMcuSeries_v2_0_0 = [kMcuSeries_iMXRT] kMcuSeries_Latest = kMcuSeries_v2_0_0 kMcuDevice_iMXRT500 = 'i.MXRT5xx' kMcuDevice_iMXRT500S = 'i.MXRT5xxS' kMcuDevice_iMXRT600 = 'i.MXRT6xx' kMcuDevice_iMXRT600S = 'i.MXRT6xxS' kMcuDevice_iMXRTxxx = [kMcuDevice_iMXRT500, kMcuDevice_iMXRT600]
def SetBalloonShape(self, event=None): """ Sets the balloon shape. :param `event`: on wxGTK, a :class:`WindowCreateEvent` event to process. """ size = self.GetSize() pos = self.GetPosition() dc = wx.MemoryDC(wx.Bitmap(1, 1)) textlabel = self._balloonmsg.GetLabel() textfont = self._balloonmsg.GetFont() textextent = dc.GetFullTextExtent(textlabel, textfont) boxheight = size.y - textextent[1] * len(textlabel.split("\n")) boxwidth = size.x position = wx.GetMousePosition() xpos = position[0] ypos = position[1] if xpos > 20 and ypos > 20: # This Is NW Positioning positioning = "NW" xpos = position[0] - boxwidth + 20 ypos = position[1] - boxheight - 20 elif xpos <= 20 and ypos <= 20: # This Is SE Positioning positioning = "SE" xpos = position[0] - 20 ypos = position[1] elif xpos > 20 and ypos <= 20: # This Is SW Positioning positioning = "SW" xpos = position[0] - boxwidth + 20 ypos = position[1] else: # This Is NE Positioning positioning = "NE" xpos = position[0] ypos = position[1] - boxheight + 20 bmp = wx.Bitmap(size.x, size.y) dc = wx.BufferedDC(None, bmp) dc.SetBackground(wx.Brush(wx.Colour(0, 0, 0))) dc.Clear() dc.SetPen(wx.Pen(wx.Colour(0, 0, 0), 1, wx.PENSTYLE_TRANSPARENT)) if self._shape == BT_ROUNDED: dc.DrawRoundedRectangle(0, 20, boxwidth, boxheight - 20, 12) elif self._shape == BT_RECTANGLE: dc.DrawRectangle(0, 20, boxwidth, boxheight - 20) if positioning == "NW": dc.DrawPolygon( ((boxwidth - 40, boxheight), (boxwidth - 20, boxheight + 20), (boxwidth - 20, boxheight))) elif positioning == "SE": dc.DrawPolygon(((20, 20), (20, 0), (40, 20))) elif positioning == "SW": dc.DrawPolygon( ((boxwidth - 40, 20), (boxwidth - 20, 0), (boxwidth - 20, 20))) else: dc.DrawPolygon( ((20, boxheight), (20, boxheight + 20), (40, boxheight))) r = wx.Region(bmp, wx.Colour(0, 0, 0)) self.hasShape = self.SetShape(r) if self._tipstyle == BT_BUTTON: colour = self.panel.GetBackgroundColour() self._closebutton.SetBackgroundColour(colour) self.SetPosition((xpos, ypos))
class TextEditMixin: """ A mixin class that enables any text in any column of a multi-column listctrl to be edited by clicking on the given row and column. You close the text editor by hitting the ENTER key or clicking somewhere else on the listctrl. You switch to the next column by hiting TAB. To use the mixin you have to include it in the class definition and call the __init__ function:: class TestListCtrl(wx.ListCtrl, TextEditMixin): def __init__(self, parent, ID, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0): wx.ListCtrl.__init__(self, parent, ID, pos, size, style) TextEditMixin.__init__(self) Authors: Steve Zatz, Pim Van Heuven ([email protected]) """ editorBgColour = wx.Colour(255, 255, 175) # Yellow editorFgColour = wx.Colour(0, 0, 0) # black def __init__(self): #editor = wx.TextCtrl(self, -1, pos=(-1,-1), size=(-1,-1), # style=wx.TE_PROCESS_ENTER|wx.TE_PROCESS_TAB \ # |wx.TE_RICH2) self.make_editor() self.Bind(wx.EVT_TEXT_ENTER, self.CloseEditor) self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDown) self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self) def make_editor(self, col_style=wx.LIST_FORMAT_LEFT): style = wx.TE_PROCESS_ENTER | wx.TE_PROCESS_TAB | wx.TE_RICH2 style |= { wx.LIST_FORMAT_LEFT: wx.TE_LEFT, wx.LIST_FORMAT_RIGHT: wx.TE_RIGHT, wx.LIST_FORMAT_CENTRE: wx.TE_CENTRE }[col_style] editor = wx.TextCtrl(self, -1, style=style) editor.SetBackgroundColour(self.editorBgColour) editor.SetForegroundColour(self.editorFgColour) font = self.GetFont() editor.SetFont(font) self.curRow = 0 self.curCol = 0 editor.Hide() if hasattr(self, 'editor'): self.editor.Destroy() self.editor = editor self.col_style = col_style self.editor.Bind(wx.EVT_CHAR, self.OnChar) self.editor.Bind(wx.EVT_KILL_FOCUS, self.CloseEditor) def OnItemSelected(self, evt): self.curRow = evt.GetIndex() evt.Skip() def OnChar(self, event): ''' Catch the TAB, Shift-TAB, cursor DOWN/UP key code so we can open the editor at the next column (if any).''' keycode = event.GetKeyCode() if keycode == wx.WXK_TAB and event.ShiftDown(): self.CloseEditor() if self.curCol - 1 >= 0: self.OpenEditor(self.curCol - 1, self.curRow) elif keycode == wx.WXK_TAB: self.CloseEditor() if self.curCol + 1 < self.GetColumnCount(): self.OpenEditor(self.curCol + 1, self.curRow) elif keycode == wx.WXK_ESCAPE: self.CloseEditor() elif keycode == wx.WXK_DOWN: self.CloseEditor() if self.curRow + 1 < self.GetItemCount(): self._SelectIndex(self.curRow + 1) self.OpenEditor(self.curCol, self.curRow) elif keycode == wx.WXK_UP: self.CloseEditor() if self.curRow > 0: self._SelectIndex(self.curRow - 1) self.OpenEditor(self.curCol, self.curRow) else: event.Skip() def OnLeftDown(self, evt=None): ''' Examine the click and double click events to see if a row has been click on twice. If so, determine the current row and columnn and open the editor.''' if self.editor.IsShown(): self.CloseEditor() x, y = evt.GetPosition() row, flags = self.HitTest((x, y)) if row != self.curRow: # self.curRow keeps track of the current row evt.Skip() return # the following should really be done in the mixin's init but # the wx.ListCtrl demo creates the columns after creating the # ListCtrl (generally not a good idea) on the other hand, # doing this here handles adjustable column widths self.col_locs = [0] loc = 0 for n in range(self.GetColumnCount()): loc = loc + self.GetColumnWidth(n) self.col_locs.append(loc) col = bisect(self.col_locs, x + self.GetScrollPos(wx.HORIZONTAL)) - 1 self.OpenEditor(col, row) def OpenEditor(self, col, row): ''' Opens an editor at the current position. ''' # give the derived class a chance to Allow/Veto this edit. evt = wx.ListEvent(wx.wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT, self.GetId()) evt.Index = row evt.Column = col item = self.GetItem(row, col) evt.Item.SetId(item.GetId()) evt.Item.SetColumn(item.GetColumn()) evt.Item.SetData(item.GetData()) evt.Item.SetText(item.GetText()) ret = self.GetEventHandler().ProcessEvent(evt) if ret and not evt.IsAllowed(): return # user code doesn't allow the edit. if self.GetColumn(col).Align != self.col_style: self.make_editor(self.GetColumn(col).Align) x0 = self.col_locs[col] x1 = self.col_locs[col + 1] - x0 scrolloffset = self.GetScrollPos(wx.HORIZONTAL) # scroll forward if x0 + x1 - scrolloffset > self.GetSize()[0]: if wx.Platform == "__WXMSW__": # don't start scrolling unless we really need to offset = x0 + x1 - self.GetSize()[0] - scrolloffset # scroll a bit more than what is minimum required # so we don't have to scroll everytime the user presses TAB # which is very tireing to the eye addoffset = self.GetSize()[0] / 4 # but be careful at the end of the list if addoffset + scrolloffset < self.GetSize()[0]: offset += addoffset self.ScrollList(offset, 0) scrolloffset = self.GetScrollPos(wx.HORIZONTAL) else: # Since we can not programmatically scroll the ListCtrl # close the editor so the user can scroll and open the editor # again self.editor.SetValue(self.GetItem(row, col).GetText()) self.curRow = row self.curCol = col self.CloseEditor() return y0 = self.GetItemRect(row)[1] editor = self.editor editor.SetSize(x0 - scrolloffset, y0, x1, -1) editor.SetValue(self.GetItem(row, col).GetText()) editor.Show() editor.Raise() editor.SetSelection(-1, -1) editor.SetFocus() self.curRow = row self.curCol = col # FIXME: this function is usually called twice - second time because # it is binded to wx.EVT_KILL_FOCUS. Can it be avoided? (MW) def CloseEditor(self, evt=None): ''' Close the editor and save the new value to the ListCtrl. ''' if not self.editor.IsShown(): return text = self.editor.GetValue() self.editor.Hide() self.SetFocus() # post wxEVT_COMMAND_LIST_END_LABEL_EDIT # Event can be vetoed. It doesn't has SetEditCanceled(), what would # require passing extra argument to CloseEditor() evt = wx.ListEvent(wx.wxEVT_COMMAND_LIST_END_LABEL_EDIT, self.GetId()) evt.Index = self.curRow evt.Column = self.curCol item = self.GetItem(self.curRow, self.curCol) evt.Item.SetId(item.GetId()) evt.Item.SetColumn(item.GetColumn()) evt.Item.SetData(item.GetData()) evt.Item.SetText(text) #should be empty string if editor was canceled ret = self.GetEventHandler().ProcessEvent(evt) if not ret or evt.IsAllowed(): if self.IsVirtual(): # replace by whather you use to populate the virtual ListCtrl # data source self.SetVirtualData(self.curRow, self.curCol, text) else: self.SetStringItem(self.curRow, self.curCol, text) self.RefreshItem(self.curRow) def _SelectIndex(self, row): listlen = self.GetItemCount() if row < 0 and not listlen: return if row > (listlen - 1): row = listlen - 1 self.SetItemState(self.curRow, ~wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED) self.EnsureVisible(row) self.SetItemState(row, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
def __init__(self, parent): wx.Panel.__init__(self, parent) self.SetBackgroundColour(wx.Colour(255, 255, 255)) self.SetAutoLayout(1) # Counter for projects loaded in current GUI self.proj_count = 0 # Floating items (to be inserted) self.float_hyper_list = [] # Fixed text and hyperlink items tooltip = wx.ToolTip(_("Measure distances")) txt_measure = wx.StaticText(self, -1, _("Measure")) txt_measure.SetToolTip(tooltip) tooltip = wx.ToolTip(_("Add text annotations")) txt_annotation = hl.HyperLinkCtrl(self, -1, _("Add text annotations")) txt_annotation.SetUnderlines(False, False, False) txt_annotation.SetColours("BLACK", "BLACK", "BLACK") txt_annotation.SetToolTip(tooltip) txt_annotation.AutoBrowse(False) txt_annotation.UpdateLink() txt_annotation.Bind(hl.EVT_HYPERLINK_LEFT, self.OnTextAnnotation) # Image(s) for buttons BMP_ANNOTATE = wx.Bitmap( os.path.join(const.ICON_DIR, "annotation.png"), wx.BITMAP_TYPE_PNG) BMP_ANGLE = wx.Bitmap( os.path.join(const.ICON_DIR, "measure_angle.jpg"), wx.BITMAP_TYPE_JPEG) BMP_DISTANCE = wx.Bitmap( os.path.join(const.ICON_DIR, "measure_line.png"), wx.BITMAP_TYPE_PNG) BMP_ANNOTATE.SetWidth(25) BMP_ANNOTATE.SetHeight(25) BMP_ANGLE.SetWidth(25) BMP_ANGLE.SetHeight(25) BMP_DISTANCE.SetWidth(25) BMP_DISTANCE.SetHeight(25) # Buttons related to hyperlinks button_style = pbtn.PB_STYLE_SQUARE | pbtn.PB_STYLE_DEFAULT button_measure_linear = pbtn.PlateButton(self, ID_BTN_MEASURE_LINEAR, "", BMP_DISTANCE, style=button_style) button_measure_angular = pbtn.PlateButton(self, ID_BTN_MEASURE_ANGULAR, "", BMP_ANGLE, style=button_style) button_annotation = pbtn.PlateButton(self, ID_BTN_ANNOTATION, "", BMP_ANNOTATE, style=button_style) # When using PlaneButton, it is necessary to bind events from parent win self.Bind(wx.EVT_BUTTON, self.OnButton) # Tags and grid sizer for fixed items flag_link = wx.EXPAND | wx.GROW | wx.LEFT | wx.TOP flag_button = wx.EXPAND | wx.GROW sizer = wx.GridBagSizer(hgap=0, vgap=0) sizer.Add(txt_measure, pos=(0, 0), flag=wx.GROW | wx.EXPAND | wx.TOP, border=3) sizer.Add(button_measure_linear, pos=(0, 1), flag=wx.GROW | wx.EXPAND) sizer.Add(button_measure_angular, pos=(0, 2), flag=wx.GROW | wx.EXPAND) sizer.Add(txt_annotation, pos=(1, 0), flag=wx.GROW | wx.EXPAND) sizer.Add(button_annotation, pos=(1, 2), span=(2, 1), flag=wx.GROW | wx.EXPAND) sizer.AddGrowableCol(0) # Add line sizers into main sizer main_sizer = wx.BoxSizer(wx.VERTICAL) main_sizer.Add(sizer, 0, wx.GROW | wx.EXPAND) main_sizer.Fit(self) # Update main sizer and panel layout self.SetSizer(sizer) self.Fit() self.sizer = main_sizer
def _applyAppTheme(self): cs = ThemeMixin.appColors self.__InitColors() self.SetBackgroundColour(wx.Colour(self.parent.GetBackgroundColour())) self.SetPressColor(cs['txtbutton_bg_hover']) self.SetLabelColor(cs['text'], cs['txtbutton_fg_hover'])
def Draw(self, dc): size = self.GetClientSize() width = size.width height = size.height tickBorder = 4 backColour = self.GetBackgroundColour() backBrush = wx.Brush(backColour, wx.SOLID) dc.SetBackground(backBrush) dc.Clear() if not self.bins or width < 50 or height < 50 or self.dataMax == self.dataMin: return textWidth, textHeight = dc.GetTextExtent( u'00:00' if self.dataMax < 60*60 else u'00:00:00' ) xLeft = dc.GetTextExtent( unicode(self.barMax) )[0] + 4 + tickBorder xRight = width - 8 - tickBorder yBottom = height - textHeight - 8 yTop = textHeight + 8 # Draw the horizontal label. # Find some reasonable tickmarks for the x axis. numlabel = (xRight - xLeft) / (textWidth * 1.5) d = (self.dataMax - self.dataMin) / float(numlabel) intervals = [1, 2, 5, 10, 15, 20, 30, 1*60, 2*60, 5*60, 10*60, 15*60, 20*60, 30*60, 1*60*60, 2*60*60, 4*60*60, 8*60*60, 12*60*60, 24*60*60] d = intervals[bisect.bisect_left(intervals, d, 0, len(intervals)-1)] dFactor = (xRight - xLeft) / (self.dataMax - self.dataMin) tStart = int(self.dataMin) tStart -= tStart % d if tStart < int(self.dataMin): tStart += d dc.SetPen(wx.Pen('light gray', 1)) for t in xrange(tStart, int(self.dataMax), d): x = xLeft + (t - self.dataMin) * dFactor if x < xLeft: continue if t < 60*60: s = '{}:{:02d}'.format((t / 60), t%60) else: s = '{}:{:02d}:{:02d}'.format(t/(60*60), (t / 60)%60, t%60) w, h = dc.GetTextExtent(s) dc.DrawText( s, x - w/2, yBottom + 4) dc.DrawText( s, x - w/2, 0 + 4 ) dc.DrawLine( x, yBottom+2, x, yTop ) # Find some reasonable tickmarks for the y axis. numlabel = float(yBottom - yTop) / (textHeight * 3) d = self.barMax / numlabel intervals = [1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500] d = intervals[bisect.bisect_left(intervals, d, 0, len(intervals)-1)] dFactor = (yBottom - yTop) / float(self.barMax) dc.SetPen(wx.Pen('light gray', 1)) for i in xrange(0, self.barMax+1, d): s = u'{}'.format(i) y = yBottom - int(i * dFactor) w, h = dc.GetTextExtent(s) dc.DrawText( s, xLeft - w - 2 - tickBorder, y-textHeight/2 - 1) dc.DrawLine( xLeft, y, xRight + tickBorder, y ) # Draw the data rectangles. pen = wx.Pen('dark gray', 1) dc.SetPen( pen ) rSelect = None self.rectField = (xLeft, yTop, float(xRight-xLeft), float(yBottom-yTop)) boxWidth = self.rectField[2] / len(self.bins) boxHeight = self.rectField[3] / self.barMax lenBins = len(self.bins) iBin = [0 for i in xrange(lenBins)] xBin = [xLeft + int(i * boxWidth) for i in xrange(len(self.bins)+1)] yHeight = [yBottom - int(i * boxHeight) for i in xrange(self.barMax+1)] self.coords = {} brushes = [wx.Brush(c) for c in self.categoryColor] for i, (v, lab, cat) in enumerate(zip(self.data, self.label, self.category)): dc.SetBrush( brushes[self.categoryMap[cat]] ) b = min(lenBins-1, int((v-self.dataMin) / self.binWidth)) self.coords[(b, iBin[b])] = i iBin[b] += 1 r = wx.Rect( xBin[b], yHeight[iBin[b]], xBin[b+1] - xBin[b], yHeight[iBin[b]-1] - yHeight[iBin[b]] ) if i == self.iSelect: rSelect = r dc.SetPen( wx.Pen(wx.Colour(255,255,0), 1) ) dc.DrawRectangle( r ) if i == self.iSelect: dc.SetPen( pen ) # draw the baseline dc.SetPen(wx.Pen('black', 2)) dc.DrawLine(xLeft-tickBorder, yBottom, xRight+tickBorder, yBottom) # draw the hoverhelp if rSelect: t = self.data[self.iSelect] if t < 60: s = '{:.2f}'.format( t ) else: t = int(t) if t < 60*60: s = '{}:{:02d}'.format((t/60), t%60) else: s = '{}:{:02d}:{:02d}'.format(t/(60*60), (t/60)%60, t%60) label = self.label[self.iSelect] category = self.category[self.iSelect] margin = 4 widthMax = max( dc.GetTextExtent(v)[0] for v in (s, label, category) ) + margin * 2 textWidth, textHeight = dc.GetTextExtent( s ) heightMax = textHeight * 3 + margin * 2 rHover = wx.Rect( rSelect.GetX() + rSelect.GetWidth() // 2 - widthMax, rSelect.GetY(), widthMax, heightMax ) if rHover.GetLeft() < 0: rHover.SetX( 0 ) if rHover.GetBottom() > height: rHover.SetY( height - rHover.GetHeight() ) dc.SetPen( wx.Pen('black', 1) ) dc.SetBrush( wx.Brush(wx.Colour(255,255,153)) ) dc.DrawRectangle( rHover ) xLeft = rHover.GetLeft() + margin yCur = rHover.GetY() + margin for v in (s, label, category): dc.DrawText( v, xLeft, yCur ) yCur += textHeight
def DrawJoystick(self, dc): # draw the guage as a maxed square in the center of this window. w, h = self.GetClientSize() edgeSize = min(w, h) xorigin = (w - edgeSize) / 2 yorigin = (h - edgeSize) / 2 center = edgeSize / 2 # Restrict our drawing activities to the square defined # above. dc.SetClippingRegion(xorigin, yorigin, edgeSize, edgeSize) # Optimize drawing a bit (for Win) dc.BeginDrawing() dc.SetBrush(wx.Brush(wx.Colour(251, 252, 237))) dc.DrawRectangle(xorigin, yorigin, edgeSize, edgeSize) dc.SetPen(wx.Pen(wx.BLACK, 1, wx.DOT_DASH)) dc.DrawLine(xorigin, yorigin + center, xorigin + edgeSize, yorigin + center) dc.DrawLine(xorigin + center, yorigin, xorigin + center, yorigin + edgeSize) if self.stick: # Get the joystick position as a float joyx = float(self.stick.GetPosition().x) joyy = float(self.stick.GetPosition().y) # Get the joystick range of motion xmin = self.stick.GetXMin() xmax = self.stick.GetXMax() if xmin < 0: xmax += abs(xmin) joyx += abs(xmin) xmin = 0 xrange = max(xmax - xmin, 1) ymin = self.stick.GetYMin() ymax = self.stick.GetYMax() if ymin < 0: ymax += abs(ymin) joyy += abs(ymin) ymin = 0 yrange = max(ymax - ymin, 1) # calc a ratio of our range versus the joystick range xratio = float(edgeSize) / xrange yratio = float(edgeSize) / yrange # calc the displayable value based on position times ratio xval = int(joyx * xratio) yval = int(joyy * yratio) # and normalize the value from our brush's origin x = xval + xorigin y = yval + yorigin # Now to draw it. dc.SetPen(wx.Pen(wx.RED, 2)) dc.CrossHair(x, y) # Turn off drawing optimization dc.EndDrawing()
def OnPaint(self, event): dc = get_paint_dc(self) fmt = "%M:%S" mins, secs = divmod(int(self._max_frame / self.fps), 60) start = time(second=0).strftime(fmt) end = time(minute=mins, second=secs).strftime(fmt) mins, secs = divmod(int(self._current_frame / self.fps), 60) current = time(minute=mins, second=secs).strftime(fmt) size = self.GetSize() y_offset = dc.GetTextExtent(start).y + 2 x_offset = size.x - 1 dc.SetPen(wx.Pen(wx.Colour(0, 0, 0))) dc.DrawLine(0, y_offset, x_offset, y_offset) dc.DrawLine(0, size.y - 1, x_offset, size.y - 1) dc.DrawLine(0, y_offset, 0, size.y - 1) dc.DrawLine(size.x - 1, y_offset, size.x - 1, size.y - 1) dc.SetBrush(wx.Brush(wx.Colour(0, 0, 0))) dc.DrawText(start, 0, 0) dc.DrawText(end, x_offset - dc.GetTextExtent(end).x, 0) dc.DrawText(current, (size.x - 1) / 2 - dc.GetTextExtent(current).x / 2, 0) cw = self.CURSOR_WIDTH / 2 px_ratio = self.px_ratio # Draw keyframes for frame in self._keyframes: midpoint = frame * px_ratio + cw if frame == self._selected_keyframe: dc.SetBrush(wx.Brush(wx.Colour(255, 255, 0))) else: dc.SetBrush(wx.Brush(wx.Colour(0, 128, 192))) dc.DrawPolygon( (wx.Point(midpoint, y_offset), wx.Point(midpoint + cw, cw + y_offset), wx.Point(midpoint, self.CURSOR_WIDTH + y_offset), wx.Point(midpoint - cw, cw + y_offset))) # Draw cursor dc.SetBrush(wx.Brush(wx.BLACK_BRUSH)) pos = self._current_frame * px_ratio + cw dc.DrawPolygon((wx.Point(pos, y_offset), wx.Point(pos + cw, cw + y_offset), wx.Point(pos, self.CURSOR_WIDTH + y_offset), wx.Point(pos - cw, cw + y_offset))) # Draw scrub cursor if self._dragging and self._scrub_frame != self._current_frame: midpoint = self._scrub_frame * px_ratio + cw if self._selected_keyframe is not None: dc.SetBrush(wx.Brush(wx.Colour(0, 128, 192))) else: dc.SetBrush(wx.Brush(wx.Colour(55, 55, 55))) dc.SetPen(wx.Pen(wx.Colour(55, 55, 55))) dc.DrawPolygon( (wx.Point(midpoint, y_offset), wx.Point(midpoint + cw, cw + y_offset), wx.Point(midpoint, self.CURSOR_WIDTH + y_offset), wx.Point(midpoint - cw, cw + y_offset)))
def __init__(self, parent, id=-1): """Initialize a DataWindow object.""" # Start with a Dialog Box (wxPython) wx.Dialog.__init__(self, parent, id, _("Data"), self.__pos(), self.__size(), style=wx.CAPTION | wx.RESIZE_BORDER) # Set "Window Variant" to small only for Mac to use small icons if "__WXMAC__" in wx.PlatformInfo: self.SetWindowVariant(wx.WINDOW_VARIANT_SMALL) vSizer = wx.BoxSizer(wx.VERTICAL) # add a Notebook Control to the Dialog Box # The wxCLIP_CHILDREN style allegedly reduces flicker. self.nb = wx.Notebook(self, -1, style=wx.CLIP_CHILDREN) # Set the Notebook's background to White. Otherwise, we get a visual anomoly on OS X with wxPython 2.9.4.0. self.nb.SetBackgroundColour(wx.Colour(255, 255, 255)) # Let the notebook remember it's parent self.nb.parent = self vSizer.Add(self.nb, 1, wx.EXPAND) # Create tabs for the Notebook Control. These tabs are complex enough that they are # instantiated as separate objects. self.DBTab = DatabaseTreeTab(self.nb) # Initialize the remaining Tabs to None for the moment self.DataItemsTab = None self.SelectedDataItemsTab = None self.KeywordsTab = None # Add the tabs to the Notebook Control self.nb.AddPage(self.DBTab, _("Database"), True) # OSX requires this for some reason or else it won't have a default # page selected. self.nb.SetSelection(0) # Handle Key Press Events self.nb.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) self.SetSizer(vSizer) self.SetAutoLayout(True) self.Layout() # If we are using the Multi-User Version ... if not TransanaConstants.singleUserVersion: # ... check to see if the Database is using SSL # and select the appropriate graphic file ... if TransanaGlobal.configData.ssl: bitmap = TransanaImages.locked.GetBitmap() else: bitmap = TransanaImages.unlocked.GetBitmap() # Place a graphic on the screen. This is NOT placed in the Sizer, but is placed on top of the notebook tabs. self.sslDBImage = wx.StaticBitmap(self, -1, bitmap, pos=(self.nb.GetSizeTuple()[0] - 32, 0), size=(16, 16)) # Make the SSL Indicator clickable self.sslDBImage.Bind(wx.EVT_LEFT_DOWN, self.OnSSLClick) # ... check to see if both the Database and the Message Server are using SSL # and select the appropriate graphic file ... if TransanaGlobal.configData.ssl and TransanaGlobal.chatIsSSL: bitmap = TransanaImages.locked.GetBitmap() else: bitmap = TransanaImages.unlocked.GetBitmap() # Place a graphic on the screen. This is NOT placed in the Sizer, but is placed on top of the notebook tabs. self.sslImage = wx.StaticBitmap(self, -1, bitmap, pos=(self.nb.GetSizeTuple()[0] - 16, 0), size=(16, 16)) # Make the SSL Indicator clickable self.sslImage.Bind(wx.EVT_LEFT_DOWN, self.OnSSLClick) # Remember the current SSL Status of the Message Server self.sslStatus = TransanaGlobal.configData.ssl and TransanaGlobal.chatIsSSL self.ControlObject = None # The ControlObject handles all inter-object communication, initialized to None # Capture Size Changes wx.EVT_SIZE(self, self.OnSize) wx.EVT_PAINT(self, self.OnPaint) if DEBUG: print "DataWindow.__init__(): Initial size:", self.GetSize() # Capture the selection of different Notebook Pages wx.EVT_NOTEBOOK_PAGE_CHANGED(self, self.nb.GetId(), self.OnNotebookPageSelect)