def loadImgLib(self, sImgLibFileName=None): """ Загрузить текст библиотеки образов. @param sImgLibFileName: Файл библиотеки образов *.py. """ if not sImgLibFileName: sImgLibFileName = self._img_lib_file_name if sImgLibFileName and sImgLibFileName != self._img_lib_file_name: self._img_lib_file_name = sImgLibFileName self._img_lib_file = None try: self._img_lib_file = open(sImgLibFileName, 'r') self._img_lib_text = self._img_lib_file.read() self._img_lib_file.close() self._img_lib_file = None if ic_mode.isDebugMode(): io_prnt.outLog(u'Загрузка библиотеки образов <%s>' % sImgLibFileName) return self._img_lib_text except: io_prnt.outErr(u'Ошибка загрузки файла библиотеки образов <%s>' % sImgLibFileName) if self._img_lib_file: self._img_lib_file.close() self._img_lib_file = None return None
def SetLabel(self, label): """ Sets the static text label and updates the control's size to exactly fit the label unless the control has wx.ST_NO_AUTORESIZE flag. """ label = label.replace('\\r\\n', '\n').replace('\\n', '\n').replace('\r\n', '\n') # Заглушка!!! if isinstance(label, str): try: label = unicode(label, 'utf-8') except: io_prnt.outLog( _('WARRNING') + ':' + 'icHeadCell, label is not in utf-8 encoding.') label = unicode(label, 'cp1251') # Заглушка!!! if label.strip().startswith('_('): label = label.replace('_(', '').replace(')', '').replace('\'', '').replace('"', '') label = _(label.encode('utf-8').strip()) wx.PyControl.SetLabel(self, label) style = self.GetWindowStyleFlag() if not style & wx.ST_NO_AUTORESIZE: self.SetSize(self.GetBestSize()) self.Refresh()
def getImgFileData(ImgFileName_): """ Получить данные файла образа. @param ImgFileName_: Имя файла образа. @return: Данные образа или None в случае ошибки. """ try: # Определить тип образа и расширение файла img_file_type = ic_bmp.getImageFileType(ImgFileName_) img_file_ext = ic_file.SplitExt(ImgFileName_)[1] # Конвертировать файл образа во временный файл tmp_file_name = tempfile.mktemp() io_prnt.outLog(u'Серилизация файла образа [%s : %s : %s]' % (ImgFileName_, img_file_ext, img_file_type)) ok, msg = img2img.convert(ImgFileName_, None, None, tmp_file_name, img_file_type, img_file_ext) # Все нормально? if not ok: io_prnt.outLog(msg) return None # Получить данные из временного файла tmp_file = open(tmp_file_name, 'rb').read() data = crunchImgData(tmp_file) ic_file.UnLink(tmp_file_name) return data except: io_prnt.outErr(u'Ошибка серилизации файла образа <%s> в строку.' % ImgFileName_) return None
def open_db_1(self): """ """ db_engine = create_engine('sqlite:///sqlite/input1.db', strategy='threadlocal') io_prnt.outLog('open sqlite:///sqlite/input1.db - ok!') return db_engine
def setKey(evalSpace, key, obj, cod_access=None): """ Функция добавляет объект в пространство имен. @param evalSpace: Пространство имен формы. @type evalSpace: C{dictionary} @param key: Ключ в пространстве имен. @type key: C{string} @param obj: Объект, который надо добавить. @param cod_access: Код доступа на изменение значения ключа. @rtype: C{bool} @return: Возвращает признак успешного добавления. """ if '_access_keys' not in evalSpace: evalSpace['_access_keys'] = {} akey = evalSpace['_access_keys'] try: if key not in akey.keys() or (key in akey.keys() and cod_access == akey[key]): if cod_access != CODE_NOBODY or (cod_access == CODE_NOBODY and key not in evalSpace): evalSpace[key] = obj if cod_access is not None: evalSpace['_access_keys'][key] = cod_access return True except: io_prnt.outLog('ERROR setKey') return False
def UnLockFile(FileName_, **If_): """ Разблокировать файл. @param FileName_: Имя файла. @param If_: Условие проверки разблокировки. Ключ записи блокировки=значение. Проверка производится по 'И'. Если такого ключа в записи нет, то его значение берется None. @return: Возвращает результат True/False. """ # Сгенерировать имя файла блокировки lock_file = os.path.splitext(FileName_)[0] + LOCK_FILE_EXT io_prnt.outLog(u'UnLockInfo: %s, %s, %s' % (lock_file, If_, ic_file.Exists(lock_file))) if os.path.exists(lock_file): if If_: lck_rec = ReadLockRecord(lock_file) # Если значения по указанным ключам равны, то все ОК can_unlock = bool( len([ key for key in If_.keys() if lck_rec.setdefault(key, None) == If_[key] ]) == len(If_)) io_prnt.outLog(u'UnLockInfo: %s, %s' % (lck_rec, can_unlock)) if can_unlock: # Ресурс можно разблокировать os.remove(lock_file) else: # Нельзя разблокировать файл return False else: # Ресурс можно разблокировать os.remove(lock_file) return True
def undo(self): """ Запуск выполнения отмены операции. @return: True/False. """ # Если функция не определена, то и не выполнять if not self.is_do_func(): return True else: io_prnt.outLog(u'Отмена ОПЕРАЦИИ <%s>' % self.name) context = self.GetContext() context['OBJ'] = self.parent context['UUID'] = self.parent.getUUID() # Пред обработка if self.isICAttrValue('prev_undo'): self.eval_attr('prev_undo') result = self.eval_attr('undo_func') # Пост обработка if self.isICAttrValue('post_undo'): self.eval_attr('post_undo') if result[0] == coderror.IC_EVAL_OK: return result[1] else: io_prnt.outWarning(u'Ошибка отмены ОПЕРАЦИИ <%s>.' % self.name) return False
def lockRes(ResName_, ResFileName_, ResFileExt_, LockDir_=None): """ Заблокировать ресурс. Имя файла блокировки гонерируется как ИмяРесурса_ИмяФайлаРесурса_РасширениеФайлаРесурса.lck. В файл блокировки записывается информация о владельце блокировки в виде словаря {'computer':Имя хоста с которого заблокировался ресурс}. @param ResName_: Имя ресурса. Если имя ресурса None, то блокируется файл ресурса целиком. @param ResFileName_: Имя файла ресурса. @param ResFileExt_: Расширение файла ресурса/тип ресурса. @param LockDir_: Папка блокировок. """ if LockDir_ is None: LockDir_ = lock.getLockDir() try: os.makedirs(LockDir_) except: pass if ResName_ is None: ResName_ = ResFileName_ lock_file = LockDir_ + '/%s_%s_%s%s' % (ResName_.strip( ), ResFileName_.strip(), ResFileExt_.strip(), lock.LOCK_FILE_EXT) comp_name = lock.ComputerName() user_name = ic.engine.ic_user.icGet('UserName') if ic_mode.isDebugMode(): io_prnt.outLog(u'Lock resource <%s>' % lock_file) return lock.LockFile( lock_file, u'{\'computer\':\'%s\',\'user\':\'%s\'}' % (comp_name, user_name))
def CreateInitFile(Path_): """ Создает файл __init__.py в директории Path_ если его там нет. @return: Возвращает True, если файл был создан или уже есть. """ if not Path_: return False try: os.makedirs(Path_) except: pass init_file = Path_ + '/__init__.py' if os.path.isfile(init_file): return True try: f = None f = open(init_file, 'w') f.write(_InitFileDefault) f.close() io_prnt.outLog(_('File %s is created.') % init_file) return True except: io_prnt.outErr(_('Create module error: %s/__init__.py') % Path_) if f: f.close() return False
def SaveResourcePickle(FileName_, Resource_): """ Сохранить ресурс в файле в формате Pickle. @param FileName_: Полное имя ресурсного файла. @param Resource_: Словарно-списковая структура спецификации. @return: Возвращает результат выполнения операции True/False. """ FileName_ = ic_file.AbsolutePath(FileName_) try: f = None # Если необходимые папки не созданы, то создать их dir_name = os.path.dirname(FileName_) try: os.makedirs(dir_name) except: pass f = open(FileName_, 'w') cPickle.dump(Resource_, f) f.close() io_prnt.outLog(_('File %s is saved in pickle format.') % FileName_) return True except: if f: f.close() io_prnt.outErr(_('Faild save file in pickle format: %s.') % FileName_) return False
def SaveResourceText(FileName_, Resource_, ToStruct_=False): """ Сохранить ресурс в файле в текстовом формате. @param FileName_: Полное имя ресурсного файла. @param Resource_: Словарно-списковая структура спецификации. @param ToStruct_: Сохранить в структурном виде ресурс? @return: Возвращает результат выполнения операции True/False. """ FileName_ = ic_file.AbsolutePath(FileName_) try: f = None # Если необходимые папки не созданы, то создать их dir_name = os.path.dirname(FileName_) try: os.makedirs(dir_name) except: pass f = open(FileName_, 'w') if ToStruct_: text = ic_util.StructToTxt(Resource_) else: text = str(Resource_) f.write(text) f.close() io_prnt.outLog( _('Resource file %s is saved in text format.') % FileName_) return True except: if f: f.close() io_prnt.outErr(_('Faild save file in text format: %s.') % FileName_) return False
def OnDiffTool(self, event): """ Утилита сравнения файлов. """ cmd = 'meld &' io_prnt.outLog(u'Выполнение команды ОС <%s>' % cmd) os.system(cmd)
def CreatePyFile(PyFileName_, PyFileBody_=None): """ Создать файл питоновского модуля. @param PyFileName_: Имя файла *.py. @param PyFileBody_: Тело файла. Если None, то заполняется по умолчанию. @return: Возвращает True, если файл был создан или уже есть. """ if os.path.isfile(PyFileName_): return True try: f = None try: os.makedirs(os.path.dirname(PyFileName_)) except: pass f = open(PyFileName_, 'w') if PyFileBody_ is None: f.write(_PyFileDefault) else: f.write(str(PyFileBody_)) f.close() io_prnt.outLog(_('Module %s is created.') % PyFileName_) return True except: io_prnt.outErr(_('Create module error: %s') % PyFileName_) if f: f.close() return False
def createMainWin(Name_, ResFile_=DEFAULT_WIN_RES_FILE, ParentWin_=None, Runner_=None): """ Функция создает из ресурса окно по его имени. @param Name_: Имя-идентификатор окна прописанный в файле ресурса. @param ResFile_: Имя ресурсного файла. @param ParentWin_: Родительское окно (если нет, то None). @param Runner_: Родительский ДВИЖОК (если нет, то None). @return: Возвращает объект окна или None в случае ошибки. """ try: from ic.components.user import ic_mainwin_wrp win = None win_struct = LoadWinStruct(Name_, ResFile_) if win_struct == {}: io_prnt.outLog(u'Нет данных о таком окне!') return None win = ic_mainwin_wrp.icMainWindow(None, component=win_struct) return win except: if win is not None: MsgLastError(win, u'Ошибка создания окна!') io_prnt.outErr(u'Ошибка создания главного окна!') return win
def getReportDir(self): """ Папка отчетов. Папка отчетов по умолчанию всегда находиться в папке проекта. Например: /defis/NSI/NSI/reports. @return: Полный путь до директории отчетов. """ if self._report_dir is None: prj_dir = ic_user.icGet('PRJ_DIR') self._report_dir = os.path.join( prj_dir, config.get_glob_var('DEFAULT_REPORT_DIRNAME')) # Проверить сразу существует ли папка if not os.path.exists(self._report_dir): try: os.makedirs(self._report_dir) io_prnt.outLog(u'Cоздание папки <%s>' % self._report_dir) description_filename = os.path.join( self._report_dir, 'descript.ion') prj_name = os.path.basename(prj_dir) ic_extend.save_file_text( description_filename, u'Отчеты прикладной системы <%s>' % prj_name) init_filename = os.path.join(self._report_dir, '__init__.py') ic_extend.save_file_text(init_filename, DEFAULT_INIT_PY_FMT % prj_name) except IOError: io_prnt.outWarning(u'Ошибка создания папки <%s>' % self._report_dir) return self._report_dir
def RunProgramm(Cmd_, Mode_=os.P_NOWAIT): """ Запуск программы на выполнение. @type Cmd_: C{string} @param Cmd_: Комманда системы. @param Mode_: Режим выполнения комманды. См os режимы выполнения. @return: True/False. """ try: parse_args = Cmd_.strip().split(' ') args = [] i = 0 while i < len(parse_args): parse_arg = parse_args[i] if parse_arg[0] == '"' and parse_arg[-1] <> '"': while parse_arg[-1] <> '"' and i < len(parse_args): i += 1 parse_arg += ' ' + parse_args[i] # Стереть """ if parse_arg[0] == '"': parse_arg = parse_arg[1:] if parse_arg[-1] == '"': parse_arg = parse_arg[:-1] args.append(parse_arg) i += 1 io_prnt.outLog('RunProgramm: %s' % args) os.spawnve(Mode_, args[0], args, os.environ) return True except: io_prnt.outErr(_('Run programm error: %s') % Cmd_) return False
def _UnLockFileWalk(args, CurDir_, CurNames_): """ Вспомогательная функция разблокировки файла на уровне каталога по имени компьютера. Используется в функции os.path.walk(). @param args: Кортеж (Имя компьютера файлы которого нужно раблокировать, Имя пользователя). @param CurDir_: Текущий директорий. @param CurNames_: Имена поддиректорий и файлов в текущей директории. """ computer_name = args[0] user_name = args[1] # Отфильтровать только файлы блокировок lock_files = [ x for x in [ic_file.Join(CurDir_, x) for x in CurNames_] if ic_file.IsFile(x) and ic_file.SplitExt(x)[1] == LOCK_FILE_EXT ] # Выбрать только свои файлы-блокировки for cur_file in lock_files: lock_record = ReadLockRecord(cur_file) io_prnt.outLog( u'Разблокировка. Компьютер <%s>. Пользователь <%s>. Запись блокировки %s' % (computer_name, user_name, str(lock_record))) if isinstance(lock_record, str) and not lock_record.strip(): # Если пустая строка в записи блокировки, то просто удаляем os.remove(cur_file) else: if not user_name: if lock_record['computer'] == computer_name: os.remove(cur_file) else: if lock_record['computer'] == computer_name and lock_record[ 'user'] == user_name: os.remove(cur_file)
def OnSetFocus(self, evt): """ Обрабатывает установку фокуса (сообщение EVT_SET_FOCUS). """ if self.bTimeLosefocus: self.bTimeLosefocus = False evt.Skip() return # Формируем пространство имен value = self.GetValue() self.evalSpace['evt'] = evt self.evalSpace['event'] = evt self.evalSpace['value'] = value evt.Skip() # Блокируем запись для редактирования, если позволяет объект данных if self.dataset and not self.evalSpace['__block_lock_rec']: rec = self.dataset.Recno() result = self.dataset.Lock(rec) if not result and rec != self._oldLockReck: self.bkillfocus = False MsgBox( self.parent, _('Record (%d) is locked. <TextField=%s>, err=%s') % (rec, self.name, str(result))) self._oldLockReck = rec self.bkillfocus = True else: io_prnt.outLog('TEXTFIELD LOCK RECORD: %s' % str(rec)) self.eval_attr('setFocus') self.bChanged = False
def testicGetRes(self): path, nm = os.path.split(__file__) res = resource.icGetRes(None, 'frm', path, nameRes='test_res') io_prnt.outLog('>>> read resource name:%s type:%s' % (res['name'], res['type'])) self.assertEqual(res['type'], 'Panel') self.assertEqual(res['name'], 'test1_panel')
def init_panel(self): """ Инициализация панели. """ if self._form: # Получаем указатель на ядро name, subsys = self._form win = self.create_obj(name, subsys) if win: self.SetPanel(win) # Вызываем у объекта функцию чтения данных на форму if self._obj: if hasattr(self._obj.metaitem.value, 'doc_uuid') and self._obj.metaitem.value.doc_uuid: io_prnt.outLog(u'>>> Загружаем документ UUID=%s' % self._obj.metaitem.value.doc_uuid) self._obj.load(self._obj.metaitem.value.doc_uuid) self._obj.startEdit() if not self._obj.isMyLock(): msgbox.MsgBox(win, u'Документ заблокирова пользователем %s' % self._obj.ownerLock()) ifs = win.GetComponentInterface() if ifs: ifs.set_object(self._obj) ifs.LoadData()
def mapclass(sysdb, tab_name=None): """ Мапируем класс. """ tab_name = tab_name or 'resource_tab' resources_tab = sa.Table( tab_name, sysdb.getMetaData(), sa.Column('res_id', sa.Integer, sa.Sequence('%s_id_seq' % tab_name), primary_key=True), sa.Column('path', sa.String(), nullable=False), sa.Column('computer', sa.String(), nullable=True), sa.Column('user', sa.String(), nullable=True), sa.Column('last_modified', sa.DateTime, onupdate=sa.func.current_timestamp()), sa.Column('res', sa.PickleType(0), nullable=False), sa.Column('lock', sa.Boolean(), default=False), sa.Column('ttl', sa.Integer, nullable=True), ) orm.clear_mappers() orm.mapper(Resources, resources_tab, extension=ResEventExtension(), properties={'_res': orm.deferred(resources_tab.c.res)}) io_prnt.outLog('MAP Resource Loader class.') return resources_tab, Resources
def open_pgs(self): """ """ db_engine = create_engine( 'postgres://*****:*****@x.ic.plus:5432/ic_db') print() io_prnt.outLog('open postgres://ic_all:[email protected]:5432/ic_db') return db_engine
def OnRegExpEditor(self, event): """ Редактор регулярных выражений. """ start_filename = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'contrib', 'pyreditor', 'pyreditor.pyw') cmd = '%s %s&' % (sys.executable, start_filename) io_prnt.outLog(u'Выполнение команды ОС <%s>' % cmd) os.system(cmd)
def isInFilteredVal(flt, fld, value, isVerSize=True): """ Функция проверяет принадлежит ли значение заданому фильтру. @type flt: C{dictionary} @param flt: Словарь задающий структурный фильтр. @type fld: C{string} @param fld: Имя атрибута, для которого проверяется значение. @type value: C{...} @param value: Проверяемое значение. @type isVerSize: C{bool} @param isVerSize: Признак того, что размер значения не может быть больше размера шаблона. @rtype: C{bool} @return: Признак принадлежность значения заданному фильтру. """ if not isinstance(flt, dict): io_prnt.outLog( _('Unexpected filter type. Must be srting type or dictionary.')) return None if fld not in flt.keys(): io_prnt.outLog(_('Filter has not key: <%s>.')) return False filt = flt[fld] if not isinstance(filt, list): if filt == value: return True else: return False else: cur = 0 for x in filt: if type(x) in (str, unicode): if value[cur:cur + len(x)] != x: return False else: cur += len(x) elif isinstance(x, int): cur += x if cur >= len(value): break # Вычисляем размер шаблона if isVerSize: cur = 0 for x in filt: if type(x) in (str, unicode): cur += len(x) elif isinstance(x, int): cur += x if cur < len(value): return False return True
def OnPrevPage(self, event): """ Обработчик переключения на предыдущую страницу. """ try: self.AdvanceSelection(False) except: io_prnt.outLog(u'Ошибка переключения страницы') event.Skip()
def OnNextPage(self, event): """ Обработчик переключения на следующую страницу. """ try: self.AdvanceSelection(True) except: io_prnt.outLog(u'Ошибка переключения страницы') event.Skip()
def isLockTable(table): """ Проверка на блокировку таблицы. """ table = __norm(table) io_prnt.outLog('%s, %s' % (table, getLockDir())) # это путь к директории флагов блокировок этой таблицы path = os.path.join(getLockDir(), table + '.lck') return osp.isdir(path)
def _find(obj): """ Поиск подстроки.""" global buff_find_str context = obj.GetContext() grid=context.GetObject(SPR_GRID_NAME) tree_grid = context.GetObject(SPR_TREE_NAME) sprav=context.GetObject(SPR_TREE_NAME).get_sprav() find_str=context.GetObject('findEdit').GetValue().strip() cur_cursor=grid.GetGridCursorRow() old_cod=tree_grid.get_cur_cod()#sprav.getPrevCode() if not find_str: return if not buff_find_str or buff_find_str.find_str != find_str or buff_find_str.isEOF(): io_prnt.outLog(u' ... find string: %s' % find_str) tab = sprav.getStorage().getSpravTabClass() tabcls = sprav.getStorage().getSpravTabClass().dataclass conn = sprav.getStorage().getSpravTabClass().getConnection() typ = sprav.getType() # Если измениласть строка поиска if old_cod: fq = tabcls.c.type.like(typ) & tabcls.c.cod.like(old_cod+u'%') & tabcls.c.name.ilike(u'%' + find_str+u'%') else: fq = tabcls.c.type.like(typ) & tabcls.c.name.ilike(u'%' +find_str+u'%') print(' ... cod=%s query:%s' % (old_cod, fq)) s = select([tabcls], fq) print(' ... select:', typ, s) res = conn.execute(s) #rec = res.fetchone() #print dir(res) if not buff_find_str: idx = res.keys.index('cod') buff_find_str = icsprav_search.sparv_search(find_str, res, cod_indx=idx) else: buff_find_str.set_data(find_str, res) print(' ... res:', res, buff_find_str.searchResult) if buff_find_str: rec = buff_find_str.next() if rec: fcod = rec[buff_find_str.cod_indx] if type(fcod) != unicode: fcod = unicode(fcod, 'utf-8') prnt_cod = sprav.getParentLevelCod(fcod) tree_grid.select_cod(prnt_cod, sel_cod=fcod) #print '.... select cod:', prnt_cod, fcod, len(prnt_cod), len(fcod), type(fcod) tree_grid.cod_name_lst = [] elif buff_find_str.cursor == -1: wx.MessageBox(u'Подстрока "%s" в справочнике не найдена.' % find_str) else: wx.MessageBox(u'Вхождений подстроки "%s" больше не найдено.' % find_str)
def get_object_link(self): """ Возвращает связанный объект, обычно грид. """ if self.object_link is None: psp = self.getICAttr('object_link') io_prnt.outLog(u'DatasetNavigator. Object link passport <%s>' % psp) object_link = self.GetKernel().getObjectByPsp(psp) self.setLink(object_link) return self.object_link
def icGetCurPage(self): """ Определеить объект текущей страницы. """ try: if 0 <= self._cur_selected_page < self.GetPageCount(): return self.GetPage(self._cur_selected_page) except: io_prnt.outLog(u'Ошибка определения объекта текущей страницы') return None