#!/usr/bin/env python

# GIMP Python plug-in to save all open images with one click.
# Copyright March 2015 Irvine McMinn <irvinemcminn@gmail.com>
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#	Modificado para exportar todo en lugar de guardar todo

from gimpfu import *

import string, os, sys

# Constants
Save_All_help = "Saves all open images with one click.  See 'Installation-and-Usage.txt' for more info"

Save_All_description = Save_All_help

# Functions
def RemoveBadChar(imgName): # 
    # list of commonly reserved char for file names based on http://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
    imgName = imgName.replace("/", "")
    imgName = imgName.replace("\\", "") # \ escaped
    imgName = imgName.replace("?", "")
    imgName = imgName.replace("%", "")
    imgName = imgName.replace("*", "")
    imgName = imgName.replace(":", "")
    imgName = imgName.replace("|", "")
    imgName = imgName.replace('"', "")
    imgName = imgName.replace("'", "")
    imgName = imgName.replace("<", "")
    imgName = imgName.replace(">", "")
    imgName = imgName.replace(" ", "-")
    return imgName


def Add_Extension(indx, imgNme, defltNme):
    if not imgNme:                                                  # null string
        newName = "Untitled" + "-" + str(indx) + ".xcf"
        indx = indx + 1
    elif not "." in imgNme:                                         # 
        newNme = imgNme + "-" + str(indx) + ".xcf"
        indx = indx + 1
    else:
        name, dot, extension = imgNme.partition(".")
        if not name:                                                # only an extension given without name
            newNme = "Untitled" + "-" + str(indx) + ".xcf"
            indx = indx + 1
        else:                                                       # it replace names extension with xcf
            if defltNme:
                newNme = name + "-" + str(indx) + ".xcf"
                indx = indx + 1
            else:
                newNme = name + ".xcf"
    return indx, newNme

def Change_filename_Extension(fileNme):
		 return fileNme
#    path, dot, extension = fileNme.partition(".")
#    newFname = path + ".xcf"
#    return newFname
    
def RemoveImportedTag(imgNme): 
		 return imgNme
#    imgNme, ebdbracket, surplus = imgNme.partition("]")
#    imgNme = imgNme.replace("[", "")
#    imgNme = imgNme +".xcf"
#    return imgNme

def MainEdit(defaultDir, useDirForAll, defaultNme):
    open_images, image_ids = pdb.gimp_image_list()
    index = 1
    oldImage = []
    defaultNme = RemoveBadChar(defaultNme) # If the file already exists with fruitcake char, fine. Otherwise prevent users trying to crash plugin with bad file names
    for n in range(open_images):
        oldImage.append(gimp.image_list()[n])
        drawable = pdb.gimp_image_get_active_drawable(oldImage[n])
        imageName = oldImage[n].name
        fileName = oldImage[n].filename
        if not fileName:      # check for null string, this indicates a preciously unsaved file
            index, imageName = Add_Extension(index, defaultNme, True)
            fileName = os.path.join(defaultDir, imageName)
        elif useDirForAll:
            if "imported" in imageName: 
                imageName = RemoveImportedTag(imageName)
            fileName = os.path.join(defaultDir, imageName)
        elif not ".xcf" in fileName:                                # make sure existing filename has an  xcf extension
            if "imported" in imageName: 
                imageName = RemoveImportedTag(imageName)
            else:
                index, imageName = Add_Extension(index, imageName, False) # catch all fail safe, unlikely to be called
            fileName = Change_filename_Extension(fileName)
        pdb.gimp_file_save(oldImage[n], drawable, fileName, imageName)
        # associate newly saved file with the display image
        newimage = pdb.gimp_file_load( fileName, imageName)
        pdb.gimp_displays_reconnect(oldImage[n], newimage)
        pdb.gimp_image_clean_all(newimage)
    pdb.gimp_message ("Success. saved all open images")
    return

############################################################################

def GetOsDocs():
    OsPath = os.path.expanduser('~')
    if sys.platform.startswith('win'):
        OsPath = os.path.join(OsPath, "My Documents", "My Pictures")
    else:
        OsPath = os.path.join(OsPath, "temp")
    return OsPath
    
register (
    "SaveAll",                                                              # Name registered in Procedure Browser
    Save_All_description,
    Save_All_help,
    "Irvine",                                                               # Author Copyright Holder
    "GPL",                                                                  # Copyright
    "March 2015",                                                           # Date
    "Save All",                                                             # Menu Entry
    "*",                                                                    # Image required
    [
    (PF_DIRNAME, "trgDir", "Directory for previously unsaved files?", GetOsDocs()),
    (PF_BOOL,   "useDir", "Use above directory for all files", False),
    (PF_STRING, "trgNme", "Base name for previously unsaved files?", "Untitled" ),
    ],
    [],
    MainEdit,                                                               # Matches to name of function being defined
    menu = "<Image>/File/Save"                                              # Menu Location
    )                                                                       # End register

main()
