Example #1
0
def wintounix(path, drives_info=None):
    # Test if we can actually convert this path, skip it if we can't
    if not (
        path[1:3] == ':\\' or path[0] == '%'
    ) and not (
        path.startswith('..\\') or path.startswith('.\\')
    ):
        return path

    if drives_info == None:
        drives_info = drives.get(use_registry=False)
    else:
        drives_info = drives_info

    path = convert_wine_path_variables(path)

    if path[0].upper() in drives_info.keys():
        if drives_info[path[0].upper()]['mapping'].endswith('/'):
            mapping = drives_info[path[0].upper()]['mapping'][:-1]
        else:
            mapping = drives_info[path[0].upper()]['mapping']
        path = '%s/%s' % ( mapping, "/".join(path[3:].split("\\")).replace('\0','') )
    elif path[0] != '%':
        path = "%s/drive_c/%s" % (common.ENV['WINEPREFIX'], "/".join(path[3:].split("\\")).replace('\0',''))

    if not os.path.exists(path) and path[0] != '%':
        """Path does not exist, trying magic..."""
        newpath = ''
        for branch in filter(len, path.split('/')):
            temppath = '%s/%s' % (newpath, branch)
            """\tTesting %s..." % temppath"""
            if not os.path.exists(temppath):
                """\tDidn't work, iterating dir..."""
                pathlist = os.listdir(newpath)
                for filename in pathlist:
                    if '~' in branch and filename.lower().startswith(branch.lower().split('~')[0]) \
                    or filename.lower() == branch.lower():
                        temppath = '%s/%s' % (newpath, filename)
                        """\tMatch found in %s." % temppath"""
                        break
            if os.path.exists(temppath):
                newpath = temppath
                """\tGot a match on \"%s\"" % newpath"""
            else:
                """\tCouldn't match, returning \"%s\"" % path"""
                return '{0}/{1}'.format(temppath, path[len(temppath):])
        """Final result:", newpath"""
        path = newpath
    return os.path.normpath(path)
Example #2
0
def wintounix(path, drives_info=None):
    # Test if we can actually convert this path, skip it if we can't
    if not (
        path[1:3] == ':\\' or path[0] == '%'
    ) and not (
        path.startswith('..\\') or path.startswith('.\\')
    ):
        return path

    if drives_info == None:
        drives_info = drives.get(use_registry=False)
    else:
        drives_info = drives_info

    path = convert_wine_path_variables(path)

    if path[0].upper() in drives_info.keys():
        if drives_info[path[0].upper()]['mapping'].endswith('/'):
            mapping = drives_info[path[0].upper()]['mapping'][:-1]
        else:
            mapping = drives_info[path[0].upper()]['mapping']
        path = '%s/%s' % ( mapping, "/".join(path[3:].split("\\")).replace('\0','') )
    elif path[0] != '%':
        path = "%s/drive_c/%s" % (common.ENV['WINEPREFIX'], "/".join(path[3:].split("\\")).replace('\0',''))

    if not os.path.exists(path) and path[0] != '%':
        """Path does not exist, trying magic..."""
        newpath = ''
        for branch in filter(len, path.split('/')):
            temppath = '%s/%s' % (newpath, branch)
            """\tTesting %s..." % temppath"""
            if not os.path.exists(temppath):
                """\tDidn't work, iterating dir..."""
                pathlist = os.listdir(newpath)
                for filename in pathlist:
                    if '~' in branch and filename.lower().startswith(branch.lower().split('~')[0]) \
                    or filename.lower() == branch.lower():
                        temppath = '%s/%s' % (newpath, filename)
                        """\tMatch found in %s." % temppath"""
                        break
            if os.path.exists(temppath):
                newpath = temppath
                """\tGot a match on \"%s\"" % newpath"""
            else:
                """\tCouldn't match, returning \"%s\"" % path"""
                return '{0}/{1}'.format(temppath, path[len(temppath):])
        """Final result:", newpath"""
        path = newpath
    return os.path.normpath(path)
Example #3
0
def unixtowin(path):
    """ See http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx for info on Windows filenames """
    if path[1:3] == ':\\':
        return path

    drives_info = drives.get(use_registry=False)
    # Strip the drives info to be in the form {'/mapping/of/drive', 'C'} so we can sort it
    drives_info = dict([ (v['mapping'], k) for k,v in drives_info.iteritems() ])
    # Go through the mappings, sorted by length of mapping, longest first
    for mapping in sorted(drives_info.keys(), key=len, reverse=True):
        drive_letter = drives_info[mapping]
        # Make sure the mapping uses the same format as the path
        # otherwise translation gets tricky.
        # Only do it if this mapping is in the same prefix though.
        if (
            mapping.split('/')[-1].startswith('drive_') and
            '/.wine/drive' not in path and
            path.split('.wine')[0] == mapping.split('.wine')[0]
        ):
            drive = mapping[-1].lower()
            for _drive_letter in (mapping[-1].lower(), mapping[-1].upper()):
                mapping_remapped = '{prefix}/dosdevices/{drive}:'.format(
                    prefix = mapping.split('/drive_')[0],
                    drive = _drive_letter
                )
                if os.path.exists(mapping_remapped):
                    mapping = mapping_remapped
                    break

        if path.startswith(mapping):
            path = mapping.join(
                path.split(mapping)[1:]
            )

            path = path.replace('\\','~')
            for i in ['<', '>', ':', '"', '|', '?', '*']:
                path = path.replace(i, '~')

            return '{drive}:\\{path}'.format(
                drive = drive_letter,
                path = path
            ).replace('/', '\\').replace('\\\\', '\\')
Example #4
0
def unixtowin(path):
    """ See http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx for info on Windows filenames """
    if path[1:3] == ':\\':
        return path

    drives_info = drives.get(use_registry=False)
    # Strip the drives info to be in the form {'/mapping/of/drive', 'C'} so we can sort it
    drives_info = dict([ (v['mapping'], k) for k,v in drives_info.iteritems() ])
    # Go through the mappings, sorted by length of mapping, longest first
    for mapping in sorted(drives_info.keys(), key=len, reverse=True):
        drive_letter = drives_info[mapping]
        # Make sure the mapping uses the same format as the path
        # otherwise translation gets tricky.
        # Only do it if this mapping is in the same prefix though.
        if (
            mapping.split('/')[-1].startswith('drive_') and
            '/.wine/drive' not in path and
            path.split('.wine')[0] == mapping.split('.wine')[0]
        ):
            drive = mapping[-1].lower()
            for _drive_letter in (mapping[-1].lower(), mapping[-1].upper()):
                mapping_remapped = '{prefix}/dosdevices/{drive}:'.format(
                    prefix = mapping.split('/drive_')[0],
                    drive = _drive_letter
                )
                if os.path.exists(mapping_remapped):
                    mapping = mapping_remapped
                    break

        if path.startswith(mapping):
            path = mapping.join(
                path.split(mapping)[1:]
            )

            path = path.replace('\\','~')
            for i in ['<', '>', ':', '"', '|', '?', '*']:
                path = path.replace(i, '~')

            return '{drive}:\\{path}'.format(
                drive = drive_letter,
                path = path
            ).replace('/', '\\').replace('\\\\', '\\')
Example #5
0
def enhance_windows_path(path):
    """Replace special Vineyard variables in a path with their meaning.
    So far there is only one: CDROM:\\ for automatic finding and/or adding of an optical disc."""
    if path.startswith('CDROM:\\'):
        # Find the drives that are listed as a CDROM type
        _drives = drives.get()
        cdroms = dict([
            (key, value) for key, value in _drives.iteritems()
            if (
                'type' in value and value['type'] == 'cdrom' or
                'type' not in value
            )
        ])
        cdrom_drive = 'D' # fallback default
        drive_is_found = False

        if len(cdroms):
            # Use the first CDROM drive that has the requested file
            for drive, info in cdroms.iteritems():
                try:
                    debug("CDROM: Trying dir: {0}".format(
                        info['mapping']
                    ))
                    if os.path.exists(
                        wintounix(
                            '{0}:{1}'.format(
                                drive,
                                string_remove_from_start(
                                    path,
                                    'CDROM:'
                                )
                            ),
                        drives_info = cdroms)
                    ):
                        cdrom_drive = drive
                        drive_is_found = True
                        debug("CDROM: Using Wine mapping ({0})".format(
                            cdrom_drive
                        ))
                        break
                except OSError:
                    continue

        if not drive_is_found:
            # Check to see if there is a mounted CD or DVD
            # and use it's path
            mount_point = mount_name = None
            mounted_cds = get_mounted_cds()
            for mount in mounted_cds:
                test_path = wintounix(
                    'D:{0}'.format(
                        string_remove_from_start(
                            path,
                            'CDROM:'
                        )
                ))

                debug("Trying if mounted disc matches:", test_path,
                    {'D': {
                        'mapping': mount['dir']
                    }}
                )
                if os.path.exists(test_path,
                    drives_info = {'D': {
                        'mapping': mount['dir']
                    }}
                ):
                    mount_point = mount['dir']
                    mount_name = filter(len, mount_point.split('/'))[-1]

            if mount_point is None:
                # No CD or DVD found, use the Windows default
                # and hope for the best
                debug("CDROM: Using Windows default ({0})".format(
                    cdrom_drive
                ))
                # the default is defined earlier
            else:
                # We found a mounted CD or DVD
                # Add it as a drive in the configuration
                available_drive_letters = [
                    i for i in string.ascii_uppercase[3:]
                    if i not in _drives.keys()
                ]
                cdrom_drive = available_drive_letters[0]
                debug("Adding drive:", (
                    cdrom_drive,
                    mount_point,
                    mount_name,
                    'cdrom'
                ))
                drives.add(
                    cdrom_drive,
                    mount_point,
                    label = mount_name,
                    drive_type = 'cdrom'
                )
                debug("CDROM: Using mounted drive ({0})".format(
                    mount_point
                ))

        path = '{0}:{1}'.format(
            cdrom_drive,
            string_remove_from_start(path, 'CDROM:')
        )
    return path
Example #6
0
def enhance_windows_path(path):
    """Replace special Vineyard variables in a path with their meaning.
    So far there is only one: CDROM:\\ for automatic finding and/or adding of an optical disc."""
    if path.startswith('CDROM:\\'):
        # Find the drives that are listed as a CDROM type
        _drives = drives.get()
        cdroms = dict([
            (key, value) for key, value in _drives.iteritems()
            if (
                'type' in value and value['type'] == 'cdrom' or
                'type' not in value
            )
        ])
        cdrom_drive = 'D' # fallback default
        drive_is_found = False

        if len(cdroms):
            # Use the first CDROM drive that has the requested file
            for drive, info in cdroms.iteritems():
                try:
                    debug("CDROM: Trying dir: {0}".format(
                        info['mapping']
                    ))
                    if os.path.exists(
                        wintounix(
                            '{0}:{1}'.format(
                                drive,
                                string_remove_from_start(
                                    path,
                                    'CDROM:'
                                )
                            ),
                        drives_info = cdroms)
                    ):
                        cdrom_drive = drive
                        drive_is_found = True
                        debug("CDROM: Using Wine mapping ({0})".format(
                            cdrom_drive
                        ))
                        break
                except OSError:
                    continue

        if not drive_is_found:
            # Check to see if there is a mounted CD or DVD
            # and use it's path
            mount_point = mount_name = None
            mounted_cds = get_mounted_cds()
            for mount in mounted_cds:
                test_path = wintounix(
                    'D:{0}'.format(
                        string_remove_from_start(
                            path,
                            'CDROM:'
                        )
                ))

                debug("Trying if mounted disc matches:", test_path,
                    {'D': {
                        'mapping': mount['dir']
                    }}
                )
                if os.path.exists(test_path,
                    drives_info = {'D': {
                        'mapping': mount['dir']
                    }}
                ):
                    mount_point = mount['dir']
                    mount_name = filter(len, mount_point.split('/'))[-1]

            if mount_point is None:
                # No CD or DVD found, use the Windows default
                # and hope for the best
                debug("CDROM: Using Windows default ({0})".format(
                    cdrom_drive
                ))
                # the default is defined earlier
            else:
                # We found a mounted CD or DVD
                # Add it as a drive in the configuration
                available_drive_letters = [
                    i for i in string.ascii_uppercase[3:]
                    if i not in _drives.keys()
                ]
                cdrom_drive = available_drive_letters[0]
                debug("Adding drive:", (
                    cdrom_drive,
                    mount_point,
                    mount_name,
                    'cdrom'
                ))
                drives.add(
                    cdrom_drive,
                    mount_point,
                    label = mount_name,
                    drive_type = 'cdrom'
                )
                debug("CDROM: Using mounted drive ({0})".format(
                    mount_point
                ))

        path = '{0}:{1}'.format(
            cdrom_drive,
            string_remove_from_start(path, 'CDROM:')
        )
    return path