def Open(self): """ Открыть узел. """ self.makeNodeDir() self._StorageDB = {} list_dir = ic_file.ListDir(self._NodeDir) for name in list_dir: # Отфильтровать папки системного назначения if name[0] != SYSTEM_DIR_PREFIX: full_name = self._NodeDir + '/' + name if ic_file.IsDir(full_name): self._StorageDB[name] = icDirStorage() self._StorageDB[name].setParentNode(self, name) self._StorageDB[name].Open() elif ic_file.IsFile(full_name): if name != DIR_STORAGE_PROPERTY_FILE_NAME: node_name = ic_file.SplitExt(name)[0] self._StorageDB[node_name] = icFileStorage() self._StorageDB[node_name].setParentNode( self, node_name) else: self.property = icFileStorage() self.property.setParentNode(self, DIR_STORAGE_PROPERTY_NAME) storage_interface.icElementStorageInterface.Open(self)
def getImgName(self, sImgFileName=None): """ Имя образа по файлу образа. """ if sImgFileName: return 'img' + ic_file.SplitExt(ic_file.BaseName(sImgFileName))[0] return 'img' + str(wx.NewId())
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 _toUnicodeResourceWalk(args, CurDir_, CurNames_): # Отфильтровать только файлы ресурсов res_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].lower() in RESOURCE_EXT ] for res_file in res_files: try: f = open(res_file, 'rb') text = f.read() f.close() except: print('ERROR open file', res_file) f.close() replace_dict_txt = text.strip() try: replace_dict = eval(replace_dict_txt) x_dict = ic_util.icStructStrRecode(replace_dict, 'cp1251', 'UNICODE') new_text = str(x_dict) print('>>', res_file, ' : ', x_dict) try: f = open(res_file, 'w') f.write(new_text) f.close() except: print('ERROR open file', res_file) f.close() except: print('Error read', res_file, ' : ', replace_dict_txt)
def addImg(self, sImgFileName=None): """ Добавить новый образ в библиотеку. """ if self._img_lib_res.isEmpty(): ic_dlg.icMsgBox(u'ОШИБКА', u'Не определена библиотека образов!', self.getObject()) return None dlg = self.GetNameObj('ImgLibDlg') if sImgFileName is None: sImgFileName = ic_dlg.icImageDlg(dlg, self._img_dir) # Сохранить выбранную папку как папку картинок self.setImgDir(ic_file.DirName(sImgFileName)) self.saveImgDir() if sImgFileName: # Серилизовать и добавить образ self._img_lib_res.addImg(sImgFileName) self._img_lib_res.saveImgLib() # Добавить в словарь образов img_name = ic_file.SplitExt(ic_file.BaseName(sImgFileName))[0] # Заменить все минусы на подчеркивание # иначе в генерирумом фалйе будут имена объектов с минусами (SyntaxisError) img_name = img_name.replace('-', '_') img = ic_bmp.createBitmap(sImgFileName) self._img_dict[img_name] = img return img_name return None
def AddOrgPage(self, Page_, Title_, OpenExists_=False, Image_=None, CanClose_=True, OpenScript_=None, CloseScript_=None, DefaultPage_=-1, not_duplicate=True): """ Добавить страницу. @param Page_: Страница-объект наследник wx.Window. @param Title_: Заголовок страницы. @param OpenExists_: Если страница уже создана-открыть ее. @param Image_: Файл образа или сам образ в заголовке страницы. @param CanClose_: Признак разрешения закрытия страницы при помощи стандартного всплывающего меню. @param OpenScript_: Блок кода открытия страницы при переключенни м/у страницами. @param CloseScript_: Блок кода закрытия страницы при переключенни м/у страницами. @param DefaultPage_: Индекс страницы, открываемой по умолчанию. Если -1, то открывается текущая добавляемая страница. @param not_dublicate: Не открывать страницу с таким же именем? """ select = DefaultPage_ == -1 if type(Page_) in (str, unicode): res_name, res_ext = ic_file.SplitExt(Page_) # По умолчанию ресурс форм: *.frm if not res_ext: res_ext = '.frm' # Создание объекта страницы main_notebook = self.GetMainNotebook() page_parent = main_notebook if main_notebook else self Page_ = icResourceParser.icCreateObject(res_name, res_ext[1:], parent=page_parent) return self.addMainNotebookPage(Page_, Title_, select, Image_, not_dublicate=not_duplicate)
def isFBP(self, sFileName): """ Проверка является ли файл модулм проекта wxformbuilder. @param sFileName: Имя файла. @return: Возвращает True/False. """ return ic_file.IsFile(sFileName) and \ (ic_file.SplitExt(sFileName)[1] == '.fbp')
def isXRC(self, sFileName): """ Проверка является ли файл XRC ресурсом форм. @param sFileName: Имя файла. @return: Возвращает True/False. """ return ic_file.IsFile(sFileName) and \ (ic_file.SplitExt(sFileName)[1] == '.xrc')
def OnImgLibBrowser(self, event): """ Браузер библиотек картинок. """ prj_file_name = self._Parent.getRoot().getPrjFileName() prj_ini_file = None if prj_file_name: prj_ini_file = ic_file.SplitExt(prj_file_name)[0]+'.ini' icimagelibrarybrowser.runImageLibraryBrowser(self._Parent.getRoot().getParent(), prj_ini_file)
def isTemplateModule(self, FileName_): """ Проверка является ли файл модулем шаблона проекта. @param FileName_: Имя файла. @return: Возвращает True/False. """ return ic_file.IsFile(FileName_) and \ (ic_file.SplitExt(FileName_)[1] == '.py' and \ ic_file.BaseName(FileName_) != '__init__.py') and \ self._findModuleSignature(FileName_, TEMPLATE_MODULE_SIGNATURE)
def addImg(self, ImgFileName_): """ Добавить образ в библиотеку образов из файла. @param ImgFileName_: Имя файла образа. """ img_name = ic_file.SplitExt(ic_file.BaseName(ImgFileName_))[0] img_data = self.getImgData(ImgFileName_) if img_data: img_block = self.createImgBlock(img_name, img_data) self.addImgBlock(img_block)
def isFBModule(self, FileName_): """ Проверка является ли файл модулем форм wxFormBuilder. @param FileName_: Имя файла. @return: Возвращает True/False. """ return ic_file.IsFile(FileName_) and \ (ic_file.SplitExt(FileName_)[1] == '.py' and ic_file.BaseName(FileName_) != '__init__.py') and \ self._findModuleSignature(FileName_, WXFB_MODULE_SIGNATURE)
def isResourceModule(self, FileName_): """ Проверка является ли файл ресурсным модулем проекта. @param FileName_: Имя файла. @return: Возвращает True/False. """ return ic_file.IsFile(FileName_) and \ (ic_file.SplitExt(FileName_)[1] == '.py' and \ ic_file.BaseName(FileName_) != '__init__.py') and \ self._findModuleSignature(FileName_, RESOURCE_MODULE_SIGNATURE)
def isImageModule(self, FileName_): """ Проверка является ли файл модулем библиотеки образов проекта. @param FileName_: Имя файла. @return: Возвращает True/False. """ return ic_file.IsFile(FileName_) and \ (ic_file.SplitExt(FileName_)[1] == '.py' and \ ic_file.BaseName(FileName_) != '__init__.py') and \ self._findModuleSignature(FileName_, IMAGE_MODULE_SIGNATURE)
def isModule(self, FileName_): """ Проверка является ли файл модулм проекта. @param FileName_: Имя файла. @return: Возвращает True/False. """ return ic_file.IsFile(FileName_) and \ (ic_file.SplitExt(FileName_)[1] == '.py' and ic_file.BaseName(FileName_) != '__init__.py') and \ (not self._findModuleSignature(FileName_, INTERFACE_MODULE_SIGNATURE))
def isXRCModule(self, FileName_): """ Проверка является ли файл модулем форм, сгенерированных утилитой pywxrc (из XRC ресурса). @param FileName_: Имя файла. @return: Возвращает True/False. """ return ic_file.IsFile(FileName_) and \ (ic_file.SplitExt(FileName_)[1] == '.py' and ic_file.BaseName(FileName_) != '__init__.py') and \ self._findModuleSignature(FileName_, XRC_MODULE_SIGNATURE)
def setBehaviour(self, BehaviourResourceFileName_): """ Установить поведение системы. @param BehaviourResourceFileName_: Имя файла ресурса со связями. """ from ic.components import icResourceParser try: file_name, file_ext = ic_file.SplitExt(BehaviourResourceFileName_) return icResourceParser.icCreateObject(file_name, file_ext[1:]) except: io_prnt.outErr( u'Ошибка установки поведения системы из файла: <%s>' % BehaviourResourceFileName_) return None
def _getNSIFieldsSpc(self, NSIRes_, NSIType_, FieldNames_): """ Взять спецификацию поля справочника. @param NSIRes_: Имя ресурсного файла справочника. @param NSIType_: Тип справочника. @param FieldNames_: Список имен полей справочника. """ if NSIRes_ is None: nsi_res_name = 'nsi_sprav' nsi_res_ext = 'mtd' else: nsi_res = ic_file.SplitExt(ic_file.BaseName(NSIRes_)) nsi_res_name = nsi_res[0] nsi_res_ext = nsi_res[1][1:] # И стереть первую точку # Получить ресурсное описание справочника nsi_sprav_manager_res = resource.icGetRes(nsi_res_name, nsi_res_ext, nameRes=nsi_res_name) if nsi_sprav_manager_res['name'] == NSIType_: # Справочник определен просто в ресурсе nsi_sprav_res = [nsi_sprav_manager_res] else: # Справочник определен в менеджере справочников nsi_sprav_res = [ sprav for sprav in nsi_sprav_manager_res['child'] if sprav['name'] == NSIType_ ] if not nsi_sprav_res: ic.io_prnt.outWarning(u'Не найден справочник <%s> в ресурсе [%s]' % (NSIType_, NSIRes_)) return None nsi_sprav_res = nsi_sprav_res[0] # Получить ресурсное описание полей nsi_tab_psp = nsi_sprav_res['table'] if nsi_tab_psp: nsi_tab_name = nsi_tab_psp[0][1] else: nsi_tab_name = 'nsi_data' nsi_tab_spc = resource.icGetRes(nsi_tab_name, 'tab', nameRes=nsi_tab_name) nsi_fields_spc = [ util.DeepCopy(field_spc) for field_spc in [ fld for fld in nsi_tab_spc['child'] if fld['name'] in FieldNames_ ] ] return nsi_fields_spc
def openChildPane(self, Page_, PaneName_): """ Открыть дочернее окно как AUI панель. @param Page_: Имя ресурсного файла окна. @param PaneName_: Имя дочерней AUI панели. """ pane = self.GetChildByName(PaneName_) if type(Page_) in (str, unicode): res_name, res_ext = ic_file.SplitExt(Page_) # По умолчанию ресурс форм: *.frm if not res_ext: res_ext = '.frm' Page_ = icResourceParser.icCreateObject(res_name, res_ext[1:], parent=self) if Page_: pane.control_name = ic_file.BaseName(res_name) pane.control_res = res_name+res_ext return pane.showControl(Page_)
def getRolesChoiceList(): """ Функция получения списка ролей, определенных в проекте. """ prj_dir = ic_user.icGet('PRJ_DIR') role_files = ic_file.GetFilesByExt(prj_dir, '.rol') # Сразу отфильтровать Pkl файлы role_files = [ role_file for role_file in role_files if '_pkl.rol' not in role_file.lower() ] # Получить только базовые имена файлов role_files = [ ic_file.SplitExt(ic_file.BaseName(role_file))[0] for role_file in role_files ] return role_files
def createControl(self, Name_, ResFileName_, subsys=None): """ Создание прикрепленного объекта. @param Name_: Имя объекта. @param ResFileName_: Имя файла ресурса объекта. """ control = None try: res_name, res_ext = ic_file.SplitExt(ResFileName_) control = icResourceParser.icCreateObject(res_name, res_ext[1:], subsys=subsys, parent=self._Parent) return control except: io_prnt.outErr( u'Ошибка создания прикрепленного к AUI панели объекта.') return None
def _toUnicodeResourcePyWalk(args, CurDir_, CurNames_): # Отфильтровать только файлы py py_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] == '.py' ] for py_file in py_files: try: f = open(py_file, 'rb') text = f.read() f.close() except: print('ERROR open file', py_file) f.close() n1 = text.find('###BEGIN') n = text.find('resource=') n_x = text.find('resource =') n2 = text.find('###END') if n1 > 0 and n2 > 0 and n > 0: n_ = text[n:].find('\n') replace_dict_txt = text[n + len('resource='):n + n_].strip() try: replace_dict = eval(replace_dict_txt) x_dict = ic_util.icStructStrRecode(replace_dict, 'cp1251', 'UNICODE') new_text = text.replace(replace_dict_txt, str(x_dict)) print('>>', py_file, ' : ', x_dict) try: f = open(py_file, 'w') f.write(new_text) f.close() except: print('ERROR open file', py_file) f.close() except: print('Error read', py_file, ' : ', replace_dict_txt) elif n1 > 0 and n2 > 0 and n_x > 0: print('!>', py_file)