from PSPApp import *

# Copyright 2005 Corel Software Inc., all rights reserved
# This file contains utility routines provided by Corel Software.
#
#   JascUtils.py - Obsolete - Please use PSPUtils.py
#
#   Utility functions

ScriptData = {}

# Begin Translatable Strings
SelectionLayer = "Selection promoted via script"
Pattern = "Pattern"
Inline = "Inline"
Gradient = "Gradient"
Linear = "Linear"
Radial = "Radial"
Rectangular = "Rectangular"
Sunburst = "Sunburst"
Solid = "Solid"
Null = "Null"
Art = "Art"
RequiresOpenImage = "This script requires an open image."
# End Translatable Strings

class SaveSelection:
    ''' define a helper class that can save any active selection to the alpha
        channel and restore it later
    '''
    def __init__( self, Environment, Doc ):
        ''' at init time we save the environment variable provided by PSP,
            and if a selection exists we save it to an alpha channel
        '''
        self.Env = Environment
        self.SavedSelection =  '__$TempSavedSelection$__'
        self.IsSaved = 0
        self.SavedOnDoc = Doc
        
        SelResult = App.Do( self.Env, 'GetRasterSelectionRect' )
        if SelResult[ 'Type' ] != App.Constants.SelectionType.None:
            # if there is a selection save it to the alpha channel
            App.Do( self.Env, 'SelectSaveDisk', {
                'FileName': self.SavedSelection, 
                'Overwrite': App.Constants.Boolean.true, 
                'GeneralSettings': {
                    'ExecutionMode': App.Constants.ExecutionMode.Silent, 
                    'AutoActionMode': App.Constants.AutoActionMode.Match
                    }
                }, Doc)
            self.IsSaved = 1    # set this so we know we saved one
            
            if SelResult[ 'Type' ] == App.Constants.SelectionType.Floating:
                # if the selection is floating promote it to a layer
                App.Do( self.Env, 'SelectPromote', {
                        'KeepSelection': App.Constants.Boolean.false, 
                        'LayerName': SelectionLayer, 
                        'GeneralSettings': {
                            'ExecutionMode': App.Constants.ExecutionMode.Silent, 
                            'AutoActionMode': App.Constants.AutoActionMode.Match
                            }
                        }, Doc)
            else:
                App.Do( self.Env, 'SelectNone' )
           
            
    def RestoreSelection( self ):
        ''' if we have saved a selection, restore it now.  If we promoted
            a floating selection to a layer we don't restore the selection
            but don't attempt to mess with the layer in any way
        '''
        if self.IsSaved == 1:
            # load the selection back from disk - this will replace any existing selection
            App.Do( self.Env, 'SelectLoadDisk', {
                    'FileName': self.SavedSelection, 
                    'Operation': App.Constants.SelectionOperation.Replace, 
                    'UpperLeft': App.Constants.Boolean.false, 
                    'ClipToCanvas': App.Constants.Boolean.false, 
                    'GreyMethod': App.Constants.CreateMaskFrom.Luminance, 
                    'Invert': App.Constants.Boolean.false, 
                    'GeneralSettings': {
                        'ExecutionMode': App.Constants.ExecutionMode.Silent, 
                        'AutoActionMode': App.Constants.AutoActionMode.Match
                        }
                    }, self.SavedOnDoc)

    # end class SaveSelection

def NameFromMaterial( Material, Delimiter=' ', IncludeTexture=1 ):
    ''' Given a material repository, return a name that describes it.
        By default the name is delimited with space, but the delimiter
        parameter can be used to override it.
        By default textures are included in the name, but can be omitted
        by setting the IncludeTexture parameter to 0
    '''
    TextureName = None
    TypeName = ''
    if Material is None:
        CoreName = Null
    else:
        if Material[ 'Pattern' ] and \
           (Material[ 'Pattern' ][ 'Name' ] or Material[ 'Pattern' ][ 'Image' ] ):
            TypeName = Pattern
            if Material[ 'Pattern' ][ 'Name' ]:
                CoreName = Material[ 'Pattern'  ][ 'Name' ]
            else:
                CoreName = Inline
        elif Material[ 'Gradient' ] and Material[ 'Gradient' ][ 'Name' ]:
            TypeName = Gradient
            GradType = {}
            GradType[ App.Constants.GradientType.Linear ] = Linear
            GradType[ App.Constants.GradientType.Rectangular ] = Rectangular
            GradType[ App.Constants.GradientType.Radial ] = Radial
            GradType[ App.Constants.GradientType.Angular ] = Sunburst
            
            CoreName = '%s%s%s' % ( Material[ 'Gradient' ][ 'Name' ], Delimiter, 
                                    GradType[ Material[ 'Gradient' ][ 'GradientType' ] ] )
        elif Material[ 'Art' ]:
            TypeName = Art
            CoreName = '%02x%02x%02x' % Material[ 'Art' ][ 'Color' ]
        else:
            TypeName = Solid
            CoreName = '%02x%02x%02x' % Material[ 'Color' ]

        if Material[ 'Texture' ] and Material[ 'Texture' ][ 'Name' ]:
            TextureName = Material[ 'Texture' ]['Name']

    if TextureName is not None and IncludeTexture != 0:
        MaterialName = '%s%s%s%s%s' % ( TypeName, Delimiter, CoreName, Delimiter, TextureName )
    else:
        MaterialName = '%s%s%s' % ( TypeName, Delimiter, CoreName )

    return MaterialName

def IsNullMaterial( Material ):
    ' check if the passed in material is none.  Returns true if null, false if non-null'
    if Material is None:    
        return App.Constants.Boolean.true   # material might be entirely none

    ArtIsNone = 0
    ColorIsNone = 0
    GradientIsNone = 0
    PatternIsNone = 0
    
    if Material['Color'] is None:
        ColorIsNone = 1

    if Material['Gradient'] is None or Material['Gradient']['Name'] is None:
        GradientIsNone = 1

    if Material['Pattern'] is None or \
       (Material['Pattern']['Name'] is None and Material['Pattern']['Image'] is None):
        PatternIsNone = 1

    if Material['Art'] is None:
        ArtIsNone = 1

    if ColorIsNone and GradientIsNone and PatternIsNone and ArtIsNone:
        return App.Constants.Boolean.true   #it works out to none
    else:
        return App.Constants.Boolean.false


def IsFlatImage( Environment, Doc ):
    'Determine if Doc consists of a single background layer.  True if flat, false if not'
    ImageInfo = App.Do( Environment, 'ReturnImageInfo', {}, Doc )
    LayerInfo = App.Do( Environment, 'ReturnLayerProperties', {}, Doc )

    if ImageInfo[ 'LayerNum' ] == 1 and LayerInfo[ 'IsBackground' ] == App.Constants.Boolean.true:
        return App.Constants.Boolean.true
    else:
        return App.Constants.Boolean.false

def IsPaletted( Environment, Doc ):
    '''Determine if the current image is paletted.  Greyscale is not counted as paletted
       Returns true on paletted, false if not
    '''
    # these are all the paletted pixel formats
    TargetFormats = [ App.Constants.PixelFormat.Index1, App.Constants.PixelFormat.Index4,
                      App.Constants.PixelFormat.Index8 ]
    
    # are we paletted?
    Info = App.Do( Environment, 'ReturnImageInfo', {}, Doc )

    if Info['PixelFormat'] in TargetFormats:
        return App.Constants.Boolean.true
    else:
        return App.Constants.Boolean.false

def IsTrueColor( Environment, Doc ):
    ''' Determine if the current image is true color.  Greyscale does not count
        Returns true for true color, false for all others
    '''
    TargetFormats = [ App.Constants.PixelFormat.BGR, App.Constants.PixelFormat.BGRA ]
    
    # are we true color?
    Info = App.Do( Environment, 'ReturnImageInfo', {}, Doc )
    if Info['PixelFormat'] in TargetFormats:
        return App.Constants.Boolean.true
    else:
        return App.Constants.Boolean.false

def IsGreyScale( Environment, Doc ):
    ' Determine if the current image (not layer) is greyscale. True if it is, false otherwise'
    TargetFormats = [ App.Constants.PixelFormat.Grey, App.Constants.PixelFormat.GreyA ]
    
    # are we true color?
    Info = App.Do( Environment, 'ReturnImageInfo', {}, Doc )
    if Info['PixelFormat'] in TargetFormats:
        return App.Constants.Boolean.true
    else:
        return App.Constants.Boolean.false

def LayerIsArtMedia( Environment, Doc ):
    'Returns true if the current layer is a artmedia layer'
    LayerInfo = App.Do( Environment, 'ReturnLayerProperties', {}, Doc )
    if LayerInfo[ 'LayerType' ] == App.Constants.LayerType.ArtMedia:
        return App.Constants.Boolean.true
    else:
        return App.Constants.Boolean.false

def LayerIsRaster( Environment, Doc ):
    'Returns true if the current layer is a raster layer'
    LayerInfo = App.Do( Environment, 'ReturnLayerProperties', {}, Doc )
    if LayerInfo[ 'LayerType' ] == App.Constants.LayerType.Raster:
        return App.Constants.Boolean.true
    else:
        return App.Constants.Boolean.false


def LayerIsVector( Environment, Doc ):
    'Returns true if the current layer is a vector layer'
    LayerInfo = App.Do( Environment, 'ReturnLayerProperties', {}, Doc )
    if LayerInfo[ 'LayerType' ] == App.Constants.LayerType.Vector:
        return App.Constants.Boolean.true
    else:
        return App.Constants.Boolean.false

def LayerIsBackground( Environment, Doc ):
    'Returns true if the current layer is the background layer'
    LayerInfo = App.Do( Environment, 'ReturnLayerProperties', {}, Doc )
    return LayerInfo[ 'IsBackground' ]
    

def GetLayerCount( Environment, Doc ):
    'Returns number of layers in Doc'
    ImageInfo = App.Do( Environment, 'ReturnImageInfo', {}, Doc )
    return ImageInfo[ 'LayerNum' ]    

def GetCurrentLayerName( Environment, Doc ):
    'Returns the name of the current layer in Doc'
    LayerInfo = App.Do( Environment, 'ReturnLayerProperties', {}, Doc )
    return LayerInfo[ 'General' ][ 'Name' ]

def PromoteToTrueColor( Environment, Doc ):
    'If the current image type is paletted, promote it to true color.  Greyscale is left alone'
    if IsPaletted( Environment, Doc ):
        App.Do( Environment, 'IncreaseColorsTo16Million', {}, Doc )
    return

def RequireADoc( Environment ):
    '''Test that we actually have a target document, and put up a message box if we dont
       Returns true if we have an open doc, false otherwise
    '''
    if App.TargetDocument is None:
        App.Do( Environment, 'MsgBox', {
                'Buttons': App.Constants.MsgButtons.OK, 
                'Icon': App.Constants.MsgIcons.Stop, 
                'Text': RequiresOpenImage, 
                })
        return App.Constants.Boolean.false
    else:
        return App.Constants.Boolean.true

    
        
 