def startElement(self, name, attrs): if name == 'Content': pass else: position = float(self.locator.getLineNumber()) / self.lines if position - self.position > 0.05: msg = _('Parsing in process...') events.emit(events.FILTER_INFO, msg, position) self.position = position obj = None cid = model.TAGNAME_TO_CID[name] obj = model.CID_TO_CLASS[cid](self.presenter.config) obj.tag = name for item in attrs._attrs.keys(): line = 'self.value=' + attrs._attrs[item] code = compile(line, '<string>', 'exec') exec code obj.__dict__[item] = self.value if self.parent_stack: parent = self.parent_stack[-1] methods.add_child(parent, obj) else: self.model = obj self.parent_stack.append(obj)
def _build_model(self): content_handler = XMLDocReader(self.presenter) error_handler = ErrorHandler() entity_resolver = EntityResolver() dtd_handler = DTDHandler() try: filename = os.path.join(self.presenter.doc_dir, 'content.xml') handler = open(filename, 'r') lines = float(sum(1 for l in handler)) handler.close() self.file_handler = open(filename, "r") input_source = InputSource() input_source.setByteStream(self.file_handler) content_handler.lines = lines xml_reader = xml.sax.make_parser() xml_reader.setContentHandler(content_handler) xml_reader.setErrorHandler(error_handler) xml_reader.setEntityResolver(entity_resolver) xml_reader.setDTDHandler(dtd_handler) xml_reader.parse(input_source) self.file_handler.close() content_handler.file = None except: errtype, value, traceback = sys.exc_info() msg = _('It seems content.xml is corrupted') + '\n' + value events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errtype, msg , traceback) self.model = content_handler.model msg = _('Content.xml is parsed successfully') events.emit(events.MESSAGES, msgconst.OK, msg)
def _build_model(self): content_handler = XMLDocReader(self.presenter) error_handler = ErrorHandler() entity_resolver = EntityResolver() dtd_handler = DTDHandler() try: filename = os.path.join(self.presenter.doc_dir, 'content.xml') handler = open(filename, 'r') lines = float(sum(1 for l in handler)) handler.close() self.file_handler = open(filename, "r") input_source = InputSource() input_source.setByteStream(self.file_handler) content_handler.lines = lines xml_reader = xml.sax.make_parser() xml_reader.setContentHandler(content_handler) xml_reader.setErrorHandler(error_handler) xml_reader.setEntityResolver(entity_resolver) xml_reader.setDTDHandler(dtd_handler) xml_reader.parse(input_source) self.file_handler.close() content_handler.file = None except: errtype, value, traceback = sys.exc_info() msg = _('It seems content.xml is corrupted') + '\n' + value events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errtype, msg, traceback) self.model = content_handler.model msg = _('Content.xml is parsed successfully') events.emit(events.MESSAGES, msgconst.OK, msg)
def end_page(self): self.canvas.showPage() self.page_count += 1 position = 1.0 if self.num_pages: position = float(self.page_count) / float(self.num_pages) events.emit(events.FILTER_INFO, self.prgs_msg, position)
def get_loader_by_id(pid): loader = _get_loader(pid) if not loader: msg = _('Loader is not found for id %s') % ( uc2const.FORMAT_NAMES[pid], ) events.emit(events.MESSAGES, msgconst.ERROR, msg) return loader
def create_jobs(self): if self.obj_stack: m11, m21, m12, m22, dx, dy = SK2_to_PLT_TRAFO if self.plt_doc.config.force_zero: bbox = [] bbox += self.obj_stack[0].cache_bbox for obj in self.obj_stack: bbox = libgeom.sum_bbox(bbox, obj.cache_bbox) dx = -bbox[0] * m11 dy = -bbox[1] * m22 trafo = [m11, m21, m12, m22, dx, dy] obj_num = len(self.obj_stack) for obj in self.obj_stack: self.counter += 1 position = float(self.counter) / obj_num if position - self.position > 0.05: msg = _('Saving in process...') events.emit(events.FILTER_INFO, msg, position) self.position = position paths = libgeom.get_flattened_path( obj, trafo, self.plt_doc.config.tolerance) if paths is None: continue for path in paths: if path and path[1]: self.jobs.append(plt_model.PltJob('', path))
def create_jobs(self): if self.obj_stack: m11, m21, m12, m22, dx, dy = SK2_to_PLT_TRAFO if self.plt_doc.config.force_zero: bbox = [] bbox += self.obj_stack[0].cache_bbox for obj in self.obj_stack: bbox = libgeom.sum_bbox(bbox, obj.cache_bbox) dx = -bbox[0] * m11 dy = -bbox[1] * m22 trafo = [m11, m21, m12, m22, dx, dy] obj_num = len(self.obj_stack) for obj in self.obj_stack: self.counter += 1 position = float(self.counter) / obj_num if position - self.position > 0.05: msg = _('Saving in process...') events.emit(events.FILTER_INFO, msg, position) self.position = position paths = libgeom.get_flattened_path(obj, trafo, self.plt_doc.config.tolerance) if paths is None: continue for path in paths: if path and path[1]: self.jobs.append(plt_model.PltJob('', path))
def load(self, presenter, path): self.presenter = presenter self.path = path if not zipfile.is_zipfile(self.path): msg = _('It seems the file is not CDRZ file') events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(2, msg) self._extract_content() self.model = None path = os.path.join(self.presenter.doc_dir, 'content', 'riffData.cdr') # try: # file = open(path, 'rb') # except: # errtype, value, trace = sys.exc_info() # msg = _('Cannot open %s file for reading') % (path) # events.emit(events.MESSAGES, msgconst.ERROR, msg) # raise IOError(errtype, msg + '\n' + value, trace) # # self.model = self.parse_file(file) # # file.close() return self.model
def render(self, objs, toplevel=False): obj_count = 0 for obj in objs: if obj.is_pixmap(): self.draw_pixmap(obj) elif obj.is_primitive(): curve_obj = obj.to_curve() if curve_obj.is_primitive(): self.draw_curve(curve_obj) else: self.render(curve_obj.childs) elif obj.is_container(): self.draw_container(obj) else: self.render(obj.childs) # ---Progress obj_count += 1 shift = 0.0 page_size = 1.0 if self.num_pages: shift = float(self.page_count) / float(self.num_pages) page_size = 1.0 / float(self.num_pages) position = shift + obj_count / len(objs) * page_size events.emit(events.FILTER_INFO, self.prgs_msg, position)
def wildcard_convert(appdata, files, options): saver_ext = _get_saver_extension(options) verbose = bool(options.get('verbose')) verbose_short = bool(options.get('verbose-short')) path = os.path.dirname(files[0]) wildcard = os.path.basename(files[0]) filelist = _get_filelist(path, '', wildcard, bool(options.get('recursive'))) if not filelist: msg = 'There are not files for requested wildcard "%s"' % wildcard events.emit(events.MESSAGES, msgconst.STOP, msg) return for filepath, subpath, filename in filelist: dir_path = os.path.join(files[1], subpath) if not os.path.exists(dir_path): os.makedirs(dir_path) out_filepath = os.path.join(dir_path, '%s.%s' % (filename, saver_ext)) kw = copy.deepcopy(options) try: convert(appdata, (filepath, out_filepath), kw) if verbose: echo() elif verbose_short: echo('Translation of "%s"' % filepath) echo('into "%s" ...[ OK ]\n' % out_filepath) except Exception: if verbose_short: echo('Translation of "%s"' % filepath) echo('into "%s" ...[ FAIL ]\n' % out_filepath)
def open(self, doc_file='', silent=False): doc_file = doc_file or \ dialogs.get_open_file_name(self.mw, config.open_dir) if doc_file and fsutils.lexists(doc_file) and fsutils.isfile(doc_file): try: doc = SK1Presenter(self, doc_file, silent) except RuntimeError: msg = _('Cannot open file:') msg = "%s\n'%s'" % (msg, doc_file) + '\n' msg += _('The file contains newer SK2 format.\n') msg += _('Try updating sK1 application from ' 'http://www.sk1project.net') dialogs.error_dialog(self.mw, self.appdata.app_name, msg) LOG.error('Cannot open file <%s>: newer SK2 format.', doc_file) return except Exception as e: msg = _('Cannot open file:') msg = "%s\n'%s'" % (msg, doc_file) + '\n' msg += _('The file may be corrupted or not supported format.') msg += '\n' msg += _('Details see in application logs.') dialogs.error_dialog(self.mw, self.appdata.app_name, msg) LOG.error('Cannot open file <%s> %s', doc_file, e) return self.docs.append(doc) config.open_dir = str(os.path.dirname(doc_file)) self.history.add_entry(doc_file) self.set_current_doc(doc) events.emit(events.APP_STATUS, _('Document opened'))
def start_page(self, w, h, left_margin=0.0, top_margin=0.0): self.canvas.translate(w / 2.0 - left_margin, h / 2.0 - top_margin) self.canvas.setPageSize((w, h)) position = 0.0 if self.num_pages: position = float(self.page_count) / float(self.num_pages) events.emit(events.FILTER_INFO, self.prgs_msg, position)
def render(self, objs, toplevel=False): obj_count = 0 for obj in objs: if obj.is_pixmap(): self.draw_pixmap(obj) elif obj.is_primitive(): curve_obj = obj.to_curve() if curve_obj.is_primitive(): self.draw_curve(curve_obj) else: self.render(curve_obj.childs) elif obj.is_container(): self.draw_container(obj) else: self.render(obj.childs) #---Progress obj_count += 1 shift = 0.0 page_size = 1.0 if self.num_pages: shift = float(self.page_count) / float(self.num_pages) page_size = 1.0 / float(self.num_pages) position = shift + obj_count / len(objs) * page_size events.emit(events.FILTER_INFO, self.prgs_msg, position)
def save_as(self): doc_file = self.current_doc.doc_file doc_file = doc_file or self.current_doc.doc_name if os.path.splitext(doc_file)[1] != "." + \ uc2const.FORMAT_EXTENSION[uc2const.SK2][0]: doc_file = os.path.splitext(doc_file)[0] + "." + \ uc2const.FORMAT_EXTENSION[uc2const.SK2][0] if not fsutils.lexists(os.path.dirname(doc_file)): doc_file = os.path.join(config.save_dir, os.path.basename(doc_file)) doc_file = dialogs.get_save_file_name(self.mw, doc_file, path_only=True) if doc_file: old_file = self.current_doc.doc_file old_name = self.current_doc.doc_name self.current_doc.set_doc_file(doc_file) try: self.make_backup(doc_file) self.current_doc.save() except Exception as e: self.current_doc.set_doc_file(old_file, old_name) first = _('Cannot save document:') msg = "%s\n'%s'." % (first, self.current_doc.doc_name) + '\n' msg += _('Please check file name and write permissions') dialogs.error_dialog(self.mw, self.appdata.app_name, msg) LOG.error('Cannot save file <%s> %s', doc_file, e) return False config.save_dir = str(os.path.dirname(doc_file)) self.history.add_entry(doc_file, appconst.SAVED) events.emit(events.DOC_SAVED, self.current_doc) events.emit(events.APP_STATUS, _('Document saved')) return True else: return False
def export_as(self): doc_file = self.current_doc.doc_file doc_file = doc_file or self.current_doc.doc_name doc_file = os.path.splitext(doc_file)[0] doc_file = os.path.join(config.export_dir, os.path.basename(doc_file)) ftype = uc2const.SAVER_FORMATS[1:] doc_file = dialogs.get_save_file_name(self.mw, doc_file, _('Export document As...'), file_types=ftype, path_only=True) if doc_file: try: self.make_backup(doc_file, True) self.current_doc.export_as(doc_file) except Exception as e: first = _('Cannot save document:') msg = "%s\n'%s'." % (first, self.current_doc.doc_name) + '\n' msg += _('Please check file name and write permissions') dialogs.error_dialog(self.mw, self.appdata.app_name, msg) LOG.warn('Cannot save file <%s>', doc_file, e) return config.export_dir = str(os.path.dirname(doc_file)) msg = _('Document is successfully exported') events.emit(events.APP_STATUS, msg)
def multiple_convert(appdata, files, options): saver_ext = _get_saver_extension(options) verbose = bool(options.get('verbose')) verbose_short = bool(options.get('verbose-short')) filelist = files[:-1] dir_path = files[-1] for filepath in filelist: if not os.path.exists(filepath): msg = 'File "%s" is not found' % filepath events.emit(events.MESSAGES, msgconst.STOP, msg) continue filename = os.path.basename(filepath).split('.', 1)[0] out_filepath = os.path.join(dir_path, '%s.%s' % (filename, saver_ext)) kw = copy.deepcopy(options) try: convert(appdata, (filepath, out_filepath), kw) if verbose: echo() elif verbose_short: echo('Translation of "%s"' % filepath) echo('into "%s" ...[ OK ]\n' % out_filepath) except Exception: if verbose_short: echo('Translation of "%s"' % filepath) echo('into "%s" ...[ FAIL ]\n' % out_filepath)
def save(self, doc=''): if not doc: doc = self.current_doc if not doc.doc_file: return self.save_as() ext = os.path.splitext(self.current_doc.doc_file)[1] if not ext == "." + uc2const.FORMAT_EXTENSION[uc2const.SK2][0]: return self.save_as() if not os.path.lexists(os.path.dirname(self.current_doc.doc_file)): return self.save_as() try: self.make_backup(self.current_doc.doc_file) doc.save() self.history.add_entry(self.current_doc.doc_file, appconst.SAVED) events.emit(events.DOC_SAVED, doc) except Exception as e: msg = _('Cannot save file:') msg = "%s\n'%s'" % (msg, self.current_doc.doc_file) + '\n' msg += _('Please check file write permissions') dialogs.error_dialog(self.mw, self.appdata.app_name, msg) LOG.error('Cannot save file <%s> %s', self.current_doc.doc_file, e) return False events.emit(events.APP_STATUS, _('Document saved')) return True
def import_palette(self, parent=None): parent = parent or self.mw file_types = uc2const.PALETTE_LOADERS doc_file = dialogs.get_open_file_name(parent, config.import_dir, _('Select palette to import'), file_types=file_types) if fsutils.lexists(doc_file) and fsutils.isfile(doc_file): pd = dialogs.ProgressDialog(_('Opening file...'), parent) try: loader = get_loader(doc_file) if not loader: raise IOError(_('Loader is not found for <%s>') % doc_file) palette = pd.run(loader, [self.appdata, doc_file, None, False, True]) if not palette: raise IOError(_('Error while opening'), doc_file) self.palettes.add_palette(palette) config.import_dir = str(os.path.dirname(doc_file)) msg = _('Palette is successfully imported') events.emit(events.APP_STATUS, msg) return palette.model.name except Exception as e: msg = _('Cannot import file:') msg = "%s\n'%s'" % (msg, doc_file) + '\n' msg += _('The file may be corrupted or not supported format.') msg += '\n' msg += _('Details see in application logs.') dialogs.error_dialog(self.mw, self.appdata.app_name, msg) LOG.error('Cannot import file <%s> %s', doc_file, e) finally: pd.destroy()
def __init__(self, path, cfgdir): self.path = path wal.Application.__init__(self) UCApplication.__init__(self, path, cfgdir, False) if wal.IS_WINXP: msg = _('WindowsXP platform is obsolete and not supported!') dialogs.error_dialog(self.mw, 'sK1', msg) sys.exit() self.appdata = AppData(self, cfgdir) log_level = config.log_level self.log_filepath = os.path.join(self.appdata.app_config_dir, 'sk1.log') mixutils.config_logging(fsutils.get_sys_path(self.log_filepath), log_level) sys.stderr = StreamLogger() LOG.info('Logging started') wal.SPIN['overlay'] = config.spin_overlay wal.SPIN['sep'] = config.spin_sep plg_dir = os.path.join(self.path, 'share', 'pd_plugins') custom_plg_dir = self.appdata.plugin_dir config.plugin_dirs = [plg_dir, custom_plg_dir] sys.path.insert(1, fsutils.get_sys_path(self.appdata.app_config_dir)) sys.path.insert(1, fsutils.get_sys_path(os.path.join(self.path, 'share'))) config.app = self LOG.info('Config is updated') self.history = AppHistoryManager(self) self.artprovider = create_artprovider() self.cursors = modes.get_cursors() self.proxy = AppProxy(self) self.insp = AppInspector(self) self.plugins = app_plugins.scan_plugins(self) self.actions = app_actions.create_actions(self) self.default_cms = AppColorManager(self) self.palettes = AppPaletteManager(self) self.clipboard = AppClipboard(self) self.mw = AppMainWindow(self) self.mw.set_global_shortcuts(self.actions) self.proxy.update() self.insp.update() LOG.info('Application is initialized') uc2.events.connect(uc2.events.MESSAGES, self.uc2_event_logging) events.connect(events.APP_STATUS, self.sk1_event_logging) self.fsw = AppFileWatcher(self, self.mw) if wal.IS_WX2: events.emit(events.NO_DOCS)
def get_loader_by_id(pid): loader = None if pid in data.LOADERS.keys(): loader = data.LOADERS[pid] else: msg = _('Loader is not found for id %u') % (pid) events.emit(events.MESSAGES, msgconst.ERROR, msg) return loader
def get_saver_by_id(pid): saver = None if pid in data.SAVERS.keys(): saver = data.SAVERS[pid] else: msg = _('Saver is not found for id %u') % (pid) events.emit(events.MESSAGES, msgconst.ERROR, msg) return saver
def __init__(self, path, cfgdir='~'): self.path = path wal.Application.__init__(self) UCApplication.__init__(self, path, cfgdir) if wal.IS_WINXP: msg = _('WindowsXP platform is obsolete and not supported!') dialogs.error_dialog(self.mw, 'sK1', msg) sys.exit() self.appdata = AppData(self, cfgdir) config.load(self.appdata.app_config) config.resource_dir = os.path.join(path_unicode(self.path), 'share') log_level = config.log_level self.log_filepath = os.path.join(self.appdata.app_config_dir, 'sk1.log') config_logging(self.log_filepath, log_level) sys.stderr = StreamLogger() LOG.info('Logging started') self.update_wal() plg_dir = os.path.join(self.path, 'share', 'pd_plugins') custom_plg_dir = self.appdata.plugin_dir config.plugin_dirs = [plg_dir, custom_plg_dir] sys.path.insert(1, self.appdata.app_config) sys.path.insert(1, os.path.join(self.path, 'share')) config.app = self LOG.info('Config is updated') self.history = AppHistoryManager(self) self.artprovider = create_artprovider() self.cursors = modes.get_cursors() self.proxy = AppProxy(self) self.insp = AppInspector(self) self.plugins = app_plugins.scan_plugins(self) self.actions = app_actions.create_actions(self) self.default_cms = AppColorManager(self) self.palettes = AppPaletteManager(self) self.clipboard = AppClipboard(self) self.mw = AppMainWindow(self) self.mw.set_global_shortcuts(self.actions) self.proxy.update() self.insp.update() LOG.info('Application is initialized') uc2.events.connect(uc2.events.MESSAGES, self.uc2_event_logging) events.connect(events.APP_STATUS, self.sk1_event_logging) if wal.IS_WX2: events.emit(events.NO_DOCS) if config.make_font_cache_on_start: generate_fcache()
def _pack_content(self): pdxf_file = ZipFile(self.presenter.doc_file, 'w') for item in self.content: path, filename = item filename = filename.encode('ascii') pdxf_file.write(path, filename, zipfile.ZIP_DEFLATED) pdxf_file.close() msg = _('PDXF file is created successfully') events.emit(events.MESSAGES, msgconst.OK, msg)
def create_jobs(self): if self.obj_stack: m11, m21, m12, m22, dx, dy = SK2_to_PLT_TRAFO if self.plt_doc.config.plt_force_zero: bbox = [] bbox += self.obj_stack[0].cache_bbox for obj in self.obj_stack: bbox = libgeom.sum_bbox(bbox, obj.cache_bbox) dx = -bbox[0] * m11 dy = -bbox[1] * m22 trafo = [ m11 * self.plt_doc.config.plt_scale, m21, m12, m22 * self.plt_doc.config.plt_scale, dx, dy ] obj_num = len(self.obj_stack) for obj in self.obj_stack: self.counter += 1 position = float(self.counter) / obj_num if position - self.position > 0.05: msg = _('Saving in progress...') events.emit(events.FILTER_INFO, msg, position) self.position = position paths = libgeom.get_flattened_paths( obj, trafo, self.plt_doc.config.plt_tolerance) if paths is None: continue for path in paths: if self.plt_doc.config.plt_optimize: rl = self.plt_doc.config.plt_rounding_level path[0] = [round(x / rl) * rl for x in path[0]] start0, start1 = [], path[0] points = [] for point in path[1]: point = [round(x / rl) * rl for x in point] if not point == start1: if point == start0: points = points[:-1] if len(points) > 1: start0, start1 = points[-1], start0 elif points: start0, start1 = [], start0 continue start0, start1 = start1, point points.append(point) path[1] = points if path and path[1]: self.jobs.append(plt_model.PltJob('', path))
def save(self, presenter, path): try: file = open(path, 'wb') except: errtype, value, traceback = sys.exc_info() msg = _('Cannot open %s file for writing') % (path) events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errtype, msg + '\n' + value, traceback) file.write(presenter.model.get_content()) file.close()
def save(self, presenter, path): try: file = open(path, 'wb') except: errtype, value, traceback = sys.exc_info() msg = _('Cannot open %s file for writing') % (path) events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errtype, msg + '\n' + value, traceback) file.write(presenter.model.get_chunk()) file.close()
def get_fileptr(path, writable=False): if not path: msg = _('There is no file path') raise IOError(errno.ENODATA, msg, '') try: return uopen(path, 'wb' if writable else 'rb') except Exception: msg = _('Cannot open %s file for writing') % path \ if writable else _('Cannot open %s file for reading') % path events.emit(events.MESSAGES, msgconst.ERROR, msg) LOG.exception(msg) raise
def load(self, presenter, path): self.presenter = presenter self.path = path if not zipfile.is_zipfile(self.path): msg = _('It seems the file is not PDXF file') events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(2, msg) self._extract_content() self._build_model() return self.model
def call_after(self, *args): if self.docs: return if config.new_doc_on_start: self.load_plugins() self.new() else: txt = _('To start, create new document or open existing') events.emit(events.APP_STATUS, txt) self.load_plugins() if not wal.IS_WX2: events.emit(events.NO_DOCS) self.update_actions()
def load(self, presenter, path): self.presenter = presenter self.path = path self.model = presenter.model self.jobs = [] try: file = open(path, 'rb') except: errtype, value, traceback = sys.exc_info() msg = _('Cannot open %s file for writing') % (path) events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errtype, msg + '\n' + value, traceback) res = file.read().split('IN;') file.close() if not len(res) == 2: msg = _( 'Wrong content in %s file: "IN;" instruction should be unique' ) % (path) events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(msg) if res[0]: self.model.string = res[0] cmds = res[1].split(';') jobs = [] job = [] stack = '' for cmd in cmds: if cmd[:2] == 'PU': stack = cmd if job: jobs.append(job) job = [] elif cmd[:2] == 'PD': if not job: if not stack: stack = 'PU0,0' job.append(stack) job.append(cmd) for job in jobs: string = '' for cmd in job: string += cmd + ';' self.jobs.append(model.PltJob(string)) self.model.childs[1].childs = self.jobs return self.model
def get_loader(path, experimental=False, return_id=False): if not fsutils.exists(path): return None if not fsutils.isfile(path): return None ret_id = None ext = get_file_extension(path) loader = None ld_formats = [] + uc2const.LOADER_FORMATS msg = 'Start to search for loader by file extension %s' % (ext.__str__()) events.emit(events.MESSAGES, msgconst.INFO, msg) if experimental: ld_formats += uc2const.EXPERIMENTAL_LOADERS for item in ld_formats: if ext in uc2const.FORMAT_EXTENSION[item]: checker = _get_checker(item) if checker and checker(path): loader = _get_loader(item) ret_id = item break if loader is None: msg = 'Loader is not found or not suitable for %s' % path events.emit(events.MESSAGES, msgconst.WARNING, msg) msg = 'Start to search loader by file content' events.emit(events.MESSAGES, msgconst.INFO, msg) for item in ld_formats: checker = _get_checker(item) if checker is not None: if checker(path): loader = _get_loader(item) ret_id = item break if loader is None: msg = 'Loader is not found for %s' % path events.emit(events.MESSAGES, msgconst.ERROR, msg) else: loader_name = loader.__str__().split(' ')[1] msg = 'Loader "%s" is found for %s' % (loader_name, path) events.emit(events.MESSAGES, msgconst.OK, msg) if return_id: return loader, ret_id return loader
def check_riff(path): try: file = open(path, 'rb') except: errtype, value, traceback = sys.exc_info() msg = _('Cannot open %s file for reading') % (path) events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errtype, msg + '\n' + value, traceback) fourcc = file.read(4) file.close() if fourcc == 'RIFF': return True return False
def check_wmf(path): try: file = open(path, 'rb') except: errtype, value, traceback = sys.exc_info() msg = _('Cannot open %s file for reading') % (path) events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errtype, msg + '\n' + value, traceback) string = file.read(4) file.close() if string == WMF_SIGNATURE: return True return False
def load(self, presenter, path): self.presenter = presenter self.path = path self.model = presenter.model self.jobs = [] try: file = open(path, 'rb') except: errtype, value, traceback = sys.exc_info() msg = _('Cannot open %s file for writing') % (path) events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errtype, msg + '\n' + value, traceback) res = file.read().split('IN;') file.close() if not len(res) == 2: msg = _('Wrong content in %s file: "IN;" instruction should be unique') % (path) events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(msg) if res[0]: self.model.string = res[0] cmds = res[1].split(';') jobs = [] job = [] stack = '' for cmd in cmds: if cmd[:2] == 'PU': stack = cmd if job: jobs.append(job) job = [] elif cmd[:2] == 'PD': if not job: if not stack: stack = 'PU0,0' job.append(stack) job.append(cmd) for job in jobs: string = '' for cmd in job: string += cmd + ';' self.jobs.append(model.PltJob(string)) self.model.childs[1].childs = self.jobs return self.model
def check_cdr(path): try: file = open(path, 'rb') except: errtype, value, traceback = sys.exc_info() msg = _('Cannot open %s file for reading') % (path) events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errtype, msg + '\n' + value, traceback) header = file.read(12) file.close() if not header[:4] == 'RIFF': return False if header[8:] in const.CDR_VERSIONS: return True else: return False
def _write_tree(self, item): self.counter += 1 position = float(self.counter) / self.obj_num if position - self.position > 0.05: msg = _('Saving in process...') events.emit(events.FILTER_INFO, msg, position) self.position = position tag = model.CID_TO_TAGNAME[item.cid] params = self._get_params(item) self._open_tag(tag, params, item.childs) if item.childs: self.ident += 1 for child in item.childs: self._write_tree(child) self.ident -= 1 self._close_tag(tag)
def _save_content(self): content_xml = os.path.join(self.presenter.doc_dir, 'content.xml') try: self.file = open(content_xml, 'wb') except: errtype, value, traceback = sys.exc_info() msg = _('Cannot open %s file for writing') % (content_xml) events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errtype, msg + '\n' + value, traceback) doc = self.presenter.model self.obj_num = doc.count() self._start() self._write_tree(doc) self._finish() msg = _('PDXF file content.xml is created') events.emit(events.MESSAGES, msgconst.OK, msg)
def load(self, presenter, path): self.presenter = presenter self.model = None self.parent_stack = [] self.file_size = os.path.getsize(path) try: file = open(path, 'rb') except: errtype, value, trace = sys.exc_info() msg = _('Cannot open %s file for reading') % (path) events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errtype, msg + '\n' + value, trace) self.model = self.parse_file(file) file.close() return self.model
def load(self, presenter, path): self.filepath = path self.presenter = presenter self.config = self.presenter.config self.file_size = os.path.getsize(path) try: self.file = open(path, 'rb') except: errtype, value, traceback = sys.exc_info() msg = _('Cannot open %s file for writing') % (path) events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errtype, msg + '\n' + value, traceback) self.do_load() self.file.close() self.position = 0 return self.model
def _write_manifest(self): xml = os.path.join(self.presenter.doc_dir, 'META-INF', 'manifest.xml') try: self.file = open(xml, 'wb') except: errtype, value, traceback = sys.exc_info() msg = _('Cannot open %s file for writing') % (xml) events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errtype, msg + '\n' + value, traceback) self._start() self.file.write('<manifest>\n') self._write_manifest_entries() self.file.write('</manifest>\n') self._finish() filename = os.path.join('META-INF', 'manifest.xml') self.content.append((xml, filename)) msg = _('PDXF file manifest.xml is created') events.emit(events.MESSAGES, msgconst.OK, msg)
def do_load(self): self.file.readline() self.style = Style() while True: self.line = self.file.readline() if not self.line: break self.line = self.line.rstrip('\r\n') position = float(self.file.tell()) / float(self.file_size) * 0.95 if position - self.position > 0.01: self.position = position msg = _('Parsing in process...') events.emit(events.FILTER_INFO, msg, position) if self.line: try: code = compile('self.' + self.line, '<string>', 'exec') exec code except: print 'error>>', self.line errtype, value, traceback = sys.exc_info() print errtype, value, traceback
def check_plt(path): file_size = os.path.getsize(path) try: file = open(path, 'rb') except: errtype, value, traceback = sys.exc_info() msg = _('Cannot open %s file for reading') % (path) events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errtype, msg + '\n' + value, traceback) if file_size > 200: string = file.read(200) else: string = file.read() file.close() if len(string.split("IN;")) > 1 and len(string.split(";")) > 2: if len(string.split(";PD")) > 1: return True return False
def _extract_content(self): pdxf_file = ZipFile(self.path, 'r') try: fl = pdxf_file.namelist() except: errtype, value, traceback = sys.exc_info() msg = _('It seems the PDXF file is corrupted') + '\n' + value events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errtype, msg , traceback) if not 'mimetype' in fl or not pdxf_file.read('mimetype') == const.DOC_MIME: msg = _('The file is corrupted or not PDXF file') events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(2, msg) filelist = [] for item in fl: if item == 'mimetype' or item[-1] == '/': continue filelist.append(item) for item in filelist: source = pdxf_file.read(item) dest = open(os.path.join(self.presenter.doc_dir, item), 'wb') dest.write(source) dest.close() msg = _('The file content is extracted successfully') events.emit(events.MESSAGES, msgconst.OK, msg)
def im_loader(appdata, filename=None, fileptr=None, translate=True, cnf={}, **kw): if filename and not fileptr: try: fileptr = open(filename, 'rb') except: errtype, value, traceback = sys.exc_info() msg = _('Cannot read %s file') % (filename) events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errtype, msg + '\n' + value, traceback) content = fileptr.read() fileptr.close() sk2_doc = SK2_Presenter(appdata, cnf) sk2_doc.doc_file = filename sk2_doc.methods.set_doc_origin(sk2_const.DOC_ORIGIN_LU) sk2_doc.methods.set_doc_units(uc2const.UNIT_PX) page = sk2_doc.methods.get_page() image_obj = sk2_model.Pixmap(sk2_doc.config) libimg.set_image_data(sk2_doc.cms, image_obj, content) orient = uc2const.PORTRAIT w = image_obj.size[0] * uc2const.px_to_pt h = image_obj.size[1] * uc2const.px_to_pt if image_obj.size[0] > image_obj.size[1]:orient = uc2const.LANDSCAPE image_obj.trafo = [1.0, 0.0, 0.0, 1.0, -w / 2.0, -h / 2.0] sk2_doc.methods.set_page_format(page, ['Custom', (w, h), orient]) sk2_doc.methods.set_default_page_format(['Custom', (w, h), orient]) grid_layer = sk2_doc.methods.get_grid_layer() grid_layer.grid = [0, 0, uc2const.px_to_pt, uc2const.px_to_pt] grid_layer.properties = [1, 0, 0] layer = sk2_doc.methods.get_layer(page) layer.childs.append(image_obj) sk2_doc.update() return sk2_doc
def get_fileptr(path, writable=False): fileptr = None if not file: msg = _('There is no file path') raise IOError(errno.ENODATA, msg, '') if writable: try: fileptr = open(path, 'wb') except: errtype, value, traceback = sys.exc_info() msg = _('Cannot open %s file for writing') % (path) events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errtype, msg + '\n' + value, traceback) else: try: fileptr = open(path, 'rb') except: errtype, value, traceback = sys.exc_info() msg = _('Cannot open %s file for reading') % (path) events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errtype, msg + '\n' + value, traceback) return fileptr
def get_loader(path, experimental=False): if not os.path.lexists(path): return None if not os.path.isfile(path):return None ext = get_file_extension(path) loader = None ld_formats = [] + data.LOADER_FORMATS msg = _('Start to search for loader by file extension %s') % (ext.__str__()) events.emit(events.MESSAGES, msgconst.INFO, msg) if experimental: ld_formats += data.EXPERIMENTAL_LOADERS for format in ld_formats: if ext in uc2const.FORMAT_EXTENSION[format]: if data.CHECKERS[format](path): loader = data.LOADERS[format] break if loader is None: msg = _('Loader is not found or not suitable for %s') % (path) events.emit(events.MESSAGES, msgconst.WARNING, msg) msg = _('Start to search loader by file content') events.emit(events.MESSAGES, msgconst.INFO, msg) for format in ld_formats: checker = data.CHECKERS[format] if not checker is None: if checker(path): loader = data.LOADERS[format] break if loader is None: msg = _('Loader is not found for %s') % (path) events.emit(events.MESSAGES, msgconst.ERROR, msg) else: msg = _('Loader is found for %s') % (path) events.emit(events.MESSAGES, msgconst.OK, msg) return loader
def do_load(self): self.jobs = [] res = self.fileptr.read().split('IN;') if not len(res) == 2: msg = _('Wrong content: "IN;" instruction should be unique') events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(msg) if res[0]: self.model.string = res[0] cmds = res[1].split(';') jobs = [] job = [] stack = '' for cmd in cmds: if cmd[:2] == 'PU': stack = cmd if job: jobs.append(job) job = [] elif cmd[:2] == 'PD': if not job: if not stack: stack = 'PU0,0' job.append(stack) job.append(cmd) for job in jobs: string = '' for cmd in job: string += cmd + ';' self.jobs.append(plt_model.PltJob(string)) self.model.childs[1].childs = self.jobs
def get_saver(path, experimental=False): ext = get_file_extension(path) saver = None sv_formats = [] + data.SAVER_FORMATS msg = _('Start to search saver by file extension %s') % (ext.__str__()) events.emit(events.MESSAGES, msgconst.INFO, msg) if experimental: sv_formats += data.EXPERIMENTAL_SAVERS for item in sv_formats: if ext in uc2const.FORMAT_EXTENSION[item]: saver = data.SAVERS[item] break if saver is None: msg = _('Saver is not found for %s file format') % (ext.__str__()) events.emit(events.MESSAGES, msgconst.ERROR, msg) else: msg = _('Saver is found for extension %s') % (ext.__str__()) events.emit(events.MESSAGES, msgconst.OK, msg) return saver
def translate(self, wmf_doc, sk2_doc): self.wmf_doc = wmf_doc self.sk2_doc = sk2_doc self.wmf_mt = wmf_doc.model self.sk2_mt = sk2_doc.model self.sk2_mtds = sk2_doc.methods inch = wmfconst.META_DPI left = top = 0 right = wmfconst.META_W bottom = wmfconst.META_H header = self.wmf_mt self.gdiobjects = [] self.dcstack = [] self.dc = DC_Data() if self.wmf_mt.is_placeable(): sig, handle, left, top, right, bottom, inch, rsvd, checksum\ = get_data(wmfconst.STRUCT_PLACEABLE, self.wmf_mt.chunk) val = 0 for word in get_data('<10h', self.wmf_mt.chunk[:20]): val = val ^ word if val != checksum: msg = 'Incorrect header checksum' events.emit(events.MESSAGES, msgconst.ERROR, msg) raise IOError(errno.ENODATA, msg, '') header = self.wmf_mt.childs[0] self.inch = inch self.bbox = (left, top, right, bottom) self.coef = uc2const.in_to_pt / self.inch self.wx = self.vx = left self.vwidth = self.wwidth = right - left self.vheight = self.wheight = bottom - top self.wy = self.vy = top self.base_trafo = [self.coef, 0, 0, -self.coef, - self.coef * self.vwidth / 2.0 - self.coef * self.vx, self.coef * self.vheight / 2.0 + self.coef * self.vy] self.update_trafo() self.rec_funcs = { wmfconst.META_SETWINDOWORG:self.tr_set_window_org, wmfconst.META_SETWINDOWEXT:self.tr_set_window_ext, wmfconst.META_SETPOLYFILLMODE:self.tr_set_polyfill_mode, wmfconst.META_SETBKMODE:self.tr_set_bg_mode, wmfconst.META_SETBKCOLOR:self.tr_set_bg_color, wmfconst.META_SAVEDC:self.tr_save_dc, wmfconst.META_RESTOREDC: self.tr_restore_dc, wmfconst.META_CREATEPENINDIRECT:self.tr_create_pen_in, wmfconst.META_CREATEBRUSHINDIRECT:self.tr_create_brush_in, wmfconst.META_CREATEFONTINDIRECT:self.tr_create_font_in, wmfconst.META_DIBCREATEPATTERNBRUSH:self.tr_dibcreate_pat_brush, wmfconst.META_STRETCHDIB:self.tr_stretch_dib, #--------- wmfconst.META_CREATEPALETTE:self.tr_create_noop, wmfconst.META_CREATEPATTERNBRUSH:self.tr_create_noop, wmfconst.META_CREATEREGION:self.tr_create_noop, #--------- wmfconst.META_SELECTOBJECT:self.tr_select_object, wmfconst.META_DELETEOBJECT:self.tr_delete_object, wmfconst.META_ELLIPSE:self.tr_ellipse, wmfconst.META_RECTANGLE:self.tr_rectangle, wmfconst.META_ROUNDRECT:self.tr_round_rectangle, wmfconst.META_POLYGON:self.tr_polygon, wmfconst.META_POLYPOLYGON:self.tr_polypolygon, wmfconst.META_POLYLINE:self.tr_polyline, wmfconst.META_ARC:self.tr_arc, wmfconst.META_CHORD:self.tr_chord, wmfconst.META_PIE:self.tr_pie, wmfconst.META_MOVETO:self.tr_moveto, wmfconst.META_LINETO:self.tr_lineto, wmfconst.META_TEXTOUT:self.tr_textout, wmfconst.META_EXTTEXTOUT:self.tr_exttextout, wmfconst.META_SETTEXTCOLOR:self.tr_set_text_color, wmfconst.META_SETTEXTALIGN:self.tr_set_text_align, wmfconst.META_SETTEXTCHAREXTRA:self.noop, wmfconst.META_SETTEXTJUSTIFICATION:self.noop, } self.translate_header(header) self.sk2_mt.do_update()
def run(self): if len(sys.argv) < 3 or '--help' in sys.argv: self.show_help() files = [] options_list = [] options = {} for item in sys.argv[1:]: if item[0] == '-': if item == '-verbose': events.connect(events.MESSAGES, self.verbose) else: options_list.append(item) else: files.append(item) if len(files) <> 2: self.show_help() if not os.path.lexists(files[0]):self.show_help() for item in options_list: result = item[1:].split('=') if not len(result) == 2: continue else: key, value = result if value == 'yes':value = True if value == 'no':value = False options[key] = value self.default_cms = cms.ColorManager() self.palettes = PaletteManager(self) print '' msg = _('Translation of') + ' "%s" ' % (files[0]) + _('into "%s"') % (files[1]) events.emit(events.MESSAGES, msgconst.JOB, msg) saver = get_saver(files[1]) if saver is None: msg = _("Output file format of '%s' is unsupported.") % (files[1]) events.emit(events.MESSAGES, msgconst.ERROR, msg) msg = _('Translation is interrupted') events.emit(events.MESSAGES, msgconst.STOP, msg) sys.exit(1) loader = get_loader(files[0]) if loader is None: msg = _("Input file format of '%s' is unsupported.") % (files[0]) events.emit(events.MESSAGES, msgconst.ERROR, msg) msg = _('Translation is interrupted') events.emit(events.MESSAGES, msgconst.STOP, msg) sys.exit(1) try: doc = loader(self.appdata, files[0]) except: msg = _("Error while loading '%s'") % (files[0]) msg += _("The file may be corrupted or contains unknown file format.") events.emit(events.MESSAGES, msgconst.ERROR, msg) msg = _('Translation is interrupted') events.emit(events.MESSAGES, msgconst.STOP, msg) print '\n', sys.exc_info()[1], sys.exc_info()[2] sys.exit(1) if doc is not None: try: saver(doc, files[1]) except: msg = _("Error while translation and saving '%s'") % (files[0]) events.emit(events.MESSAGES, msgconst.ERROR, msg) msg = _('Translation is interrupted') events.emit(events.MESSAGES, msgconst.STOP, msg) print '\n', sys.exc_info()[1], sys.exc_info()[2] sys.exit(1) else: msg = _("Error while model creating for '%s'") % (files[0]) events.emit(events.MESSAGES, msgconst.ERROR, msg) msg = _('Translation is interrupted') events.emit(events.MESSAGES, msgconst.STOP, msg) sys.exit(1) doc.close() events.emit(events.MESSAGES, msgconst.OK, _('Translation is successful')) print '' sys.exit(0)