Esempio n. 1
0
 def find_exe(self, program, name=None):
     if name is None:
         name = system.title(program)
     path = system.find_exe(program)
     if not path:
         raise Exception('You need to install "%s" first.' % name)
     self.exe[program] = path
Esempio n. 2
0
 def find_exe(self, program, name=None):
     if name is None:
         name = system.title(program)
     path = system.find_exe(program)
     if not path:
         raise Exception('You need to install "%s" first.' % name)
     self.exe[program] = path
Esempio n. 3
0
 def collect_fonts():
     """Collect a list of all font filenames."""
     #try first with locate otherwise with find
     for command in LOCATE:
         try:
             if system.find_exe(command[0]):
                 output = locate_files(command)
                 files = [line for line in output
                     if line[-4:].lower() in ['.ttf', '.otf']]
                 if files:
                     return files
         except:
             pass
     from other.findsystem import findFonts
     return findFonts()
Esempio n. 4
0
 def collect_fonts():
     """Collect a list of all font filenames."""
     #try first with locate otherwise with find
     output = set()
     for command in LOCATE:
         try:
             if system.find_exe(command[0]):
                 output = output.union(locate_files(command))
         except:
             pass
     files = [
         line for line in output if line[-4:].lower() in ['.ttf', '.otf']
     ]
     # was locate or mdfind succesfull?
     if files:
         return files
     # emergency solution
     from other.findsystem import findFonts
     return findFonts()
Esempio n. 5
0
 def to_python(self, x, label):
     command = super(CommandLineField, self).to_python(x, label)
     #check if exists
     if self.needs_exe:
         exe = name = command.split()[0]
         if not os.path.isfile(exe):
             exe = system.find_exe(exe)
         if exe is None:
             raise self.raise_error_not_found(label, name)
     #check for in file
     if self.needs_in and not RE_FILE_IN.search(command):
         self.raise_error_file(label, 'file_in')
     #check for out file
     if self.needs_out:
         file_out = RE_FILE_OUT.findall(command)
         if not file_out:
             self.raise_error_file(label, 'file_out')
         elif len(file_out) > 1:
             self.raise_error_out_max(label, 'file_out')
     return command
Esempio n. 6
0
 def to_python(self, x, label):
     command = super(CommandLineField, self).to_python(x, label)
     #check if exists
     if self.needs_exe:
         exe = name = command.split()[0]
         if not os.path.isfile(exe):
             exe = system.find_exe(exe)
         if exe is None:
             raise self.raise_error_not_found(label, name)
     #check for in file
     if self.needs_in and not RE_FILE_IN.search(command):
         self.raise_error_file(label, 'file_in')
     #check for out file
     if self.needs_out:
         file_out = RE_FILE_OUT.findall(command)
         if not file_out:
             self.raise_error_file(label, 'file_out')
         elif len(file_out) > 1:
             self.raise_error_out_max(label, 'file_out')
     return command
Esempio n. 7
0
    ['locate', '-i', '.ttf', '.otf'],
    ['find', '/', '-iname', '*.ttf', '-o', '-name', '*.otf'],
]

#collect_fonts (system dependent)
if sys.platform.startswith('win'):
    #3thrd party module in other
    from other.findsystem import findFonts

    def collect_fonts():
        """Collect a list of all font filenames."""
        return findFonts()
else:
    #better unix alternative for collect_fonts/findFonts
    #presume findutils are present
    if not system.find_exe('locate'):
        sys.exit(_('Please install "%s" first.') % 'locate')

    def locate_files(command):
        return subprocess.Popen(command,
            stdout=subprocess.PIPE).stdout.read().splitlines()

    def collect_fonts():
        """Collect a list of all font filenames."""
        #try first with locate otherwise with find
        for command in LOCATE:
            try:
                if system.find_exe(command[0]):
                    output = locate_files(command)
                    files = [line for line in output
                        if line[-4:].lower() in ['.ttf', '.otf']]
Esempio n. 8
0
            image.info['Convertor'] = app
            return image
    finally:
        if temp:
            temp.close(force_remove=False)
        elif temp_ext and os.path.exists(temp_file):
            os.remove(temp_file)
    message = _('Could not open image with %s.') % app + \
        '\n\n%s: %s\n\n%s: %s\n\n%s: %s' % \
        (_('Command'), command, _('Output'), output, _('Error'), error)
    raise IOError(message)


#libtiff

TIFFINFO = system.find_exe("tiffinfo")
TIFFCP = system.find_exe("tiffcp")

if TIFFINFO and TIFFCP:

    RE_TIFF_FIELD = re.compile('\s+(.*?):\s+(.*?)\n')
    RE_TIFF_FIELD_IMAGE = re.compile(' Image (.*?):\s+(.*?)$')

    TIFF_COMPRESSION = {
        'CCITT Group 3': 'g3',
        'CCITT Group 4': 'g4',
        'Deflate': 'zip',
        'JPEG': 'jpeg',
        'LZW': 'lzw',
        'PackBits': 'packbits',
        'None': 'none',
        elif temp_ext and os.path.exists(temp_file):
            os.remove(temp_file)
    message = _("Could not open image with %s.") % app + "\n\n%s: %s\n\n%s: %s\n\n%s: %s" % (
        _("Command"),
        command,
        _("Output"),
        output,
        _("Error"),
        error,
    )
    raise IOError(message)


# libtiff

TIFFINFO = system.find_exe("tiffinfo")
TIFFCP = system.find_exe("tiffcp")

if TIFFINFO and TIFFCP:

    RE_TIFF_FIELD = re.compile("\s+(.*?):\s+(.*?)\n")
    RE_TIFF_FIELD_IMAGE = re.compile(" Image (.*?):\s+(.*?)$")

    TIFF_COMPRESSION = {
        "CCITT Group 3": "g3",
        "CCITT Group 4": "g4",
        "Deflate": "zip",
        "JPEG": "jpeg",
        "LZW": "lzw",
        "PackBits": "packbits",
        "None": "none",
Esempio n. 10
0
def register():
    """find_exe needs to happen in a function so BIN_PATHS can be set."""

    #libtiff
    global TIFFINFO, TIFFINFO, get_info_libtiff, open_libtiff, save_libtiff

    TIFFINFO = system.find_exe("tiffinfo")
    TIFFCP = system.find_exe("tiffcp")

    if TIFFINFO and TIFFCP:

        def get_info_libtiff(filename, temp=False):
            """Get tiff info of a file with ``tiffinfo``, which needs to be
            installed on your system.

            :param filename: name of tiff image file
            :type filename: string
            :returns: info about the file
            :rtype: dict
            """
            result = {}

            def set(key, value):
                key = 'libtiff.' + key.lower().replace(' ', '.')
                if not (key in result):
                    result[key] = value

            stdout, stderr, err = system.call_out_err_temp(
                (TIFFINFO, filename),
                input=[filename],
                output=[],
                universal_newlines=True,
            )
            if not err:
                for match in RE_TIFF_FIELD.finditer(stdout):
                    value = match.group(2)
                    again = RE_TIFF_FIELD_IMAGE.search(value)
                    if again:
                        set('Image %s' % again.group(1), again.group(2))
                        set(match.group(1), value[:again.start()])
                    else:
                        set(match.group(1), value)
            if not result:
                raise IOError('Not a TIFF or MDI file, bad magic number.')
            result['compression'] = \
                TIFF_COMPRESSION[result['libtiff.compression.scheme']]
            if temp:
                return result, temp_file
            return result

        def open_libtiff(filename):
            """Opens a tiff file with ``tiffcp``, which needs to be installed
            on your system.

            :param filename: name of tiff image file
            :type filename: string
            :returns: PIL image
            :rtype: Image.Image
            """
            # get info
            info, temp_info = get_info_libtiff(filename, temp=True)
            if temp_info:
                filename = temp_info.path
            # extract
            temp = system.TempFile()
            command = (TIFFCP, '-c', 'none', '-r', '-1', filename, temp.path)
            try:
                returncode = system.call(command)
                if returncode == 0:
                    # use copy() otherwise temp file can't be deleted (win)
                    image = Image.open(temp.path).copy()
                    image.info.update(info)
                    image.info['Convertor'] = 'libtiff'
                    return image
            finally:
                if temp_info:
                    temp_info.close()
                temp.close(force_remove=False)
            raise IOError('Could not extract tiff image with tiffcp.')

        def save_libtiff(image, filename, compression=None, **options):
            """Saves a tiff compressed file with tiffcp.

            :param image: PIL image
            :type image: Image.Image
            :param filename: name of tiff image file
            :type filename: string
            :param compression: g3, g4, jpeg, lzw, tiff_lzw
            :type compression: string
            :returns: log message
            :rtype: string
            """
            if compression is None:
                compression = image.info['compression']
            option = []
            if compression in ['raw', 'none']:
                image.save(filename, 'tiff', **options)
                return ''
            elif compression in ['g3', 'g4'] and image.mode != '1':
                image = image.convert('1')
            elif compression == 'jpeg':
                option = ['-r', '16']
                if image.mode == 'RGBA':
                    image = image.convert('RGB')
            elif compression == 'tiff_lzw':
                compression = 'lzw'
            temp = system.TempFile()
            temp_c = system.TempFile()
            try:
                image.save(temp.path, 'tiff', **options)
                input = [TIFFCP, '-c', compression]
                if option:
                    input.extend(option)
                input.extend([temp.path, temp_c.path])
                stdout, stderr, err = system.call_out_err(
                    input,
                    universal_newlines=True,
                )
            finally:
                temp.close()
                temp_c.close(dest=filename)
            if err or stdout or stderr:
                raise Exception(
                    'tiffcp (%s): %s%s\n%s' % (err, stdout, stderr, input), )
            return ''

    else:
        open_libtiff = save_libtiff = get_info_libtiff = None

    # inkscape

    global INKSCAPE, open_inkscape

    INKSCAPE = system.find_exe('inkscape')

    if INKSCAPE:

        def open_inkscape(filename):
            """Open an Inkscape file."""
            command = [INKSCAPE, filename, '-e']
            return open_image_with_command(filename, command, 'inkscape')

    else:

        open_inkscape = None

    # imagemagick

    global IMAGEMAGICK_IDENTIFY, IMAGEMAGICK_CONVERT, \
           open_imagemagick, verify_imagemagick

    IMAGEMAGICK_IDENTIFY = system.find_exe('identify')
    if IMAGEMAGICK_IDENTIFY:
        IMAGEMAGICK_CONVERT = system.find_exe('convert')
    else:
        IMAGEMAGICK_CONVERT = None

    if IMAGEMAGICK_CONVERT:

        def open_imagemagick(filename):
            """Open an image with Imagemagick."""
            command = [
                IMAGEMAGICK_CONVERT, filename, '-interlace', 'none',
                '-background', 'none', '-flatten'
            ]
            return open_image_with_command(filename, command, 'imagemagick')

    else:

        open_imagemagick = None

    if IMAGEMAGICK_IDENTIFY:

        def verify_imagemagick(filename):
            """Verify an image with Imagemagick."""
            command = (IMAGEMAGICK_IDENTIFY, '-quiet', filename)
            retcode = system.call(command)
            if retcode == 0:
                return True
            return False

    else:

        verify_imagemagick = None

    # xcf tools (gimp)

    global XCF2PNG, XCFINFO, open_xcf, verify_xcf

    XCF2PNG = system.find_exe('xcf2png')
    XCFINFO = system.find_exe('xcfinfo')

    if XCF2PNG:

        def open_xcf(filename):
            """Open a gimp file."""
            command = [XCF2PNG, filename, '-o']
            return open_image_with_command(filename, command, 'xcf2png')

    else:

        open_xcf = None

    if XCFINFO:

        def verify_xcf(filename):
            """Verify a gimp file."""
            command = (XCFINFO, '-u', filename)
            retcode = system.call(command)
            if retcode == 0:
                return True
            return False

    else:

        verify_xcf = None

    # dcraw

    global DCRAW, open_dcraw, verify_dcraw

    DCRAW = system.find_exe('dcraw')

    if DCRAW:

        def open_dcraw(filename):
            """Open a camera raw image file."""
            command = [DCRAW, '-w', filename]
            return open_image_with_command(filename,
                                           command,
                                           'dcraw',
                                           temp_ext='ppm')

        def verify_dcraw(filename):
            """Verify a camera raw image file."""
            command = (DCRAW, '-i', filename)
            retcode = system.call(command)
            if retcode == 0:
                return True
            return False

    else:

        open_dcraw = None
        verify_dcraw = None

    # register methods

    # IMPORTANT: the order of registering is important, the method
    # which is first registered gets more priority

    global WITHOUT_PIL, ENHANCE_PIL, VERIFY_WITHOUT_PIL

    WITHOUT_PIL = system.MethodRegister()
    WITHOUT_PIL.register(['xcf'], open_xcf)
    WITHOUT_PIL.register(RAW_EXTENSIONS, open_dcraw)
    WITHOUT_PIL.register(['svg', 'svgz'], open_inkscape)
    WITHOUT_PIL.register(
        [
            'ai', 'avi', 'cmyk', 'cmyka', 'dpx', 'eps', 'exr', 'mng', 'mov',
            'mpeg', 'mpg', 'otf', 'pdf', 'pict', 'ps', 'psd', 'svg', 'svgz',
            'ttf', 'wmf', 'xcf', 'xpm', 'ycbcr', 'ycbcra', 'yuv'
        ],
        open_imagemagick,
    )

    # This is for file formats which PIL can read, but not all subformats
    # For example: compressed tiff files

    ENHANCE_PIL = system.MethodRegister()
    ENHANCE_PIL.register(['tiff'], open_libtiff)
    ENHANCE_PIL.register(['png'], open_imagemagick)

    VERIFY_WITHOUT_PIL = system.MethodRegister()
    VERIFY_WITHOUT_PIL.register(['xcf'], verify_xcf)
    VERIFY_WITHOUT_PIL.register(RAW_EXTENSIONS, verify_dcraw)
    VERIFY_WITHOUT_PIL.register(
        ['eps', 'psd', 'pdf', 'svg', 'svgz', 'wmf', 'xcf'],
        verify_imagemagick,
    )

    global IMAGE_EXTENSIONS, IMAGE_READ_EXTENSIONS
    # update read extensions
    IMAGE_READ_EXTENSIONS = set(IMAGE_READ_EXTENSIONS)\
        .union(WITHOUT_PIL.extensions)
    IMAGE_READ_EXTENSIONS = sorted(IMAGE_READ_EXTENSIONS)
    # update read and write extensions
    IMAGE_EXTENSIONS = [
        ext for ext in IMAGE_READ_EXTENSIONS if ext in IMAGE_WRITE_EXTENSIONS
    ]

    global verify_image

    def verify_image(info_file,
                     valid,
                     invalid,
                     method_register=VERIFY_WITHOUT_PIL):
        extension = system.file_extension(info_file['path'])
        if extension in method_register.extensions:
            verify_image_without_pil(info_file, method_register, valid,
                                     invalid)
        else:
            verify_image_with_pil(info_file, valid, invalid)
Esempio n. 11
0
    ['locate', '-i', '.ttf', '.otf'],
    #['find', '/', '-iname', '*.ttf', '-o', '-name', '*.otf'],
]

#collect_fonts (system dependent)
if sys.platform.startswith('win'):
    #3thrd party module in other
    from other.findsystem import findFonts

    def collect_fonts():
        """Collect a list of all font filenames."""
        return findFonts()
else:
    #better unix alternative for collect_fonts/findFonts
    #presume findutils are present
    if sys.platform.startswith('linux') and not system.find_exe('locate'):
        sys.exit(_('Please install "%s" first.') % 'locate')
    elif sys.platform.startswith('darwin'):
        # use spotlight on Mac OS X
        LOCATE.extend([['mdfind', '.ttf'], ['mdfind', '.otf']])

    def locate_files(command):
        return subprocess.Popen(
            command, stdout=subprocess.PIPE).stdout.read().splitlines()

    def collect_fonts():
        """Collect a list of all font filenames."""
        #try first with locate otherwise with find
        output = set()
        for command in LOCATE:
            try: