from JascApp import *
import JascUtils
from Tkinter import *
import tkMessageBox

def ScriptProperties():
    return {
        'Author': u'Jasc Software, Inc.',
        'Copyright': u'Copyright (c) 2002-2004 Jasc Software, Inc.  All rights reserved.',
        'Description': "Prompt for the number of cells in an image, and set the grid to match",
        'Host': u'Paint Shop Pro',
        'Host Version': u'8.00'
        }

# Begin Translatable Strings
DefineCells = "Define Cells"
NumberOfCells = "Enter the number of cells to have in the grid.\nThe default gridline color will be used."
CellsAcross = "Cells across:"
CellsDown = "Cells down:"
OKText = "OK"
CancelText = "Cancel"
CellsAcrossInvalid = "Cells across invalid"
CellsAcrossCondition = "Cells across must be between 1 and %d"
CellsDownInvalid = "Cells down invalid"
CellsDownCondition = "Cells down must be between 1 and %d"
CancelAborting = "Cancel pressed - aborting"
SettingGrid = "Setting grid for %d horizontally, %d vertically"
EnterCells = "Enter Cells"
# End Translatable Strings

class CellCountDlg(Frame):
    ''' define the dialog used to prompt the user for the number of cells'''
    def __init__( self, parent, title ):
        Frame.__init__(self, parent)    # init our parent

        # if we exit with OK this will be set to 1.  A zero means we pressed cancel
        self.OKPressed = 0
        
        # define all the variables attached to the controls
        self.GridLinesX = IntVar()
        self.GridLinesX.set( 3 )

        self.GridLinesY = IntVar()
        self.GridLinesY.set( 3 )
        
        # define the basics of the window
        self.pack(expand=YES, fill=BOTH)
        self.master.title(DefineCells)
       
        # put some explanatory text on the window
        Label( self, text = NumberOfCells,
               justify=LEFT ).pack(expand=YES, fill=BOTH, side=TOP)

        # make a subframe to hold the cells across controls
        XFrame = Frame( self )
        XLabel = Label( XFrame, text=CellsAcross, width=30 )
        XLabel.pack( expand=YES, fill=BOTH, side=LEFT )
        self.XEntry = Entry( XFrame, textvariable=self.GridLinesX )
        self.XEntry.pack( expand=YES, fill=BOTH, side=RIGHT )
        XFrame.pack(side=TOP)
        
        # do the same thing for the cells down controls
        YFrame = Frame( self )
        YLabel = Label( YFrame, text=CellsDown, width=30 )
        YLabel.pack( expand=YES, fill=BOTH, side=LEFT )
        self.YEntry = Entry( YFrame, textvariable=self.GridLinesY )
        self.YEntry.pack( expand=YES, fill=BOTH, side=RIGHT )
        YFrame.pack(side=TOP)
        
        # put OK/Cancel buttons on the dialog - parts of this lifted from TkSimpleDialog
        ButtonFrame = Frame(self)
        OKButton = Button( ButtonFrame, text=OKText, width=10,
                           command=self.OnOK, default=ACTIVE )
        OKButton.pack(side=LEFT, padx=5, pady=5)
        CancelButton = Button( ButtonFrame, text=CancelText, width=10,
                               command=self.OnCancel )
        CancelButton.pack(side=LEFT, padx=5, pady=5)
        ButtonFrame.pack()
        
        self.bind('<Return>', self.OnOK)
        self.bind('<Escape>', self.OnCancel)
       

    def OnOK(self, event=None):
        ''' called by pressing the OK button - validates data, and if no error
            sets a good return code and dismisses the dialog by calling OnCancel
        '''
        try:
            X = self.GridLinesX.get()
        except ValueError:
            X = 0

        try:            
            Y = self.GridLinesY.get()
        except ValueError:
            Y = 0
        
        if X < 1 or X > App.TargetDocument.Width - 1:
            App.Do( GlobalEnv, 'StartForeignWindow', { 'WindowHandle': 0 } )
            tkMessageBox.showerror( CellsAcrossInvalid,
                                    CellsAcrossCondition % (App.TargetDocument.Width - 1) )
            App.Do( GlobalEnv, 'StartForeignWindow', { 'WindowHandle': int(self.winfo_id()) } )
            return 
        if Y < 1 or Y > App.TargetDocument.Height - 1:
            App.Do( GlobalEnv, 'StartForeignWindow', { 'WindowHandle': 0 } )
            tkMessageBox.showerror( CellsDownInvalid,
                                    CellsDownCondition % (App.TargetDocument.Height - 1) )
            App.Do( GlobalEnv, 'StartForeignWindow', { 'WindowHandle': int(self.winfo_id()) } )
            return 

        # if we got here we passed validation
        self.OKPressed = 1
        
        # finish by pressing the Cancel button
        self.OnCancel()

    def OnCancel(self, event=None):
        # on cancel we simply terminate the message loop
        self.quit()


def Do(Environment):
    global GlobalEnv
    GlobalEnv = Environment
    if JascUtils.RequireADoc( Environment ) == App.Constants.Boolean.false:
        return
    
    # create the root TK window    
    root = Tk()
    
    # create the dialog and show the dialog
    Dlg = CellCountDlg( root, EnterCells)
    
    # tell PSP that a foreign dialog is running.  This causes PSP to do some additional
    # work to keep the UI updating properly and to prevent the script window from going
    # behind PSP.
    App.Do( Environment, 'StartForeignWindow', { 'WindowHandle': int(root.winfo_id()) } )
   
    root.mainloop()
    App.Do( Environment, 'StartForeignWindow', { 'WindowHandle': 0 } )
    root.destroy()
    
    
    # if the user pressed cancel in the dialog just return
    if not Dlg.OKPressed:
        print CancelAborting
        return

    # get the number of cells to use    
    CellsAcross = Dlg.GridLinesX.get()
    CellsDown = Dlg.GridLinesY.get()

    # now divide those into the height and width to get the of the grid -
    # any errors will accumulate on the right and bottom sides
    GridSpacingX = App.TargetDocument.Width / CellsAcross
    GridSpacingY = App.TargetDocument.Height / CellsDown
    
    print SettingGrid % ( GridSpacingX, GridSpacingY)
    App.Do( Environment, 'GridGuideSnapProperties', {
            'CurrentHorzGridSpacing': GridSpacingX, 
            'CurrentVertGridSpacing': GridSpacingY, 
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Silent, 
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            })

    # turn on the grid
    App.Do( Environment, 'ShowGrid', {
            'ShowGrid': App.Constants.ShowCommands.Show, 
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Default, 
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            })

