Beispiel #1
0
    def _get_bitmap(self, id, component, indx, push_indx=-1, dis_indx=-1):
        """
        Возвращает картинки инструмента.
        """
        if self.image_list:
            if indx < self.image_list.GetImageCount():
                bmp = self.image_list.GetBitmap(indx)
            else:
                bmp = None

            if bmp is None:
                bmp = common.imgEdtTBTool

            push_bmp, dis_bmp = wx.NullBitmap, wx.NullBitmap
            if push_indx >= 0:
                push_bmp = self.image_list.GetBitmap(push_indx)
            if dis_indx >= 0:
                dis_bmp = self.image_list.GetBitmap(dis_indx)
            return bmp, push_bmp, dis_bmp

        # Активная картинка
        bitmap = util.getICAttr(component['bitmap'],
                                self.evalSpace,
                                msg='ERROR')
        if not (bitmap and issubclass(bitmap.__class__, wx.Bitmap)):
            bitmap = ic_bmp.createBitmap(component['bitmap'])
            if not bitmap:
                bitmap = common.imgEdtImage
        # Неактивная картинка
        dis_bitmap = util.getICAttr(component['disabledBitmap'],
                                    self.evalSpace,
                                    msg='ERROR')
        if not (dis_bitmap and issubclass(bitmap.__class__, wx.Bitmap)):
            dis_bitmap = ic_bmp.createBitmap(component['disabledBitmap'])
            if not dis_bitmap:
                dis_bitmap = wx.NullBitmap
        #   Картинка в нажатом состоянии
        push_bitmap = util.getICAttr('pushedBitmap',
                                     self.evalSpace,
                                     msg='ERROR')
        if not (push_bitmap and issubclass(push_bitmap.__class__, wx.Bitmap)):
            push_bitmap = ic_bmp.createBitmap(component['pushedBitmap'])
            if not push_bitmap:
                push_bitmap = wx.NullBitmap

        return bitmap, push_bitmap, dis_bitmap
Beispiel #2
0
    def __init__(self, parent, id, component, logType=0, evalSpace=None,
                 bCounter=False, progressDlg=None):
        """
        Конструктор для создания icComboBox.

        @type parent: C{wx.Window}
        @param parent: Указатель на родительское окно.
        @type id: C{int}
        @param id: Идентификатор окна.
        @type component: C{dictionary}
        @param component: Словарь описания компонента.
        @type logType: C{int}
        @param logType: Тип лога (0 - консоль, 1- файл, 2- окно лога).
        @param evalSpace: Пространство имен, необходимых для вычисления внешних выражений.
        @type evalSpace: C{dictionary}
        """
        util.icSpcDefStruct(SPC_IC_COMBOBOX, component)
        icWidget.__init__(self, parent, id, component, logType, evalSpace)
        
        self.bChanged = 0
        self.items = component['items']
        fgr = component['foregroundColor']
        bgr = component['backgroundColor']
        size = component['size']
        pos = component['position']
        style = component['style']

        # --- Обрабатываем аттрибут инициализации списка
        if not component['items']:
            self.items = []
        elif type(component['items']) in (list, tuple):
            self.items = component['items']
        elif isinstance(component['items'], dict):
            self._dictRepl = component['items']
            self.items = self._dictRepl.values()
            self.items.sort()
        else:
            ret = util.getICAttr('@'+component['items'], self.evalSpace,
                                 'getICAttr() Error in icchoice.__init__(...) <items> name=%s' % self.name)

            if type(ret) in (list, tuple):
                self.items = ret
            elif isinstance(ret, dict):
                self._dictRepl = ret
                self.items = self._dictRepl.values()
                self.items.sort()
            else:
                self.items = []

        wx.ComboBox.__init__(self, parent, id, component['value'], pos, size, self.items, style, name=self.name)

        if fgr is not None:
            self.SetForegroundColour(wx.Colour(fgr[0], fgr[1], fgr[2]))

        if bgr is not None:
            self.SetBackgroundColour(wx.Colour(bgr[0], bgr[1], bgr[2]))

        self.BindICEvt()
Beispiel #3
0
    def RefreshData(self, data=None):
        """
        Функция обновляет данные в таблице.
        """
        self.ClearAll()
        self.colLabels = []
        self.colNames = []
        self.exCols = []
        self.retInfo = [0, []]
        i = 0
        #   Определяем подписи и типы колонок
        for col in self.cols:
            bShow = True
            try:
                attr_show = '@' + col['show']
                bShow = util.getICAttr(attr_show, self.evalSpace,
                                       'Error in getICAttr in iclistdataset <show>=%s' % col['show'])
            except:
                pass
            
            if col['attr'] != 'UV' and bShow:
                self.colNames.append(col['name'])
                self.colLabels.append(col['label'])
                self.exCols.append(col)
                self.InsertColumn(i, col['label'])
                if 'width' in col:
                    try:
                        self.SetColumnWidth(i, col['width'])
                    except:
                        pass

                i += 1

        #   Получаем курсор на источник данных
        if self.dataset is None:
            log.debug(u'icListDataset RefreshData: %s Source: <%s>' % (data, self.source))
            #   Если источник данных прописан
            if self.source:
                MsgBox(self.grid,
                       _('icListDataset: Data source %s is not defined in the object context.') % self.link_res)
            #   В обратном случае используем стандартный icSimpleDataset
            else:
                self.dataset = icsimpledataset.icSimpleDataset(icwidget.icNewId(),
                                                               {'description': self.exCols})
        elif data and not self.source:
            self.dataset.SetDataBuff(data)
            
        #   Обновляем данные в буффере
        try:
            self.dataset.Refresh()
        except:
            msg = _('Refrsh data error. <dataset=%s>') % self.dataset.name
            MsgBox(None, msg)

        #   Определяем количество строк
        self.SetItemCount(self.dataset.getRecordCount())
        self.Refresh()
Beispiel #4
0
    def ReloadAttr(self, res, component):
        """
        Перегружает нужные атрибуты ресурсного описания.

        @type res: C{dictionary}
        @param res: Ресурсное описание, в котором заменяются атрибуты.
        @type component: C{dictionary}
        @param component: Ресурсное описание ссылки.
        """
        attrs = getAddProperyLst(SPC_IC_DATALINK, component.keys(),
                                 icDefInf.icUnSpecAttr)

        #   Атрибуты начинающиеся с '__' являются служебными и не обрабатываются
        attrs = [x for x in attrs if x.find('__') != 0]

        #   Переопределяем аттибуты компонента класса данных
        for attr in attrs:

            reload_attr = util.getICAttr(component[attr], self.evalSpace)

            #   Если дополнительный атрибут задан в виде <typ:name.attr>, то
            #   используем для переопределения атрибута дерева специальную
            #   функцию.
            if ':' in attr and '.' in attr:
                div = attr.split(':')
                name, prp = div[-1].split('.')

                if setResAttr(res, div[0], name, prp, reload_attr, self._uuid):
                    io_prnt.outLog(u'setResAttr() [%s : %s : %s]' %
                                   (div[0], name, prp))
            else:
                if attr in res:
                    res[attr] = reload_attr
                else:
                    io_prnt.outWarning(
                        u'RELOAD ATTRIBUTE ERROR in icdataset.icDataLink.__init__(...): Invalid attribute name <%s> in component name:%s'
                        % (attr, component['name']))

        return res
Beispiel #5
0
    def __init__(self,
                 parent=None,
                 id=-1,
                 component={},
                 logType=0,
                 evalSpace=None,
                 bCounter=False,
                 progressDlg=None):
        """
        Конструктор для создания icStaticBitmap.

        @type parent: C{wx.Window}
        @param parent: Указатель на родительское окно.
        @type id: C{int}
        @param id: Идентификатор окна.
        @type component: C{dictionary}
        @param component: Словарь описания компонента.
        @type logType: C{int}
        @param logType: Тип лога (0 - консоль, 1- файл, 2- окно лога).
        @param evalSpace: Пространство имен, необходимых для вычисления внешних выражений.
        @type evalSpace: C{dictionary}
        """
        self.editor = None

        util.icSpcDefStruct(SPC_IC_BITMAP, component)
        icWidget.__init__(self, parent, id, component, logType, evalSpace)

        pos = component['position']
        style = component['style']
        size = component['size']
        self.hlp = component['hlp']
        fgr = component['foregroundColor']
        bgr = component['backgroundColor']
        img = None

        if component['field_name'] is None:
            self.field_name = self.name
        else:
            self.field_name = component['field_name']

        try:
            self.file = self.dataset.getNameValue(self.field_name)
        except:
            self.file = component['file']
            img = util.getICAttr(component['file'],
                                 self.evalSpace,
                                 msg='ERROR')

        if img and issubclass(img.__class__, wx.Bitmap):
            pass
        else:
            self.file = util.getICAttr(component['file'],
                                       self.evalSpace,
                                       msg='ERROR')
            bmptype = icBitmapType(self.file)

            if bmptype is not None and os.path.isfile(self.file):
                img = wx.Image(self.file, bmptype).ConvertToBitmap()
            else:
                img = common.icDefaultStaticPic

        if size == (-1, -1):
            size = wx.Size(img.GetWidth(), img.GetHeight())

        wx.StaticBitmap.__init__(self,
                                 parent,
                                 id,
                                 img,
                                 pos,
                                 size,
                                 style=style,
                                 name=self.name)

        if fgr is not None:
            self.SetForegroundColour(wx.Colour(fgr[0], fgr[1], fgr[2]))

        if bgr is not None:
            self.SetBackgroundColour(wx.Colour(bgr[0], bgr[1], bgr[2]))

        self.Bind(wx.EVT_LEFT_DOWN, self.OnSelect)
        self.BindICEvt()
Beispiel #6
0
    def __init__(self,
                 parent,
                 id,
                 component,
                 logType=0,
                 evalSpace=None,
                 bCounter=False,
                 progressDlg=None):
        """
        Конструктор для создания icTextField.
        @type parent: C{wx.Window}
        @param parent: Указатель на родительское окно.
        @type id: C{int}
        @param id: Идентификатор окна.
        @type component: C{dictionary}
        @param component: Словарь описания компонента.
        @type logType: C{int}
        @param logType: Тип лога (0 - консоль, 1- файл, 2- окно лога).
        @param evalSpace: Пространство имен, необходимых для вычисления внешних выражений.
        @type evalSpace: C{dictionary}
        """
        self.bkillfocus = True
        #   Признак временной потери фокуса
        self.bTimeLosefocus = False
        self.counter = 0
        self.id = id
        self.bChanged = False
        #   Номер последней заблокированной записи
        self._oldLockReck = -1
        #   Старое значение
        self._oldValue = None

        util.icSpcDefStruct(SPC_IC_TEXTFIELD, component)
        icWidget.__init__(self, parent, id, component, logType, evalSpace)

        if self.refresh in [None, []]:
            self.refresh = self.recount

        fgr = component['foregroundColor']
        bgr = component['backgroundColor']
        text = component['value']

        #   Вычисляем текст поля после создания объекта#
        if text.find('@') == -1:
            val = util.getICAttr('@' + text, self.evalSpace, None)
        else:
            val = util.getICAttr(
                '@' + text, self.evalSpace,
                'Error in ictextfield.__init__()<text>. Name:' + self.name)

        if not val:
            val = text

        if component['field_name'] in ('', None, 'None'):
            self.field_name = self.name
        else:
            self.field_name = component['field_name']

        size = component['size']
        pos = component['position']
        font = component['font']

        #   Преобразователи предстваления
        self.getvalue = component['getvalue']
        self.setvalue = component['setvalue']
        #   Шаблон ввода и служебные атрибуты
        self.pic = component['pic']
        self.pictype, self.typeFld = defPicType(self.pic, '')
        #   Обработчики событий
        self.hlp = component['hlp']
        self.ctrl = component['ctrl']
        self.keydown = component['keyDown']
        self.setfocus = component['setFocus']
        self.use_fdict = component['use_fdict']

        if not type(val) in (str, unicode):
            val = str(val)

        wx.TextCtrl.__init__(self,
                             parent,
                             id,
                             val,
                             pos,
                             size,
                             self.style,
                             name=self.name)

        obj = icFont(font)
        self.SetFont(obj)

        if fgr is not None:
            self.SetForegroundColour(wx.Colour(fgr[0], fgr[1], fgr[2]))

        if bgr is not None:
            self.SetBackgroundColour(wx.Colour(bgr[0], bgr[1], bgr[2]))

        try:
            self.SetValue(str(self.dataset.getNameValue(self.field_name)))
        except:
            pass

        #   Читаем частотный словарь ввода
        self._freqDict = None
        self.SetFreqDict(self.use_fdict)

        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.Bind(wx.EVT_TEXT, self.OnTextChanged, id=id)
        self.Bind(icEvents.EVT_TEXT_TEMPL, self.OnTempl)
        self.Bind(icEvents.EVT_AUTO_TEXT_FILL, self.OnAutoTextFill)
        self.BindICEvt()
        self.bBlockChangeEvt = False
    def __init__(self,
                 parent,
                 id,
                 component,
                 logType=0,
                 evalSpace=None,
                 bCounter=False,
                 progressDlg=None):
        """
        Конструктор для создания icImageButton

        @type parent: C{wx.Window}
        @param parent: Указатель на родительское окно
        @type id: C{int}
        @param id: Идентификатор окна
        @type component: C{dictionary}
        @param component: Словарь описания компонента
        @type logType: C{int}
        @param logType: Тип лога (0 - консоль, 1- файл, 2- окно лога)
        @param evalSpace: Пространство имен, необходимых для вычисления внешних выражений
        @type evalSpace: C{dictionary}
        """
        util.icSpcDefStruct(SPC_IC_TOGGLE_IMGBUTTON, component)
        icWidget.__init__(self, parent, id, component, logType, evalSpace)

        fgr = component['foregroundColor']
        bgr = component['backgroundColor']
        sz = component['size']
        pos = component['position']
        border = component['border']

        self.image = img = util.getICAttr(
            component['image'], evalSpace,
            'Error in getICAttr in icimagebutton. name=%s attribute <image>' %
            self.name)

        if type(img) in (str,
                         unicode) and img not in ['', 'None', u'', u'None']:
            bmptype = icBitmapType(img)
            img = wx.Image(img, bmptype).ConvertToBitmap()
        elif not img:
            img = common.imgEdtImage

        x = sz[0]

        if x == -2:
            x = img.getWidth()

        y = sz[1]

        if y == -2:
            y = img.getHeight()

        #   Устанавливае реальные размеры для дальнейшего использования
        component['size'] = (x, y)
        sz = (x, y)

        style = component['style']
        self.mouse_click = component['mouseClick']
        self.mouse_down = component['mouseDown']
        self.mouse_up = component['mouseUp']
        self.mouse_contextdown = component['mouseContextDown']
        self.label = component['label']
        self.shortHelpString = component['shortHelpString']
        self.bFocusIndicator = component['bFocusIndicator']
        self._helpWin = None

        buttons.ThemedGenBitmapTextToggleButton.__init__(self,
                                                         parent,
                                                         id,
                                                         img,
                                                         self.label,
                                                         pos,
                                                         sz,
                                                         style=style,
                                                         name=self.name)

        self.SetBezelWidth(1)

        if fgr is not None:
            self.SetForegroundColour(wx.Colour(fgr[0], fgr[1], fgr[2]))

        if bgr is not None:
            self.SetBackgroundColour(wx.Colour(bgr[0], bgr[1], bgr[2]))

        self.Bind(wx.EVT_BUTTON, self.OnMouseClick, id=id)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnMouseUp)
        self.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseContextDown)
        self.Bind(wx.EVT_MOTION, self.OnMouseMove)
        self.BindICEvt()
Beispiel #8
0
    def __init__(self,
                 parent,
                 id,
                 component,
                 logType=0,
                 evalSpace={},
                 bCounter=False,
                 progressDlg=None):
        """
        Конструктор для создания icChoice.

        @type parent: C{wx.Window}
        @param parent: Указатель на родительское окно
        @type id: C{int}
        @param id: Идентификатор окна
        @type component: C{dictionary}
        @param component: Словарь описания компонента
        @type logType: C{int}
        @param logType: Тип лога (0 - консоль, 1- файл, 2- окно лога)
        @param evalSpace: Пространство имен, необходимых для вычисления внешних выражений
        @type evalSpace: C{dictionary}
        """
        self.bChanged = 0

        util.icSpcDefStruct(SPC_IC_CHOICE, component)
        icWidget.__init__(self, parent, id, component, logType, evalSpace)

        fgr = component['foregroundColor']
        bgr = component['backgroundColor']
        size = component['size']
        pos = component['position']
        style = component['style']

        if component['field_name'] is None:
            self.field_name = self.name
        else:
            self.field_name = component['field_name']

        self.losefocus = component['loseFocus']
        self.setfocus = component['setFocus']
        self.choice = component['choice']

        #   Номер последней заблокированной записи
        self._oldLockReck = -1

        #   Словарь замен. Ключи - соответствующие значения в объекте данных, значения  формируют список выбора
        self._dictRepl = None
        self._itemsLst = None

        # Обрабатываем аттрибут инициализации списка
        if not component['items']:
            self.items = []
        elif type(component['items']) in (list, tuple):
            self.items = component['items']
        elif isinstance(component['items'], dict):
            self._dictRepl = component['items']
            self.items = self._dictRepl.values()
            self.items.sort()
        else:
            ret = util.getICAttr(
                '@' + component['items'], self.evalSpace,
                'getICAttr() Error in icchoice.__init__(...) <items> name=%s' %
                self.name)

            if type(ret) in (list, tuple):
                self.items = ret
            elif isinstance(ret, dict):
                self._dictRepl = ret
                self.items = self._dictRepl.values()
                self.items.sort()
            else:
                self.items = []

        # Создаем объект
        wx.Choice.__init__(self,
                           parent,
                           id,
                           pos,
                           size,
                           self.items,
                           style,
                           name=self.name)

        if fgr is not None:
            self.SetForegroundColour(wx.Colour(fgr[0], fgr[1], fgr[2]))

        if bgr is not None:
            self.SetBackgroundColour(wx.Colour(bgr[0], bgr[1], bgr[2]))

        try:
            self.SetValue(self.dataset.getNameValue(self.field_name))
        except:
            pass

        self.Bind(wx.EVT_CHOICE, self.OnChoice, id=id)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.BindICEvt()
Beispiel #9
0
    def __init__(self,
                 parent,
                 id,
                 component,
                 logType=0,
                 evalSpace=None,
                 bCounter=False,
                 progressDlg=None):
        """
        Конструктор для создания icGrid.
        @type parent: C{wx.Window}
        @param parent: Указатель на родительское окно.
        @type id: C{int}
        @param id: Идентификатор окна.
        @type component: C{dictionary}
        @param component: Словарь описания компонента.
        @type logType: C{int}
        @param logType: Тип лога (0 - консоль, 1- файл, 2- окно лога).
        @param evalSpace: Пространство имен, необходимых для вычисления внешних выражений.
        @type evalSpace: C{dictionary}
        """
        component = util.icSpcDefStruct(SPC_IC_GRID, component)
        icwidget.icWidget.__init__(self, parent, id, component, logType,
                                   evalSpace)
        self.pos = component['position']
        self.cols = copy.deepcopy([
            x for x in component['cols']
            if util.isAcivateRes(x, evalSpace) and x['type'] == 'GridCell'
        ])
        self.line_color = component['line_color']
        self.label_attr = copy.deepcopy(component['label_attr'])
        self.cell_attr = copy.deepcopy(component['cell_attr'])
        self.label_height = int(component['label_height'])

        self.getattr = component['getattr']
        self.keydown = component['keyDown']
        self.selected = component['selected']
        self.changed = component['changed']
        self.delrec = component['delRec']
        self.addrec = component['init']
        self.post_addrec = component['post_init']
        self.post_delrec = component['post_del']

        util.icSpcDefStruct(SPC_IC_LABELATTR, self.label_attr)
        util.icSpcDefStruct(SPC_IC_FONT, self.label_attr['font'])

        #   Преобразуем выравнивание
        if not isinstance(self.label_attr, str):
            aln = self.label_attr['alignment']
            if isinstance(aln, str):
                try:
                    aln = eval(aln)
                except:
                    aln = ('left', 'middle')
            if aln is not None:
                self.label_attr['alignment'] = getIdAlignment(aln[0], aln[1])

        util.icSpcDefStruct(SPC_IC_CELLATTR, self.cell_attr)
        util.icSpcDefStruct(SPC_IC_FONT, self.cell_attr['font'])

        #   Преобразуем выравнивание
        if not isinstance(self.cell_attr, str):
            aln = self.cell_attr['alignment']
            if isinstance(aln, str):
                try:
                    aln = eval(aln)
                except:
                    aln = ('left', 'middle')
            if aln is not None:
                self.cell_attr['alignment'] = getIdAlignment(aln[0], aln[1])

        #   Переводим значение аттрибутов колонок в верхний регистр
        for col in self.cols:
            #   Заменяем все имена колонок на алиасы
            if 'alias' in col and not col['alias'] in [None, '', 'None']:
                col['name'] = col['alias']

            util.icSpcDefStruct(SPC_IC_CELL, col)
            util.icSpcDefStruct(SPC_IC_CELLATTR, col['cell_attr'])

            if isinstance(col['attr'], str):
                col['attr'] = col['attr'].upper()

            #   Преобразуем выравнивание для ячеек колоноки
            if 'cell_attr' in col and 'alignment' in col['cell_attr']:
                aln = col['cell_attr']['alignment']
                if isinstance(aln, str):
                    try:
                        aln = eval(aln)
                    except:
                        aln = ('left', 'middle')
                if aln is not None:
                    col['cell_attr']['alignment'] = getIdAlignment(
                        aln[0], aln[1])

            #   Вычисляем атрибут <show> колонки
            bShow = 1
            if 'show' in col:
                if type(col['show']) in (str, unicode):
                    attr_show = '@' + col['show']
                    keyExpr = self.GetUUIDAttr('show', col['name'])
                    bShow = util.getICAttr(
                        attr_show, evalSpace,
                        u'Error in getICAttr in icgrid. col name=%s <show>=%s <key>=%s'
                        % (col['name'], col['show'], keyExpr))
                else:
                    bShow = col['show']

            col['show'] = bShow

        grid.Grid.__init__(self,
                           parent,
                           id,
                           self.pos,
                           self.size,
                           name=self.name,
                           style=component['style'])
        glr.GridWithLabelRenderersMixin.__init__(self)

        self.SetDefaultRowSize(component['row_height'])

        # Указатель на сложную шапку
        self.header = None
        #   Обработчики событий
        self.Bind(grid.EVT_GRID_COL_SIZE, self.OnColSize)
        self.Bind(grid.EVT_GRID_SELECT_CELL, self.OnSelected)
        self.Bind(wx.EVT_SCROLLWIN_LINEUP, self.OnScrollLineUp)
        self.Bind(wx.EVT_SCROLLWIN_LINEDOWN, self.OnScrollLineDown)
        self.Bind(wx.EVT_SCROLLWIN_PAGEUP, self.OnScrollPageUp)
        self.Bind(wx.EVT_SCROLLWIN_PAGEDOWN, self.OnScrollPageDown)
        self.Bind(wx.EVT_SCROLLWIN_THUMBTRACK, self.OnScrollTrack)
        self.Bind(wx.EVT_SIZE, self.OnSizeGrid)
        #   Переменные где хранятся значения ряда и колонки, котрые выбираются
        #   после вызова функции PostSelect().
        self._selEventRow = -1
        self._selEventCol = -1
Beispiel #10
0
    def __init__(self, parent, id, component, logType=0, evalSpace=None,
                 bCounter=False, progressDlg=None):
        """
        Конструктор базового класса пользовательских компонентов.
        @type parent: C{wx.Window}
        @param parent: Указатель на родительское окно.
        @type id: C{int}
        @param id: Идентификатор окна.
        @type component: C{dictionary}
        @param component: Словарь описания компонента.
        @type logType: C{int}
        @param logType: Тип лога (0 - консоль, 1- файл, 2- окно лога).
        @param evalSpace: Пространство имен, необходимых для вычисления внешних выражений.
        @type evalSpace: C{dictionary}
        @type bCounter: C{bool}
        @param bCounter: Признак отображения в ProgressBar-е. Иногда это не нужно -
            для создания объектов полученных по ссылки. Т. к. они не учтены при подсчете
            общего количества объектов.
        @type progressDlg: C{wx.ProgressDialog}
        @param progressDlg: Указатель на идикатор создания формы.
        """
        component = util.icSpcDefStruct(self.component_spc, component)

        #   По спецификации создаем соответствующие атрибуты (кроме служебных атрибутов)
        lst_keys = [x for x in component.keys() if not x.startswith('__')]
        
        for key in lst_keys:
            setattr(self, key, component[key])
            
        parentModule.icHeadCell.__init__(self, parent, id, component, logType, evalSpace)
        
        if not self.path:
            self.path = os.getcwd()
        else:
            self.path = util.getICAttr(component['path'], self.evalSpace, msg='ERROR')
            
        self.path = self.path.replace('\\', '/')
        if self.path[-1] != '/':
            self.path += '/'

        #   Создаем список картинок. Каждому состоянию соответствует картинка
        self._alignmentImg = eval(self.alignmentImg)
        
        self.imageList = []
        self.statesDict = {}
        
        for indx, nm in enumerate(self.images):
            if not type(nm) in (str, unicode):
                img = nm
                self.imageList.append(img)
            else:
                file = self.path+nm
                bmptype = icbitmap.icBitmapType(file)
                if bmptype is not None and os.path.isfile(file):
                    image_file = wx.Image(file, bmptype)
                    img = image_file.ConvertToBitmap()
                    self.imageList.append(img)
                
            if indx < len(self.states):
                st = self.states[indx]
            else:
                st = None
                
            self.statesDict[indx] = (img, st)

        self.imageState = None
        self._oldState = -1
        self.SetState(0)
        
        #   Регистрация обработчиков событий
        self.Bind(wx.EVT_LEFT_UP, self.OnMouseClick)
        self.BindICEvt()

        #   Создаем дочерние компоненты
        self.childCreator(bCounter, progressDlg)
Beispiel #11
0
    def __init__(self,
                 parent,
                 id=-1,
                 component={},
                 logType=0,
                 evalSpace={},
                 bCounter=False,
                 progressDlg=None):
        """
        Конструктор для создания объекта icBoxSizer.
        @type parent: C{wxWindow}
        @param parent: Указатель на родительское окно.
        @type id: C{int}
        @param id: Идентификатор окна.
        @type component: C{dictionary}
        @param component: Словарь описания компонента.
        @type logType: C{int}
        @param logType: Тип лога (0 - консоль, 1- файл, 2- окно лога).
        @param evalSpace: Пространство имен, необходимых для вычисления внешних выражений.
        @type evalSpace: C{dictionary}
        """
        icSpcDefStruct(SPC_IC_HEADCELL, component)
        icwidget.icWidget.__init__(self, parent, id, component, logType,
                                   evalSpace)
        self.position = pos = component['position']
        self.size = size = component['size']
        self.span = component['span']
        label = self.getICAttr('label')
        if not label:
            label = ''

        self.add_style = wx.EXPAND | wx.GROW
        self._isSort = getICAttr(
            '@' + str(component['isSort']), self.evalSpace,
            'Error in icheadgrid.__init__()<isSort>. Name:' + self.name)
        self.shortHelpString = component['shortHelpString']
        self._helpWin = None
        # -----------------------------------------------------------------------
        aln = component['alignment']
        if type(aln) in (str, unicode):
            try:
                aln = eval(aln)
            except:
                aln = ('centred', 'middle')

        horiz, vert = self.alignment = aln

        if horiz == 'centred':
            style = wx.ALIGN_CENTRE
        elif horiz == 'right':
            style = wx.ALIGN_RIGHT
        else:
            style = wx.ALIGN_LEFT

        style = style | wx.ST_NO_AUTORESIZE | wx.NO_BORDER

        # ----------------------------------------------------------------------
        wx.PyControl.__init__(self,
                              parent,
                              id,
                              pos,
                              size,
                              style,
                              name=self.name)
        # ----------------------------------------------------------------------
        self.SetLabel(label)
        self.SetPosition(pos)
        font = parent.GetFont()
        if not font.Ok():
            font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        wx.PyControl.SetFont(self, font)

        self.defBackClr = parent.GetBackgroundColour()
        if not self.defBackClr.Ok():
            self.defBackClr = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE)
        self.SetBackgroundColour(self.defBackClr)

        clr = parent.GetForegroundColour()
        if not clr.Ok():
            clr = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNTEXT)
        self.SetForegroundColour(clr)

        rw, rh = size
        bw, bh = self.GetBestSize()
        if rw == -1:
            rw = bw
        if rh == -1:
            rh = bh
        self.SetSize(wx.Size(rw, rh))
        # ----------------------------------------------------------------------

        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(wx.EVT_MOTION, self.OnMove)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave)
        self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnter)
        self.Bind(wx.EVT_SIZE, self.OnSize)

        self.BindICEvt()

        #   Цвета текста и фона
        self.bgr = bgr = component['backgroundColor']
        if component['backgroundColor2']:
            self.bgr2 = bgr2 = wx.Colour(*component['backgroundColor2'])
        else:
            self.bgr2 = bgr2 = None

        if not bgr2:
            if bgr:
                self.bgr2 = graphicUtils.GetMidColor(wx.Colour(*bgr),
                                                     wx.Colour(0, 0, 0), 0.25)
            else:
                self.bgr2 = graphicUtils.GetMidColor(
                    parent.GetBackgroundColour(), wx.Colour(0, 0, 0), 0.25)

        self.fgr = fgr = component['foregroundColor']

        #   Цвета границы
        self.leftColor = component['borderLeftColor']
        self.topColor = component['borderTopColor']
        self.rightColor = component['borderRightColor']
        self.bottomColor = component['borderBottomColor']
        self.borderStep = component['borderStep']
        self.borderWidth = component['borderWidth']
        self.cursorColor = component['cursorColor']

        #   Стиль границы - соответствует стиль wx.Pen
        self.borderStyle = None
        ret, val = self.eval_attr('borderStyle')
        if ret:
            self.borderStyle = val

        if not self.borderStyle or not isinstance(self.borderStyle, wx.SOLID):
            self.borderStyle = wx.SOLID

        #   Тип штриховки фона
        self.backgroundType = component['backgroundType']

        #   Изображение подложки
        if component['bgrImage'] and issubclass(
                component['bgrImage'].__class__, wx.Bitmap):
            self.bgrImage = component['bgrImage']
        else:
            self.bgrImage = self.countAttr('bgrImage')

        #   Шрифт текста
        self.font = font = component['font']

        if bgr:
            self.SetBackgroundColour(bgr)

        if fgr:
            self.SetForegroundColour(fgr)

        if font:
            obj = icFont(font)
            self.SetFont(obj)

        # Направление сортировки.
        #  0 - сортировка не установлена
        #  1 - сортировка по возрастанию
        # -1 - сортировка по убыванию
        self.sortDirection = 0

        #
        self.bButton = False
        self._buttonPress = False
        self._buttonEnter = False

        # Описание наличия скругленных углов границы в виде (LT, RT, RB, LB)
        self.SetRoundCorners(
            ((component.get('roundConer', None) or []) + [0] * 4)[:4])

        #   Создаем дочерние компоненты
        self.child = component['child']
        if 'child' in component:
            self.childCreator(bCounter, progressDlg)
Beispiel #12
0
    def __init__(self,
                 parent,
                 id,
                 component,
                 logType=0,
                 evalSpace=None,
                 bCounter=False,
                 progressDlg=None,
                 *arg,
                 **kwarg):
        """
        Конструктор для создания icSpinner

        @type parent: C{wx.Window}
        @param parent: Указатель на родительское окно
        @type id: C{int}
        @param id: Идентификатор окна
        @type component: C{dictionary}
        @param component: Словарь описания компонента.
        @type logType: C{int}
        @param logType: Тип лога (0 - консоль, 1- файл, 2- окно лога)
        @param evalSpace: Пространство имен, необходимых для вычисления внешних выражений.
        @type evalSpace: C{dictionary}
        """
        self.bChanged = 0

        component = util.icSpcDefStruct(SPC_IC_SPINNER, component)
        icWidget.__init__(self, parent, id, component, logType, evalSpace)

        #   По спецификации создаем соответствующие атрибуты (кроме служебных атрибутов)
        lst_keys = [x for x in component.keys() if not x.startswith('__')]
        for key in lst_keys:
            setattr(self, key, component[key])

        if component['field_name'] is None:
            self.field_name = self.name
        else:
            self.field_name = component['field_name']

        min = util.getICAttr(
            component['min'], evalSpace,
            'Error in getICAttr in icspinner. name=%s <min>=%s' %
            (self.name, component['min']))
        max = util.getICAttr(
            component['max'], evalSpace,
            'Error in getICAttr in icspinner. name=%s <max>=%s' %
            (self.name, component['max']))
        val = util.getICAttr(
            component['value'], evalSpace,
            'Error in getICAttr in icspinner. name=%s <value>=%s' %
            (self.name, component['value']))

        fgr = component['foregroundColor']
        bgr = component['backgroundColor']
        style = component['style']
        pos = component['position']
        size = component['size']
        size = (int(size[0]), int(size[1]))
        font = component['font']

        #   Номер последней заблокированной записи
        self._oldLockReck = -1

        wx.SpinCtrl.__init__(self,
                             parent,
                             id,
                             str(val),
                             pos,
                             size,
                             style,
                             min=min,
                             max=max,
                             name=self.name)

        if fgr is not None:
            self.SetForegroundColour(wx.Colour(fgr[0], fgr[1], fgr[2]))

        if bgr is not None:
            self.SetBackgroundColour(wx.Colour(bgr[0], bgr[1], bgr[2]))

        try:
            self.SetValue(str(self.dataset.getNameValue(self.field_name)))
        except:
            pass

        obj = icFont(font)
        self.SetFont(obj)

        self.Bind(wx.EVT_SPIN, self.OnSpin, id=id)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.BindICEvt()
Beispiel #13
0
    def __init__(self,
                 parent,
                 id,
                 component,
                 logType=0,
                 evalSpace={},
                 bCounter=False,
                 progressDlg=None):
        """
        Конструктор для создания icStaticText

        @type parent: C{wx.Window}
        @param parent: Указатель на родительское окно
        @type id: C{int}
        @param id: Идентификатор окна
        @type component: C{dictionary}
        @param component: Словарь описания компонента
        @type logType: C{int}
        @param logType: Тип лога (0 - консоль, 1- файл, 2- окно лога)
        @param evalSpace: Пространство имен, необходимых для вычисления внешних выражений
        @type evalSpace: C{dictionary}
        """
        icSpcDefStruct(SPC_IC_STATICTEXT, component)
        icWidget.__init__(self, parent, id, component, logType, evalSpace)

        text = component['text']
        pos = component['position']
        size = component['size']
        fgr = component['foregroundColor']
        bgr = component['backgroundColor']
        font = component['font']
        style = component['style']

        #   Вычисляем текст поля после создания объекта
        if text.find('@') == -1:
            val = getICAttr('@' + text, self.evalSpace, None)
        else:
            val = getICAttr(
                '@' + text, self.evalSpace,
                'Error in icstatictext.__init__()<text>. Name:' + self.name)

        if not val:
            val = text

        wx.StaticText.__init__(self,
                               parent,
                               id,
                               val,
                               pos,
                               size=size,
                               style=style,
                               name=self.name)

        if fgr is not None:
            self.SetForegroundColour(wx.Colour(fgr[0], fgr[1], fgr[2]))

        if bgr is not None:
            self.SetBackgroundColour(wx.Colour(bgr[0], bgr[1], bgr[2]))

        obj = icFont(font)
        self.SetFont(obj)