Ejemplo n.º 1
0
    def onBrowseSS(self, event):  # wxGlade: frameShuffleNew.<event_handler>
        
        #openFileDialog = wx.lib.imagebrowser.ImageDialog(self, 'samples/')
        with ib.ImageDialog(self) as openFileDialog:
            
            if openFileDialog.ShowModal() == wx.ID_CANCEL:
                return     # the user changed idea...

            # proceed loading the file chosen by the user
            # this can be done with e.g. wxPython input streams:
            try:
                PILimage = Image.open(openFileDialog.GetFile())
            except:
                wx.LogError("Cannot open file '%s'."%openFileDialog.GetPath())
                pass
        
        self.pathImage = openFileDialog.GetFile()
        openFileDialog.Destroy()
        
        self.PILimage = PILimage.crop(config.varBox)
        
        #print self.PILimage.resize((240,240))
        
        self.bitmap.SetBitmap(libImgConverter.PilImageToWxBitmap(self.PILimage.resize((240,240))))
        
        self.onRecognize()
Ejemplo n.º 2
0
    def OnOpenFile(self, evt):
        # open an image file to identify
        openImageDialog = imagebrowser.ImageDialog(None)
        if openImageDialog.ShowModal() == wx.ID_OK:
            self.imageName = openImageDialog.GetFile()
            self.showImageName.SetLabel(u"图像文件:".encode('gbk') +
                                        self.imageName)
            #self.showImageName.SetLabel( u"图像文件:"+self.imageName ) #use this in linux
            # BITTYPE_TYPE_ANY will auto detect the picture's type
            self.image = Image.open(self.imageName)
            self.imageOfBitmap = wx.Image(
                name=self.imageName,
                type=wx.BITMAP_TYPE_ANY).ConvertToBitmap()
            self.bPicShow = True
            self.Refresh()
        elif openImageDialog.ShowModal() == wx.ID_CANCEL:
            # keep last status
            print "you canceled to choose an image"
        else:
            wx.MessageBox("ERROR", u"图像文件不正确", wx.ICON_INFORMATION, self)
            self.showImageName.SetLabel(u"图像文件:None")
            self.bPicShow = False
            self.Refresh()

        openImageDialog.Destroy()
Ejemplo n.º 3
0
    def OnImgSettings(self, evt=None):

        # color correction
        if self.choColor.GetStringSelection() == 'Manual':
            self.sttCbalance.Enable()
            self.spnCbalance.Enable()
        else:
            self.sttCbalance.Disable()
            self.spnCbalance.Disable()
        # gamma correction
        if self.choGamma.GetStringSelection() == 'Manual':
            self.sttContrast.Enable()
            self.spnContrast.Enable()
            self.sttBrightness.Enable()
            self.spnBrightness.Enable()
        else:
            self.sttContrast.Disable()
            self.spnContrast.Disable()
            self.sttBrightness.Disable()
            self.spnBrightness.Disable()
        # image filtering
        if self.choSharpen.GetStringSelection() == 'Manual':
            self.sttSharpness.Enable()
            self.spnSharpness.Enable()
        else:
            self.sttSharpness.Disable()
            self.spnSharpness.Disable()

        # background image selection
        if self.choBackground.GetStringSelection() == 'Select':
            dlg = ib.ImageDialog(self, IMAGE_DIR)
            dlg.Centre()

            if dlg.ShowModal() == wx.ID_OK:
                fpath = dlg.GetFile()
                img, res = self.LoadFile(fpath, True)

                if img is not None:
                    # set background image
                    self.lbkScan.SetBackground(img)

                    # insert filename to the choice box
                    fname = fpath.rpartition('/')[2].rpartition('.')[0]
                    if self.choBackground.GetCount() == 2:
                        self.choBackground.Insert(fname, 1)
                    else:
                        self.choBackground.SetString(1, fname)
                    self.choBackground.SetSelection(1)

                else:
                    self.status.SetStatusText('Failed to load the image file.')
                    self.choBackground.SetSelection(0)
            else:
                self.choBackground.SetSelection(0)

            dlg.Destroy()

        # update settings for the selected page
        if len(self.lbkScan.data):
            self.lbkScan.UpdateSettings(self.GetImgSettings())
Ejemplo n.º 4
0
    def OnAbrirImage(self,event):
        wildcard = "JPG (*.jpg)|*.jpg|" "PNG (*.png)|*.png|" "GIF (*.gif)|*.gif|" 
        dialog = imagebrowser.ImageDialog(None)
        
        if dialog.ShowModal() == wx.ID_OK:
            #wx.MessageBox(dialog)
            
            #------------------------------------------------------------------
            #El siguiente codigo funciona    
            #------------------------------------------------------------------
##            f = np.arange(0, 6, .01)
##            y = np.sin(x**4)*np.exp(-x)
##            self.axes.plot(x,y)
##            self.canvas = FigureCanvas(self.p2, wx.ID_ANY, self.figure)
            #------------------------------------------------------------------
            
            #img = wx.Image(name,wx.BITMAP_TYPE_ANY)    
            #x = np.arange(0, 6, .01)
            #y = np.sin(x**2)*np.exp(-x)
            #ellipses = x*x/9 + y*y/4 -1
            #plt.imshow(ellipses)
            
            #plt.imshow(ellipses)
            f = plt.imread(dialog.GetFile())
            self.axes.imshow(f,cmap=cm.gray)
            #contour(self.canvas, origin='lower', extent=[-1,1,-1,1])
            #xlabel('x')
            #ylabel('y')
            #title('A spiral !')
            #BW = im2bw(f, graythresh(f))
            self.canvas = FigureCanvas(self.p2, wx.ID_ANY, self.figure)
Ejemplo n.º 5
0
    def OnAbrirImage1(self,event):
        wildcard = "JPG (*.jpg)|*.jpg|" "PNG (*.png)|*.png|" "GIF (*.gif)|*.gif|" 
        dialog = imagebrowser.ImageDialog(None)
        
        if dialog.ShowModal() == wx.ID_OK:
##            wx.MessageBox(dialog.GetFile())GetPath()
##            wx.MessageDialog(dialog)
            #------------------------------------------------------------------
            #El siguiente codigo funciona    
            #------------------------------------------------------------------
##            f = np.arange(0, 6, .01)
##            y = np.sin(x**4)*np.exp(-x)
##            self.axes.plot(x,y)
##            self.canvas = FigureCanvas(self.p2, wx.ID_ANY, self.figure)
            #------------------------------------------------------------------
            
            #img = wx.Image(name,wx.BITMAP_TYPE_ANY)    
            #x = np.arange(0, 6, .01)
            #y = np.sin(x**2)*np.exp(-x)
            #ellipses = x*x/9 + y*y/4 -1
            #plt.imshow(ellipses)
            
            #plt.imshow(ellipses)
##            f = plt.imread(dialog.GetFile())

            f = plt.imread('/home/falvarez/matwork/E61EXT_MIG.jpg')
            win.axes.imshow(f,cmap=cm.gray)
Ejemplo n.º 6
0
    def OnAbrirImage1(self, event):
        wildcard = "JPG (*.jpg)|*.jpg|" "PNG (*.png)|*.png|" "GIF (*.gif)|*.gif|"
        dialog = imagebrowser.ImageDialog(None)

        if dialog.ShowModal() == wx.ID_OK:
            wx.MessageBox(dialog)
            #img = wx.Image(name,wx.BITMAP_TYPE_ANY)
            #x = np.arange(0, 6, .01)
            #y = np.sin(x**2)*np.exp(-x)
            #ellipses = x*x/9 + y*y/4 -1
            #self.plt.imshow(ellipses)

            #plt.imshow(ellipses)
            #self.imread('/home/falvarez/matwork/E61EXT_MIG.jpg')
            #self.canvas = FigureCanvas(self.p2, wx.ID_ANY, self.figure)
            #plt.imshow(self.canvas)
            #wx.MessageBox(dialog.GetFile())
            #f = plt.imread('/home/falvarez/matwork/E61EXT_MIG.jpg')
            #plt.imshow(f)
            #im = Image.open(dialog,self.p1)
            #im.show(self.p1)

            im = Image.open(dialog)

            im.show(self.axes)
Ejemplo n.º 7
0
 def EditClicked(self, event=None):
     dlg = ib.ImageDialog(self, get_picture_dir())
     dlg.Centre()
     if dlg.ShowModal() == wx.ID_OK:
         self.iconpath = dlg.GetFile()
         self.process_input()
     else:
         pass
     dlg.Destroy()
Ejemplo n.º 8
0
 def OnIconButton(self, evt):
     # open the image browser dialog
     dlg = ib.ImageDialog(self, get_picture_dir())
     dlg.Centre()
     if dlg.ShowModal() == wx.ID_OK:
         self.iconpath = dlg.GetFile()
         self.process_input()
     else:
         pass
     dlg.Destroy()
Ejemplo n.º 9
0
    def OnShowDialog(self, event):
        dlg = imagebrowser.ImageDialog(self, self.lastpath)
        if dlg.ShowModal() == wx.ID_OK:
            self.lastpath = dlg.GetDirectory()
            imgpath = dlg.GetFile()
            bitmap = wx.Bitmap(imgpath)

            if bitmap.IsOk():
                self.bmp.SetBitmap(bitmap)
                self.Layout()
                self.bmp.Refresh()
        dlg.Destroy()
Ejemplo n.º 10
0
def main_window():
    app = wx.App(False)
    dialog = imagebrowser.ImageDialog(None)
    if dialog.ShowModal() == wx.ID_OK:
        image_address = dialog.GetFile()
        print("Вы выбрали файл: " + image_address)
        if not scale_image_2x(image_address):
            wx.MessageBox('Вы выбрали НЕ изображение\nПопробуйте ещё раз.', 'Проблема с изображением',
                          wx.OK | wx.ICON_WARNING)
            print('Изображение не найдено!')
        else:
            print('Дело сделано!')
    dialog.Destroy()
Ejemplo n.º 11
0
 def OnShowDialog(self, event):
     # Create the dialog with the path cached
     # from the last time it was opened
     dlg = imagebrowser.ImageDialog(self, self.lastpath)
     if dlg.ShowModal() == wx.ID_OK:
         # Save the last used path
         self.lastpath = dlg.GetDirectory()
         imgpath = dlg.GetFile()
         bitmap = wx.Bitmap(imgpath)
         if bitmap.IsOk():
             self.bmp.SetBitmap(bitmap)
             self.Layout()
             self.bmp.Refresh()
     dlg.Destroy()
Ejemplo n.º 12
0
 def OpenImgFile(self, evt):
     openImageDialog = imagebrowser.ImageDialog(None)
     if openImageDialog.ShowModal() == wx.ID_OK:
         fileName = openImageDialog.GetFile()
         self.imageOfBitmap = wx.Image(
             name=fileName, type=wx.BITMAP_TYPE_ANY).ConvertToBitmap()
         size = self.imageOfBitmap.GetSize()
         self.SetClientSizeWH(size[0] + 200, size[1] + 100)
         self.Refresh()
     elif openImageDialog.ShowModal() == wx.ID_CANCEL:
         print "you canceled to choose an image"
     else:
         wx.MessageBox("ERROR", u"图像文件不正确", wx.ICON_EXCLAMATION, self)
         self.Refresh()
     openImageDialog.Destroy()
    def OnButton(self, event):
        # get current working directory
        dir = os.getcwd()

        # set the initial directory for the demo bitmaps
        initial_dir = os.path.join(dir, 'bitmaps')

        # open the image browser dialog
        dlg = ib.ImageDialog(self, initial_dir)

        dlg.Centre()

        if dlg.ShowModal() == wx.ID_OK:
            # show the selected file
            self.log.WriteText("You Selected File: " + dlg.GetFile())
        else:
            self.log.WriteText("You pressed Cancel\n")

        dlg.Destroy()
Ejemplo n.º 14
0
    def OnFile(self, evt):
        """
        Internal event for the CONTROLS_SELECT_FILE event.
        Read the selection with GetFile().
        """
        self.live.suspend()
        initial_dir = os.getcwd()
        dlg = ib.ImageDialog(self, initial_dir)
        dlg.Centre()

        #TODO: Process file selection
        if dlg.ShowModal() == wx.ID_OK:
            # show the selected file
            self.fileSelection = dlg.GetFile()
            evt.Skip()
        else:
            self.fileSelection = None

        dlg.Destroy()
        self.live.resume()
    def onBrowseThumb(self, evt):
        path = ''

        # open the image browser dialog
        dlg = ib.ImageDialog(self, path)
        dlg.Centre()
        if dlg.ShowModal() == wx.ID_OK:
            iconpath = dlg.GetFile()

            try:
                im = wx.Image(iconpath)
                if im is None:
                    self.show_inputerror(self.utility.lang.get('cantopenfile'))
                else:
                    self.thumbCtl.SetValue(iconpath)
            except:
                self.show_inputerror(self.utility.lang.get('iconbadformat'))
        else:
            pass

        dlg.Destroy()
Ejemplo n.º 16
0
	def __init__(self, top):
		self.top = top
		dg = imagebrowser.ImageDialog(None, HOME_PATH)
		dg.SetSize((500, 400))		
		if dg.ShowModal() == wx.ID_OK:
			n = dg.GetFile() 
		dg.Destroy()
		self.orig = wx.Image(n, wx.BITMAP_TYPE_ANY)   
		self.img1 = wx.Image(n, wx.BITMAP_TYPE_ANY)   
		self.w = self.img1.GetWidth() 
		self.h = self.img1.GetHeight()
		ds = wx.DisplaySize()
		self.initpos = ds[1] / 4
		if self.w < 1000:
			self.wig = (ds[0] / 2, ds[1] / 2)
		else:
			self.wig = (ds[0] / 1.2, ds[1] / 1.2)
		wx.Frame.__init__(self, None, title=_("Write image"), size=self.wig) 
		self.sp = wx.SplitterWindow(self, style=wx.SP_NOBORDER)	
		self.p = wx.Panel(self.sp, size=self.wig, style=wx.SUNKEN_BORDER) 
		self.p2 = wx.Panel(self.sp, size=self.wig, style=wx.SUNKEN_BORDER) 
		self.p2.Hide()   
		wx.StaticBitmap(self.p, -1, wx.BitmapFromImage(self.img1), pos=(0,31))
		mon = ['80%', '60%', '40%', '20%', '10%', '5%']
		self.ch =wx.ComboBox(self.p, value='0', choices=mon, size=(102, 30), pos=(32, 0), style=wx.CB_DROPDOWN)
		buttons_cb = wx.Button(self.p, -1, "-",size=(30, 30), pos=(0, 0))
		buttons_cb.Bind(wx.EVT_BUTTON, self.Tu, buttons_cb)
		buttons_cv = wx.Button(self.p, -1, "+",size=(30, 30), pos=(136, 0))
		buttons_cv.Bind(wx.EVT_BUTTON, self.Su, buttons_cv)
		bwr = wx.Button(self.p, -1, _("Write"), size=(90, 30), pos=(444, 0))
		bwr.Bind(wx.EVT_BUTTON, self.write, bwr)
		bor = wx.Button(self.p, -1, "OrigImage", size=(90, 30), pos=(352, 0))
		bor.Bind(wx.EVT_BUTTON, self.Orig, bor)
		buttons_cm = wx.Button(self.p, -1, "Mirror",size=(90, 30), pos=(168, 0))
		buttons_cm.Bind(wx.EVT_BUTTON, self.MuH, buttons_cm)
		buttons_cmv = wx.Button(self.p, -1, "Rotate",size=(90, 30), pos=(260, 0))
		buttons_cmv.Bind(wx.EVT_BUTTON, self.MuV, buttons_cmv)
Ejemplo n.º 17
0
 def test_imagebrowserDlgGetters(self):
     dlg = ib.ImageDialog(None)
     dlg.GetFile()
     dlg.GetDirectory()
     dlg.Destroy()
Ejemplo n.º 18
0
 def test_imagebrowserDlg(self):
     # a typical use case
     dlg = ib.ImageDialog(self.frame, set_dir=os.getcwd())
     dlg.Destroy()
Ejemplo n.º 19
0
import wx
import wx.lib.imagebrowser as imagebrowser

if __name__ == "__main__":
    app = wx.PySimpleApp()
    dialog = imagebrowser.ImageDialog(None)
    if dialog.ShowModal() == wx.ID_OK:
        print "You Selected File: " + dialog.GetFile()
    dialog.Destroy()
 def onBrowseImage(self, event):
     dlg = imagebrowser.ImageDialog(self)
     if dlg.ShowModal() == wx.ID_OK:
         print(dlg.GetFile())
Ejemplo n.º 21
0
    def on_new_anim_button(self, evt):
        self.iec.editorCtrl.PopDown()

        newanimdlg = NewAnimationDialog(wx.GetApp().frame,
                                        -1,
                                        size=(500, 400),
                                        style=wx.DEFAULT_DIALOG_STYLE)
        newanimdlg.CenterOnScreen()
        newanimdlg.name.SetValue(self.iec.resource.__class__.__name__ +
                                 "_anim")
        val = newanimdlg.ShowModal()

        if val == wx.ID_OK:
            project = wx.GetApp().frame.project
            res = wx.GetApp().frame.pb.active_resource
            res.sync()
            name = newanimdlg.name.GetValue()
            filename = project.ask_to_import(newanimdlg.filename.GetValue())

            if filename.endswith('.psd'):
                import PIL.Image
                img = PIL.Image.open(str(filename))
                base = str(filename[:-4]) + '.png'
                import tempfile
                import exceptions
                import shutil

                tempdir = tempfile.gettempdir()
                tempdir = tempdir + '/psd_outputs'
                shutil.rmtree(tempdir, ignore_errors=True)

                try:
                    os.mkdir(tempdir)
                except:
                    pass

                for index, layer in enumerate(img.layers):
                    img.seek(index)
                    img.save(
                        join(
                            tempdir,
                            os.path.basename(base) + "_" +
                            layer[0].decode('utf-8') + ".png"))

                dlg = ib.ImageDialog(self, tempdir)
                dlg.Centre()

                if dlg.ShowModal() == wx.ID_OK:
                    filename = wx.GetApp(
                    ).frame.project.project_path + '/' + os.path.basename(
                        dlg.GetFile())
                    shutil.copyfile(dlg.GetFile(), filename)

                else:
                    self.iec.editorCtrl.PopDown()
                    newanimdlg.Destroy()
                    return

                shutil.rmtree(tempdir, ignore_errors=True)

            nom = get_parent_class(self.iec.resource.__class__)
            classe = res.get_class(nom)
            c = classe.add_class(name, ["Animation"],
                                 ["filenames = [" + repr(filename) + "]\n"])
            res.ast_has_changed = True
            res.topy()
            wx.GetApp().gns.run(res.listing)
            wx.GetApp().artub_frame.update_treeitem(res)
            self.iec.editorCtrl.SetValue(nom + '.' + name)
            if os.name != "posix":  # Hack
                self.iec.editorCtrl.PopDown()
            self.iec.propEditor.inspectorPost(False)

        newanimdlg.Destroy()
Ejemplo n.º 22
0
#!/usr/bin/env python

#-Imports.--------------------------------------------------------------------

#--wxPython Imports.
import wx
import wx.lib.imagebrowser as IB

if __name__ == '__main__':
    app = wx.App(False)

    dlg = IB.ImageDialog(None)
    dlg.Centre()
    if dlg.ShowModal() == wx.ID_OK:
        print("You Selected File: " + dlg.GetFile())
    else:
        print("You pressed Cancel")
    dlg.Destroy()

    app.MainLoop()
Ejemplo n.º 23
0
    def OnToolClick(self, evt):
        tid = evt.GetId()

        # new file
        if tid == self.tidNew:
            if self.dirty:
                if wx.MessageBox('Data will be lost... Continue?', 'Confirm',
                                 wx.YES_NO) == wx.NO:
                    return
            self.lbkScan.New()
            self.dirty = False

        # text mode scan
        elif tid == self.tidText:
            self.ScanPage('Text')

        # image mode scan
        elif tid == self.tidImage:
            self.ScanPage('Image')

        # copy to clipboard
        elif tid == self.tidClip:
            if self.toolbar.GetToolState(tid):
                self.EnableControls('RBand')
                self.status.SetStatusText('Select region to copy')
                self.lbkScan.StartRBand()
            else:
                self.status.SetStatusText('Image copied to clipboard')
                self.lbkScan.StopRBand()
                self.EnableControls('Normal')

        # load image file
        elif tid == self.tidLoad:
            dlg = ib.ImageDialog(self, IMAGE_DIR)
            dlg.Centre()

            # image with certain margin around
            if dlg.ShowModal() == wx.ID_OK:

                fpath = dlg.GetFile()
                img, res = self.LoadFile(fpath)

                if img is not None:
                    self.lbkScan.AddData({
                        'src':
                        img,
                        'info':
                        fpath.rpartition('/')[2].rpartition('.')[0],
                        'dpi': (res, res),
                        'settings':
                        self.GetImgSettings()
                    })
                    self.dirty = True
                else:
                    self.status.SetStatusText('Failed to load the image file.')

            dlg.Destroy()

        # delete the page
        elif tid == self.tidDelete:
            self.lbkScan.Delete()

        # save data
        elif tid == self.tidSave:
            self.SaveFile()

        # change default scan mode
        elif tid == self.tidSetup:
            dlg = SetupDialog(self)
            dlg.FillChoiceLists(self.scanner.GetModes(),
                                self.scanner.GetResolutions(),
                                self.scanner.GetScanAreas())
            dlg.SetSelections(self.txtScanPrms, self.imgScanPrms)

            if dlg.ShowModal() == wx.ID_OK:
                (self.txtScanPrms, self.imgScanPrms) = dlg.GetSelections()

            dlg.Destroy()
Ejemplo n.º 24
0
    def SelectProp(self, evt):
        """
		"""

        row, col = evt.GetRow(), evt.GetCol()

        table = self.GetTable()

        typ = table.dataTypes[row][1]
        prop = self.GetCellValue(row, 0)

        if prop == 'fill' or re.findall(
                "[.]*color[.]*", prop, flags=re.IGNORECASE):
            val = self.GetCellValue(row, 1)
            dlg = wx.ColourDialog(self.parent)
            dlg.GetColourData().SetChooseFull(True)
            if dlg.ShowModal() == wx.ID_OK:
                data = dlg.GetColourData()
                val = str([RGBToHEX(data.GetColour().Get())])
                self.SetCellValue(row, 1, val)
            else:
                dlg.Destroy()
                return False

            dlg.Destroy()

            self.AcceptProp(row, col)

        elif prop == 'font':
            val = eval(self.GetCellValue(row, 1))
            default_font = wx.Font(val[0], val[1], val[2], val[3], False,
                                   val[4])
            data = wx.FontData()
            if sys.platform == 'win32':
                data.EnableEffects(True)
            data.SetAllowSymbols(False)
            data.SetInitialFont(default_font)
            data.SetRange(10, 30)
            dlg = wx.FontDialog(self.parent, data)
            if dlg.ShowModal() == wx.ID_OK:
                data = dlg.GetFontData()
                font = data.GetChosenFont()
                color = data.GetColour()
                val = [
                    font.GetPointSize(),
                    font.GetFamily(),
                    font.GetStyle(),
                    font.GetWeight(),
                    font.GetFaceName()
                ]
                self.SetCellValue(row, 1, str(val))
            else:
                dlg.Destroy()
                return False

            dlg.Destroy()

            self.AcceptProp(row, col)

        elif prop == 'label':

            d = LabelGUI.LabelDialog(self.parent, self.parent.model)
            d.ShowModal()

            self.SetCellValue(row, 1, str(self.parent.model.label))
            self.AcceptProp(row, col)

        elif prop == 'image_path':

            dlg = ib.ImageDialog(self, os.path.join(HOME_PATH))
            dlg.Centre()

            if dlg.ShowModal() == wx.ID_OK:
                val = os.path.normpath(dlg.GetFile())
                if val != self.GetCellValue(row, 1):
                    self.SetCellValue(row, 1, val)
                    self.canvas.UpdateShapes([self.parent.model])
            else:
                dlg.Destroy()
                return False

            dlg.Destroy()

            self.AcceptProp(row, col)

        elif 'filename' in str(prop).lower():
            wcd = _('Data files All files (*)|*')
            val = self.GetCellValue(row, 1)
            default_dir = os.path.dirname(val) if os.path.exists(
                os.path.dirname(val)) else HOME_PATH
            dlg = wx.FileDialog(self,
                                message=_("Select file ..."),
                                defaultDir=default_dir,
                                defaultFile="",
                                wildcard=wcd,
                                style=wx.OPEN | wx.CHANGE_DIR)
            if dlg.ShowModal() == wx.ID_OK:
                val = os.path.normpath(dlg.GetPath())
                if val != self.GetCellValue(row, 1):
                    self.SetCellValue(row, 1, val)
                    self.canvas.UpdateShapes([self.parent.model])
            else:
                dlg.Destroy()
                return False

            dlg.Destroy()

            self.AcceptProp(row, col)

        elif prop == 'python_path':

            model = self.parent.model

            ### for .amd or .cmd
            if model.model_path != '':
                wcd = _(
                    'Atomic DEVSimPy model (*.amd)|*.amd|Coupled DEVSimPy model (*.cmd)|*.cmd|All files (*)|*'
                )
            else:
                wcd = _('Python files (*.py)|*.py|All files (*)|*')

            default_dir = os.path.dirname(model.python_path) if os.path.exists(
                os.path.dirname(model.python_path)) else DOMAIN_PATH
            dlg = wx.FileDialog(self,
                                message=_("Select file ..."),
                                defaultDir=default_dir,
                                defaultFile="",
                                wildcard=wcd,
                                style=wx.OPEN | wx.CHANGE_DIR)
            if dlg.ShowModal() == wx.ID_OK:
                new_python_path = os.path.normpath(dlg.GetPath())

                ### if the user would like to load a compressed python file, he just give the name of compressed file that contain the python file
                if zipfile.is_zipfile(new_python_path):
                    zf = zipfile.ZipFile(new_python_path, 'r')
                    new_python_path = os.path.join(
                        new_python_path,
                        filter(
                            lambda f: f.endswith('.py') and f != 'plugins.py',
                            zf.namelist())[0])
                    ### update model path
                    model.model_path = os.path.dirname(new_python_path)

                self.SetCellValue(row, 1, new_python_path)

                # behavioral args update (because depends of the new class coming from new python file)
                new_cls = Components.GetClass(new_python_path)

                if inspect.isclass(new_cls):

                    ### update attributes (behavioral ang graphic)
                    model.args = Components.GetArgs(new_cls)
                    model.SetAttributes(Attributable.GRAPHICAL_ATTR)

                    ### TODO: when ScopeGUI and DiskGUI will be amd models, delete this line)
                    ### delete xlabel and ylabel attributes if exist
                    model.RemoveAttribute('xlabel')
                    model.RemoveAttribute('ylabel')
                    ### Update of DEVSimPy model from new python behavioral file (ContainerBlock is not considered because he did not behavioral)
                    if new_cls.__name__ in ('To_Disk', 'MessagesCollector'):
                        model.__class__ = Container.DiskGUI
                    elif new_cls.__name__ == 'QuickScope':
                        model.__class__ = Container.ScopeGUI
                        model.AddAttribute("xlabel")
                        model.AddAttribute("ylabel")
                    elif True in map(lambda a: 'DomainStructure' in str(a),
                                     new_cls.__bases__):
                        model.__class__ = Container.ContainerBlock
                    else:
                        model.__class__ = Container.CodeBlock

                    ### if we change the python file from zipfile we compresse the new python file and we update the python_path value
                    if zipfile.is_zipfile(model.model_path):
                        zf = ZipManager.Zip(model.model_path)
                        zf.Update([new_python_path])
                        #model.model_path =

                    ### update flag and color if bad filename
                    if model.bad_filename_path_flag:
                        model.bad_filename_path_flag = False
                else:
                    Container.MsgBoxError(evt, self, new_cls)
                    dlg.Destroy()
                    return False
            else:
                dlg.Destroy()
                return False

            dlg.Destroy()

            self.AcceptProp(row, col)

        elif typ == "list":
            frame = ListEditor(self,
                               wx.ID_ANY,
                               _('List editor'),
                               values=self.GetCellValue(row, 1))
            if frame.ShowModal() == wx.ID_CANCEL:
                self.SetCellValue(row, 1, frame.GetValueAsString())
            else:
                frame.Destroy()

            self.AcceptProp(row, col)

        elif typ == 'dict':
            frame = DictionaryEditor(self,
                                     wx.ID_ANY,
                                     _('List editor'),
                                     values=self.GetCellValue(row, 1))
            if frame.ShowModal() == wx.ID_CANCEL:
                self.SetCellValue(row, 1, frame.GetValueAsString())
            else:
                frame.Destroy()

            self.AcceptProp(row, col)
        elif 'choice' in typ:
            self.AcceptProp(row, col)
        else:
            pass

        ### all properties grid update (because the python classe has been changed)
        ### here, because OnAcceptProp should be executed before
        if prop == 'python_path':

            ### Update table from new model
            table.UpdateRowBehavioralData(model)
            self.SetTable(table, False)
            self.ForceRefresh()
            self.AutoSizeColumns()

            # code updating
            if isinstance(model, Achievable):
                new_code = CodeCB(self.parent, wx.ID_ANY, model)
                #self.parent.boxH.Remove(0)
                if hasattr(self.parent, '_boxH'):
                    # DeleteWindows work better in vista
                    if wx.VERSION_STRING < '4.0':
                        self.parent._boxH.DeleteWindows()
                        self.parent._boxH.AddWindow(new_code,
                                                    1,
                                                    wx.EXPAND,
                                                    userData='code')
                    else:
                        self.parent._boxH.Clear()
                        self.parent._boxH.Add(new_code,
                                              1,
                                              wx.EXPAND,
                                              userData='code')

                    self.parent._boxH.Layout()
                else:
                    sys.stdout.write("_boxH is unknown!")
Ejemplo n.º 25
0
class NameIconWizardPage(WizardPageSimple):
    """ Ask user for public name and icon """
    def __init__(self, parent, type):
        WizardPageSimple.__init__(self, parent)
        self.utility = parent.utility

        # 0. mainbox
        mainbox = wx.BoxSizer(wx.VERTICAL)

        # 1. topbox
        topbox = wx.BoxSizer(wx.VERTICAL)

        # Ask public name
        name = self.utility.session.get_nickname()

        name_box = wx.BoxSizer(wx.HORIZONTAL)
        self.myname = wx.TextCtrl(self, -1, name)
        name_box.Add(wx.StaticText(self, -1, self.utility.lang.get('myname')),
                     0, wx.ALIGN_CENTER_VERTICAL)
        name_box.Add(self.myname, 0,
                     wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, 5)
        topbox.Add(name_box, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
                   5)

        # Ask public user icon / avatar
        icon_box = wx.BoxSizer(wx.HORIZONTAL)
        icon_box.Add(wx.StaticText(self, -1, self.utility.lang.get('myicon')),
                     0, wx.ALIGN_CENTER_VERTICAL)

        ## TODO: integrate this code with makefriends.py, especially checking code
        self.iconbtn = None
        self.iconmime, self.icondata = self.utility.session.get_mugshot()
        if self.icondata:
            bm = data2wxBitmap(self.iconmime, self.icondata)
        else:
            im = IconsManager.getInstance()
            bm = im.get_default('personsMode', 'DEFAULT_THUMB')

        self.iconbtn = wx.BitmapButton(self, -1, bm)
        icon_box.Add(self.iconbtn, 0,
                     wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, 5)
        #label = wx.StaticText(self, -1, self.utility.lang.get('obligiconformat'))
        #icon_box.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
        self.Bind(wx.EVT_BUTTON, self.OnIconButton, self.iconbtn)
        topbox.Add(icon_box, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
                   5)

        mainbox.Add(topbox, 0, wx.EXPAND)
        self.SetSizerAndFit(mainbox)

    def OnIconButton(self, evt):
        try:
            if sys.platform == 'win32':
                # Arno goes win32, find location of "My Pictures"
                # see http://www.mvps.org/access/api/api0054.htm
                from win32com.shell import shell
                pidl = shell.SHGetSpecialFolderLocation(0, 0x27)
                path = shell.SHGetPathFromIDList(pidl)
            else:
                path = os.path.expandvars('$HOME')
        except Exception, msg:
            path = ''
            print_exc()

        # open the image browser dialog
        dlg = ib.ImageDialog(self, path)
        dlg.Centre()
        if dlg.ShowModal() == wx.ID_OK:
            self.iconpath = dlg.GetFile()

            try:
                im = wx.Image(self.iconpath)
                if im is None:
                    self.show_inputerror(self.utility.lang.get('cantopenfile'))
                else:
                    bm = wx.BitmapFromImage(im.Scale(64, 64), -1)
                    self.iconbtn.SetBitmapLabel(bm)
                    iconfile = file(self.iconpath, 'rb')
                    self.icondata = iconfile.read()
                    self.iconmime = mimetypes.guess_type(
                        self.iconpath)[0] or 'image/jpeg'
                    iconfile.close()
            except:
                self.show_inputerror(self.utility.lang.get('iconbadformat'))
        else:
            pass

        dlg.Destroy()
Ejemplo n.º 26
0
 def OnColor(self,event):
     dialog = imagebrowser.ImageDialog(self, set_dir = 'c:\MS\thesis\python')
     if dialog.ShowModal()== wx.ID_OK:
         print "you selected file:" + dialog.GetFile()
     dialog.Destroy()
Ejemplo n.º 27
0
 def test_imagebrowserDlgChangeTypes(self):
     dlg = ib.ImageDialog(None)
     dlg.ChangeFileTypes(
         (("GIF (*.gif)", "*.gif"), ("PNG (*.png)", "*.png")))
     dlg.Destroy()
Ejemplo n.º 28
0
    def __init__(self, parent, key, val, global_config, env):
        if DEBUG: print key, val
        self.parent = parent
        self.env = env
        self.key = key
        self.val = val
        self.global_config = global_config
        self.env = env

        WIDGET_W = global_config['CONFIG_WIDGET_W']['value']
        WIDGET_H = global_config['CONFIG_WIDGET_H']['value']
        self.wsize = wx.Size(WIDGET_W, WIDGET_H)

        self.sbox = wx.StaticBox(self.parent, -1, key, style=wx.BORDER_STATIC)
        self.sbox.SetWindowStyle(wx.BORDER_NONE)

        self.sizer = wx.StaticBoxSizer(self.sbox, wx.HORIZONTAL)
        self.widget = None
        self.label = None
        self.defaultB = None
        self.showColourDialogB = None
        self.defaultBID = wx.NewId()
        self.set = 0
        self.bmp = None

        #every CfgCtrlObj has a defaultB:
        self.defaultB = wx.Button(self.parent,
                                  self.defaultBID,
                                  "Default",
                                  size=self.wsize)

        if self.val['wtype'] == 'wx.ComboBox':
            cbID = wx.NewId()
            cb = wx.ComboBox(self.parent, cbID, size=self.wsize, choices=[])
            for idx in range(len(self.val['default'])):
                cb.Append(self.val['default'][idx])
            cb.SetValue(self.val['value'])
            self.widget = cb

            #self.widget.SetValue(self.val['value'])
            self.sizer.Add(self.widget)
            wx.EVT_COMBOBOX(self.parent, cbID, self.comboCB)

            if self.val['icon']:
                #in this version, if icon, then actor.
                fname = os.path.abspath(
                    os.path.join(self.env.sitepkgdir, global_config['APPNAME'],
                                 'Actors', self.val['value'], 'icon.gif'))
                gif = wx.Image(fname, wx.BITMAP_TYPE_GIF).ConvertToBitmap()
                self.bmp = wx.StaticBitmap(
                    self.parent, -1, gif)  #,size=wx.Size(WIDGET_W,WIDGET_W)
                self.sizer.Add(self.bmp)
            else:
                self.label = wx.StaticText(self.parent,
                                           wx.NewId(),
                                           '',
                                           size=self.wsize)
                self.sizer.Add(self.label)

            wx.EVT_BUTTON(self.defaultB, self.defaultBID, self.defaultCB)

        elif self.val['wtype'] == 'wx.TextCtrl':
            self.widget = wx.TextCtrl(self.parent,
                                      wx.NewId(),
                                      style=self.val['style'],
                                      size=self.wsize)
            self.widget.SetValue(self.val['value'])
            self.widget.SetLabel(self.val['descr'])
            self.sizer.Add(self.widget)

            label_str = ''
            self.label = wx.StaticText(self.parent,
                                       wx.NewId(),
                                       label_str,
                                       size=self.wsize)
            self.sizer.Add(self.label)

            wx.EVT_BUTTON(self.defaultB, self.defaultBID, self.defaultCB)

        elif self.val['wtype'] == 'wx.ImageDialog':
            ImgBrowserID = wx.NewId()
            self.widget = ib.ImageDialog(
                self.parent,
                self.val['path'],
            )

            ibID = wx.NewId()
            self.ibB = wx.Button(self.parent,
                                 ibID,
                                 "ImageDialog",
                                 size=self.wsize)
            self.sizer.Add(self.ibB)
            wx.EVT_BUTTON(self.ibB, ibID, self.imagedialogCB)

            label_str = ''
            self.label = wx.StaticText(self.parent,
                                       wx.NewId(),
                                       label_str,
                                       size=self.wsize)
            self.label.SetLabel(self.val['value'])
            self.sizer.Add(self.label)

            wx.EVT_BUTTON(self.defaultB, self.defaultBID, self.defaultCB)

        elif self.val['wtype'] == 'wx.FileDialog':

            FileDialogID = wx.NewId()
            self.widget = wx.FileDialog(
                self.parent,
                message="Choose file",
                defaultDir=self.val['path'],
            )

            fdID = wx.NewId()
            self.fdB = wx.Button(self.parent,
                                 fdID,
                                 "ShowDialog",
                                 size=self.wsize)
            self.sizer.Add(self.fdB)
            wx.EVT_BUTTON(self.fdB, fdID, self.filedialogCB)

            label_str = ''
            self.label = wx.StaticText(self.parent,
                                       wx.NewId(),
                                       label_str,
                                       size=self.wsize)
            self.label.SetLabel(self.val['value'])
            self.sizer.Add(self.label)

            wx.EVT_BUTTON(self.defaultB, self.defaultBID, self.defaultCB)

        elif self.val['wtype'] == 'wx.CheckBox':
            CheckBoxID = wx.NewId()
            self.widget = wx.CheckBox(self.parent,
                                      CheckBoxID,
                                      "",
                                      size=self.wsize)
            self.widget.SetValue(int(self.val['value']))
            self.sizer.Add(self.widget)
            wx.EVT_CHECKBOX(self.widget, CheckBoxID, self.checkboxCB)

            label_str = ''
            self.label = wx.StaticText(self.parent,
                                       wx.NewId(),
                                       label_str,
                                       size=self.wsize)
            self.label.SetLabel( ` self.val['value'] `)
            self.sizer.Add(self.label)

            wx.EVT_BUTTON(self.defaultB, self.defaultBID, self.defaultCB)

            self.checkboxCB(None)  #to set the label after label exists

        elif self.val['wtype'] == 'wx.SpinCtrl':
            SpinCtrlID = wx.NewId()
            self.widget = wx.SpinCtrl(self.parent, SpinCtrlID, size=self.wsize)
            self.widget.SetRange(self.val['min'], self.val['max'])
            self.widget.SetValue(int(self.val['value']))
            self.sizer.Add(self.widget)
            wx.EVT_SPINCTRL(self.widget, SpinCtrlID, self.spinctrlCB)

            label_str = ''
            self.label = wx.StaticText(self.parent,
                                       wx.NewId(),
                                       label_str,
                                       size=self.wsize)
            self.label.SetLabel( ` self.val['value'] `)
            self.sizer.Add(self.label)

            wx.EVT_BUTTON(self.defaultB, self.defaultBID, self.defaultCB)

        elif self.val['wtype'] == 'wx.ColourDialog':

            self.widget = wx.ColourDialog(self.parent)
            self.widget.GetColourData().SetChooseFull(True)
            self.widget.GetColourData().SetColour(
                wx.Colour(self.val['value'][0], self.val['value'][1],
                          self.val['value'][2]))

            showColourDialogBID = wx.NewId()
            self.showColourDialogB = wx.Button(self.parent,
                                               showColourDialogBID,
                                               "ShowDialog",
                                               size=self.wsize)
            self.showColourDialogB.SetBackgroundColour(
                self.widget.GetColourData().GetColour().Get())
            self.sizer.Add(self.showColourDialogB)
            wx.EVT_BUTTON(self.showColourDialogB, showColourDialogBID,
                          self.showColourDialogCB)

            label_str = ''
            self.label = wx.StaticText(self.parent,
                                       wx.NewId(),
                                       label_str,
                                       size=self.wsize)
            self.label.SetLabel( ` self.val['value'] `)
            self.sizer.Add(self.label)

            self.defaultB.SetBackgroundColour(self.val['default'])
            wx.EVT_BUTTON(self.defaultB, self.defaultBID, self.defaultCB)

        elif self.val['wtype'] == 'wx.Slider':

            self.widget = wx.Slider(self.parent,
                                    wx.NewId(),
                                    int(self.val['value'] *
                                        self.val['divisor']),
                                    int(self.val['min']),
                                    int(self.val['max']),
                                    style=self.val['style'],
                                    size=self.wsize)

            self.sizer.Add(self.widget)

            sliderID = wx.NewId()
            div = self.val['divisor']
            if div == 1.: label_str = "%.0f" % (self.val['value'])
            if div == 10.: label_str = "%.1f" % (self.val['value'])
            if div == 100.: label_str = "%.2f" % (self.val['value'])
            if div == 1000.: label_str = "%.3f" % (self.val['value'])
            if div == 10000.: label_str = "%.4f" % (self.val['value'])

            self.label = wx.StaticText(self.parent,
                                       sliderID,
                                       label_str,
                                       size=self.wsize)
            self.sizer.Add(self.label)

            wx.EVT_BUTTON(self.defaultB, self.defaultBID, self.defaultCB)
            wx.EVT_SCROLL(self.widget, self.sliderCB)

        self.sizer.Add(self.defaultB)
        if self.val.has_key('tooltip'):
            if DEBUG: print self.val
            self.defaultB.SetToolTip(wx.ToolTip(self.val['tooltip']))
Ejemplo n.º 29
0
class MakeFriendsDialog(wx.Dialog):
    def __init__(self, parent, utility, editfriend=None):
        #provider = wx.SimpleHelpProvider()
        #wx.HelpProvider_Set(provider)

        self.utility = utility
        self.editfriend = editfriend

        style = wx.DEFAULT_DIALOG_STYLE
        #| wx.RESIZE_BORDER
        pos = wx.DefaultPosition
        size = wx.Size(600, 200)
        #size, split = self.getWindowSettings()

        if editfriend is None:
            title = self.utility.lang.get('addfriend')
        else:
            title = self.utility.lang.get('editfriend')
        wx.Dialog.__init__(self, parent, -1, title, size=size, style=style)
        pre = wx.PreDialog()
        pre.SetExtraStyle(wx.DIALOG_EX_CONTEXTHELP)
        pre.Create(parent, -1, title, pos, size, style)
        self.PostCreate(pre)

        sizer = wx.BoxSizer(wx.VERTICAL)

        label = wx.StaticText(self, -1, title)
        sizer.Add(label, 0, wx.ALIGN_CENTRE | wx.ALL, 5)

        # name
        box = wx.BoxSizer(wx.HORIZONTAL)

        label = wx.StaticText(self, -1,
                              self.utility.lang.get('name') + ':',
                              wx.DefaultPosition, wx.Size(40, 18))
        #label.SetHelpText("")
        box.Add(label, 0, wx.ALIGN_CENTRE | wx.ALL, 5)

        if editfriend is not None:
            name = editfriend['name']
        else:
            name = ''
        self.name_text = wx.TextCtrl(self, -1, name, size=(140, -1))
        ##self.name_text.SetHelpText(self.utility.lang.get('nickname_help'))
        box.Add(self.name_text, 0, wx.ALIGN_CENTRE | wx.ALL, 5)

        sizer.Add(box, 0, wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)

        # text about e-mail invitation
        label = wx.StaticText(self, -1,
                              self.utility.lang.get('pasteinvitationemail'),
                              wx.DefaultPosition)
        label.Wrap(500)
        sizer.Add(label, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)

        # ip
        box = wx.BoxSizer(wx.HORIZONTAL)

        label = wx.StaticText(self, -1,
                              self.utility.lang.get('ipaddress') + ':',
                              wx.DefaultPosition, wx.Size(40, 18))
        #label.SetHelpText("")
        box.Add(label, 0, wx.ALIGN_CENTRE | wx.ALL, 5)

        if editfriend is not None:
            ip = editfriend['ip']
        else:
            ip = ''
        self.ip_text = wx.TextCtrl(self, -1, ip, size=(140, -1))
        ##self.ip_text.SetHelpText(self.utility.lang.get('friendsipaddr_help'))
        box.Add(self.ip_text, 0, wx.ALIGN_CENTRE | wx.ALL, 5)

        sizer.Add(
            box, 0, wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT
            | wx.BOTTOM, 5)

        # port
        box = wx.BoxSizer(wx.HORIZONTAL)

        label = wx.StaticText(self, -1, self.utility.lang.get('portnumber'),
                              wx.DefaultPosition, wx.Size(40, 18))
        #label.SetHelpText("")
        box.Add(label, 0, wx.ALIGN_CENTRE | wx.ALL, 5)

        if editfriend is not None:
            port_str = str(editfriend['port'])
        else:
            port_str = ''
        self.port_text = wx.TextCtrl(self, -1, port_str, size=(140, -1))
        ##self.port_text.SetHelpText(self.utility.lang.get('friendsport_help'))
        box.Add(self.port_text, 0, wx.ALIGN_CENTRE | wx.ALL, 5)

        sizer.Add(
            box, 0, wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT
            | wx.BOTTOM, 5)

        # permid
        box = wx.BoxSizer(wx.HORIZONTAL)

        label = wx.StaticText(self, -1,
                              self.utility.lang.get('permid') + ':',
                              wx.DefaultPosition, wx.Size(40, 18))
        #label.SetHelpText("")
        box.Add(label, 0, wx.ALIGN_CENTRE | wx.ALL, 5)

        if editfriend is not None:
            permid = show_permid(editfriend['permid'])
        else:
            permid = ''
        self.permid_text = wx.TextCtrl(self, -1, permid, size=(300, -1))
        ## self.permid_text.SetHelpText(self.utility.lang.get('friendspermid_help'))
        box.Add(self.permid_text, 0, wx.ALIGN_CENTRE | wx.ALL, 5)

        sizer.Add(box, 0, wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5)
        """
        # picture
        box = wx.BoxSizer(wx.HORIZONTAL)

        label = wx.StaticText(self, -1, self.utility.lang.get('icon'))
        #label.SetHelpText("")
        box.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5)

        if editfriend is not None and editfriend.has_key('icon'):
            icon = str(editfriend['icon'])
        else:   
            icon = ''
        self.icon_path = wx.TextCtrl(self, -1, icon, size=(80,-1))
        ## self.icon_path.SetHelpText(self.utility.lang.get('friendsicon_help'))
        box.Add(self.icon_path, 3, wx.ALIGN_CENTRE|wx.ALL, 5)
        
        iconbtn = wx.Button(self, -1, label=self.utility.lang.get('browsebtn'))
        box.Add(iconbtn, 1, wx.ALIGN_CENTRE|wx.ALL, 5)
        self.Bind(wx.EVT_BUTTON, self.OnIconButton, iconbtn)

        sizer.Add(box, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        """

        box = wx.BoxSizer(wx.HORIZONTAL)
        line = wx.StaticLine(self, -1, size=(20, -1), style=wx.LI_HORIZONTAL)
        sizer.Add(line, 0,
                  wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.RIGHT | wx.TOP, 5)
        btnsizer = wx.StdDialogButtonSizer()

        ##if (sys.platform != 'win32'):
        ##    btn = wx.ContextHelpButton(self)
        ##    btnsizer.AddButton(btn)

        if editfriend is None:
            lbl = self.utility.lang.get('buttons_add')
        else:
            lbl = self.utility.lang.get('buttons_update')
        btn = wx.Button(self, wx.ID_OK, label=lbl)
        btn.SetDefault()
        btnsizer.AddButton(btn)
        self.Bind(wx.EVT_BUTTON, self.OnAddEditFriend, btn)

        btn = wx.Button(self, wx.ID_CANCEL)
        btnsizer.AddButton(btn)
        btnsizer.Realize()

        #sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        sizer.Add(btnsizer, 0, wx.ALIGN_CENTER | wx.ALL, 5)

        self.SetSizer(sizer)
        sizer.Fit(self)

    def OnAddEditFriend(self, event):
        name = self.name_text.GetValue()
        ip = str(self.ip_text.GetValue())
        b64permid = str(self.permid_text.GetValue())
        try:
            permid = base64.decodestring(b64permid + '\n')
        except:
            print_exc()
            permid = ''
        #icon = self.icon_path.GetValue()
        try:
            port = int(self.port_text.GetValue())
        except:
            port = 0

        if len(name) == 0:
            self.show_inputerror(self.utility.lang.get('nicknameempty_error'))
        elif len(permid) == 0:
            self.show_inputerror(self.utility.lang.get('friendspermid_error'))
        elif port == 0:
            self.show_inputerror(self.utility.lang.get('friendsport_error'))
        else:
            fdb = FriendDBHandler.getInstance()
            pdb = PeerDBHandler.getInstance()

            #friend = {'permid':permid, 'ip':ip, 'port':port, 'name':name, 'icon':newiconfilename}
            #friend = {'permid':permid, 'ip':ip, 'port':port, 'name':name}
            friend = {'ip': ip, 'port': port, 'name': name}
            if self.editfriend is not None:
                if self.editfriend['permid'] != permid:
                    fdb.deleteFriend(self.editfriend['permid'])
                    pdb.deletePeer(self.editfriend['permid'])

            #fdb.addExternalFriend(friend)
            pdb.addPeer(permid, friend)
            fdb.setFriend(permid)

            event.Skip(
            )  # must be done, otherwise ShowModal() returns wrong error
            self.Destroy()
        """            
        elif icon != '' and not os.path.exists(icon):
            self.show_inputerror(self.utility.lang.get('fiendsiconnotfound_error'))
        else:
            newiconfilename = ''
            if icon != '':
                ret = self.mm.create_from_file(permid,icon)
                if not ret:
                    self.show_inputerror(self.utility.lang.get('friendsiconnotbmp_error'))
                    return
        """

    def OnIconButton(self, evt):
        # get current working directory
        # TODO: record the last opened path in config file
        try:
            path = os.path.join(os.getcwd(), 'icons')
            path = os.path.join(path, 'mugshots')
        except Exception, msg:
            path = ''

        # open the image browser dialog
        dlg = ib.ImageDialog(self, path)

        dlg.Centre()

        if dlg.ShowModal() == wx.ID_OK:
            self.icon_path.SetValue(dlg.GetFile())
        else:
            pass

        dlg.Destroy()
Ejemplo n.º 30
0
    def OnAbrirImage1(self, event):
        wildcard = "JPG (*.jpg)|*.jpg|" "PNG (*.png)|*.png|" "GIF (*.gif)|*.gif|"
        dialog = imagebrowser.ImageDialog(None)

        if dialog.ShowModal() == wx.ID_OK:
            wx.MessageBox(dialog)