wx_util.py :  » Business-Application » hylaPEx » hylapex » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Business Application » hylaPEx 
hylaPEx » hylapex » wx_util.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

import os, sys, exceptions, string, traceback
from library.ftp import read_conf
import wx, wx.grid, types

class resize:
    def __init__(self, wx, lst_pos = {}, lst_not_use = ['wx.Timer'], default = 'm', min_dim = 1, deb = 0):
        #wx is the instance of a frame
        #
        #lst_pos is a dict that contain a key with the name of a control (string)
        #and a value (string) m (I move the widget), r (I resize), l (I leave it there is). 
        #min_pos is 0, 1, 2, 3 and it control if the frame must have a mini dimension, 1 controll all, 
        #2 control the height, 3 control the weight
        #
        #To use wxresize: 
        #1)put in your __init__
        #  self.wx = wx_util.resize(self,{'some_control':'m',})
        #  there same_control is a control that U want to resize
        #2)put a EVT_SIZE(self, self.OnFrameSize) in your Frame
        #  and create a OnFrameSize(self, event) function with a 
        #    self.wx.ctrl_size()
        #    event.Skip()
        #That's all
        #
        self.wx = wx
        self.lst_pos = lst_pos
        self.default = default
        self.min_dim = min_dim
        self.lst_not_use = lst_not_use
        self.inst = getCtrls(wx)
        self.deb = deb
        #Now self.inst is a dict with {Name: [type, instance]}
        self.__frm()
    def __frm(self):
        #Get the init position of the frame
        self.frm_size_h_init, self.frm_size_l_init = self.wx.GetSize()
        self.dim_init={}
        #Get the init position of the widgets
        for widget in self.inst.keys():
            w = self.inst[widget]
            if w in self.lst_not_use: continue
            dim_tmp = []
            try:
                dim_tmp.append(w[1].GetSize())
                dim_tmp.append(w[1].GetPosition())
                size_h, size_l = w[1].GetSize()
                pos_h, pos_l = w[1].GetPosition()
                dim_tmp.append(self.frm_size_h_init - (pos_h + size_h))
                dim_tmp.append(self.frm_size_l_init - (pos_l + size_l))
                #dict self.dim_init has in every list: 
                # absolute size, absolute position, dist from h, dist from l
                self.dim_init[widget] = dim_tmp
            except:
                pass
    def ctrl_size(self):
        frm_size_h, frm_size_l = self.wx.GetSize()
        #Control the dims of frame, if is lesser thant init dim, resize
        if self.min_dim == 1 and (frm_size_h < self.frm_size_h_init \
            or frm_size_l < self.frm_size_l_init):
            self.wx.SetSize((self.frm_size_h_init, self.frm_size_l_init))
            frm_size_h = self.frm_size_h_init
            frm_size_l = self.frm_size_l_init
        elif self.min_dim == 2 and (frm_size_h < self.frm_size_h_init):
            self.wx.SetSize((self.frm_size_h_init, frm_size_l))
            frm_size_h = self.frm_size_h_init
        elif self.min_dim == 3 and (frm_size_l < self.frm_size_l_init):
            self.wx.SetSize((self.frm_size_l_init, frm_size_h))
            frm_size_l = self.frm_size_l_init
        elif self.min_dim == 4 and (frm_size_l > self.frm_size_l_init):
            self.wx.SetSize((frm_size_h, self.frm_size_l_init))
            frm_size_l = self.frm_size_l_init            
        #Go with widgets
        lst_wigets = self.lst_pos.keys()
        for widget in self.inst:
            w = self.inst[widget] 
            if w[0] in self.lst_not_use: continue
            if self.default == 'l' and widget not in lst_wigets: continue
            size_h, size_l = w[1].GetSize()
            pos_h, pos_l = w[1].GetPosition()
            dist_h = frm_size_h - (pos_h + size_h)
            dist_l = frm_size_l - (pos_l + size_l)
            tmp = self.dim_init[widget]
            if self.deb:
                print widget
            #Move the widget horrizontaly and verticaly
            if (not widget in self.lst_pos and self.default == 'm') or \
                (widget in self.lst_pos and self.lst_pos[widget] == 'm'):
                new_pos_h = frm_size_h - (tmp[0][0] + tmp[2])
                new_pos_l = frm_size_l - (tmp[0][1] + tmp[3])
                w[1].SetPosition((new_pos_h, new_pos_l))
            #Move the widget horrizontaly
            elif (not widget in self.lst_pos and self.default == 'mh') or \
                (widget in self.lst_pos and self.lst_pos[widget] == 'mh'):
                new_pos_h = frm_size_h - (tmp[0][0] + tmp[2])
                w[1].SetPosition((new_pos_h, tmp[1][1]))
            #Move the widget verticaly
            elif (not widget in self.lst_pos and self.default == 'mv') or \
                (widget in self.lst_pos and self.lst_pos[widget] == 'mv'):
                new_pos_l = frm_size_l - (tmp[0][1] + tmp[3])
                w[1].SetPosition((tmp[1][0], new_pos_l))
            #Resize the widget horrizontaly and verticaly
            elif (not widget in self.lst_pos and self.default == 'r') or \
                (widget in self.lst_pos and self.lst_pos[widget] == 'r'):
                new_dim_h = frm_size_h - (tmp[1][0] + tmp[2])
                new_dim_l = frm_size_l - (tmp[1][1] + tmp[3])
                w[1].SetSize((new_dim_h, new_dim_l))
            #Resize the widget verticaly
            elif (not widget in self.lst_pos and self.default == 'rv') or \
                (widget in self.lst_pos and self.lst_pos[widget] == 'rv'):
                new_dim_l = frm_size_l - (tmp[1][1] + tmp[3])
                w[1].SetSize((tmp[0][0], new_dim_l))
            #Resize the widget verticaly
            elif (not widget in self.lst_pos and self.default == 'rh') or \
                (widget in self.lst_pos and self.lst_pos[widget] == 'rh'):
                new_dim_h = frm_size_h - (tmp[1][0] + tmp[2])
                w[1].SetSize((new_dim_h, tmp[0][1]))
            #Leave the widget where is
            elif (not widget in self.lst_pos and self.default == 'l') or \
                (widget in self.lst_pos and self.lst_pos[widget] == 'l'):
                continue


class rename_ctrls:
    def __init__(self, wx, frm, path = None, lang = 'it', exclude = []):
        if path:
            self.my_path = path
        else:
            self.my_path = os.path.dirname(os.path.abspath(sys.argv[0]))
        
        self.exclude = exclude
        self.frm = frm
        self.wx = wx
        self.inst = getCtrls(wx)
        self.file_name = os.path.join(self.my_path, prefix_lang_file + lang)

    def rename(self):
        self.conf = read_conf.conf_parser(self.file_name, self.frm)
        if self.conf.exist():
            return
        
        if not self.conf.has_section(self.frm): 
            self.__update_lang_file(self.conf)
            self.conf.exit()
            return
        #self.__update_new_ctrls(self.conf)
        #print self.inst.keys()
        vals = self.conf.get_items_dict()
        
        for val in vals.keys():
            self.__set_name(val, vals[val])
                
    def get_all(self):
        return self.conf.get_items_dict()
        
    def get(self, val, default=0):
        return self.conf.get(val, default=default)

    def get_list(self, val, default=0):
        tmp = self.conf.get(val, default=default)
        if not tmp: return ''
        return [ x.strip() for x in tmp.split(',') ]

    def SetGridFieldNames(self, grid_name):
        if not self.inst.has_key(grid_name):
            print 'No grid %s on set fileds' % grid_name
            return
        gr_inst = self.inst[grid_name][1]
        grid_name = '_'+ grid_name +'_fields'
        vals = self.conf.get_items_dict()[grid_name]
        list_vals = self.get_list(grid_name)
        if not list_vals: 
            print 'No values on grid %s' % grid_name
            return
        for num, val in enumerate(list_vals):
            try:
                gr_inst.SetColLabelValue(num, val)
            except Exception, ex:
                print ex

    def __update_lang_file(self, conf):
        conf.add_section(self.frm)
        for k in self.inst.keys():
            conf.set(k,'')
    def __update_new_ctrls(self, conf):
        for k in self.inst.keys():
            if not conf.has_option(k):
                conf.set(k,'')
        conf.exit()
        
    def __set_name(self, ctrl, val):
        if ctrl in self.exclude: return
        
        try:
            ctrl_lbl = ctrl_TT = ctrl_title = 0
            if not ctrl in self.inst.keys(): 
                if ctrl.endswith('_tt'):
                    ctrl = ctrl[1:-3]
                    if ctrl in self.inst:
                        ctrl_TT = 1
                    else:
                        return
                elif ctrl.startswith('_lbl'):
                    ctrl_lbl = 1
                    ctrl = ctrl[:-4]
                elif ctrl == '_title' and hasattr(self.wx, "SetTitle"):
                    self.wx.SetTitle(val)
                    return
                else:
                    if ctrl.startswith('_'): return
                    oneFound = 0
                    for c in ('bt', 'chk', 'lbl',):
                        CL = len(c)
                        nameWithUpper = ctrl[:CL] + ctrl[CL:CL+1].upper() + ctrl[CL+1:] 
                        if nameWithUpper in self.inst.keys():
                            ctrl = nameWithUpper
                            oneFound = 1
                            break
                    if not oneFound: return
            type_wx, inst = self.inst[ctrl][0], self.inst[ctrl][1]
            if type_wx == 'CheckBox':
                if len(val) == 0:
                    return
                inst.SetSize((int(len(val) * 7), inst.GetSize()[1]))
            elif type_wx == 'RadioBox':
                NOC = inst.GetCount()
                for num, v in enumerate(val.split(',')):
                    if num >= NOC: continue
                    inst.SetItemLabel(num, v.strip())
                if ctrl_lbl:
                    inst.SetLabel(val)
                return
            elif type_wx == 'StaticText':
                val = CtrlString(val)
            elif type_wx == 'Choice':
                for i in val.split(','):
                    inst.Append(i.strip())
                return
            if val != '':
                if ctrl_TT:
                    inst.SetToolTipString(val)
                else:
                    inst.SetLabel(val)
        except Exception, ex:
            print 'Exception on __setname ', ex
            pass
    
def CtrlString(val):
    if val.find(r'\n') != -1:
        list_val = [x.strip() for x in val.split(r'\n')]
        val_out = string.join(list_val, '\n')
        return val_out
    else:
        return val

class controls_state:
    def __init__(self, wx):
        self.inst = getCtrls(wx)
        self.wx = wx
    def get(self, exclude = []):
        #Get values of controls
        vals = {}
        for k in self.inst.keys():
            if k in exclude: continue
            if k[:3] in ('txt', 'chk', 'sld'):
                vals[k] = self.inst[k][1].GetValue()
            elif k[:3] == 'cho':
                vals[k] = self.inst[k][1].GetStringSelection()
        return vals
    def set(self, vals, exclude = []):
        #Put the val into controls
        self.inst = getCtrls(self.wx)
        for k in self.inst.keys():
            if k in exclude: continue
            try:
                val = vals[k]; pre = k[:3]
                if pre == 'txt':
                    self.inst[k][1].SetValue(val)
                elif pre in ('chk', 'sld'):
                    self.inst[k][1].SetValue(int(val))
                elif pre == 'cho':
                    try:
                        self.inst[k][1].SetStringSelection(str(val))
                    except:
                        print 'Exception on set controls_state. Error:', k, val, traceback.format_exc()
                        pass
            except KeyError:
                pass
            except TypeError:
                print "I don't accept this value for this widget!!", val, type(val), self.inst[k][1]
                raise 

prefix_lang_file = 'language_'
def get_available_lang(path):
    langs = list()
    from ConfigParser import RawConfigParser
    for i in os.listdir(path):
        if i[:len(prefix_lang_file)] == prefix_lang_file:
            cod = i[len(prefix_lang_file):]
            cp = RawConfigParser()
            cp.read(os.path.join(path, prefix_lang_file + cod))
            dict_def = cp.defaults()
            del cp
            if dict_def.has_key('description'):
                descr = dict_def['description']
            else:
                descr = ''                
            langs.append((cod, descr))
    return langs

def get_language(s):
    return s.split(' ')[1][1:-1]
    
def getCtrls(inst):
    di = inst.__dict__
    di_new = dict()
    for k in di.keys():
        di_new[k.lower()] = di[k]
    di = di_new
    dict_out = {}
    for k in di.keys():
        #k = k.lower()
        try:
            tmp = str(di[k]).split()
            #if di[k] is a variable, continue
            if len(tmp) <= 1: continue
            if k[:4] == '_my_':
                dict_out[k] = tmp[2], di[k]
            if float(wx.__version__[:3]) < 2.4:
                tmp = tmp[0].split('.')
                if len(tmp) > 2:
                    if tmp[2][:2] == 'wx':
                        dict_out[k] = tmp[2], di[k]
                    #For wxToggleButton
                    elif tmp[3][:2] == 'wx':
                        dict_out[k] = tmp[3], di[k]
            else:
                for strFind in ('<wx._controls.', 'wx.grid.', 'wx_util.sortGrid',
                                '__main__.BT', 'img_view.btCtrl', 'unipex.sortGrid'):
                    #print strFind, tmp[0]
                    if tmp[0].find(strFind) != -1:
                        o = tmp[0].replace(strFind, '').replace(';', '')
                        dict_out[k] = o, di[k]
                        break
                #print 
                """
                if tmp[0].find() != -1:
                    o = tmp[0].replace('<wx._controls.', '').replace(';', '')
                    dict_out[k] = o, di[k]
                elif tmp[0].find() != -1:
                    o = tmp[0].replace('wx.grid.', '').replace(';', '')
                    dict_out[k] = o, di[k]
                #For my sorted grid
                elif tmp[0].find() != -1:
                    o = tmp[0].replace('wx_util.sortGrid', '').replace(';', '')
                    dict_out[k] = o, di[k]
                #For my buttons
                elif tmp[0].find() != -1:
                    o = tmp[0].replace('__main__.BT', '').replace(';', '')
                    dict_out[k] = o, di[k]
                elif tmp[0].find() != -1:
                    o = tmp[0].replace('__main__.BT', '').replace(';', '')
                    dict_out[k] = o, di[k]"""
                        
        except Exception, ex:
            print 'Exception on getCtrls', ex
        #Now dict_out is a dict with {Name: [type, instance]}
    return dict_out

def del_mask2img(file, dims = (25,25)):
    img = wx.Image(file, wx.BITMAP_TYPE_ANY)
    img.Rescale(dims[0], dims[1])
    bmp = wx.BitmapFromImage(img)
    mask = wx.Mask(bmp, wx.WHITE)
    bmp.SetMask(mask)
    return bmp

TYPE_STR = 0
TYPE_INT = 1

class sortGrid(wx.grid.Grid):
    def __init__(self, *args, **kargs):
        
        self.internalTable = 0
        IT = 'internalTable'
        EO = 'enableOrd'
        if IT in kargs.keys():
            if kargs[IT] == 1: self.internalTable = 1
            kargs.pop(IT)
        
        EnableOrd = 0
        if EO in kargs.keys(): 
            if kargs[EO] == 1: EnableOrd = 1
            kargs.pop(EO)
        else:
            EnableOrd = 1
        
        super(sortGrid, self).__init__(*args, **kargs)
        if EnableOrd: self.enableOrd()
        self.AutoSizeColumns(False)
        
        self.__postSortCall = None
        self.dataColType = dict()
        if self.internalTable:
            self._table = TableGrid(self)
            self.SetTable(self._table, True)
        
    # ------------------ #
    # Overwrited methods #
    # ------------------ #
    
    def AppendCols(self, num=1):
        if self.internalTable:
            self._table.AppendCol(num)
        else:
            super(sortGrid, self).AppendCols(num)
    
    def AppendRows(self, num=1):
        if self.internalTable:
            self._table.AppendRow(num)
        else:
            super(sortGrid, self).AppendRows(num)
    
    def InsertRows(self, pos=0, num=1):
        if self.internalTable:
            self._table.InsertRow(pos, num)
        else:
            super(sortGrid, self).InsertRows(pos, num)
    
    def InsertCols(self, pos=0, num=1):
        if self.internalTable:
            self._table.InsertCol(pos, num)
        else:
            super(sortGrid, self).InsertCols(pos, num)
    
    def DeleteCols(self, pos=0, num=1):
        if self.internalTable:
            self._table.DeleteCol(pos, num)
        else:
            super(sortGrid, self).DeleteCols(pos, num)
    
    def DeleteRows(self, pos=0, num=1):
        if self.internalTable:
            self._table.DeleteRow(pos, num)
        else:
            super(sortGrid, self).DeleteRows(pos, num)
    
    def SetCellValue(self, row, col, colValue):
        if self.internalTable:
            self._table.setCellValue(row, col, colValue)
        else:
            if not isinstance(colValue, basestring):
                colValue = str(colValue)
            super(sortGrid, self).SetCellValue(row, col, colValue)
    
    def SetColLabelValue(self, col, value):
        if self.internalTable:
            self._table.setColLabelValue(col, value)
        else:
            super(sortGrid, self).SetColLabelValue(col, value)

    def SetRowLabelValue(self, row, value):
        if self.internalTable:
            self._table.setRolLabelValue(row, value)
        else:
            super(sortGrid, self).SetRowLabelValue(row, value)
    
    def CreateGrid(self, numRows, numCols):
        """ Vitual method that allow the backward compatibility for the "old" 
            grid method
        """
        if self.internalTable:
            self.AppendRows(numRows)
            self.AppendCols(numCols)
            #Create an empty list data and set it
            lstCol = [ "" for col in xrange(numCols) ]
            self._table.setData( [ lstCol for row in xrange(numRows) ])
        else:
            super(sortGrid, self).CreateGrid(numRows, numCols)
    
    def setData(self, data):
        """ Set the data into the table in one shot!
        """
        if self.internalTable:
            self._table.setData(data)
        else:
            for row, rowVal in enumerate(data):
                for col, colVal in enumerate(rowVal):
                    self.SetCellValue(row, col, colVal)
                    
    # ------------ #
    # Sort methods #
    # ------------ #
    
    def enablePostSortCall(self, funct, passValues = True):
        """ Enable the funct's call after the grid sort due to the label 
            pression. If passValues is true, I pass the grid values to that
            function.
        """
        self.__postSortCall = funct
        self.__postSortPass = passValues
        self.Bind(wx.EVT_SCROLLWIN, self.onScroll)
    
    def onScroll(self, event):
        event.Skip()
        #print len(self._table.getData())
        self.__ctrlAndCallPostCall(self._table.getData())
        #print "scroll", event.GetEventType()
        
    
    def enableOrd(self):
        """ Enable the automatic (click on label) sort
        """
        
        # A click in the column header will set these:
        self.sortedColumn = -1
        self.sortedColumnDescending = True
        self.__attribute = None
        
        # trap the column label's paint event:
        columnLabelWindow = self.GetGridColLabelWindow()
        columnLabelWindow.Bind(wx.EVT_PAINT, self.__OnColumnHeaderPaint)

        # trap the grid label's left click:
        self.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.__OnGridLabelLeftClick)
        
    def populateSortGrid(self, colToSort=-1, update=0):
        """ Populate or sort the grid. If it's an update,
            not do a new sort or add data to grid, only
            re-sort the current sorted column
        """
        if update:
            data = self.__order_cols(self.sortedColumn)
        elif colToSort != -1:
            self.sortedColumn = colToSort
            data = self.__order_cols(colToSort)
        self.__update_grid(data)
        self.Refresh()
        return data
    
    def setDataColType(self, dataColType):
        """ Set the col's type into the grid
            You can pass me a list/tuple with two values (colInt, type), or
            a dict with {colInt: type}
        """
        if type( dataColType ) in ( types.TupleType, types.ListType ):
            self.dataColType = dict()
            for col, t in dataColType:
                self.dataColType[ int(col) ] = t
        else:
            self.dataColType = dataColType
    
    def setRowData(self, row, data):
        """
        """
        self._table.setRowData(row, data)
        
    # -------------------- #
    # Sort methods private #
    # -------------------- #
    
    def __OnColumnHeaderPaint(self, evt):
        """ Paint the column labels
        """
        w = self.GetGridColLabelWindow()
        dc = wx.PaintDC(w)
        clientRect = w.GetClientRect()
        font = dc.GetFont()

        # For each column, draw it's rectangle, it's column name,
        # and it's sort indicator, if appropriate:

        totColSize = -self.GetViewStart()[0]*self.GetScrollPixelsPerUnit()[0] # Thanks Roger Binns
        for col in range(self.GetNumberCols()):
            dc.SetBrush(wx.Brush("WHEAT", wx.TRANSPARENT))
            dc.SetTextForeground(wx.BLACK)
            colSize = self.GetColSize(col)
            rect = (totColSize,0,colSize,self.GetColLabelSize())
            dc.DrawRectangle(rect[0] - (col<>0 and 1 or 0), rect[1],
                             rect[2] + (col<>0 and 1 or 0), rect[3])
            totColSize += colSize

            if col == self.sortedColumn:
                font.SetWeight(wx.BOLD)
                # draw a triangle, pointed up or down, at the
                # top left of the column.
                left = rect[0] + 3
                top = rect[1] + 3

                dc.SetBrush(wx.Brush("WHEAT", wx.SOLID))
                if self.sortedColumnDescending:
                    dc.DrawPolygon([(left,top), (left+6,top), (left+3,top+4)])
                else:
                    dc.DrawPolygon([(left+3,top), (left+6, top+4), (left, top+4)])
            else:
                font.SetWeight(wx.NORMAL)
            
            #Pay attention when a column has 0 size
            if colSize == 0: continue
            
            dc.SetFont(font)
            dc.DrawLabel("%s" % self.GetColLabelValue(col),
                     rect, wx.ALIGN_CENTER | wx.ALIGN_TOP)

    def __OnGridLabelLeftClick(self, evt):
        """ Precess the click label event
            and all the sort work
        """
        col = evt.GetCol()
        if col == -1:
            evt.Skip()
            return
        gridCol = evt.GetCol()
        
        descending = False
        if gridCol == self.sortedColumn:
            if self.sortedColumnDescending == False:
                descending = True
        
        self.sortedColumn = gridCol
        self.sortedColumnDescending = descending
        data = self.__order_cols(gridCol)
        self.__update_grid(data)
        
        self.Refresh()
        
    def __order_cols(self, colPress):
        """ Order the data into the col by the colPress
        """
        self.__attribute = colPress
        data = self.__get_data_grid()
        #data.sort(self.__compare)
        data = self._mysort(data)
        if self.sortedColumnDescending:
            data.reverse()
        return data
    
    def _mysort(self, data):
        """
        """
        if self.__attribute in self.dataColType.keys() and \
            self.dataColType[self.__attribute] == TYPE_INT:
            lst = [ (int(x[self.__attribute]), i, x) for i, x in enumerate(data) ] 
        else:
            lst = [ (x[self.__attribute], i, x) for i, x in enumerate(data) ] 
        lst.sort()
        lst = [ x for _, _, x in lst ]
        return lst
        
    def __compare(self, x, y) :
        """ Compare function
        """
        
        
        if self.__attribute in self.dataColType.keys() and \
            self.dataColType[self.__attribute] == TYPE_INT:
            compare = cmp( int(x[self.__attribute] ), int( y[self.__attribute]) )
        else:
            compare = cmp(x[self.__attribute], y[self.__attribute])
        return compare
            
    def __update_grid(self, data):
        """ Set the data into grid
            I don't make the control of the right number of rows and cols
        """
        if self.internalTable:
            self._table.setData(data)
        else:
            for row, row_val in enumerate(data):
                for col, col_data in enumerate(row_val): 
                    self.SetCellValue(row, col, col_data)
        self.__ctrlAndCallPostCall(data)
    
    def __ctrlAndCallPostCall(self, data = None):
        """If needed, call the required function"""
        if self.__postSortCall:
            if self.__postSortPass and data:
                self.__postSortCall(data)
            else:
                self.__postSortCall()
        
    
    def __get_data_grid(self):
        """ Return the data on the grid
        """
        data = list()
        for row in xrange(self.GetNumberRows()):
            row_data = [ self.GetCellValue(row, col) 
                        for col in xrange(self.GetNumberCols()) ]
            data.append(row_data)
        return data    
    
    # ------------------------ #
    # Up / Down buttons method #
    # used for move up/down    #
    # selected rows            #
    # ------------------------ #
    
    def enableBtUpDown(self, btUp, btDown):
        """ Work with up and down buttons to move the row
            selected, if there is...
        """
        self.btUp, self.btDown = btUp, btDown
        self.btUp.Bind(wx.EVT_BUTTON, self.__OnBt_upButton)
        self.btDown.Bind(wx.EVT_BUTTON, self.__OnBt_downButton)
        
    def __OnBt_upButton(self, event):
        """ Preocess the up button
        """
        row = self.GetSelectedRows()
        if not row or row[0] == 0: return
        row = row[0]
        fields = [ self.GetCellValue(row, col)
                   for col in xrange(self.GetNumberCols()) ]
        self.InsertRows(row-1)
        for col, value in enumerate(fields):
            self.SetCellValue(row-1, col, value)
        self.DeleteRows(row+1)
        self.SelectRow(row-1)

    def __OnBt_downButton(self, event):
        """ Preocess the down button
        """
        row = self.GetSelectedRows()
        if not row or row[0] == self.GetNumberRows() -1: return
        row = row[0]
        fields = [ self.GetCellValue(row, col)
                   for col in xrange(self.GetNumberCols()) ]
        self.InsertRows(row+2)
        for col, value in enumerate(fields):
            self.SetCellValue(row+2, col, value)
        self.DeleteRows(row)
        self.SelectRow(row+1)


class TableGrid(wx.grid.PyGridTableBase):

    def __init__(self, parent, data=None, colLabels=None, rowLabels=None):
        """ Pass me the parent grid and the data to put
            into the grid
        """
        super(TableGrid,self).__init__()
        self._parent = parent
        
        if not data: data = list(list())
        self._data = data
        if not colLabels: self._colLabels = list()
        else:             self._colLabels = colLabels
        if not rowLabels: self._rowLabels = list()
        else:             self._rowLabels = rowLabels
        
    def setData(self, data):
        """ Set my data in one shot
        """
        self._data = data
    
    def setRowData(self, row, data):
        """
        """
        self._data[row] = data
        self.__msg((wx.grid.GRIDTABLE_REQUEST_VIEW_SEND_VALUES, ))
    
    def getData(self):
        """ Return the current data
        """
        return self._data
    
    def setCellValue(self, row, col, value):
        """ Set one cell value
            Don't call me for update all the cell values, 
            I'll take a lot of time. 
            Call setData instead
        """
        if len(self._data) < row:
            for i in range( row - len(self._data) ): 
                self.data.append(list())
        
        if self._data and len(self._data[0]) < col:
            colToAdd = col - ( len(self._data[0]) )
            for num, i in enumerate(self._data):
                for col in xrange(colToAdd): i.append("")

        #if not self._data: return
        self._data[row][col] = value
        
    def GetNumberRows(self):
        """ No comments :)
        """
        if not self._data: return 0
        else:              return len(self._data) +1

    def GetNumberCols(self):
        """ No comments :)
        """
        if not self._data: return 0
        else:              return len(self._data[0]) +1

    def GetValue(self, row, col):
        """ Return the cell (list buffer) value
        """
        if not self._data:  data = ""
        elif row >= len(self._data) or col >= len(self._data[0]): data = ""
        else: data = self._data[row][col]
        
        return data

    def IsEmptyCell(self, row, col):
        """ Return if the cell is empty
        """
        
        if not self._data:  return True
        else:
            try:
                if not self._data[row][col]: return True 
                else:                        return False
            except:
                return False

    def setColLabelValue(self, col, value):
        """ Set the col label value
        """
        if len(self._colLabels) > col:
            self._colLabels.pop(col)
        self._colLabels.insert(col, value)

    def setRolLabelValue(self, row, value):
        """ Set the row label value
        """
        if len(self._rowLabels) > row:
            self._rowLabels.pop(col)
        self._rowLabels.insert(row, value)
    
    def GetColLabelValue(self, col):
        """ End get it
        """
        if not self._colLabels: return col
        return self._colLabels[col]

    def GetRowLabelValue(self, row):
        """ End get it
        """
        if not self._rowLabels: return row
        return self._rowLabels[row]
    
    
    # optional methods
    def AppendCol(self, num=1):
        """ Internal append col
        """
        for row in xrange(self.GetNumberRows()-1):
            for col in xrange(num): self._data[row].append( "" )
        
        self.__msg((wx.grid.GRIDTABLE_NOTIFY_COLS_APPENDED, num),
            (wx.grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES,))

    def AppendRow(self, num=1):
        for i in xrange(num):
            self._data.append( [ "" for x in self._colLabels ] )
        self.__msg((wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED, num),
            (wx.grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES,))

    def DeleteCol(self, col, num=1):
        self.__msg((wx.grid.GRIDTABLE_NOTIFY_COLS_DELETED, col, num))

    def DeleteRow(self, row, num=1):
        self.__msg((wx.grid.GRIDTABLE_NOTIFY_ROWS_DELETED, row, num))

    def InsertCol(self, col, num=1):
        self.__msg((wx.grid.GRIDTABLE_NOTIFY_COLS_INSERTED, col, num),
            (wx.grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES,))

    def InsertRow(self, pos, num=1):
        for i in range(pos, pos+num):
            self._data.insert(i, [ "" for x in xrange(self.GetNumberCols()-1) ] )
        
        self.__msg((wx.grid.GRIDTABLE_NOTIFY_ROWS_INSERTED, pos, num),
            (wx.grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES,))

    def __msg(self, *tups): # helper method
        p = self._parent #XXX self.GetView()?
        if p and tups:
            p.BeginBatch()
        for t in tups:
            m = wx.grid.GridTableMessage(self, *t)
            p.ProcessTableMessage(m)
            p.EndBatch()
    
class GoToggleButton:
    def __init__(self, lst_but):
        self.lst_but = lst_but
        self.last = list()        
    
    def go(self, bt, side):
        self.last.append(bt)
        set_last = 0
        for i in self.lst_but:
            if side == True and i == bt:
                i.SetValue(True)
            elif side == True:
                i.SetValue(False)
            elif i == bt:
                i.SetValue(False)
            else:
                set_last = 1
        
        if set_last and len(self.last) > 2:
            self.last[-1].SetValue(False)
            self.last.pop(0)
        
        self.last.append(bt)
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.