Esempio n. 1
0
def check_package(path, name):
    full_path = os.path.join(path, name)
    if not fsutils.isdir(full_path) or name[0] == '.':
        return False
    py_file = os.path.join(full_path, '__init__.py')
    pyc_file = os.path.join(full_path, '__init__.pyc')
    return fsutils.exists(py_file) or fsutils.exists(pyc_file)
Esempio n. 2
0
 def make_backup(self, doc_file, export=False):
     if not export and not config.make_backup:
         return
     if export and not config.make_export_backup:
         return
     if fsutils.exists(doc_file):
         if fsutils.exists(doc_file + '~'):
             os.remove(get_sys_path(doc_file + '~'))
         os.rename(get_sys_path(doc_file), get_sys_path(doc_file + '~'))
Esempio n. 3
0
 def make_backup(doc_file, export=False):
     if not export and not config.make_backup:
         return
     if export and not config.make_export_backup:
         return
     if fsutils.exists(doc_file):
         if fsutils.exists(doc_file + '~'):
             fsutils.remove(doc_file + '~')
         fsutils.rename(doc_file, doc_file + '~')
Esempio n. 4
0
 def on_timer(self, *_args):
     if fsutils.exists(self.socket):
         self.mw.raise_window()
         with fsutils.uopen(self.socket, 'rb') as fp:
             lines = fp.readlines()
         fsutils.remove(self.socket)
         [
             self.app.open(item.strip('\n')) for item in lines
             if fsutils.exists(item.strip('\n'))
         ]
     if not fsutils.exists(self.lock):
         with fsutils.uopen(self.lock, 'wb') as fp:
             fp.write('\n')
Esempio n. 5
0
def check_server(cfgdir):
    cfg_dir = os.path.join(cfgdir, '.config', 'sk1-wx')
    lock = os.path.join(cfg_dir, 'lock')
    if config.app_server and fsutils.exists(lock):
        socket = os.path.join(cfg_dir, 'socket')
        with fsutils.uopen(socket, 'wb') as fp:
            for item in sys.argv[1:]:
                fp.write('%s\n' % item)
        time.sleep(2)
        if fsutils.exists(socket):
            fsutils.remove(socket)
        else:
            sys.exit(0)
Esempio n. 6
0
 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.exists(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
Esempio n. 7
0
 def save_selected(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.exists(os.path.dirname(doc_file)):
         doc_file = os.path.join(config.save_dir,
                                 os.path.basename(doc_file))
     msg = _('Save selected objects only as...')
     doc_file = dialogs.get_save_file_name(self.mw, doc_file, msg,
                                           path_only=True)
     if doc_file:
         try:
             self.make_backup(doc_file)
             self.current_doc.save_selected(doc_file)
             self.history.add_entry(doc_file, appconst.SAVED)
         except Exception as e:
             first = _('Cannot save document:')
             msg = "%s\n'%s'." % (first, doc_file) + '\n'
             msg += _('Please check requested file format '
                      'and write permissions')
             dialogs.error_dialog(self.mw, self.appdata.app_name, msg)
             LOG.error('Cannot save file <%s> %s', doc_file, e)
Esempio n. 8
0
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 = 'By file content loader is not found for %s' % path
        events.emit(events.MESSAGES, msgconst.WARNING, msg)
        msg = 'Try using fallback loader'
        events.emit(events.MESSAGES, msgconst.INFO, msg)
        if fallback_check(path):
            loader = im_loader

    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
Esempio n. 9
0
 def file_info(self, objects):
     doc_name = self.doc.doc_name
     doc_file = self.doc.doc_file
     data = [_('File'), [_('Name and location:'), doc_file or doc_name]]
     if doc_file and fsutils.exists(doc_file):
         doc_stat = os.stat(doc_file)
         st_size = '%s bytes' % doc_stat.st_size
         st_mtime = datetime.fromtimestamp(doc_stat.st_mtime).strftime('%c')
         data += [[_('File size:'), st_size], [_('Modified:'), st_mtime]]
     return data
Esempio n. 10
0
    def __init__(self, app, cfgdir='~'):
        # --- Init paths
        path = fsutils.expanduser(os.path.join(cfgdir, '.config', 'sk1-wx'))
        self.app_config_dir = path

        UCData.__init__(self, app, check=False)
        self.check_config_dirs()

        self.app_palette_dir = os.path.join(path, 'palettes')
        self.plugin_dir = os.path.join(path, 'sk1_custom_plugins')
        self.app_temp_dir = os.path.join(path, 'temp')

        # --- Check config directories
        paths = (self.app_palette_dir, self.plugin_dir, self.app_temp_dir)
        [fsutils.makedirs(item) for item in paths if not fsutils.exists(item)]

        plugin_dir_init = os.path.join(self.plugin_dir, '__init__.py')
        if not fsutils.exists(plugin_dir_init):
            fsutils.get_fileptr(plugin_dir_init, True).close()
Esempio n. 11
0
def get_langs():
    if not LANGS:
        LANGS.append(_('system'))
    path = os.path.join(config.resource_dir, 'locales')
    langs = ['en', ]
    if fsutils.exists(path):
        langs += [item for item in os.listdir(fsutils.get_sys_path(path))
                  if fsutils.isdir(os.path.join(path, item))]
    langs.sort()
    for item in langs:
        LANGS.append(item)
Esempio n. 12
0
 def load_logs(self, log_path):
     if not fsutils.exists(log_path):
         return
     fileptr = fsutils.get_fileptr(log_path)
     self.logs = []
     while True:
         line = fileptr.readline()
         if not line:
             break
         self.logs.append(line)
     self.parse_logs()
     self.change_title(log_path)
Esempio n. 13
0
    def check_config_dirs(self):

        if not fsutils.exists(self.app_config_dir):
            fsutils.makedirs(self.app_config_dir)

        self.app_config = os.path.join(self.app_config_dir, 'preferences.cfg')

        # Check color profiles directory
        self.app_color_profile_dir = os.path.join(self.app_config_dir,
                                                  'profiles')
        if not fsutils.exists(self.app_color_profile_dir):
            fsutils.makedirs(self.app_color_profile_dir)

        from uc2.cms import libcms

        for item in uc2const.COLORSPACES + [uc2const.COLOR_DISPLAY, ]:
            filename = 'built-in_%s.icm' % item
            path = os.path.join(self.app_color_profile_dir, filename)
            if not fsutils.exists(path):
                path = fsutils.get_sys_path(path)
                libcms.cms_save_default_profile(path, item)
Esempio n. 14
0
def change_config(options):
    config = uc2.config
    if len(options) < 2:
        echo('Please provide configuration values to change.')
        return
    for key, value in options.items():
        if key in BOOL_ATTRS:
            config.__dict__[key] = bool(value)
        elif key == 'log_level':
            if value in LEVELS:
                config.log_level = value
        elif key in INTENT_ATTRS:
            if isinstance(value, int) and value in INTENTS:
                config.__dict__[key] = value
            elif value in INTENTS:
                config.__dict__[key] = INTENTS[value]
        elif key in PROFILES and isinstance(value, str):
            if not value:
                config.__dict__[key] = ''
                continue
            cs = uc2const.COLORSPACES[PROFILES.index(key)]
            path = fsutils.normalize_path(value)
            if not fsutils.exists(path):
                echo('ERROR: file "%s" is not found!' % path)
                continue
            profile_name = cms.get_profile_name(path)
            if not profile_name:
                echo('ERROR: file "%s" is not valid color profile!' % path)
                continue
            profile_dir = config.app.appdata.app_color_profile_dir
            dest_path = os.path.join(profile_dir, '%s.icc' % cs)
            if fsutils.exists(dest_path):
                fsutils.remove(dest_path)
            fsutils.copy(path, dest_path)
            profile_dict = PROFILE_DICTS[PROFILES.index(key)]
            config.__dict__[profile_dict] = {profile_name: dest_path}
            config.__dict__[key] = profile_name
Esempio n. 15
0
    def translate_pic(self, obj, cfg):
        if not obj.childs:
            return
        pic = obj.childs[0]
        filename = pic.file
        if filename:
            file_dir = os.path.dirname(self.fig_doc.doc_file)
            image_path = os.path.join(file_dir, filename)
            image_path = os.path.abspath(image_path)
            if fsutils.exists(image_path):
                pixmap = sk2_model.Pixmap(cfg)
                pixmap.handler.load_from_file(self.sk2_doc.cms, image_path)
                img_w, img_h = pixmap.size

                bbox = libgeom.bbox_for_points(obj.points)
                size = libgeom.bbox_size(bbox)
                x, y = 1.0 * bbox[0], 1.0 * bbox[1]
                w, h = 1.0 * size[0], 1.0 * size[1]

                trafo = [1.0, 0.0, 0.0, 1.0, -img_w / 2.0, -img_h / 2.0]
                if pic.flipped:
                    trafo_rotate = libgeom.trafo_rotate_grad(90.0)
                    trafo = libgeom.multiply_trafo(trafo, trafo_rotate)
                    trafo_f = [
                        1.0 * img_w / img_h, 0.0, 0.0, 1.0 * img_h / img_w,
                        0.0, 0.0
                    ]
                    trafo = libgeom.multiply_trafo(trafo, trafo_f)

                # rotate
                angle = self.fig_mtds.get_pic_angle(obj)
                trafo_r = libgeom.trafo_rotate_grad(angle)
                trafo = libgeom.multiply_trafo(trafo, trafo_r)
                # scale to box size
                if angle in [90.0, 270.0]:
                    img_w, img_h = img_h, img_w
                trafo1 = [w / img_w, 0.0, 0.0, -h / img_h, 0.0, 0.0]
                trafo = libgeom.multiply_trafo(trafo, trafo1)
                # move to origin point
                trafo3 = [1.0, 0.0, 0.0, 1.0, w / 2.0 + x, h / 2.0 + y]
                trafo = libgeom.multiply_trafo(trafo, trafo3)
                # applying document trafo
                trafo = libgeom.multiply_trafo(trafo, self.trafo)
                pixmap.trafo = trafo
                return pixmap
Esempio n. 16
0
    def close(self):
        filename = self.doc_file
        self.doc_file = ''
        if self.model is not None:
            self.model.destroy()
        self.model = None
        model_name = uc2const.FORMAT_NAMES[self.cid]
        self.send_ok(_('<%s> document model is destroyed for %s') %
                     (model_name, filename))

        if self.doc_dir and fsutils.exists(self.doc_dir):
            try:
                fs.xremove_dir(self.doc_dir)
                self.send_ok(_('Cache is cleared for') + ' %s' % filename)
            except Exception as e:
                msg = _('Cache clearing is unsuccessful')
                self.send_error(msg)
                LOG.warning(msg + ' %s', e)
                LOG.exception(e)
Esempio n. 17
0
 def import_profile(self):
     src = dialogs.get_open_file_name(self,
                                      config.profile_import_dir,
                                      _('Select profile to import'),
                                      file_types=[ICC, ICM])
     if not src:
         return
     name = get_profile_name(src)
     title = self.app.appdata.app_name
     if name is None:
         msg = _('Cannot open profile')
         msg = "%s '%s'" % (msg, src)
         sec = _('The profile may be corrupted or in an unsupported format')
         wal.error_dialog(self, title, msg + '\n' + sec)
         return
     if name in self.pf_list:
         msg = _('Selected profile cannot be added to profile list:')
         msg = "%s '%s'" % (msg, name)
         sec = _('It seems like you have already imported this profile')
         wal.error_dialog(self, title, msg + '\n' + sec)
         return
     filename = os.path.basename(src)
     dst_dir = self.app.appdata.app_color_profile_dir
     dst = os.path.join(dst_dir, filename)
     if fsutils.exists(dst):
         msg = _('Selected file has been added to profile pool')
         msg = "%s '%s'" % (msg, src)
         sec = _('If you still wish to import the file, try renaming it')
         wal.error_dialog(self, title, msg + '\n' + sec)
         return
     try:
         shutil.copy(fsutils.get_sys_path(src), fsutils.get_sys_path(dst))
     except Exception:
         msg = _('Cannot copy file')
         msg = "%s '%s'" % (msg, src)
         sec = _('Please check write permissions for config directory:')
         sec += '\n%s' % dst_dir
         wal.error_dialog(self, title, msg + '\n' + sec)
         return
     config.profile_import_dir = os.path.dirname(src)
     self.profiles[name] = filename
     self.apply_changes()
     self.viewer.set_active(self.pf_list.index(name))
Esempio n. 18
0
 def load(self, filename=None):
     self.filename = filename
     if fsutils.exists(filename):
         content_handler = XMLPrefReader(pref=self)
         error_handler = ErrorHandler()
         entity_resolver = EntityResolver()
         dtd_handler = DTDHandler()
         try:
             input_file = fsutils.get_fileptr(filename)
             input_source = InputSource()
             input_source.setByteStream(input_file)
             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)
             input_file.close()
         except Exception as e:
             LOG.error('Cannot read preferences from %s %s', filename, e)
Esempio n. 19
0
    def load(self, filename=None, fileptr=None):
        if filename and fsutils.exists(filename):
            self.doc_file = filename
        elif not fileptr:
            msg = _('Error while loading:') + ' ' + _('No file')
            self.send_error(msg)
            raise IOError(msg)

        try:
            self.parsing_msg(0.03)
            self.send_info(_('Parsing in progress...'))
            self.model = self.loader.load(self, filename, fileptr)
        except Exception as e:
            self.close()
            LOG.error('Error loading %s', filename)
            LOG.exception(e)
            raise

        model_name = uc2const.FORMAT_NAMES[self.cid]
        self.send_ok(_('<%s> document model is created') % model_name)
        self.update()
Esempio n. 20
0
    def load(self, filename=None):
        self.filename = filename
        if fsutils.exists(filename):
            try:
                fileobj = fsutils.get_fileptr(filename)
            except Exception:
                return

            while True:
                line = fileobj.readline()
                if line.startswith('<?xml') or not line:
                    break
                if line.startswith('#'):
                    continue
                line = path_system('self.%s' % line)
                try:
                    code = compile(line, '<string>', 'exec')
                    exec code
                except Exception as e:
                    LOG.error('ERROR>>> %s\n%s', line, e)
            fileobj.close()
Esempio n. 21
0
    def close(self):
        filename = self.doc_file
        self.doc_file = ''
        if self.model is not None:
            self.model.destroy()
        self.model = None
        filename = filename.encode('utf-8') \
            if isinstance(filename, unicode) else filename
        model_name = uc2const.FORMAT_NAMES[self.cid]
        self.send_ok(_('<%s> document model is destroyed for %s') %
                     (model_name, filename))

        if self.doc_dir and fsutils.exists(self.doc_dir):
            try:
                fs.xremove_dir(fsutils.get_sys_path(self.doc_dir))
                self.send_ok(_('Cache is cleared for') + ' %s' % filename)
            except Exception as e:
                msg = _('Cache clearing is unsuccessful')
                self.send_error(msg)
                LOG.warn(msg + ' %s', e)
                LOG.exception(e)
Esempio n. 22
0
    def save(self, doc=None):
        doc = doc or 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 fsutils.exists(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
Esempio n. 23
0
 def destroy(self):
     if fsutils.exists(self.lock):
         fsutils.remove(self.lock)
     if self.timer.is_running():
         self.timer.stop()
Esempio n. 24
0
 def load_data(self, image_path):
     if fsutils.exists(image_path):
         self.raw_image = Image.open(image_path)
         self.raw_image.load()
Esempio n. 25
0
    def run(self, current_dir=None):
        if len(sys.argv) == 1:
            dt = self.appdata
            mark = '' if not dt.build else ' build %s' % dt.build
            msg = '%s %s%s%s\n' % (dt.app_name, dt.version, dt.revision, mark)
            cmds.show_short_help(msg)
            sys.exit(0)
        elif cmds.check_args(cmds.HELP_CMDS):
            cmds.show_help(self.appdata)
            sys.exit(0)
        elif cmds.check_args(cmds.PARTS_CMDS):
            cmds.show_parts(self.appdata)
            sys.exit(0)
        elif cmds.check_args(cmds.LOG_CMDS):
            log_filepath = os.path.join(self.appdata.app_config_dir, 'uc2.log')
            log_filepath = log_filepath.decode('utf-8')
            with open(log_filepath, 'rb') as fileptr:
                echo(fileptr.read())
            sys.exit(0)
        elif cmds.check_args(cmds.DIR_CMDS):
            echo(os.path.dirname(os.path.dirname(__file__)))
            sys.exit(0)
        elif cmds.check_args(cmds.CFG_SHOW_CMDS):
            cmds.show_config()
            sys.exit(0)
        elif cmds.check_args(cmds.CONFIG_CMDS):
            options = cmds.parse_cmd_args(current_dir)[1]
            cmds.normalize_options(options)
            cmds.change_config(options)
            self.config.save()
            sys.exit(0)
        elif len(sys.argv) == 2:
            cmds.show_short_help('Not enough arguments!')
            sys.exit(1)

        self.do_verbose = cmds.check_args(cmds.VERBOSE_CMDS)
        current_dir = os.getcwdu() if current_dir is None else current_dir
        files, options = cmds.parse_cmd_args(current_dir)

        if not files:
            cmds.show_short_help('File names are not provided!')
            sys.exit(1)
        elif len(files) == 1:
            msg = 'Destination directory or file name is not provided!'
            cmds.show_short_help(msg)
            sys.exit(1)

        command = cmds.convert
        if any(['*' in files[0], '?' in files[0]]):
            command = cmds.wildcard_convert
            if os.path.exists(files[1]):
                if not os.path.isdir(files[1]):
                    msg = 'Destination directory "%s" is not a directory!'
                    cmds.show_short_help(msg % files[1])
                    sys.exit(1)
            else:
                os.makedirs(files[1])
        elif len(files) > 2:
            command = cmds.multiple_convert
            if os.path.exists(files[-1]):
                if not os.path.isdir(files[-1]):
                    msg = 'Destination directory "%s" is not a directory!'
                    cmds.show_short_help(msg % files[-1])
                    sys.exit(1)
            else:
                os.makedirs(files[-1])
        elif not fsutils.exists(files[0]):
            cmds.show_short_help('Source file "%s" is not found!' % files[0])
            sys.exit(1)

        events.connect(events.MESSAGES, self.verbose)
        log_level = options.get('log', self.config.log_level)
        self.log_filepath = os.path.join(self.appdata.app_config_dir,
                                         'uc2.log')
        config_logging(self.log_filepath, log_level)

        self.default_cms = app_cms.AppColorManager(self)
        self.palettes = PaletteManager(self)

        # EXECUTION ----------------------------
        status = 0
        # noinspection PyBroadException
        try:
            command(self.appdata, files, options)
        except Exception:
            status = 1

        if self.do_verbose:
            echo()
        sys.exit(status)