#!/bin/sh
#
############################################################################
#
# MODULE:	d.out.file for GRASS 6 (2005/9/3; 2007/5/14)
# AUTHOR(S):	Michael Barton and Hamish Bowman
#		  Original routine to read current display geometry
#		  written by Hamish Bowman & Glynn Clements
# PURPOSE:	To redraw current displayed maps to graphics file output
# COPYRIGHT:	(C) 2005-2007 by the GRASS Development Team
#
#		This program is free software under the GNU General Public
#		License (>=v2). Read the file COPYING that comes with GRASS
#		for details.
#
#############################################################################

#%Module
#%  description: Saves the contents of the active display monitor to a graphics file.
#%  keywords: display, export
#%End
#%option
#% key: output
#% type: string
#% description: Name for output file (do NOT add extension)
#% gisprompt: new_file,file,output
#% required : yes
#%end
#%option
#% key: format
#% type: string
#% options: png,ppm,tif,geotiff,jpg,bmp,ps,eps,svg,pdf
#% answer: png
#% description: Graphics file format
#% required : yes
#%end
#%option
#% key: resolution
#% type: integer
#% answer: 1
#% label: Dimensions of output file versus current window size
#% description: (same=1, double size=2, quadruple size=4)
#% guisection: Images
#% required : no
#%end
#%option
#% key: size
#% type: integer
#% key_desc: width,height
#% description: Width and height of output image (overrides resolution setting)
#% guisection: Images
#% required : no
#%end
#%option
#% key: compression
#% type: integer
#% options: 0-9
#% answer: 9
#% label: Compression for PNG files
#% description: (0=none, 1=fastest, 9=most; lossless, only time vs. filesize)
#% required : no
#% guisection: Images
#%end
#%option
#% key: quality
#% type: integer
#% answer: 75
#% options: 10-100
#% label: File size/quality for JPEG files
#% description: (10=smallest/worst, 100=largest/best)
#### 10 is hardcoded as smallest value in gdal/frmts/jpeg/jpgdataset.cpp. why not 0?
#% required : no
#% guisection: Images
#%end
#%option
#% key: paper
#% type: string
#% answer: a4
#% description: Paper size for PostScript output
#% options: a4,a3,a2,a1,a0,us-letter,us-legal,us-tabloid
#### Sizes from lib/psdriver/Graph_set.c
#% guisection: PostScript
#% required : no
#%end
#### margin setting not currently allowed in PS driver
## #%option
## #% key: margins
## #% type: integer
## #% key_desc: bottom,top,left,right
## #% description: Margins (in points) for PostScript output
## #% guisection: PostScript
## #% required : no
## #%end
#%option
#% key: ps_level
#% type: integer
#% options: 1-3
#% answer: 2
#% description: PostScript level (only limits functionality!)
#% guisection: PostScript
#% required : no
#% end
#%option
#% key: createopt
#% type: string
#% label: GeoTIFF creation option(s)
#% description: In the form of "NAME=VALUE", separate multiple entries with a comma.
#% guisection: GeoTIFF
#% required : no
#%end
#%option
#% key: metaopt
#% type: string
#% label: GeoTIFF metadata key(s) and value(s) to add
#% description: In the form of "META-TAG=VALUE", separate multiple entries with a comma.
#% guisection: GeoTIFF
#% required : no
#%end
#%flag
#% key: b
#% description: Set background color to black (white default)
#% end
#%flag
#% key: t
#% description: Set transparent background
#% guisection: Images
#% end
#%flag
#% key: c
#% description: Use the Cario driver to render images
#% guisection: Images
#% end
#%flag
#% key: r
#% description: Set paper orientation to landscape (for PostScript output)
#% guisection: PostScript
#%end
#%flag
#% key: m
#% description: Do not crop away margins
#% guisection: GeoTIFF
#%end


if  [ -z "$GISBASE" ] ; then
   echo "You must be in GRASS GIS to run this program." 1>&2
   exit 1
fi

if [ "$1" != "@ARGS_PARSED@" ] ; then
   exec g.parser "$0" "$@"
fi

#### set environment so that awk works properly in all languages
unset LC_ALL
LC_NUMERIC=C
export LC_NUMERIC


#### Check the current status of the monitor
monitorcheck1="`d.mon -p | grep -v "No monitor currently selected"`"
if [ -z "$monitorcheck1" ] ; then
   g.message -e "You must select a display monitor."
   exit 1
fi

curr_mon="`d.mon -p | cut -f2 -d: | awk '{print $1}'`"

monitorcheck2="`d.mon -L | grep "^$curr_mon" | grep -v "not running"`"
if [ -z "$monitorcheck2" ] ; then
   g.message -e "Selected display monitor not running."
   exit 1
fi

if [ `echo "$curr_mon" | grep -c '^x.$'` -ne 1 ] ; then
   g.message -e "Only X monitors are supported."
   exit 1
fi

case "$GIS_OPT_FORMAT" in
   pdf | svg)
     if [ $GIS_FLAG_C -eq 0 ] ; then
	g.message "Using the Cairo driver."
	GIS_FLAG_C=1
     fi
     ;;
esac

if [ $GIS_FLAG_C -eq 1 ] &&  [ `d.mon -l | grep -c '^cairo'` -eq 0 ] ; then
   g.message -e "Cairo driver not present in this build of GRASS."
   exit 1
fi


#### set variables
res="$GIS_OPT_RESOLUTION"

if [ -z "$GRASS_VERBOSE" ] || [ "$GRASS_VERBOSE" -le 2 ] ; then
  BEQUIET="--quiet"
else
  BEQUIET=""
fi

#capture current display monitor and geometry
# identify current monitor
currmon="`d.mon -L | grep "(selected)" | awk '{print $1}'`"
curr_width="`d.info -d | cut -f2 -d' '`"
curr_height="`d.info -d | cut -f3 -d' '`"

if [ -z "$GIS_OPT_SIZE" ] ; then
   #set dimension multiplier
   out_width="`expr $res \* $curr_width`"
   out_height="`expr $res \* $curr_height`"
else
   out_width="`echo $GIS_OPT_SIZE | cut -f1 -d,`"
   out_height="`echo $GIS_OPT_SIZE | cut -f2 -d,`"
fi

#set output geometry
GRASS_WIDTH="$out_width"
export GRASS_WIDTH
GRASS_HEIGHT="$out_height"
export GRASS_HEIGHT


#set other output options
if [ "$GIS_FLAG_B" -eq 1 ] ; then
    GRASS_BACKGROUNDCOLOR=000000
else
    GRASS_BACKGROUNDCOLOR=FFFFFF
fi
export GRASS_BACKGROUNDCOLOR

if [ "$GIS_FLAG_T" -eq 1 ] ; then
    GRASS_TRANSPARENT=TRUE
else
    GRASS_TRANSPARENT=FALSE
fi
export GRASS_TRANSPARENT


#set output file name and format
case "$GIS_OPT_FORMAT" in
   png | ppm | ps | eps | svg | pdf)
     output="${GIS_OPT_OUTPUT}.${GIS_OPT_FORMAT}"
     ;;
   tif | geotiff | jpg)
     output="`g.tempfile pid=$$`.ppm"
     ;;
   bmp)
     if [ $GIS_FLAG_C -eq 1 ] ; then
	output="${GIS_OPT_OUTPUT}.${GIS_OPT_FORMAT}"
     else
	output="`g.tempfile pid=$$`.ppm"
     fi
     ;;
esac

if [ "$GIS_OPT_FORMAT" = "geotiff" ] ; then
    outname="${GIS_OPT_OUTPUT}.tif"
else
    outname="${GIS_OPT_OUTPUT}.${GIS_OPT_FORMAT}"
fi


#is there a simpler way of testing for --overwrite?
if [ -e "$outname" ] ; then
   if [ -z "$GRASS_OVERWRITE" ] || [ "$GRASS_OVERWRITE" -ne 1 ] ; then
      g.message -e "File <$outname> already exists"
      exit 1
   fi
fi


if [ "$GIS_OPT_FORMAT" = "ps" ] || [ "$GIS_OPT_FORMAT" = "eps" ] ; then
    if [ $GIS_FLAG_C -eq 1 ] ; then
	if [ $GIS_FLAG_R -eq 1 ] ; then
	   g.message -w "Cairo driver doesn't know how to do landscape mode"
	fi
	if [ "$GIS_OPT_FORMAT" = "eps" ] ; then
	   g.message -e "Cairo driver doesn't support EPS"
	   exit 1
	fi
    fi

    if [ $GIS_FLAG_C -eq 0 ] ; then
	GRAPHICS_DRIVER=PS
	GRASS_PSFILE="$output"
	export GRASS_PSFILE
    else
	GRAPHICS_DRIVER=cairo
	GRASS_CAIROFILE="$output"
	export GRASS_CAIROFILE
    fi

    if [ "$GIS_OPT_FORMAT" = "ps" ] ; then
	GRASS_PAPER="$GIS_OPT_PAPER"
	export GRASS_PAPER
    else
	unset GRASS_PAPER
	if [ `d.save -a | grep '^d.frame' | grep -c -v full_screen` -gt 0 ] ; then
	    g.message -w 'Encapsulated PostScript and mutil-frame displays do not mix!'
	fi
    fi

    if [ "$GIS_OPT_PS_LEVEL" -lt 2 ] ; then
	GRASS_TRUECOLOR=FALSE
    else
	GRASS_TRUECOLOR=TRUE
    fi
    export GRASS_TRUECOLOR

    if [ "$GIS_FLAG_R" -eq 1 ] ; then
	GRASS_LANDSCAPE=TRUE
	export GRASS_LANDSCAPE
    else
	unset GRASS_LANDSCAPE
    fi

else
    if [ $GIS_FLAG_C -eq 0 ] ; then
	GRAPHICS_DRIVER=PNG
	GRASS_PNGFILE="$output"
	export GRASS_PNGFILE
    else
	GRAPHICS_DRIVER=cairo
	GRASS_CAIROFILE="$output"
	export GRASS_CAIROFILE
    fi

    #make sure that output is 24 bit color
    GRASS_TRUECOLOR=TRUE
    export GRASS_TRUECOLOR

    GRASS_PNG_COMPRESSION="$GIS_OPT_COMPRESSION"
    export GRASS_PNG_COMPRESSION
fi


g.message "Saving display from Monitor: [$curr_mon] to <$outname>."
# what does the Cairo/PS driver do?
if [ "$GIS_OPT_FORMAT" != "ps" ] ; then
    g.message "Image size [$out_width x $out_height]"
else
    g.message "Image size [$GRASS_PAPER]"
fi

################################
#export display to PNG/PS driver

if [ "$GIS_FLAG_T" -eq 1 ] ; then
   # skip flood filling of background
   dsave=`d.save -a | grep -v '^d.erase'`
else
   dsave=`d.save -a`
fi

d.mon start=$GRAPHICS_DRIVER $BEQUIET
  # 'd.info -b' for white band removal
  BOX=`d.info -b | cut -f2 -d':'`
  # 'd.info -g' to get GeoTIFF bounds when keeping white margin bands
  eval `d.info -g`
  eval "$dsave"
d.mon stop=$GRAPHICS_DRIVER $BEQUIET
################################

g.message "Screen export complete. (writing the file may take a small amount of time)"


if [ $GIS_FLAG_M -eq 0 ] ; then
   # chop off out of region borders 
   eval `g.region -g`

   BOX_L=`echo $BOX | cut -f1 -d' '`
   BOX_R=`echo $BOX | cut -f2 -d' '`
   BOX_T=`echo $BOX | cut -f3 -d' '`
   BOX_B=`echo $BOX | cut -f4 -d' '`
   BOX_WIDTH=`echo $BOX_R $BOX_L | awk '{print $1 - $2}'`
   BOX_HEIGHT=`echo $BOX_B $BOX_T | awk '{print $1 - $2}'`

   CROP_PARAM="-srcwin $BOX_L $BOX_T $BOX_WIDTH $BOX_HEIGHT"
   g.message "Image crop [$BOX_WIDTH x $BOX_HEIGHT]"
else
   CROP_PARAM=""
fi


d.mon select="$curr_mon"

case "$GIS_OPT_FORMAT" in
   png | ppm | ps | eps | svg | pdf)
     g.message "Done."
     exit
     ;;
   tif | geotiff | jpg)
     # delay not needed if using GRASS_PNG_AUTO_WRITE ?
     g.message "Waiting for file to write ..."
     sleep 2
     ;;
   bmp)
     if [ $GIS_FLAG_C -eq 1 ] ; then
	g.message "Done."
	exit
     else
	# delay not needed if using GRASS_PNG_AUTO_WRITE ?
	g.message "Waiting for file to write ..."
	sleep 2
     fi
     ;;
esac


case "$GIS_OPT_FORMAT" in
   tif)
     g.message "Translating to TIFF format" 
     gdal_translate -of GTIFF $CROP_PARAM -quiet "$output" "$outname"
     EXITCODE=$?
     ;;
   jpg)
     g.message "Translating to JPEG format" 
     gdal_translate -of JPEG -co QUALITY="$GIS_OPT_QUALITY" \
	 $CROP_PARAM -quiet "$output" "$outname"
     EXITCODE=$?
     ;;
   bmp)
     g.message "Translating to BMP format" 
     gdal_translate -of BMP $CROP_PARAM -quiet "$output" "$outname"
     EXITCODE=$?
     ;;
   geotiff)
     g.message "Translating to GeoTIFF format" 
     

     PROJ_WKT="`g.proj -wf`"
     CO=""
     if [ -n "$GIS_OPT_CREATEOPT" ] ; then
	IFS=,
	for KEYVALUE in $GIS_OPT_CREATEOPT ; do
	   CO="$CO -co $KEYVALUE"
	done
     fi
     MO=""
     if [ -n "$GIS_OPT_METAOPT" ] ; then
	IFS=,
	for KEYVALUE in $GIS_OPT_METAOPT ; do
	   MO="$MO -mo $KEYVALUE"
	done
     fi
     unset IFS

     gdal_translate -of GTIFF -a_ullr $w $n $e $s -quiet $CROP_PARAM \
	-a_srs "$PROJ_WKT" $CO $MO "$output" "$outname"
     EXITCODE=$?
     ;;
esac


\rm "$output"

g.message "Done."

exit $EXITCODE
