from JascApp import *

import os
import _winreg


def ScriptProperties():
    return {
        'Author': u'Jasc Software, Inc.',
        'Copyright': u'Copyright (c) 2004 Jasc Software, Inc.  All rights reserved.',
        'Description': "Add PSP8 File locations to PSP9.",
        'Host': u'Paint Shop Pro 9',
        'Host Version': u'9.00',
        'ForceTextEditor': App.Constants.Boolean.true
        }

# Begin Translatable Strings
NoPSP8FoldersFound = "No PSP8 folders found."
FilesHaveBeenAdded = "Files in \"%s\" have been added to the File Locations preferences."
Brushes = "Brushes"
BumpMaps = "Bump Maps"
DeformationMaps = "Deformation Maps"
DisplacementMaps = "Displacement Maps"
EnvironmentMaps = "Environment Maps"
Gradients = "Gradients"
Masks = "Masks"
Palettes = "Palettes"
Patterns = "Patterns"
PictureFrames = "Picture Frames"
PictureTubes = "Picture Tubes"
PresetShapes = "Preset Shapes"
Presets = "Presets"
PrintTemplates = "Print Templates"
QuickGuides = "Quick Guides"
SampleImages = "Sample Images"
ScriptsRestricted = "Scripts-Restricted"
ScriptsTrusted = "Scripts-Trusted"
Selections = "Selections"
StyledLines = "Styled Lines"
Swatches = "Swatches"
Textures = "Textures"
# End Translatable Strings

SilentAlways = {
    'ExecutionMode': App.Constants.ExecutionMode.Silent,
    'AutoActionMode': App.Constants.AutoActionMode.AllAlways,
    'Version': ((9,0,0),1)
    }

def Do(Environment):
    try:
        hKey = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software\\Jasc\\Global")
        MyPSP8FileRoot, datatype = _winreg.QueryValueEx(hKey, "PSP8DefaultWrite")
        assert(datatype == _winreg.REG_SZ)
        _winreg.CloseKey(hKey)

        if not (os.path.exists(MyPSP8FileRoot) and os.path.isdir(MyPSP8FileRoot)):
            raise Exception
    except:
        App.Do(Environment, 'MsgBox', {
            'Text': NoPSP8FoldersFound,
            'Icon': App.Constants.MsgIcons.Stop,
            'Buttons': App.Constants.MsgButtons.OK,
            'GeneralSettings': {'Version': ((9,0,0),1) }
            })
        return

    # A listing of known PSP8 folders, along with optional mappings
    # if the key name is different than the folder name
    PSP8Folders = [
        Brushes,
        BumpMaps,
        DeformationMaps,
        EnvironmentMaps,
        Gradients,
        Masks,
        Palettes,
        Patterns,
        PictureFrames,
        PictureTubes,
        PresetShapes,
        Presets,
        PrintTemplates,
        QuickGuides,
        SampleImages,
        ScriptsRestricted,
        ScriptsTrusted,
        Selections,
        StyledLines,
        Swatches,
        Textures,
        ]

    # Pull the current PSP9 file locations from the registry
    PSP9FileLocations = FetchPSP9FileLocationsFromRegistry()

    for folder in PSP8Folders:
        path = os.path.join(MyPSP8FileRoot, folder)
        if os.path.exists(path) and os.path.isdir(path):
            scriptkey = TranslateFolderToScript(folder)
            Dict = PSP9FileLocations[scriptkey]
            if not Dict is None:
                AppendFolderToList(Dict['Folders'], path, 0, ShouldFileLocationHaveRecursiveFlag(scriptkey))

    # Special case for textures
    path = os.path.join(MyPSP8FileRoot, Textures)
    if os.path.exists(path) and os.path.isdir(path):
        AppendFolderToList(PSP9FileLocations['DisplacementMaps']['Folders'], path, 0, 1)

    App.Do(Environment, 'FileLocations', {
            'Locations': PSP9FileLocations,
            'GeneralSettings': SilentAlways,
            })

    App.Do(Environment, 'MsgBox', {
        'Text': FilesHaveBeenAdded % MyPSP8FileRoot,
        'Icon': App.Constants.MsgIcons.Info,
        'Buttons': App.Constants.MsgButtons.OK,
        'GeneralSettings': {'Version': ((9,0,0),1) }
        })


# It'd be convenient to simply use the ReturnFileLocations script command to get
# the file locations, but we need to be able to get the flags associated
# with each item, which can only be gotten from the registry
def FetchPSP9FileLocationsFromRegistry():
    # The "None" items are ones we don't want to query -- we can't port anything over from PSP8
    PSP9FileLocations = {
        'Browsers': None,
        'Brushes': {},
        'BumpMaps': {},
        'Cache': None,
        'Categories': None,
        'CMYKProfiles': None,
        'DeformationMaps': {},
        'DisplacementMaps': {},
        'EnvironmentMaps': {},
        'Frames': {},
        'Gradients': {},
        'Masks': {},
        'MixerPages': None,
        'Palettes': {},
        'Patterns': {},
        'Plugins': None,
        'PostscriptResources': None,
        'Presets': {},
        'PrintTemplates': {},
        'PythonLibraries': None,
        'PythonSourceEditor': None,
        'QuickGuides': {},
        'RestrictedScripts': {},
        'SampleImages': {},
        'Selections': {},
        'Shapes': {},
        'StyledLines': {},
        'Swatches': {},
        'Textures': {},
        'TrustedScripts': {},
        'Tubes': {},
        'UndoTemp': None,
        'Workspaces': None,
    }

    for scriptkey in PSP9FileLocations.keys():
        if not PSP9FileLocations[scriptkey] is None:
            try:
                subkey = TranslateScriptToRegistry(scriptkey)
                hKey = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software\\Jasc\\Paint Shop Pro 9\\FileLocations\\" + subkey, 0, _winreg.KEY_READ)
                
                Count, datatype = _winreg.QueryValueEx(hKey, "Count")
                assert(datatype == _winreg.REG_DWORD)

                SaveFolderIndex, datatype = _winreg.QueryValueEx(hKey, "DirIndex")
                assert(datatype == _winreg.REG_DWORD)

                PSP9FileLocations[scriptkey]['SaveFolderIndex'] = SaveFolderIndex

                Folders = []
                for i in range(Count):
                    hKeyFolder = _winreg.OpenKey(hKey, str(i))
                    Dir, datatype = _winreg.QueryValueEx(hKeyFolder, "Dir")
                    assert(datatype == _winreg.REG_SZ)

                    Flag, datatype = _winreg.QueryValueEx(hKeyFolder, "Flag")
                    assert(datatype == _winreg.REG_DWORD)

                    _winreg.CloseKey(hKeyFolder)

                    # QuickGuides is special -- it shouldn't have a second flag parameter in the tuple
                    AppendFolderToList(Folders, Dir, Flag, ShouldFileLocationHaveRecursiveFlag(scriptkey))

                PSP9FileLocations[scriptkey]['Folders'] = Folders                
            
                _winreg.CloseKey(hKey)
            except:
                # Something went wrong -- blank out this entry, so we don't damage preferences
                PSP9FileLocations[scriptkey] = None

    return PSP9FileLocations                

def AppendFolderToList(List, Folder, Flag, IncludeRecursiveFlag):
    # If the folder is already in the list, don't add it again.
    for item in List:
        if item[0] == Folder:
            return

    Tuple = ()    
    if IncludeRecursiveFlag:
        Tuple = (unicode(Folder), ((Flag & 0x02) == 0), ((Flag & 0x04) == 0))
    else:
        Tuple = (unicode(Folder), ((Flag & 0x02) == 0))
        
    List.append(Tuple)

def ShouldFileLocationHaveRecursiveFlag(scriptkey):
    OmitRecursiveFlag = ["QuickGuides", "SampleImages"]

    return not scriptkey in OmitRecursiveFlag

def TranslateScriptToRegistry(key):
    # This dictionary maps from FileLocations script strings to registry strings
    # 'Script' : 'Registry'
    MapScriptToRegistry = {
        'BumpMaps': 'Bump Maps',
        'DeformationMaps': 'Deformation Maps',
        'DisplacementMaps': 'Displacement Maps',
        'EnvironmentMaps': 'Environment Maps',
        'Plugins': 'PlugIns',
        'PrintTemplates': 'Print Templates',
        'QuickGuides': 'Quick Guides',
        'SampleImages': 'Sample Images',
        'StyledLines': 'Styled Lines',
        }

    if key in MapScriptToRegistry:
        return MapScriptToRegistry[key]

    return key    

def TranslateFolderToScript(key):
    MapFolderToScript = {
        BumpMaps : "BumpMaps",
        DeformationMaps : "DeformationMaps",
        DisplacementMaps : "DisplacementMaps",
        EnvironmentMaps : "EnvironmentMaps",
        PictureFrames : "Frames",
        PictureTubes : "Tubes",
        PresetShapes : "Shapes",
        PrintTemplates : "PrintTemplates",
        QuickGuides : "QuickGuides",
        SampleImages : "SampleImages",
        ScriptsRestricted : "RestrictedScripts",
        ScriptsTrusted : "TrustedScripts",
        StyledLines : "StyledLines",
        }

    if key in MapFolderToScript:
        return MapFolderToScript[key]

    return key
