示例#1
0
def test_copy_with_relative_path():
    src = relative_to(__file__, 'test-resources/a/file')

    copy_relative(src, '../b/file_copy')

    expected = relative_to(__file__, 'test-resources/b/file_copy')
    assert os.path.exists(expected)

    os.remove(expected)
示例#2
0
def test_ordering():
    prefix = file.relative_to(__file__, 'test-resources/files/')
    collection = GimpFileCollection.create_from_pathname(file.relative_to(__file__, 'test-resources/files/**'))
    collection = collection.replace_prefix(prefix)
    assert [
        'first.xcf',
        'second.xcf',
        'a/third.xcf',
        'a/b/fourth.xcf',
    ] == collection.get_files()
示例#3
0
def test_replace_path_components():
    prefix = file.relative_to(__file__, 'test-resources/files/')
    suffix = '.xcf'
    collection = GimpFileCollection.create_from_pathname(file.relative_to(__file__, 'test-resources/files/**'))

    collection = collection.replace_path_components(prefix, '#', suffix, '%')

    assert [
        '#first%.xcf',
        '#second%.xcf',
        '#a/third%.xcf',
        '#a/b/fourth%.xcf',
    ] == collection.get_files()
示例#4
0
def test_create_from_pathname_with_file():
    prefix = file.relative_to(__file__, 'test-resources/files/')

    collection = GimpFileCollection.create_from_pathname(file.relative_to(__file__, 'test-resources/files/first'))
    assert len(collection.get_files()) == 1
    assert prefix == collection.get_prefix()

    collection = GimpFileCollection.create_from_pathname(file.relative_to(__file__, 'test-resources/files/first.xcf'))
    assert len(collection.get_files()) == 1
    assert prefix == collection.get_prefix()

    collection = GimpFileCollection.create_from_pathname(file.relative_to(__file__, 'test-resources/files/first.png'))
    assert len(collection.get_files()) == 0
    assert '' == collection.get_prefix()
示例#5
0
    def run(self):
        if not self._dry_run:
            from pgimp.doc.GimpDocumentationGenerator import GimpDocumentationGenerator
            from pgimp.doc.output.OutputPythonSkeleton import OutputPythonSkeleton

            generate_python_skeleton = GimpDocumentationGenerator(
                OutputPythonSkeleton(file.relative_to(__file__, 'gimp')))
            generate_python_skeleton()
            target_dir = self.build_lib
            shutil.copytree(file.relative_to(__file__, 'gimp'),
                            os.path.join(target_dir, 'gimp'))
            shutil.copytree(file.relative_to(__file__, 'gimpenums'),
                            os.path.join(target_dir, 'gimpenums'))
            shutil.copytree(file.relative_to(__file__, 'gimpfu'),
                            os.path.join(target_dir, 'gimpfu'))
        return build_py.run(self)
示例#6
0
def test_replace_path_components_without_replacements():
    collection = GimpFileCollection.create_from_pathname(file.relative_to(__file__, 'test-resources/files/**'))

    files_before = collection.get_files()
    collection = collection.replace_path_components()
    files_after = collection.get_files()

    assert files_before == files_after
示例#7
0
def test_copy_with_absolute_path():
    src = relative_to(__file__, 'test-resources/a/file')
    tmp = tempfile.mktemp()

    copy_relative(src, tmp)

    expected = tmp
    assert os.path.exists(expected)

    os.remove(expected)
示例#8
0
def test_clear_selection():
    file_with_selection_original = file.relative_to(__file__, 'test-resources/selection.xcf')
    with TempFile('.xcf') as file_with_selection:
        shutil.copyfile(file_with_selection_original, file_with_selection)
        collection = GimpFileCollection([file_with_selection])

        selections_before = _has_selections(collection)
        assert selections_before[file_with_selection]

        collection.clear_selection(timeout_in_seconds=10)

        selections_after = _has_selections(collection)
        assert not selections_after[file_with_selection]
def test_generate_python_skeletons():
    generate_python_skeleton = GimpDocumentationGenerator(
        OutputPythonSkeleton(file.relative_to(__file__, '../../gimp')))
    generate_python_skeleton()

    def assert_file_exists(f: str):
        assert os.path.exists(
            os.path.join(file.relative_to(__file__, '../../'), f))

    assert_file_exists('gimp/__init__.py')
    assert_file_exists('gimp/pdb.py')
    assert_file_exists('gimpenums/__init__.py')
    assert_file_exists('gimpfu/__init__.py')
示例#10
0
def test_create():
    filename = file.relative_to(__file__, 'test-resources/test-create.xcf')
    layer_bg = np.array([
        [[255, 255, 255], [0, 0, 0], [255, 255, 255]],
        [[255, 255, 255], [255, 255, 255], [255, 255, 255]],
    ],
                        dtype=np.uint8)

    gimp_file = GimpFile(filename)
    gimp_file.create('Background', layer_bg)

    exists = os.path.exists(filename)
    actual = gimp_file.layer_to_numpy('Background')
    os.remove(filename)

    assert exists
    assert np.all(layer_bg == actual)
示例#11
0
def test_merge_layer_from_file_with_cleared_selection():
    src = file.relative_to(__file__, 'test-resources/selection.xcf')
    with TempFile('.xcf') as dst:
        src_file = GimpFile(src)
        dst_file = GimpFile(dst)
        dst_file.create('Background', np.zeros(shape=(3, 3, 3),
                                               dtype=np.uint8))
        dst_file.merge_layer_from_file(src_file, 'Background')

        new_layer_contents = dst_file.layer_to_numpy('Background')

        assert np.all(
            np.array([
                [[255, 255, 255], [255, 255, 255], [255, 255, 255]],
                [[255, 0, 0], [255, 0, 0], [255, 255, 255]],
                [[255, 255, 255], [255, 255, 255], [255, 255, 255]],
            ],
                     dtype=np.uint8) == new_layer_contents)
示例#12
0
def test_create_from_pathname_with_recursive_match():
    prefix = file.relative_to(__file__, 'test-resources/files/')

    collection = GimpFileCollection.create_from_pathname(file.relative_to(__file__, 'test-resources/files/**'))
    assert len(collection.get_files()) == 4
    assert prefix == collection.get_prefix()

    collection = GimpFileCollection.create_from_pathname(file.relative_to(__file__, 'test-resources/files/**/'))
    assert len(collection.get_files()) == 4
    assert prefix == collection.get_prefix()

    collection = GimpFileCollection.create_from_pathname(file.relative_to(__file__, 'test-resources/files/**/*'))
    assert len(collection.get_files()) == 4
    assert prefix == collection.get_prefix()

    collection = GimpFileCollection.create_from_pathname(file.relative_to(__file__, 'test-resources/files/**/*.xcf'))
    assert len(collection.get_files()) == 4
    assert prefix == collection.get_prefix()

    collection = GimpFileCollection.create_from_pathname(file.relative_to(__file__, 'test-resources/files/**/*.png'))
    assert len(collection.get_files()) == 0
    assert '' == collection.get_prefix()
示例#13
0
# Copyright 2018 Mathias Burger <*****@*****.**>
#
# SPDX-License-Identifier: MIT

import os
import tempfile

import numpy as np
from pytest import approx

import gimpenums
from pgimp.GimpFile import GimpFile, LayerType, ColorMap, GimpFileType
from pgimp.util import file
from pgimp.util.TempFile import TempFile

rgb_file = GimpFile(file.relative_to(__file__, 'test-resources/rgb.xcf'))
"""
The file rgb.xcf contains a 3x2 image with white 'Background' layer and 'Red', 'Green', 'Blue' layers with differing 
opacity. The layer 'Background' contains a black pixel at y=0, x=1, the others pixels are white.
"""


def test_layer_to_numpy():
    actual = rgb_file.layer_to_numpy('Background')
    expected = np.array([
        [[255, 255, 255], [0, 0, 0], [255, 255, 255]],
        [[255, 255, 255], [255, 255, 255], [255, 255, 255]],
    ],
                        dtype=np.uint8)

    assert np.all(expected == actual)
            return_json(result)
            """)
        enums = self._execute(enum_dump)
        self._output.gimpenums(enums)

    def _document_gimpfu_constants(self):
        const_dump = textwrap.dedent("""
            import gimpfu
            from pgimp.gimp.parameter import return_json

            result = filter(lambda s: not s.startswith('__') and s.isupper(), dir(gimpfu))
            result = zip(result, map(lambda s: eval('gimpfu.' + s), result))
            result = filter(lambda v: type(v[1]).__name__ not in ['instance', 'function'] , result)

            return_json(result)
            """)
        constants = self._execute(const_dump)
        self._output.gimpfu_constants(constants)


if __name__ == '__main__':
    import sys
    from pgimp.util import file
    sys.path.append(file.relative_to(__file__, '../../'))
    from pgimp.doc.output.OutputPythonSkeleton import OutputPythonSkeleton

    generate_python_skeleton = GimpDocumentationGenerator(
        OutputPythonSkeleton(file.relative_to(__file__, '../../gimp')))
    generate_python_skeleton()
示例#15
0
    def _send_to_gimp(
            self,
            code: str,
            timeout_in_seconds: float = None,
            binary=False,
            parameters: dict = None,
    ) -> Union[str, bytes, None]:

        if not is_gimp_present():
            raise GimpNotInstalledException('A working gimp installation with gimp on the PATH is necessary.')

        command = []
        if is_xvfb_present():
            command.append(path_to_xvfb_run())
            command.append(FLAG_AUTO_SERVERNUM)  # workaround for defunct xvfb-run processes on ubuntu 16.04
        command.append(path_to_gimp_executable())
        command.extend([
            FLAG_NO_INTERFACE,
            FLAG_NO_DATA,
            FLAG_NO_FONTS,
            FLAG_PYTHON_INTERPRETER,
            FLAG_NON_INTERACTIVE,
            FLAG_FROM_STDIN
        ])

        gimp_environment = {'__working_directory__': self._working_directory}
        gimp_environment.update(os.environ.copy())
        if 'PYTHONPATH' not in gimp_environment:
            gimp_environment['__PYTHONPATH__'] = python2_pythonpath()
        else:
            gimp_environment['__PYTHONPATH__'] = python2_pythonpath() + ':' + gimp_environment['PYTHONPATH']
        gimp_environment.update({k: v for k, v in self._environment.items() if self._environment[k] is not None})

        parameters = parameters or {}
        parameters_parsed = {}
        for parameter, value in parameters.items():
            if isinstance(value, str):
                parameters_parsed[parameter] = value
            elif isinstance(value, (bool, int, float, bytes)):
                parameters_parsed[parameter] = repr(value)
            elif isinstance(value, (list, tuple, dict)):
                parameters_parsed[parameter] = json.dumps(value)
            else:
                raise GimpScriptException('Cannot interpret parameter type {:s}'.format(type(value).__name__))

        gimp_environment.update({k: v for k, v in parameters_parsed.items() if parameters_parsed[k] is not None})

        with TempFile('.stdout', 'pgimp') as stdout_file, TempFile('.stderr', 'pgimp') as stderr_file:
            gimp_environment['__stdout__'] = stdout_file
            gimp_environment['__stderr__'] = stderr_file
            gimp_environment['__binary__'] = str(binary)

            self._gimp_process = subprocess.Popen(
                command,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                env=gimp_environment,
            )

            initializer = file.get_content(file.relative_to(__file__, 'gimp/initializer.py')) + '\n'
            extend_path = "sys.path.append('{:s}')\n".format(os.path.dirname(os.path.dirname(__file__)))
            quit_gimp = '\npdb.gimp_quit(0)'

            code = initializer + extend_path + code + quit_gimp

            if pgimp.execute_scripts_with_process_check:
                import psutil

                if is_xvfb_present():
                    expected_processes = {'xvfb', 'gimp', 'script-fu', 'python'}
                else:
                    expected_processes = {'script-fu', 'python'}

                process = psutil.Process(self._gimp_process.pid)
                process_children = self._wait_for_child_processes_to_start(process, expected_processes)

            try:
                self._gimp_process.communicate(code.encode(), timeout=timeout_in_seconds)
            except subprocess.TimeoutExpired as exception:
                self._gimp_process.kill()
                raise GimpScriptExecutionTimeoutException(str(exception) + '\nCode that was executed:\n' + code)
            finally:
                if pgimp.execute_scripts_with_process_check:
                    self._kill_non_terminated_processes(process_children)

            stdout_content = read(stdout_file, 'r' if not binary else 'rb')
            stderr_content = read(stderr_file, 'r')

        if stderr_content:
            error_lines = stderr_content.strip().split('\n')
            if error_lines[-1].startswith('__GIMP_SCRIPT_ERROR__'):
                error_string = stderr_content.rsplit('\n', 1)[0] + '\n'
                if self._file_to_execute:
                    error_string = error_string.replace('File "<string>"', 'File "{:s}"'.format(self._file_to_execute), 1)
                raise GimpScriptException(error_string)
            raise GimpScriptException('\n'.join(error_lines))

        return stdout_content
示例#16
0
def test_replace_path_components_with_non_existing_component():
    collection = GimpFileCollection.create_from_pathname(file.relative_to(__file__, 'test-resources/files/**'))

    with pytest.raises(NonExistingPathComponentException):
        collection.replace_path_components('wrong_prefix', '#')
 def assert_file_exists(f: str):
     assert os.path.exists(
         os.path.join(file.relative_to(__file__, '../../'), f))
示例#18
0
import os

import numpy as np

from pgimp.GimpFile import GimpFile
from pgimp.util import file
from pgimp.util.TempFile import TempFile

if __name__ == '__main__':
    img_path = file.relative_to(__file__, '../../../doc/source/_static/img')
    png_file = os.path.join(img_path, 'mask_applied.png')

    height = 100
    width = 200

    # layer content
    bg = np.zeros(shape=(height, width), dtype=np.uint8)
    fg = np.ones(shape=(height, width), dtype=np.uint8) * 255
    mask = np.zeros(shape=(height, width), dtype=np.uint8)
    mask[:, width//4:3*width//4+1] = 255

    with TempFile('.xcf') as xcf, TempFile('.npz') as npz:
        # create gimp file
        gimp_file = GimpFile(xcf) \
            .create('Background', bg) \
            .add_layer_from_numpy('Foreground', fg) \
            .add_layer_from_numpy('Mask', mask)

        # save layer data to numpy arrays
        arr_bg = gimp_file.layer_to_numpy('Background')
        arr_fg = gimp_file.layer_to_numpy('Foreground')