move branch adempire311 to trunk

This commit is contained in:
vpj-cd 2006-11-17 03:12:59 +00:00
parent 6c0c1618cf
commit c62705c72f
51 changed files with 15581 additions and 0 deletions

12
print/.classpath Normal file
View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="src" path="/dbPort"/>
<classpathentry kind="src" path="/tools"/>
<classpathentry kind="src" path="/looks"/>
<classpathentry kind="lib" path="/tools/lib/barbecue-1.0.6d.jar"/>
<classpathentry kind="lib" path="/lib/CCTools.jar"/>
<classpathentry kind="lib" path="/lib/jPDF.jar"/>
<classpathentry kind="output" path="build"/>
</classpath>

25
print/.project Normal file
View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>print</name>
<comment></comment>
<projects>
<project>dbPort</project>
<project>looks</project>
<project>tools</project>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.ibm.etools.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

2
print/.xdoclet Normal file
View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<configurations/>

21
print/RUN_build.bat Normal file
View File

@ -0,0 +1,21 @@
@Title Build Print
@Rem $Header: /cvsroot/adempiere/print/RUN_build.bat,v 1.9 2005/09/16 00:50:35 jjanke Exp $
@CALL ..\utils_dev\myDevEnv.bat
@IF %ADEMPIERE_ENV%==N GOTO NOBUILD
@IF NOT %ADEMPIERE_ENV%==Y GOTO NOBUILD
@echo Cleanup ...
@"%JAVA_HOME%\bin\java" -Dant.home="." %ANT_PROPERTIES% org.apache.tools.ant.Main clean
@echo Building ...
@"%JAVA_HOME%\bin\java" -Dant.home="." %ANT_PROPERTIES% org.apache.tools.ant.Main printDistribute
@Echo Done ...
@sleep 60
@exit
:NOBUILD
@Echo Check myDevEnv.bat (copy from myDevEnvTemplate.bat)
@Pause

18
print/RUN_build.sh Normal file
View File

@ -0,0 +1,18 @@
# Module compiling script
# Ported from Windows script Marek Mosiewicz<marek.mosiewicz@jotel.com.pl>
SAVED_DIR=`pwd` #save current dir
cd `dirname $0`/../utils_dev #change dir to place where script resides - doesn not work with sym links
UTILS_DEV=`pwd` #this is adempiere source
cd $SAVED_DIR #back to the saved directory
. $UTILS_DEV/myDevEnv.sh #call environment
echo done
if [ ! $ADEMPIERE_ENV==Y ] ; then
echo "Can't set developemeent environemnt - check myDevEnv.sh"
exit 1
fi
echo running Ant
$JAVA_HOME/bin/java -Dant.home="." $ANT_PROPERTIES org.apache.tools.ant.Main

84
print/build.xml Normal file
View File

@ -0,0 +1,84 @@
<!-- ============================================= -->
<!-- Print -->
<!-- ============================================= -->
<!-- $Header: /cvs/adempiere/print/build.xml,v 1.2 2006/07/03 16:52:01 jjanke Exp $ -->
<project name="print" default="printDistribute" basedir=".">
<description>
This buildfile is used to build the print subproject within
the Adempiere project.
</description>
<!-- set global properties for this build -->
<property environment="env"/>
<property name="src" value="src"/>
<property name="build.dir" value="build"/>
<property name="dist.dir" value="."/>
<property name="jar.path" value="../lib"/>
<property name="jar.name" value="Print"/>
<!-- set path to include the necessary jar files for javac -->
<path id="project.class.path">
<pathelement path="${classpath}"/>
<pathelement path="../lib/CCTools.jar"/>
<pathelement path="../looks/CLooks.jar"/>
<pathelement path="../dbPort/dbPort.jar"/>
<pathelement path="../lib/freepdf.jar"/>
</path>
<target name="printInit" description="initialization target">
<echo message="=========== Build Print"/>
<!-- create the time stamp -->
<tstamp/>
<!-- create the build directory structure used by compile -->
<mkdir dir="${build.dir}"/>
<!-- check for the distribution directory -->
<available file="${dist.dir}" type="dir" property="dist.dir.exists"/>
</target>
<target name="printMakedir" depends="printInit" unless="dist.dir.exists">
<!-- create the distribution directory if not available -->
<mkdir dir="${dist}/${dist.dir}"/>
</target>
<target name="printCompile" depends="printMakedir">
<!-- compile the java code from ${src} into ${build.dir} -->
<javac srcdir="${src}" destdir="${build.dir}"
deprecation="on" debug="on" encoding="${env.ENCODING}">
<classpath refid="project.class.path"/>
</javac>
<!-- copy all image & sound files from src to the build directory -->
<copy todir="${build.dir}">
<fileset dir="${src}">
<include name="**/images/*"/>
<include name="**/*.gif"/>
<include name="**/*.jpg"/>
<include name="**/*.wav"/>
<include name="**/*.htm"/>
<include name="**/*.html"/>
<include name="**/*.properties"/>
<exclude name="**/package.html"/>
</fileset>
</copy>
</target>
<!-- =========================================== -->
<!-- Distribution -->
<!-- =========================================== -->
<target name="printDistribute" depends="printCompile">
<!-- put everything from ${build.dir} into the ${jar.name}.jar file -->
<jar jarfile="${dist.dir}/${jar.name}.jar" basedir="${build.dir}"/>
</target>
<target name="clean">
<!-- Delete the ${build.dir} directory trees -->
<delete dir="${build.dir}"/>
<delete file="${dist.dir}/${jar.name}.jar" failonerror="false"/>
</target>
</project>

5
print/documentation.bat Normal file
View File

@ -0,0 +1,5 @@
@Rem API Documentation for Base
call ..\doc\documentation.bat src doc -private
@pause

2
print/packages.txt Normal file
View File

@ -0,0 +1,2 @@
org.compiere.print
org.compiere.print.layout

33
print/print.html Normal file
View File

@ -0,0 +1,33 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>JBuilder Project print.jpx</title>
</head>
<body>
<h1>Project print Notes</h1>
<hr><table border="0">
<tr><th align="left" valign="top">Title:</th><td align="left" valign="top">
<!-- Type Title below -->
</td></tr>
<tr><th align="left" valign="top">Author:</th><td align="left" valign="top">
<!-- Type Author below -->
</td></tr>
<tr><th align="left" valign="top">Company:</th><td align="left" valign="top">
<!-- Type Company below -->
</td></tr>
<tr><th align="left" valign="top">Description:</th><td align="left" valign="top">
<!-- Type Description below -->
</td></tr>
</table><hr>
<h2>Things to do... </h2>
<ol>
<!-- Edit this section to keep track of your to do items -->
<li>First
<li>Second
</ol>
</body>
</html>

10
print/printData.dtd Normal file
View File

@ -0,0 +1,10 @@
<?xml version='1.0' encoding='UTF-8' ?>
<!--Generated by XML Authority-->
<!ELEMENT printData (element | printData)+>
<!ATTLIST printData name CDATA #IMPLIED >
<!ELEMENT element (#PCDATA)>
<!ATTLIST element name CDATA #IMPLIED >

View File

@ -0,0 +1,142 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.awt.print.*;
import org.compiere.model.*;
import org.compiere.print.layout.*;
import org.compiere.util.*;
import com.qoppa.pdf.*;
import com.qoppa.pdfProcess.*;
/**
* Archive Engine.
* Based on Settings on Client Level
* Keys set for
* - Menu Reports - AD_Report_ID
* - Win Report - AD_Table_ID
* - Documents - AD_Table_ID & Record_ID & C_Customer_ID
*
* @author Jorg Janke
* @version $Id: ArchiveEngine.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $
*/
public class ArchiveEngine
{
/**
* Get/Create Archive.
* @param layout layout
* @param info print info
* @return existing document or newly created if Client enabled archiving.
* Will return NULL if archiving not enabled
*/
public PDFDocument archive (LayoutEngine layout, PrintInfo info)
{
// Do we need to Archive ?
MClient client = MClient.get(layout.getCtx());
String aaClient = client.getAutoArchive();
String aaRole = null; // role.getAutoArchive(); // TODO
String aa = aaClient;
if (aa == null)
aa = MClient.AUTOARCHIVE_None;
if (aaRole != null)
{
if (aaRole.equals(MClient.AUTOARCHIVE_AllReportsDocuments))
aa = aaRole;
else if (aaRole.equals(MClient.AUTOARCHIVE_Documents) && !aaClient.equals(MClient.AUTOARCHIVE_AllReportsDocuments))
aa = aaRole;
}
// Mothing to Archive
if (aa.equals(MClient.AUTOARCHIVE_None))
return null;
// Archive External only
if (aa.equals(MClient.AUTOARCHIVE_ExternalDocuments))
{
if (info.isReport())
return null;
}
// Archive Documents only
if (aa.equals(MClient.AUTOARCHIVE_Documents))
{
if (info.isReport())
return null;
}
// Create Printable
byte[] data = Document.getPDFAsArray(layout.getPageable(false)); // No Copy
if (data == null)
return null;
// TODO to be done async
MArchive archive = new MArchive (layout.getCtx(),info, null);
archive.setBinaryData(data);
archive.save();
return null;
} // archive
/**
* Can we archive the document?
* @param layout layout
* @return true if can be archived
*/
public static boolean isValid (LayoutEngine layout)
{
return (layout != null
&& Document.isValid((Pageable)layout)
&& layout.getNumberOfPages() > 0);
} // isValid
/**
* Get Archive Engine
* @return engine
*/
public static ArchiveEngine get()
{
if (s_engine == null)
s_engine = new ArchiveEngine();
return s_engine;
} // get
// Create Archiver
static {
s_engine = new ArchiveEngine();
}
/** Logger */
private static CLogger log = CLogger.getCLogger(ArchiveEngine.class);
/** Singleton */
private static ArchiveEngine s_engine = null;
/**************************************************************************
* ArchiveEngine
*/
private ArchiveEngine ()
{
super ();
if (s_engine == null)
s_engine = this;
} // ArchiveEngine
/** The base document */
// private PDFDocument m_document = Document.createBlank();
} // ArchiveEngine

View File

@ -0,0 +1,426 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.awt.*;
import java.awt.print.*;
import java.util.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;
import org.compiere.util.*;
/**
* Adempiere Paper
*
* @author Jorg Janke
* @version $Id: CPaper.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $
*/
public class CPaper extends Paper
{
/**
* Constructor.
* Derive Paper from PageForamt
* @param pf PageFormat
*/
public CPaper (PageFormat pf)
{
super();
m_landscape = pf.getOrientation() != PageFormat.PORTRAIT;
// try to find MediaSize
float x = (float)pf.getWidth();
float y = (float)pf.getHeight();
MediaSizeName msn = MediaSize.findMedia (x/72, y/72, MediaSize.INCH);
MediaSize ms = null;
if (msn == null)
msn = MediaSize.findMedia (y/72, x/72, MediaSize.INCH); // flip it
if (msn != null)
ms = MediaSize.getMediaSizeForName(msn);
setMediaSize(ms, m_landscape);
// set size directly
setSize(pf.getWidth(), pf.getHeight());
setImageableArea(pf.getImageableX(), pf.getImageableY(),
pf.getImageableWidth(), pf.getImageableHeight());
} // CPaper
/**
* Constructor.
* Get Media Size from Default Language
* @param landscape true if landscape, false if portrait
*/
public CPaper (boolean landscape)
{
this (Language.getLoginLanguage(), landscape);
} // CPaper
/**
* Constructor.
* Get Media Size from Language,
* @param language language to derive media size
* @param landscape true if landscape, false if portrait
*/
private CPaper (Language language, boolean landscape)
{
this (language.getMediaSize(), landscape);
} // CPaper
/**
* Detail Constructor 1/2 inch on all sides
* @param mediaSize media size
* @param landscape true if landscape, false if portrait
*/
private CPaper (MediaSize mediaSize, boolean landscape)
{
this (mediaSize, landscape, 36, 36, 36, 36);
} // CPaper
/**
* Detail Constructor
* @param mediaSize media size
* @param left x in 1/72 inch
* @param top y in 1/72 inch
* @param right right x in 1/72
* @param bottom bottom y in 1/72
* @param landscape true if landscape, false if portrait
*/
public CPaper (MediaSize mediaSize, boolean landscape,
double left, double top, double right, double bottom)
{
super();
setMediaSize (mediaSize, landscape);
setImageableArea(left, top, getWidth()-left-right, getHeight()-top-bottom);
} // CPaper
/** Media size */
private MediaSize m_mediaSize;
/** Landscape flag */
private boolean m_landscape = false;
/** Logger */
private static CLogger log = CLogger.getCLogger(CPaper.class);
/**
* Set Media Size
* @param mediaSize media size
* @param landscape true if landscape, false if portrait
*/
public void setMediaSize (MediaSize mediaSize, boolean landscape)
{
if (mediaSize == null)
throw new IllegalArgumentException("MediaSize is null");
m_mediaSize = mediaSize;
m_landscape = landscape;
// Get Sise in Inch * 72
double width = m_mediaSize.getX (MediaSize.INCH) * 72;
double height = m_mediaSize.getY (MediaSize.INCH) * 72;
// Set Size
setSize (width, height);
log.fine(mediaSize.getMediaSizeName() + ": " + m_mediaSize + " - Landscape=" + m_landscape);
} // setMediaSize
/**
* Get Media Size
* @return media size
*/
public MediaSizeName getMediaSizeName()
{
return m_mediaSize.getMediaSizeName();
} // getMediaSizeName
/**
* Get Media Size
* @return media size
*/
public MediaSize getMediaSize()
{
return m_mediaSize;
} // getMediaSize
/**
* Get Printable Media Area
* @return Printable Area
*/
public MediaPrintableArea getMediaPrintableArea()
{
MediaPrintableArea area = new MediaPrintableArea ((float)getImageableX()/72, (float)getImageableY()/72,
(float)getImageableWidth()/72, (float)getImageableHeight()/72, MediaPrintableArea.INCH);
// log.fine( "CPaper.getMediaPrintableArea", area.toString(MediaPrintableArea.INCH, "\""));
return area;
} // getMediaPrintableArea
/**
* Get Printable Media Area
* @param area Printable Area
*/
public void setMediaPrintableArea (MediaPrintableArea area)
{
int inch = MediaPrintableArea.INCH;
log.fine(area.toString(inch, "\""));
setImageableArea(area.getX(inch)*72, area.getY(inch)*72,
area.getWidth(inch)*72, area.getHeight(inch)*72);
} // setMediaPrintableArea
/**
* Is Landscape
* @return true if landscape
*/
public boolean isLandscape()
{
return m_landscape;
} // isLandscape
/*************************************************************************/
/**
* Show Dialog and Set Paper
* @param job printer job
* @return true if changed.
*/
public boolean pageSetupDialog(PrinterJob job)
{
PrintRequestAttributeSet prats = getPrintRequestAttributeSet();
// Page Dialog
PageFormat pf = job.pageDialog(prats);
setPrintRequestAttributeSet(prats);
return true;
} // pageSetupDialog
/**
* Return Print Request Attributes
* @return PrintRequestAttributeSet
*/
public PrintRequestAttributeSet getPrintRequestAttributeSet()
{
PrintRequestAttributeSet pratts = new HashPrintRequestAttributeSet();
// media-printable-area = (25.4,25.4)->(165.1,228.6)mm - class javax.print.attribute.standard.MediaPrintableArea
pratts.add(getMediaPrintableArea());
// orientation-requested = landscape - class javax.print.attribute.standard.OrientationRequested
if (isLandscape())
pratts.add(OrientationRequested.LANDSCAPE);
else
pratts.add(OrientationRequested.PORTRAIT);
// media = na-legal
pratts.add(getMediaSizeName());
return pratts;
} // getPrintRequestAttributes
/**
* Set Print Request Attributes
* @param prats PrintRequestAttributeSet
*/
public void setPrintRequestAttributeSet (PrintRequestAttributeSet prats)
{
boolean landscape = m_landscape;
MediaSize ms = m_mediaSize;
MediaPrintableArea area = getMediaPrintableArea();
Attribute[] atts = prats.toArray();
for (int i = 0; i < atts.length; i++)
{
if (atts[i] instanceof OrientationRequested)
{
OrientationRequested or = (OrientationRequested)atts[i];
if (or.equals(OrientationRequested.PORTRAIT))
landscape = false;
else
landscape = true;
}
else if (atts[i] instanceof MediaSizeName)
{
MediaSizeName msn = (MediaSizeName)atts[i];
ms = MediaSize.getMediaSizeForName(msn);
}
else if (atts[i] instanceof MediaPrintableArea)
{
area = (MediaPrintableArea)atts[i];
}
else // unhandeled
System.out.println(atts[i].getName() + " = " + atts[i] + " - " + atts[i].getCategory());
}
//
setMediaSize(ms, landscape);
setMediaPrintableArea(area);
} // getPrintRequestAttributes
/*************************************************************************/
/**
* Get the Page Format for the Papaer
* @return Page Format
*/
public PageFormat getPageFormat()
{
PageFormat pf = new PageFormat();
pf.setPaper(this);
int orient = PageFormat.PORTRAIT;
if (m_landscape)
orient = PageFormat.LANDSCAPE;
pf.setOrientation(orient);
return pf;
} // getPageFormat
/*************************************************************************/
/**
* Get String Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer("CPaper[");
sb.append(getWidth()/72).append("x").append(getHeight()/72).append('"')
.append(m_landscape ? " Landscape " : " Portrait ")
.append("x=").append(getImageableX())
.append(",y=").append(getImageableY())
.append(" w=").append(getImageableWidth())
.append(",h=").append(getImageableHeight())
.append("]");
return sb.toString();
} // toString
/**
* Get "nice" String Representation
* @param ctx context
* @return info
*/
public String toString (Properties ctx)
{
StringBuffer sb = new StringBuffer();
// Print Media size
sb.append(m_mediaSize.getMediaSizeName());
// Print dimension
String name = m_mediaSize.getMediaSizeName().toString();
if (!name.startsWith("iso"))
sb.append(" - ").append(m_mediaSize.toString(MediaSize.INCH,"\""))
.append(" (").append(getMediaPrintableArea().toString(MediaPrintableArea.INCH,"\""));
if (!name.startsWith("na"))
sb.append(" - ").append(m_mediaSize.toString(MediaSize.MM,"mm"))
.append(" (").append(getMediaPrintableArea().toString(MediaPrintableArea.MM,"mm"));
// Print Orientation
sb.append(") - ")
.append(Msg.getMsg(ctx, m_landscape ? "Landscape" : "Portrait"));
return sb.toString();
} // toString
/**
* Equals
* @param obj compare
* @return true if equal
*/
public boolean equals (Object obj)
{
if (obj instanceof CPaper)
{
CPaper cp = (CPaper)obj;
if (cp.isLandscape() != m_landscape)
return false;
// media size is more descriptive
if (getImageableX() == cp.getImageableX() && getImageableY() == cp.getImageableY()
&& getImageableWidth() == cp.getImageableWidth() && getImageableHeight() == cp.getImageableHeight())
return true;
}
return false;
} // equals
/*************************************************************************/
/**
* Get Width in 1/72 inch
* @param orientationCorrected correct for orientation
* @return width
*/
public double getWidth (boolean orientationCorrected)
{
if (orientationCorrected && m_landscape)
return super.getHeight();
return super.getWidth();
}
/**
* Get Height in 1/72 inch
* @param orientationCorrected correct for orientation
* @return height
*/
public double getHeight (boolean orientationCorrected)
{
if (orientationCorrected && m_landscape)
return super.getWidth();
return super.getHeight();
}
/**
* Get Image Y in 1/72 inch
* @param orientationCorrected correct for orientation
* @return imagable Y
*/
public double getImageableY (boolean orientationCorrected)
{
if (orientationCorrected && m_landscape)
return super.getImageableX();
return super.getImageableY();
}
/**
* Get Image X in 1/72 inch
* @param orientationCorrected correct for orientation
* @return imagable X
*/
public double getImageableX (boolean orientationCorrected)
{
if (orientationCorrected && m_landscape)
return super.getImageableY();
return super.getImageableX();
}
/**
* Get Image Height in 1/72 inch
* @param orientationCorrected correct for orientation
* @return imagable height
*/
public double getImageableHeight (boolean orientationCorrected)
{
if (orientationCorrected && m_landscape)
return super.getImageableWidth();
return super.getImageableHeight();
}
/**
* Get Image Width in 1/72 inch
* @param orientationCorrected correct for orientation
* @return imagable width
*/
public double getImageableWidth (boolean orientationCorrected)
{
if (orientationCorrected && m_landscape)
return super.getImageableHeight();
return super.getImageableWidth();
}
/**
* Get Margin
* @param orientationCorrected correct for orientation
* @return margin
*/
public Insets getMargin (boolean orientationCorrected)
{
return new Insets ((int)getImageableY(orientationCorrected), // top
(int)getImageableX(orientationCorrected), // left
(int)(getHeight(orientationCorrected)-getImageableY(orientationCorrected)-getImageableHeight(orientationCorrected)), // bottom
(int)(getWidth(orientationCorrected)-getImageableX(orientationCorrected)-getImageableWidth(orientationCorrected))); // right
} // getMargin
} // CPapaer

View File

@ -0,0 +1,158 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.awt.event.*;
import java.awt.print.*;
import javax.print.*;
import org.compiere.swing.*;
import org.compiere.util.*;
/**
* Adempiere Printer Selection
*
* @author Jorg Janke
* @version $Id: CPrinter.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $
*/
public class CPrinter extends CComboBox implements ActionListener
{
/**
* Get Print (Services) Names
* @return Printer Name array
*/
public static String[] getPrinterNames()
{
String[] retValue = new String[s_services.length];
for (int i = 0; i < s_services.length; i++)
retValue[i] = s_services[i].getName();
return retValue;
} // getPrintServiceNames
/**
* Return default PrinterJob
* @return PrinterJob
*/
public static PrinterJob getPrinterJob()
{
return getPrinterJob(Ini.getProperty(Ini.P_PRINTER));
} // getPrinterJob
/**
* Return PrinterJob with selected printer name.
* @param printerName if null, get default printer (Ini)
* @return PrinterJob
*/
public static PrinterJob getPrinterJob (String printerName)
{
PrinterJob pj = null;
PrintService ps = null;
try
{
pj = PrinterJob.getPrinterJob();
// find printer service
if (printerName == null || printerName.length() == 0)
printerName = Ini.getProperty(Ini.P_PRINTER);
if (printerName != null && printerName.length() != 0)
{
// System.out.println("CPrinter.getPrinterJob - searching " + printerName);
for (int i = 0; i < s_services.length; i++)
{
String serviceName = s_services[i].getName();
if (printerName.equals(serviceName))
{
ps = s_services[i];
// System.out.println("CPrinter.getPrinterJob - found " + printerName);
break;
}
// System.out.println("CPrinter.getPrinterJob - not: " + serviceName);
}
} // find printer service
try
{
if (ps != null)
pj.setPrintService(ps);
}
catch (Exception e)
{
log.warning("Could not set Print Service: " + e.toString());
}
//
PrintService psUsed = pj.getPrintService();
if (psUsed == null)
log.warning("Print Service not Found");
else
{
String serviceName = psUsed.getName();
if (printerName != null && !printerName.equals(serviceName))
log.warning("Not found: " + printerName + " - Used: " + serviceName);
}
}
catch (Exception e)
{
log.warning("Could not create for " + printerName + ": " + e.toString());
}
return pj;
} // getPrinterJob
/** Available Printer Services */
// private static PrintService[] s_services = PrinterJob.lookupPrintServices();
private static PrintService[] s_services = PrintServiceLookup.lookupPrintServices(null,null);
/** Logger */
private static CLogger log = CLogger.getCLogger (CPrinter.class);
/**************************************************************************
* Create PrinterJob
*/
public CPrinter()
{
super(getPrinterNames());
// Set Default
setValue(Ini.getProperty(Ini.P_PRINTER));
this.addActionListener(this);
} // CPrinter
/**
* Action Listener
* @param e event
*/
public void actionPerformed (ActionEvent e)
{
} // actionPerformed
/**
* Get PrintService
* @return print service
*/
public PrintService getPrintService()
{
String currentService = (String)getSelectedItem();
for (int i = 0; i < s_services.length; i++)
{
if (s_services[i].getName().equals(currentService))
return s_services[i];
}
return PrintServiceLookup.lookupDefaultPrintService();
} // getPrintService
} // CPrinter

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,245 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.awt.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.model.*;
import org.compiere.util.*;
/**
* AD_PrintColor Print Color Model
*
* @author Jorg Janke
* @version $Id: MPrintColor.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $
*/
public class MPrintColor extends X_AD_PrintColor
{
/**************************************************************************
* Create Color in Database and save
* @param color color
* @param name name
* @return MPrintColor
*/
static MPrintColor create (Color color, String name)
{
MPrintColor pc = new MPrintColor (Env.getCtx(), 0, null);
pc.setName(name);
pc.setColor(color);
pc.save();
return pc;
} // create
/*************************************************************************/
/** Dark Green */
public static final Color darkGreen = new Color (0, 128, 0);
/** Black Green */
public static final Color blackGreen = new Color (0, 64, 0);
/** Dark Blue */
public static final Color darkBlue = new Color (0, 0, 128);
/** Black Blue */
public static final Color blackBlue = new Color (0, 0, 64);
/** White Gray */
public static final Color whiteGray = new Color (224, 224, 224);
/** Brown */
public static final Color brown = new Color (153, 102, 51);
/** Dark Brown */
public static final Color darkBrown = new Color (102, 51, 0);
/*************************************************************************/
/** Cached Colors */
static private CCache<Integer,MPrintColor> s_colors = new CCache<Integer,MPrintColor>("AD_PrintColor", 20);
/** Static Logger */
private static CLogger s_log = CLogger.getCLogger (MPrintColor.class);
/**
* Get Color.
* if id = 0, it returns a new color (black) - but do not modify/save as cached
* @param ctx context
* @param AD_PrintColor_ID id
* @return Color
*/
static public MPrintColor get (Properties ctx, int AD_PrintColor_ID)
{
// if (AD_PrintColor_ID == 0)
// return new MPrintColor (ctx, 0);
Integer key = new Integer(AD_PrintColor_ID);
MPrintColor pc = (MPrintColor)s_colors.get(key);
if (pc == null)
{
pc = new MPrintColor (ctx, AD_PrintColor_ID, null);
s_colors.put(key, pc);
}
return pc;
} // get
/**
* Get Color
* @param ctx context
* @param AD_PrintColor_ID id
* @return Color or null
*/
static public MPrintColor get (Properties ctx, String AD_PrintColor_ID)
{
if (AD_PrintColor_ID == null || AD_PrintColor_ID.length() == 0)
return null;
try
{
int id = Integer.parseInt(AD_PrintColor_ID);
return get(ctx, id);
}
catch (Exception e)
{
s_log.log(Level.SEVERE, "AD_PrintColor_ID=" + AD_PrintColor_ID
+ " - " + e.toString());
}
return null;
} // get
/**************************************************************************
* Constructor
* @param ctx context
* @param AD_PrintColor_ID ID
* @param trxName transaction
*/
public MPrintColor(Properties ctx, int AD_PrintColor_ID, String trxName)
{
super (ctx, AD_PrintColor_ID, trxName);
if (AD_PrintColor_ID == 0)
setIsDefault(false);
} // MPrintColor
/** Color cached */
private Color m_cacheColor = null;
/**
* Get Color
* @return Color
*/
public Color getColor()
{
if (m_cacheColor != null)
return m_cacheColor;
String code = getCode();
if (code == null || code.equals("."))
m_cacheColor = Color.black;
try
{
if (code != null && !code.equals("."))
{
int rgba = Integer.parseInt(code);
m_cacheColor = new Color(rgba, false);
}
}
catch (Exception e)
{
log.log(Level.SEVERE, "MPrintColor.getColor", e);
}
if (code == null)
m_cacheColor = Color.black;
// log.fine( "MPrintColor.getColor " + code, m_cacheColor);
return m_cacheColor;
} // getColor
/**
* Set Color
* @param color Color
*/
public void setColor (Color color)
{
int rgba = color.getRGB();
super.setCode(String.valueOf(rgba));
} // setColor
/**
* Get Color as RRGGBB hex string for HTML font tag
* @return rgb hex value
*/
public String getRRGGBB()
{
Color color = getColor();
StringBuffer sb = new StringBuffer();
sb.append(Util.toHex((byte)color.getRed()))
.append(Util.toHex((byte)color.getGreen()))
.append(Util.toHex((byte)color.getBlue()));
return sb.toString();
} // getRRGGBB
/**
* String Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer("MPrintColor[");
sb.append("ID=").append(get_ID())
.append(",Name=").append(getName())
.append(",RGB=").append(getCode())
.append(",").append(getColor())
.append("]");
return sb.toString();
} // toString
/**************************************************************************
* Create Standard Colors
* @param args args
*/
public static void main(String[] args)
{
org.compiere.Adempiere.startupEnvironment(true);
Color[] colors = new Color[]
{Color.black, Color.red, Color.green, Color.blue,
Color.darkGray, Color.gray, Color.lightGray, Color.white,
Color.cyan, Color.magenta, Color.orange, Color.pink, Color.yellow,
SystemColor.textHighlight};
String[] names = new String[]
{"Black", "Red", "Green", "Blue",
"Gray dark", "Gray", "Gray light", "White",
"Cyan", "Magenta", "Orange", "Pink", "Yellow",
"Blue dark"};
for (int i = 0; i < colors.length; i++)
System.out.println(names[i] + " = " + colors[i] + " RGB=" + colors[i].getRGB()
+ " -> " + new Color(colors[i].getRGB(), false)
+ " -> " + new Color(colors[i].getRGB(), true));
/**
// Create Colors
for (int i = 0; i < colors.length; i++)
create(colors[i], names[i]);
create(whiteGray, "Gray white");
create(darkGreen, "Green dark");
create(blackGreen, "Green black");
create(blackBlue, "Blue black");
create(brown, "Brown");
create(darkBrown, "Brown dark");
**/
// Read All Colors
int[] IDs = PO.getAllIDs ("AD_PrintColor", null, null);
for (int i = 0; i < IDs.length; i++)
{
MPrintColor pc = new MPrintColor(Env.getCtx(), IDs[i], null);
System.out.println(IDs[i] + ": " + pc + " = " + pc.getColor() + ", RGB=" + pc.getColor().getRGB());
}
} // main
} // MPrintColor

View File

@ -0,0 +1,245 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.awt.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.model.*;
import org.compiere.util.*;
/**
* AD_PrintFont Print Font Model
*
* @author Jorg Janke
* @version $Id: MPrintFont.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $
*/
public class MPrintFont extends X_AD_PrintFont
{
/**
* Constructor
* @param ctx context
* @param AD_PrintFont_ID ID
* @param trxName transaction
*/
private MPrintFont(Properties ctx, int AD_PrintFont_ID, String trxName)
{
super (ctx, AD_PrintFont_ID, trxName);
if (AD_PrintFont_ID == 0)
setIsDefault(false);
} // MPrintFont
/** Font cached */
private Font m_cacheFont = null;
/*************************************************************************/
/**
* Get Font
* @return Font
*/
public Font getFont()
{
if (m_cacheFont != null)
return m_cacheFont;
String code = (String)get_Value("Code");
if (code == null || code.equals("."))
m_cacheFont = new Font (null);
try
{
if (code != null && !code.equals("."))
// fontfamilyname-style-pointsize
m_cacheFont = Font.decode(code);
}
catch (Exception e)
{
log.log(Level.SEVERE, "MPrintFont.getFont", e);
}
if (code == null)
m_cacheFont = new Font (null); // family=dialog,name=Dialog,style=plain,size=12
// log.fine( "MPrintFont.getFont " + code, m_cacheFont);
return m_cacheFont;
} // getFont
/**
* Set Font
* @param font Font
*/
public void setFont (Font font)
{
// fontfamilyname-style-pointsize
StringBuffer sb = new StringBuffer();
sb.append(font.getFamily()).append("-");
int style = font.getStyle();
if (style == Font.PLAIN)
sb.append("PLAIN");
else if (style == Font.BOLD)
sb.append("BOLD");
else if (style == Font.ITALIC)
sb.append("ITALIC");
else if (style == (Font.BOLD + Font.ITALIC))
sb.append("BOLDITALIC");
sb.append("-").append(font.getSize());
setCode(sb.toString());
} // setFont
/*************************************************************************/
/**
* Create Font in Database and save
* @param font font
* @return PrintFont
*/
static MPrintFont create (Font font)
{
MPrintFont pf = new MPrintFont(Env.getCtx(), 0, null);
StringBuffer name = new StringBuffer (font.getName());
if (font.isBold())
name.append(" bold");
if (font.isItalic())
name.append(" italic");
name.append(" ").append(font.getSize());
pf.setName(name.toString());
pf.setFont(font);
pf.save();
return pf;
} // create
/**
* String Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer("MPrintFont[");
sb.append("ID=").append(get_ID())
.append(",Name=").append(getName())
.append("PSName=").append(getFont().getPSName())
.append(getFont())
.append("]");
return sb.toString();
} // toString
/**
* Get PostScript Level 2 definition.
* e.g. /dialog 12 selectfont
* @return PostScript command
*/
public String toPS()
{
StringBuffer sb = new StringBuffer("/");
sb.append(getFont().getPSName());
if (getFont().isBold())
sb.append(" Bold");
if (getFont().isItalic())
sb.append(" Italic");
sb.append(" ").append(getFont().getSize())
.append(" selectfont");
return sb.toString();
} // toPS
/**
* Dump Font
* @param font font
*/
static void dump (Font font)
{
System.out.println("Family=" + font.getFamily());
System.out.println("FontName=" + font.getFontName());
System.out.println("Name=" + font.getName());
System.out.println("PSName=" + font.getPSName());
System.out.println("Style=" + font.getStyle());
System.out.println("Size=" + font.getSize());
System.out.println("Attributes:");
Map map = font.getAttributes();
Iterator keys = map.keySet().iterator();
while (keys.hasNext())
{
Object key = keys.next();
Object value = map.get(key);
System.out.println(" - " + key + "=" + value);
}
System.out.println(font);
} // dump
/*************************************************************************/
/** Cached Fonts */
static private CCache<Integer,MPrintFont> s_fonts = new CCache<Integer,MPrintFont>("AD_PrintFont", 20);
/**
* Get Font
* @param AD_PrintFont_ID id
* @return Font
*/
static public MPrintFont get (int AD_PrintFont_ID)
{
Integer key = new Integer(AD_PrintFont_ID);
MPrintFont pf = (MPrintFont)s_fonts.get(key);
if (pf == null)
{
pf = new MPrintFont (Env.getCtx(), AD_PrintFont_ID, null);
s_fonts.put(key, pf);
}
return pf;
} // get
/*************************************************************************/
/**
* Seed Fonts
* @param args args
*/
public static void main(String[] args)
{
System.out.println("Available Fonts:");
String[] family = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
for (int i = 0; i < family.length; i++)
System.out.println(" - " + family[i]);
org.compiere.Adempiere.startup(true);
MPrintFont pf = new MPrintFont(Env.getCtx(), 100, null);
dump( pf.getFont() );
String[] systemLocical = new String[] {"Dialog", "DialogInput", "Monospaced", "Serif", "SansSerif"};
for (int i = 0; i < systemLocical.length; i++)
{
// create(new Font(systemLocical[i], Font.BOLD, 13));
// create(new Font(systemLocical[i], Font.PLAIN, 11));
// create(new Font(systemLocical[i], Font.BOLD, 11));
// create(new Font(systemLocical[i], Font.ITALIC, 11));
// create(new Font(systemLocical[i], Font.PLAIN, 10));
// create(new Font(systemLocical[i], Font.BOLD, 10));
// create(new Font(systemLocical[i], Font.ITALIC, 10));
// create(new Font(systemLocical[i], Font.PLAIN, 9));
// create(new Font(systemLocical[i], Font.BOLD, 9));
// create(new Font(systemLocical[i], Font.ITALIC, 9));
// create(new Font(systemLocical[i], Font.PLAIN, 8));
// create(new Font(systemLocical[i], Font.BOLD, 8));
// create(new Font(systemLocical[i], Font.ITALIC, 8));
}
// Read All Fonts
int[] IDs = PO.getAllIDs ("AD_PrintFont", null, null);
for (int i = 0; i < IDs.length; i++)
{
pf = new MPrintFont(Env.getCtx(), IDs[i], null);
System.out.println(IDs[i] + " = " + pf.getFont());
}
} // main
} // MPrintFont

View File

@ -0,0 +1,863 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.model.*;
import org.compiere.util.*;
/**
* AD_PrintFormat - Print Format Model.
* (Add missing Items with PrintFormatUtil)
*
* @author Jorg Janke
* @version $Id: MPrintFormat.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $
*/
public class MPrintFormat extends X_AD_PrintFormat
{
/**
* Public Constructor.
* Use static get methods
* @param ctx context
* @param AD_PrintFormat_ID AD_PrintFormat_ID
* @param trxName transaction
*/
public MPrintFormat (Properties ctx, int AD_PrintFormat_ID, String trxName)
{
super (ctx, AD_PrintFormat_ID, trxName);
// Language=[Deutsch,Locale=de_DE,AD_Language=en_US,DatePattern=DD.MM.YYYY,DecimalPoint=false]
m_language = Language.getLoginLanguage();
if (AD_PrintFormat_ID == 0)
{
setStandardHeaderFooter(true);
setIsTableBased(true);
setIsForm(false);
setIsDefault(false);
}
m_items = getItems();
} // MPrintFormat
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MPrintFormat (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
m_language = Language.getLoginLanguage();
m_items = getItems();
} // MPrintFormat
/** Items */
private MPrintFormatItem[] m_items = null;
/** Translation View Language */
private String m_translationViewLanguage = null;
/** Language of Report */
private Language m_language;
/** Table Format */
private MPrintTableFormat m_tFormat;
private static CLogger s_log = CLogger.getCLogger (MPrintFormat.class);
/**
* Get Language
* @return language
*/
public Language getLanguage()
{
return m_language;
} // getLanguage
/**
* Set Language
* @param language language
*/
public void setLanguage(Language language)
{
if (language != null)
{
m_language = language;
// log.fine("setLanguage - " + language);
}
m_translationViewLanguage = null;
} // getLanguage
/**
* Get AD_Column_ID of Order Columns
* @return Array of AD_Column_IDs in Sort Order
*/
public int[] getOrderAD_Column_IDs()
{
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); // SortNo - AD_Column_ID
for (int i = 0; i < m_items.length; i++)
{
// Sort Order and Column must be > 0
if (m_items[i].getSortNo() != 0 && m_items[i].getAD_Column_ID() != 0)
map.put(new Integer(m_items[i].getSortNo()), new Integer(m_items[i].getAD_Column_ID()));
}
// Get SortNo and Sort them
Integer[] keys = new Integer[map.keySet().size()];
map.keySet().toArray(keys);
Arrays.sort(keys);
// Create AD_Column_ID array
int[] retValue = new int[keys.length];
for (int i = 0; i < keys.length; i++)
{
Integer value = (Integer)map.get(keys[i]);
retValue[i] = value.intValue();
}
return retValue;
} // getOrderAD_Column_IDs
/**
* Get AD_Column_IDs of columns in Report
* @return Array of AD_Column_ID
*/
public int[] getAD_Column_IDs()
{
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < m_items.length; i++)
{
if (m_items[i].getAD_Column_ID() != 0 && m_items[i].isPrinted())
list.add(new Integer(m_items[i].getAD_Column_ID()));
}
// Convert
int[] retValue = new int[list.size()];
for (int i = 0; i < list.size(); i++)
retValue[i] = ((Integer)list.get(i)).intValue();
return retValue;
} // getAD_Column_IDs
/**
* Set Items
* @param items items
*/
private void setItems (MPrintFormatItem[] items)
{
if (items != null)
m_items = items;
} // setItems
/**
* Get active Items
* @return items
*/
private MPrintFormatItem[] getItems()
{
ArrayList<MPrintFormatItem> list = new ArrayList<MPrintFormatItem>();
String sql = "SELECT * FROM AD_PrintFormatItem pfi "
+ "WHERE pfi.AD_PrintFormat_ID=? AND pfi.IsActive='Y'"
// Display restrictions - Passwords, etc.
+ " AND NOT EXISTS (SELECT * FROM AD_Field f "
+ "WHERE pfi.AD_Column_ID=f.AD_Column_ID"
+ " AND (f.IsEncrypted='Y' OR f.ObscureType IS NOT NULL))"
+ "ORDER BY SeqNo";
MRole role = MRole.getDefault(getCtx(), false);
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, get_ID());
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
MPrintFormatItem pfi = new MPrintFormatItem(p_ctx, rs, get_TrxName());
if (role.isColumnAccess(getAD_Table_ID(), pfi.getAD_Column_ID(), true))
list.add (pfi);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
//
MPrintFormatItem[] retValue = new MPrintFormatItem[list.size()];
list.toArray(retValue);
return retValue;
} // getItems
/**
* Get Item Count
* @return number of items or -1 if items not defined
*/
public int getItemCount()
{
if (m_items == null)
return -1;
return m_items.length;
} // getItemCount
/**
* Get Print Format Item
* @param index index
* @return Print Format Item
*/
public MPrintFormatItem getItem (int index)
{
if (index < 0 || index >= m_items.length)
throw new ArrayIndexOutOfBoundsException("Index=" + index + " - Length=" + m_items.length);
return m_items[index];
} // getItem
/**
* Set the translation of the Format Items to the original
*/
public void setTranslation()
{
StringBuffer sb = new StringBuffer ("UPDATE AD_PrintFormatItem_Trl t"
+ " SET (PrintName, PrintNameSuffix)="
+ " (SELECT PrintName, PrintNameSuffix FROM AD_PrintFormatItem i WHERE i.AD_PrintFormatItem_ID=t.AD_PrintFormatItem_ID) "
+ "WHERE AD_PrintFormatItem_ID IN"
+ " (SELECT AD_PrintFormatItem_ID FROM AD_PrintFormatItem WHERE AD_PrintFormat_ID=").append(get_ID()).append(")");
int no = DB.executeUpdate(sb.toString(), get_TrxName());
log.fine("setTranslation #" + no);
} // setTranslation
/**************************************************************************
* Set Standard Header
* @param standardHeaderFooter true if std header
*/
public void setStandardHeaderFooter (boolean standardHeaderFooter)
{
super.setIsStandardHeaderFooter(standardHeaderFooter);
if (standardHeaderFooter)
{
setFooterMargin(0);
setHeaderMargin(0);
}
} // setSatndardHeaderFooter
/**
* Set Table based.
* Reset Form
* @param tableBased true if table based
*/
public void setIsTableBased (boolean tableBased)
{
super.setIsTableBased (tableBased);
if (tableBased)
super.setIsForm(false);
} // setIsTableBased
/**************************************************************************
* Set Translation View Language.
* @param language language (checked for base language)
*/
public void setTranslationLanguage (Language language)
{
if (language == null || language.isBaseLanguage())
{
log.info("Ignored - " + language);
m_translationViewLanguage = null;
}
else
{
log.info("Language=" + language.getAD_Language());
m_translationViewLanguage = language.getAD_Language();
m_language = language;
}
} // setTranslationLanguage
/**
* Get Translation View use
* @return true if a translation view is used
*/
public boolean isTranslationView()
{
return m_translationViewLanguage != null;
} // isTranslationView
/**
* Update the Query to access the Translation View.
* Can be called multiple times, adds only if not set already
* @param query query to be updated
*/
public void setTranslationViewQuery (MQuery query)
{
// Set Table Name and add add restriction, if a view and language set
if (m_translationViewLanguage != null && query != null && query.getTableName().toUpperCase().endsWith("_V"))
{
query.setTableName(query.getTableName() + "t");
query.addRestriction("AD_Language", MQuery.EQUAL, m_translationViewLanguage);
}
} // setTranslationViewQuery
/**************************************************************************
* Get Optional TableFormat
* @param AD_PrintTableFormat_ID table format
*/
public void setAD_PrintTableFormat_ID (int AD_PrintTableFormat_ID)
{
super.setAD_PrintTableFormat_ID(AD_PrintTableFormat_ID);
m_tFormat = MPrintTableFormat.get (getCtx(), AD_PrintTableFormat_ID, getAD_PrintFont_ID());
} // getAD_PrintTableFormat_ID
/**
* Get Table Format
* @return Table Format
*/
public MPrintTableFormat getTableFormat()
{
if (m_tFormat == null)
m_tFormat = MPrintTableFormat.get(getCtx(), getAD_PrintTableFormat_ID(), getAD_PrintFont_ID());
return m_tFormat;
} // getTableFormat
/**
* Sting Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer ("MPrintFormat[ID=").append(get_ID())
.append(",Name=").append(getName())
.append(",Language=").append(getLanguage())
.append(",Items=").append(getItemCount())
.append("]");
return sb.toString();
} // toString
/**************************************************************************
* Load Special data (images, ..).
* To be extended by sub-classes
* @param rs result set
* @param index zero based index
* @return value value
* @throws SQLException
*/
protected Object loadSpecial (ResultSet rs, int index) throws SQLException
{
// CreateCopy
// log.config(p_info.getColumnName(index));
return null;
} // loadSpecial
/**
* Save Special Data.
* To be extended by sub-classes
* @param value value
* @param index index
* @return SQL code for INSERT VALUES clause
*/
protected String saveNewSpecial (Object value, int index)
{
// CreateCopy
// String colName = p_info.getColumnName(index);
// String colClass = p_info.getColumnClass(index).toString();
// String colValue = value == null ? "null" : value.getClass().toString();
// log.log(Level.SEVERE, "Unknown class for column " + colName + " (" + colClass + ") - Value=" + colValue);
if (value == null)
return "NULL";
return value.toString();
} // saveNewSpecial
/**************************************************************************
* Create MPrintFormat for Table
* @param ctx context
* @param AD_Table_ID table
* @return print format
*/
static public MPrintFormat createFromTable (Properties ctx, int AD_Table_ID)
{
return createFromTable(ctx, AD_Table_ID, 0);
} // createFromTable
/**
* Create MPrintFormat for Table
* @param ctx context
* @param AD_Table_ID table
* @param AD_PrintFormat_ID 0 or existing PrintFormat
* @return print format
*/
static public MPrintFormat createFromTable (Properties ctx,
int AD_Table_ID, int AD_PrintFormat_ID)
{
int AD_Client_ID = Env.getAD_Client_ID(ctx);
s_log.info ("AD_Table_ID=" + AD_Table_ID + " - AD_Client_ID=" + AD_Client_ID);
MPrintFormat pf = new MPrintFormat(ctx, AD_PrintFormat_ID, null);
pf.setAD_Table_ID (AD_Table_ID);
// Get Info
String sql = "SELECT TableName," // 1
+ " (SELECT COUNT(*) FROM AD_PrintFormat x WHERE x.AD_Table_ID=t.AD_Table_ID AND x.AD_Client_ID=c.AD_Client_ID) AS Count,"
+ " COALESCE (cpc.AD_PrintColor_ID, pc.AD_PrintColor_ID) AS AD_PrintColor_ID," // 3
+ " COALESCE (cpf.AD_PrintFont_ID, pf.AD_PrintFont_ID) AS AD_PrintFont_ID,"
+ " COALESCE (cpp.AD_PrintPaper_ID, pp.AD_PrintPaper_ID) AS AD_PrintPaper_ID "
+ "FROM AD_Table t, AD_Client c"
+ " LEFT OUTER JOIN AD_PrintColor cpc ON (cpc.AD_Client_ID=c.AD_Client_ID AND cpc.IsDefault='Y')"
+ " LEFT OUTER JOIN AD_PrintFont cpf ON (cpf.AD_Client_ID=c.AD_Client_ID AND cpf.IsDefault='Y')"
+ " LEFT OUTER JOIN AD_PrintPaper cpp ON (cpp.AD_Client_ID=c.AD_Client_ID AND cpp.IsDefault='Y'),"
+ " AD_PrintColor pc, AD_PrintFont pf, AD_PrintPaper pp "
+ "WHERE t.AD_Table_ID=? AND c.AD_Client_ID=?" // #1/2
+ " AND pc.IsDefault='Y' AND pf.IsDefault='Y' AND pp.IsDefault='Y'";
boolean error = true;
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, AD_Table_ID);
pstmt.setInt(2, AD_Client_ID);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
// Name
String TableName = rs.getString(1);
String ColumnName = TableName + "_ID";
String s = ColumnName;
if (!ColumnName.equals("T_Report_ID"))
{
s = Msg.translate (ctx, ColumnName);
if (ColumnName.equals (s)) // not found
s = Msg.translate (ctx, TableName);
}
int count = rs.getInt(2);
if (count > 0)
s += "_" + (count+1);
pf.setName(s);
//
pf.setAD_PrintColor_ID(rs.getInt(3));
pf.setAD_PrintFont_ID(rs.getInt(4));
pf.setAD_PrintPaper_ID(rs.getInt(5));
//
error = false;
}
else
s_log.log(Level.SEVERE, "No info found " + AD_Table_ID);
rs.close();
pstmt.close();
}
catch (SQLException e)
{
s_log.log(Level.SEVERE, sql, e);
}
if (error)
return null;
// Save & complete
if (!pf.save())
return null;
// pf.dump();
pf.setItems (createItems(ctx, pf));
//
return pf;
} // createFromTable
/**
* Create MPrintFormat for ReportView
* @param ctx context
* @param AD_ReportView_ID ReportView
* @param ReportName - optional Report Name
* @return print format
*/
static public MPrintFormat createFromReportView (Properties ctx, int AD_ReportView_ID, String ReportName)
{
int AD_Client_ID = Env.getAD_Client_ID(ctx);
s_log.info ("AD_ReportView_ID=" + AD_ReportView_ID + " - AD_Client_ID=" + AD_Client_ID + " - " + ReportName);
MPrintFormat pf = new MPrintFormat(ctx, 0, null);
pf.setAD_ReportView_ID (AD_ReportView_ID);
// Get Info
String sql = "SELECT t.TableName,"
+ " (SELECT COUNT(*) FROM AD_PrintFormat x WHERE x.AD_ReportView_ID=rv.AD_ReportView_ID AND x.AD_Client_ID=c.AD_Client_ID) AS Count,"
+ " COALESCE (cpc.AD_PrintColor_ID, pc.AD_PrintColor_ID) AS AD_PrintColor_ID,"
+ " COALESCE (cpf.AD_PrintFont_ID, pf.AD_PrintFont_ID) AS AD_PrintFont_ID,"
+ " COALESCE (cpp.AD_PrintPaper_ID, pp.AD_PrintPaper_ID) AS AD_PrintPaper_ID,"
+ " t.AD_Table_ID "
+ "FROM AD_ReportView rv"
+ " INNER JOIN AD_Table t ON (rv.AD_Table_ID=t.AD_Table_ID),"
+ " AD_Client c"
+ " LEFT OUTER JOIN AD_PrintColor cpc ON (cpc.AD_Client_ID=c.AD_Client_ID AND cpc.IsDefault='Y')"
+ " LEFT OUTER JOIN AD_PrintFont cpf ON (cpf.AD_Client_ID=c.AD_Client_ID AND cpf.IsDefault='Y')"
+ " LEFT OUTER JOIN AD_PrintPaper cpp ON (cpp.AD_Client_ID=c.AD_Client_ID AND cpp.IsDefault='Y'),"
+ " AD_PrintColor pc, AD_PrintFont pf, AD_PrintPaper pp "
+ "WHERE rv.AD_ReportView_ID=? AND c.AD_Client_ID=?"
+ " AND pc.IsDefault='Y' AND pf.IsDefault='Y' AND pp.IsDefault='Y'";
boolean error = true;
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, AD_ReportView_ID);
pstmt.setInt(2, AD_Client_ID);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
// Name
String name = ReportName;
if (name == null || name.length() == 0)
name = rs.getString(1); // TableName
int count = rs.getInt(2);
if (count > 0)
name += "_" + count;
pf.setName(name);
//
pf.setAD_PrintColor_ID(rs.getInt(3));
pf.setAD_PrintFont_ID(rs.getInt(4));
pf.setAD_PrintPaper_ID(rs.getInt(5));
//
pf.setAD_Table_ID (rs.getInt(6));
error = false;
}
else
s_log.log(Level.SEVERE, "Not found: AD_ReportView_ID=" + AD_ReportView_ID);
rs.close();
pstmt.close();
}
catch (SQLException e)
{
s_log.log(Level.SEVERE, sql, e);
}
if (error)
return null;
// Save & complete
if (!pf.save())
return null;
// pf.dump();
pf.setItems (createItems(ctx, pf));
//
return pf;
} // createFromReportView
/**
* Create Items.
* Using the display order of Fields in some Tab
* @param ctx context
* @param format print format
* @return items
*/
static private MPrintFormatItem[] createItems (Properties ctx, MPrintFormat format)
{
s_log.fine ("From window Tab ...");
ArrayList<MPrintFormatItem> list = new ArrayList<MPrintFormatItem>();
// Get Column List from Tab
String sql = "SELECT AD_Column_ID " //, Name, IsDisplayed, SeqNo
+ "FROM AD_Field "
+ "WHERE AD_Tab_ID=(SELECT AD_Tab_ID FROM AD_Tab WHERE AD_Table_ID=? AND ROWNUM=1)"
+ " AND IsEncrypted='N' AND ObscureType IS NULL "
+ "ORDER BY COALESCE(IsDisplayed,'N') DESC, SortNo, SeqNo, Name";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, format.get_TrxName());
pstmt.setInt(1, format.getAD_Table_ID());
ResultSet rs = pstmt.executeQuery();
int seqNo = 1;
while (rs.next())
{
MPrintFormatItem pfi = MPrintFormatItem.createFromColumn (format, rs.getInt(1), seqNo++);
if (pfi != null)
{
list.add (pfi);
s_log.finest("Tab: " + pfi);
}
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
s_log.log(Level.SEVERE, "(tab) - " + sql, e);
}
// No Tab found for Table
if (list.size() == 0)
{
s_log.fine("From Table ...");
sql = "SELECT AD_Column_ID "
+ "FROM AD_Column "
+ "WHERE AD_Table_ID=? "
+ "ORDER BY IsIdentifier DESC, SeqNo, Name";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, format.get_TrxName());
pstmt.setInt(1, format.getAD_Table_ID());
ResultSet rs = pstmt.executeQuery();
int seqNo = 1;
while (rs.next())
{
MPrintFormatItem pfi = MPrintFormatItem.createFromColumn (format, rs.getInt(1), seqNo++);
if (pfi != null)
{
list.add (pfi);
s_log.finest("Table: " + pfi);
}
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
s_log.log(Level.SEVERE, "(table) - " + sql, e);
}
}
//
MPrintFormatItem[] retValue = new MPrintFormatItem[list.size()];
list.toArray(retValue);
s_log.info(format + " - #" + retValue.length);
return retValue;
} // createItems
/**
* Copy Items
* @param fromFormat from print format
* @param toFormat to print format (client, id)
* @return items
*/
static private MPrintFormatItem[] copyItems (MPrintFormat fromFormat, MPrintFormat toFormat)
{
s_log.info("From=" + fromFormat);
ArrayList<MPrintFormatItem> list = new ArrayList<MPrintFormatItem>();
MPrintFormatItem[] items = fromFormat.getItems();
for (int i = 0; i < items.length; i++)
{
MPrintFormatItem pfi = items[i].copyToClient (toFormat.getAD_Client_ID(), toFormat.get_ID());
if (pfi != null)
list.add (pfi);
}
//
MPrintFormatItem[] retValue = new MPrintFormatItem[list.size()];
list.toArray(retValue);
copyTranslationItems (items, retValue); // JTP fix
return retValue;
} // copyItems
/**
* Copy translation records (from - to)
* @param fromItems from items
* @param toItems to items
*/
static private void copyTranslationItems (MPrintFormatItem[] fromItems,
MPrintFormatItem[] toItems)
{
if (fromItems == null || toItems == null)
return; // should not happen
int counter = 0;
for (int i = 0; i < fromItems.length; i++)
{
int fromID = fromItems[i].getAD_PrintFormatItem_ID();
int toID = toItems[i].getAD_PrintFormatItem_ID();
StringBuffer sql = new StringBuffer("UPDATE AD_PrintFormatItem_Trl new ")
// Set
.append("SET (PrintName, PrintNameSuffix, IsTranslated) = ")
.append("(")
.append("SELECT PrintName, PrintNameSuffix, IsTranslated ")
.append("FROM AD_PrintFormatItem_Trl old ")
.append("WHERE old.AD_Language=new.AD_Language")
.append(" AND AD_PrintFormatItem_ID =").append(fromID)
.append(") ")
// WHERE
.append("WHERE AD_PrintFormatItem_ID=").append(toID)
.append(" AND EXISTS (SELECT AD_PrintFormatItem_ID ")
.append(" FROM AD_PrintFormatItem_trl old")
.append(" WHERE old.AD_Language=new.AD_Language")
.append(" AND AD_PrintFormatItem_ID =").append(fromID)
.append(")");
int no = DB.executeUpdate(sql.toString(), null);
if (no == 0) // if first has no translation, the rest does neither
break;
counter += no;
} // for
s_log.finest("#" + counter);
} // copyTranslationItems
/**************************************************************************
* Copy existing Definition To Client
* @param ctx context
* @param from_AD_PrintFormat_ID format
* @param to_AD_PrintFormat_ID format
* @return print format
*/
public static MPrintFormat copy (Properties ctx,
int from_AD_PrintFormat_ID, int to_AD_PrintFormat_ID)
{
return copy (ctx, from_AD_PrintFormat_ID, to_AD_PrintFormat_ID, -1);
} // copy
/**
* Copy existing Definition To Client
* @param ctx context
* @param AD_PrintFormat_ID format
* @param to_Client_ID to client
* @return print format
*/
public static MPrintFormat copyToClient (Properties ctx,
int AD_PrintFormat_ID, int to_Client_ID)
{
return copy (ctx, AD_PrintFormat_ID, 0, to_Client_ID);
} // copy
/**
* Copy existing Definition To Client
* @param ctx context
* @param from_AD_PrintFormat_ID format
* @param to_AD_PrintFormat_ID to format or 0 for new
* @param to_Client_ID to client (ignored, if to_AD_PrintFormat_ID <> 0)
* @return print format
*/
private static MPrintFormat copy (Properties ctx, int from_AD_PrintFormat_ID,
int to_AD_PrintFormat_ID, int to_Client_ID)
{
s_log.info ("From AD_PrintFormat_ID=" + from_AD_PrintFormat_ID
+ ", To AD_PrintFormat_ID=" + to_AD_PrintFormat_ID
+ ", To Client_ID=" + to_Client_ID);
if (from_AD_PrintFormat_ID == 0)
throw new IllegalArgumentException ("From_AD_PrintFormat_ID is 0");
//
MPrintFormat from = new MPrintFormat(ctx, from_AD_PrintFormat_ID, null);
MPrintFormat to = new MPrintFormat (ctx, to_AD_PrintFormat_ID, null); // could be 0
MPrintFormat.copyValues (from, to);
// New
if (to_AD_PrintFormat_ID == 0)
{
if (to_Client_ID < 0)
to_Client_ID = Env.getAD_Client_ID(ctx);
to.setClientOrg (to_Client_ID, 0);
}
// Set Name - Remove TEMPLATE - add copy
to.setName(Util.replace(to.getName(), "TEMPLATE", String.valueOf(to_Client_ID)));
to.setName(to.getName()
+ " " + Msg.getMsg(ctx, "Copy")
+ " " + to.hashCode()); // unique name
//
to.save();
// Copy Items
to.setItems(copyItems(from,to));
return to;
} // copyToClient
/*************************************************************************/
/** Cached Formats */
static private CCache<Integer,MPrintFormat> s_formats = new CCache<Integer,MPrintFormat>("AD_PrintFormat", 30);
/**
* Get Format
* @param ctx context
* @param AD_PrintFormat_ID id
* @param readFromDisk refresh from disk
* @return Format
*/
static public MPrintFormat get (Properties ctx, int AD_PrintFormat_ID, boolean readFromDisk)
{
Integer key = new Integer(AD_PrintFormat_ID);
MPrintFormat pf = null;
if (!readFromDisk)
pf = (MPrintFormat)s_formats.get(key);
if (pf == null)
{
pf = new MPrintFormat (ctx, AD_PrintFormat_ID, null);
s_formats.put(key, pf);
}
return pf;
} // get
/**
* Get (default) Printformat for Report View or Table
* @param ctx context
* @param AD_ReportView_ID id or 0
* @param AD_Table_ID id or 0
* @return first print format found or null
*/
static public MPrintFormat get (Properties ctx, int AD_ReportView_ID, int AD_Table_ID)
{
MPrintFormat retValue = null;
PreparedStatement pstmt = null;
String sql = "SELECT * FROM AD_PrintFormat WHERE ";
if (AD_ReportView_ID > 0)
sql += "AD_ReportView_ID=?";
else
sql += "AD_Table_ID=?";
sql += " ORDER BY IsDefault DESC";
try
{
pstmt = DB.prepareStatement (sql, null);
pstmt.setInt (1, AD_ReportView_ID > 0 ? AD_ReportView_ID : AD_Table_ID);
ResultSet rs = pstmt.executeQuery ();
if (rs.next ())
retValue = new MPrintFormat (ctx, rs, null);
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
s_log.log(Level.SEVERE, sql, e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
return retValue;
} // get
/**
* Delete Format from Cache
* @param AD_PrintFormat_ID id
*/
static public void deleteFromCache (int AD_PrintFormat_ID)
{
Integer key = new Integer(AD_PrintFormat_ID);
s_formats.put(key, null);
} // deleteFromCache
/**************************************************************************
* Test
* @param args arga
*/
static public void main (String[] args)
{
org.compiere.Adempiere.startup(true);
/**
MPrintFormat.createFromTable(Env.getCtx(), 496); // Order
MPrintFormat.createFromTable(Env.getCtx(), 497);
MPrintFormat.createFromTable(Env.getCtx(), 516); // Invoice
MPrintFormat.createFromTable(Env.getCtx(), 495);
MPrintFormat.createFromTable(Env.getCtx(), 500); // Shipment
MPrintFormat.createFromTable(Env.getCtx(), 501);
MPrintFormat.createFromTable(Env.getCtx(), 498); // Check
MPrintFormat.createFromTable(Env.getCtx(), 499);
MPrintFormat.createFromTable(Env.getCtx(), 498); // Remittance
**/
} // main
} // MPrintFormat

View File

@ -0,0 +1,596 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.model.*;
import org.compiere.util.*;
/**
* Print Format Item Model.
* Caches Column Name
* (Add missing Items with PrintFormatUtil)
*
* @author Jorg Janke
* @version $Id: MPrintFormatItem.java,v 1.3 2006/08/03 22:17:17 jjanke Exp $
*/
public class MPrintFormatItem extends X_AD_PrintFormatItem
{
/**
* Constructor
* @param ctx context
* @param AD_PrintFormatItem_ID AD_PrintFormatItem_ID
* @param trxName transaction
*/
public MPrintFormatItem (Properties ctx, int AD_PrintFormatItem_ID, String trxName)
{
super (ctx, AD_PrintFormatItem_ID, trxName);
// Default Setting
if (AD_PrintFormatItem_ID == 0)
{
setFieldAlignmentType(FIELDALIGNMENTTYPE_Default);
setLineAlignmentType(LINEALIGNMENTTYPE_None);
setPrintFormatType(PRINTFORMATTYPE_Text);
setPrintAreaType(PRINTAREATYPE_Content);
setShapeType(SHAPETYPE_NormalRectangle);
//
setIsCentrallyMaintained(true);
setIsRelativePosition(true);
setIsNextLine(false);
setIsNextPage(false);
setIsSetNLPosition(false);
setIsFilledRectangle(false);
setIsImageField(false);
setXSpace(0);
setYSpace(0);
setXPosition(0);
setYPosition(0);
setMaxWidth(0);
setIsFixedWidth(false);
setIsHeightOneLine(false);
setMaxHeight(0);
setLineWidth(1);
setArcDiameter(0);
//
setIsOrderBy(false);
setSortNo(0);
setIsGroupBy(false);
setIsPageBreak(false);
setIsSummarized(false);
setIsAveraged(false);
setIsCounted(false);
setIsMinCalc(false);
setIsMaxCalc(false);
setIsVarianceCalc(false);
setIsDeviationCalc(false);
setIsRunningTotal(false);
setImageIsAttached(false);
setIsSuppressNull(false);
}
} // MPrintFormatItem
/**
* Constructor
* @param ctx context
* @param rs ResultSet
* @param trxName transaction
*/
public MPrintFormatItem (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MPrintFormatItem
/** Locally cached column name */
private String m_columnName = null;
/** Locally cached label translations */
private HashMap<String,String> m_translationLabel;
/** Locally cached suffix translations */
private HashMap<String,String> m_translationSuffix;
private static CLogger s_log = CLogger.getCLogger (MPrintFormatItem.class);
/**************************************************************************
* Get print name with language
* @param language language - ignored if IsMultiLingualDocument not 'Y'
* @return print name
*/
public String getPrintName (Language language)
{
if (language == null || Env.isBaseLanguage(language, "AD_PrintFormatItem"))
return getPrintName();
loadTranslations();
String retValue = (String)m_translationLabel.get(language.getAD_Language());
if (retValue == null || retValue.length() == 0)
return getPrintName();
return retValue;
} // getPrintName
/**
* Get print name suffix with language
* @param language language - ignored if IsMultiLingualDocument not 'Y'
* @return print name suffix
*/
public String getPrintNameSuffix (Language language)
{
if (language == null || Env.isBaseLanguage(language, "AD_PrintFormatItem"))
return getPrintNameSuffix();
loadTranslations();
String retValue = (String)m_translationSuffix.get(language.getAD_Language());
if (retValue == null || retValue.length() == 0)
return getPrintNameSuffix();
return retValue;
} // getPrintNameSuffix
/**
* Load Translations
*/
private void loadTranslations()
{
if (m_translationLabel == null)
{
m_translationLabel = new HashMap<String,String>();
m_translationSuffix = new HashMap<String,String>();
String sql = "SELECT AD_Language, PrintName, PrintNameSuffix FROM AD_PrintFormatItem_Trl WHERE AD_PrintFormatItem_ID=?";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, get_ID());
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
m_translationLabel.put (rs.getString (1), rs.getString (2));
m_translationSuffix.put (rs.getString (1), rs.getString (3));
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, "loadTrl", e);
}
}
} // loadTranslations
/**
* Type Field
* @return true if field
*/
public boolean isTypeField()
{
return getPrintFormatType().equals(PRINTFORMATTYPE_Field);
}
/**
* Type Text
* @return true if text
*/
public boolean isTypeText()
{
return getPrintFormatType().equals(PRINTFORMATTYPE_Text);
}
/**
* Type Print Format
* @return true if print format
*/
public boolean isTypePrintFormat()
{
return getPrintFormatType().equals(PRINTFORMATTYPE_PrintFormat);
}
/**
* Type Image
* @return true if image
*/
public boolean isTypeImage()
{
return getPrintFormatType().equals(PRINTFORMATTYPE_Image);
}
/**
* Type Box
* @return true if box
*/
public boolean isTypeBox()
{
return getPrintFormatType().equals(PRINTFORMATTYPE_Line)
|| getPrintFormatType().equals(PRINTFORMATTYPE_Rectangle);
}
/**
* Field Center
* @return true if center
*/
public boolean isFieldCenter()
{
return getFieldAlignmentType().equals(FIELDALIGNMENTTYPE_Center);
}
/**
* Field Align Leading
* @return true if leading
*/
public boolean isFieldAlignLeading()
{
return getFieldAlignmentType().equals(FIELDALIGNMENTTYPE_LeadingLeft);
}
/**
* Field Align Trailing
* @return true if trailing
*/
public boolean isFieldAlignTrailing()
{
return getFieldAlignmentType().equals(FIELDALIGNMENTTYPE_TrailingRight);
}
/**
* Field Align Block
* @return true if block
*/
public boolean isFieldAlignBlock()
{
return getFieldAlignmentType().equals(FIELDALIGNMENTTYPE_Block);
}
/**
* Field Align Default
* @return true if default alignment
*/
public boolean isFieldAlignDefault()
{
return getFieldAlignmentType().equals(FIELDALIGNMENTTYPE_Default);
}
/**
* Line Align Center
* @return true if center
*/
public boolean isLineAlignCenter()
{
return getLineAlignmentType().equals(LINEALIGNMENTTYPE_Center);
}
/**
* Line Align Leading
* @return true if leading
*/
public boolean isLineAlignLeading()
{
return getLineAlignmentType().equals(LINEALIGNMENTTYPE_LeadingLeft);
}
/**
* Line Align Trailing
* @return true if trailing
*/
public boolean isLineAlignTrailing()
{
return getLineAlignmentType().equals(LINEALIGNMENTTYPE_TrailingRight);
}
/**
* Header
* @return true if area is header
*/
public boolean isHeader()
{
return getPrintAreaType().equals(PRINTAREATYPE_Header);
}
/**
* Content
* @return true if area is centent
*/
public boolean isContent()
{
return getPrintAreaType().equals(PRINTAREATYPE_Content);
}
/**
* Footer
* @return true if area is footer
*/
public boolean isFooter()
{
return getPrintAreaType().equals(PRINTAREATYPE_Footer);
}
/**
* Barcode
* @return true if barcode selected
*/
public boolean isBarcode()
{
String s = getBarcodeType();
return s != null && s.length() > 0;
}
/**************************************************************************
* String representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer("MPrintFormatItem[");
sb.append("ID=").append(get_ID())
.append(",Name=").append(getName())
.append(",Print=").append(getPrintName())
.append(", Seq=").append(getSeqNo())
.append(",Sort=").append(getSortNo())
.append(", Area=").append(getPrintAreaType())
.append(", MaxWidth=").append(getMaxWidth())
.append(",MaxHeight=").append(getMaxHeight())
.append(",OneLine=").append(isHeightOneLine())
.append(", Relative=").append(isRelativePosition());
if (isRelativePosition())
sb.append(",X=").append(getXSpace()).append(",Y=").append(getYSpace())
.append(",LineAlign=").append(getLineAlignmentType())
.append(",NewLine=").append(isNextLine())
.append(",NewPage=").append(isPageBreak());
else
sb.append(",X=").append(getXPosition()).append(",Y=").append(getYPosition());
sb.append(",FieldAlign=").append(getFieldAlignmentType());
//
sb.append(", Type=").append(getPrintFormatType());
if (isTypeText())
;
else if (isTypeField())
sb.append(",AD_Column_ID=").append(getAD_Column_ID());
else if (isTypePrintFormat())
sb.append(",AD_PrintFormatChild_ID=").append(getAD_PrintFormatChild_ID())
.append(",AD_Column_ID=").append(getAD_Column_ID());
else if (isTypeImage())
sb.append(",ImageIsAttached=").append(isImageIsAttached()).append(",ImageURL=").append(getImageURL());
//
sb.append(", Printed=").append(isPrinted())
.append(",SeqNo=").append(getSeqNo())
.append(",OrderBy=").append(isOrderBy())
.append(",SortNo=").append(getSortNo())
.append(",Summarized=").append(isSummarized());
sb.append("]");
return sb.toString();
} // toString
/*************************************************************************/
/** Lookup Map of AD_Column_ID for ColumnName */
private static CCache<Integer,String> s_columns = new CCache<Integer,String>("AD_PrintFormatItem", 200);
/**
* Get ColumnName from AD_Column_ID
* @return ColumnName
*/
public String getColumnName()
{
if (m_columnName == null) // Get Column Name from AD_Column not index
m_columnName = getColumnName (new Integer(getAD_Column_ID()));
return m_columnName;
} // getColumnName
/**
* Get Column Name from AD_Column_ID.
* Be careful not to confuse it with PO method getAD_Column_ID (index)
* @param AD_Column_ID column
* @return Column Name
*/
private static String getColumnName (Integer AD_Column_ID)
{
if (AD_Column_ID == null || AD_Column_ID.intValue() == 0)
return null;
//
String retValue = (String)s_columns.get(AD_Column_ID);
if (retValue == null)
{
String sql = "SELECT ColumnName FROM AD_Column WHERE AD_Column_ID=?";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, AD_Column_ID.intValue());
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
retValue = rs.getString(1);
s_columns.put(AD_Column_ID, retValue);
}
else
s_log.log(Level.SEVERE, "Not found AD_Column_ID=" + AD_Column_ID);
rs.close();
pstmt.close();
}
catch (SQLException e)
{
s_log.log(Level.SEVERE, "AD_Column_ID=" + AD_Column_ID, e);
}
}
return retValue;
} // getColumnName
/**************************************************************************
* Create Print Format Item from Column
* @param format parent
* @param AD_Column_ID column
* @param seqNo sequence of display if 0 it is not printed
* @return Print Format Item
*/
public static MPrintFormatItem createFromColumn (MPrintFormat format, int AD_Column_ID, int seqNo)
{
MPrintFormatItem pfi = new MPrintFormatItem (format.getCtx(), 0, null);
pfi.setAD_PrintFormat_ID (format.getAD_PrintFormat_ID());
pfi.setClientOrg(format);
pfi.setAD_Column_ID(AD_Column_ID);
pfi.setPrintFormatType(PRINTFORMATTYPE_Field);
// translation is dome by trigger
String sql = "SELECT c.ColumnName,e.Name,e.PrintName, " // 1..3
+ "c.AD_Reference_ID,c.IsKey,c.SeqNo " // 4..6
+ "FROM AD_Column c, AD_Element e "
+ "WHERE c.AD_Column_ID=?"
+ " AND c.AD_Element_ID=e.AD_Element_ID";
// translate base entry if single language - trigger copies to trl tables
Language language = format.getLanguage();
boolean trl = !Env.isMultiLingualDocument(format.getCtx()) && !language.isBaseLanguage();
if (trl)
sql = "SELECT c.ColumnName,e.Name,e.PrintName, " // 1..3
+ "c.AD_Reference_ID,c.IsKey,c.SeqNo " // 4..6
+ "FROM AD_Column c, AD_Element_Trl e "
+ "WHERE c.AD_Column_ID=?"
+ " AND c.AD_Element_ID=e.AD_Element_ID"
+ " AND e.AD_Language=?";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, AD_Column_ID);
if (trl)
pstmt.setString(2, language.getAD_Language());
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
String ColumnName = rs.getString(1);
pfi.setName(rs.getString(2));
pfi.setPrintName(rs.getString(3));
int displayType = rs.getInt(4);
if (DisplayType.isNumeric(displayType))
pfi.setFieldAlignmentType(FIELDALIGNMENTTYPE_TrailingRight);
else if (displayType == DisplayType.Text || displayType == DisplayType.Memo )
pfi.setFieldAlignmentType(FIELDALIGNMENTTYPE_Block);
else
pfi.setFieldAlignmentType(FIELDALIGNMENTTYPE_LeadingLeft);
boolean isKey = "Y".equals(rs.getString(5));
//
if (isKey
|| ColumnName.startsWith("Created") || ColumnName.startsWith("Updated")
|| ColumnName.equals("AD_Client_ID") || ColumnName.equals("AD_Org_ID")
|| ColumnName.equals("IsActive")
|| displayType == DisplayType.Button || displayType == DisplayType.Binary
|| displayType == DisplayType.ID || displayType == DisplayType.Image
|| displayType == DisplayType.RowID
|| seqNo == 0 )
{
pfi.setIsPrinted(false);
pfi.setSeqNo(0);
}
else
{
pfi.setIsPrinted(true);
pfi.setSeqNo(seqNo);
}
int idSeqNo = rs.getInt(6); // IsIdentifier SortNo
if (idSeqNo > 0)
{
pfi.setIsOrderBy(true);
pfi.setSortNo(idSeqNo);
}
}
else
s_log.log(Level.SEVERE, "Not Found AD_Column_ID=" + AD_Column_ID
+ " Trl=" + trl + " " + language.getAD_Language());
rs.close();
pstmt.close();
}
catch (SQLException e)
{
s_log.log(Level.SEVERE, sql, e);
}
if (!pfi.save())
return null;
// pfi.dump();
return pfi;
} // createFromColumn
/**
* Copy existing Definition To Client
* @param To_Client_ID to client
* @param AD_PrintFormat_ID parent print format
* @return print format item
*/
public MPrintFormatItem copyToClient (int To_Client_ID, int AD_PrintFormat_ID)
{
MPrintFormatItem to = new MPrintFormatItem (p_ctx, 0, null);
MPrintFormatItem.copyValues(this, to);
to.setClientOrg(To_Client_ID, 0);
to.setAD_PrintFormat_ID(AD_PrintFormat_ID);
to.save();
return to;
} // copyToClient
/**
* Before Save
* @param newRecord
* @return true if ok
*/
protected boolean beforeSave (boolean newRecord)
{
// Order
if (!isOrderBy())
{
setSortNo(0);
setIsGroupBy(false);
setIsPageBreak(false);
}
// Rel Position
if (isRelativePosition())
{
setXPosition(0);
setYPosition(0);
}
else
{
setXSpace(0);
setYSpace(0);
}
// Image
if (isImageField())
{
setImageIsAttached(false);
setImageURL(null);
}
return true;
} // beforeSave
/**
* After Save
* @param newRecord new
* @param success success
* @return success
*/
protected boolean afterSave (boolean newRecord, boolean success)
{
// Set Translation from Element
if (newRecord
// && MClient.get(getCtx()).isMultiLingualDocument()
&& getPrintName() != null && getPrintName().length() > 0)
{
String sql = "UPDATE AD_PrintFormatItem_Trl trl "
+ "SET PrintName = (SELECT e.PrintName "
+ "FROM AD_Element_Trl e, AD_Column c "
+ "WHERE e.AD_Language=trl.AD_Language"
+ " AND e.AD_Element_ID=c.AD_Element_ID"
+ " AND c.AD_Column_ID=" + getAD_Column_ID() + ") "
+ "WHERE AD_PrintFormatItem_ID = " + get_ID()
+ " AND EXISTS (SELECT * "
+ "FROM AD_Element_Trl e, AD_Column c "
+ "WHERE e.AD_Language=trl.AD_Language"
+ " AND e.AD_Element_ID=c.AD_Element_ID"
+ " AND c.AD_Column_ID=" + getAD_Column_ID()
+ " AND trl.AD_PrintFormatItem_ID = " + get_ID() + ")"
+ " AND EXISTS (SELECT * FROM AD_Client "
+ "WHERE AD_Client_ID=trl.AD_Client_ID AND IsMultiLingualDocument='Y')";
int no = DB.executeUpdate(sql, get_TrxName());
log.fine("translations updated #" + no);
}
return success;
} // afterSave
} // MPrintFormatItem

View File

@ -0,0 +1,87 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.math.*;
import org.compiere.process.*;
/**
* MPrintFormat Process.
* Performs Copy existing or Create from Table
* Called when pressing the Copy/Create button in Window Print Format
*
* @author Jorg Janke
* @version $Id: MPrintFormatProcess.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $
*/
public class MPrintFormatProcess extends SvrProcess
{
/** PrintFormat */
private BigDecimal m_AD_PrintFormat_ID;
/** Table */
private BigDecimal m_AD_Table_ID;
/**
* Prepare - get Parameters.
*/
protected void prepare()
{
ProcessInfoParameter[] para = getParameter();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else if (name.equals("AD_PrintFormat_ID"))
m_AD_PrintFormat_ID = ((BigDecimal)para[i].getParameter());
else if (name.equals("AD_Table_ID"))
m_AD_Table_ID = ((BigDecimal)para[i].getParameter());
else
log.equals("prepare - Unknown Parameter=" + para[i].getParameterName());
}
} // prepare
/**
* Perrform process.
* <pre>
* If AD_Table_ID is not null, create from table,
* otherwise copy from AD_PrintFormat_ID
* </pre>
* @return Message
* @throws Exception
*/
protected String doIt() throws Exception
{
if (m_AD_Table_ID != null && m_AD_Table_ID.intValue() > 0)
{
log.info("Create from AD_Table_ID=" + m_AD_Table_ID);
MPrintFormat pf = MPrintFormat.createFromTable(getCtx(), m_AD_Table_ID.intValue(), getRecord_ID());
addLog(m_AD_Table_ID.intValue(), null, new BigDecimal(pf.getItemCount()), pf.getName());
return pf.getName() + " #" + pf.getItemCount();
}
else if (m_AD_PrintFormat_ID != null && m_AD_PrintFormat_ID.intValue() > 0)
{
log.info("Copy from AD_PrintFormat_ID=" + m_AD_PrintFormat_ID);
MPrintFormat pf = MPrintFormat.copy (getCtx(), m_AD_PrintFormat_ID.intValue(), getRecord_ID());
addLog(m_AD_PrintFormat_ID.intValue(), null, new BigDecimal(pf.getItemCount()), pf.getName());
return pf.getName() + " #" + pf.getItemCount();
}
else
throw new Exception (MSG_InvalidArguments);
} // doIt
} // MPrintFormatProcess

View File

@ -0,0 +1,54 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.sql.*;
import java.util.*;
import org.compiere.model.*;
/**
* Graph Model
*
* @author Jorg Janke
* @version $Id: MPrintGraph.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $
*/
public class MPrintGraph extends X_AD_PrintGraph
{
/**
* Standard Constructor
* @param ctx context
* @param AD_PrintGraph_ID graph id
* @param trxName trx
*/
public MPrintGraph (Properties ctx, int AD_PrintGraph_ID, String trxName)
{
super (ctx, AD_PrintGraph_ID, trxName);
} // MPrintGraph
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName trx
*/
public MPrintGraph (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MPrintGraph
} // MPrintGraph

View File

@ -0,0 +1,252 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.sql.*;
import java.util.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;
import org.compiere.model.*;
import org.compiere.util.*;
/**
* AD_PrintPaper Print Paper Model
*
* @author Jorg Janke
* @version $Id: MPrintPaper.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $
*/
public class MPrintPaper extends X_AD_PrintPaper
{
/**
* Get Paper
* @param AD_PrintPaper_ID id
* @return Paper
*/
static public MPrintPaper get (int AD_PrintPaper_ID)
{
Integer key = new Integer(AD_PrintPaper_ID);
MPrintPaper pp = (MPrintPaper)s_papers.get(key);
if (pp == null)
{
pp = new MPrintPaper (Env.getCtx(), AD_PrintPaper_ID, null);
s_papers.put(key, pp);
}
else
s_log.config("AD_PrintPaper_ID=" + AD_PrintPaper_ID);
return pp;
} // get
/**
* Create Paper and save
* @param name name
* @param landscape landscape
* @return Paper
*/
static MPrintPaper create (String name, boolean landscape)
{
MPrintPaper pp = new MPrintPaper (Env.getCtx(), 0, null);
pp.setName(name);
pp.setIsLandscape(landscape);
pp.save();
return pp;
} // create
/** Logger */
private static CLogger s_log = CLogger.getCLogger(MPrintPaper.class);
/** Cached Fonts */
static private CCache<Integer,MPrintPaper> s_papers
= new CCache<Integer,MPrintPaper>("AD_PrintPaper", 5);
/**************************************************************************
* Constructor
* @param ctx context
* @param AD_PrintPaper_ID ID if 0 A4
* @param trxName transaction
*/
public MPrintPaper(Properties ctx, int AD_PrintPaper_ID, String trxName)
{
super(ctx, AD_PrintPaper_ID, trxName);
if (AD_PrintPaper_ID == 0)
{
setIsDefault (false);
setIsLandscape (true);
setCode ("iso-a4");
setMarginTop (36);
setMarginBottom (36);
setMarginLeft (36);
setMarginRight (36);
}
} // MPrintPaper
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName trx
*/
public MPrintPaper (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MPrintPaper
/** Media Size */
private MediaSize m_mediaSize = null;
/**************************************************************************
* Get Media Size.
* The search is hard coded as the javax.print.MediaSize* info is private
* @return MediaSize from Code
*/
public MediaSize getMediaSize()
{
if (m_mediaSize != null)
return m_mediaSize;
//
String nameCode = getCode();
if (nameCode != null)
{
// Get Name
MediaSizeName nameMedia = null;
CMediaSizeName msn = new CMediaSizeName(4);
String[] names = msn.getStringTable();
for (int i = 0; i < names.length; i++)
{
String name = names[i];
if (name.equalsIgnoreCase(nameCode))
{
nameMedia = (MediaSizeName)msn.getEnumValueTable()[i];
log.finer("Name=" + nameMedia);
break;
}
}
if (nameMedia != null)
{
m_mediaSize = MediaSize.getMediaSizeForName(nameMedia);
log.fine("Name->Size=" + m_mediaSize);
}
}
// Create New Media Size
if (m_mediaSize == null)
{
float x = getSizeX().floatValue();
float y = getSizeY().floatValue();
if (x > 0 && y > 0)
{
m_mediaSize = new MediaSize(x, y, getUnitsInt(), MediaSizeName.A);
log.fine("Size=" + m_mediaSize);
}
}
// Fallback
if (m_mediaSize == null)
m_mediaSize = getMediaSizeDefault();
return m_mediaSize;
} // getMediaSize
/**
* Get Media Size
* @return Default Media Size based on Language
*/
public MediaSize getMediaSizeDefault()
{
m_mediaSize = Language.getLoginLanguage().getMediaSize();
if (m_mediaSize == null)
m_mediaSize = MediaSize.ISO.A4;
log.fine("Size=" + m_mediaSize);
return m_mediaSize;
} // getMediaSizeDefault
/**
* Get Units Int
* @return units
*/
public int getUnitsInt()
{
String du = getDimensionUnits();
if (du == null || DIMENSIONUNITS_MM.equals(du))
return Size2DSyntax.MM;
else
return Size2DSyntax.INCH;
} // getUnits
/**
* Get CPaper
* @return CPaper
*/
public CPaper getCPaper()
{
CPaper retValue = new CPaper (getMediaSize(), isLandscape(),
getMarginLeft(), getMarginTop(), getMarginRight(), getMarginBottom());
return retValue;
} // getCPaper
/**
* Media Size Name
*/
class CMediaSizeName extends MediaSizeName
{
/**
* CMediaSizeName
* @param code
*/
public CMediaSizeName(int code)
{
super (code);
} // CMediaSizeName
/**
* Get String Table
* @return string
*/
public String[] getStringTable ()
{
return super.getStringTable ();
}
/**
* Get Enum Value Table
* @return Media Sizes
*/
public EnumSyntax[] getEnumValueTable ()
{
return super.getEnumValueTable ();
}
} // CMediaSizeName
/**************************************************************************
* Test
* @param args args
*/
public static void main(String[] args)
{
org.compiere.Adempiere.startupEnvironment(true);
// create ("Standard Landscape", true);
// create ("Standard Portrait", false);
// Read All Papers
int[] IDs = PO.getAllIDs ("AD_PrintPaper", null, null);
for (int i = 0; i < IDs.length; i++)
{
System.out.println("--");
MPrintPaper pp = new MPrintPaper(Env.getCtx(), IDs[i], null);
pp.dump();
}
}
} // MPrintPaper

View File

@ -0,0 +1,597 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.awt.*;
import java.math.*;
import java.sql.*;
import java.util.*;
import org.compiere.model.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Table Print Format
*
* @author Jorg Janke
* @version $Id: MPrintTableFormat.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $
*/
public class MPrintTableFormat extends X_AD_PrintTableFormat
{
/**
* Standard Constructor
* @param ctx context
* @param AD_PrintTableFormat_ID table format
* @param trxName transaction
*/
public MPrintTableFormat (Properties ctx, int AD_PrintTableFormat_ID, String trxName)
{
super (ctx, AD_PrintTableFormat_ID, trxName);
if (AD_PrintTableFormat_ID == 0)
{
// setName (null);
setIsDefault (false);
setIsPaintHeaderLines (true); // Y
setIsPaintBoundaryLines (false);
setIsPaintHLines (false);
setIsPaintVLines (false);
setIsPrintFunctionSymbols (true);
}
} // MPrintTableFormat
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MPrintTableFormat (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MPrintTableFormat
/*************************************************************************/
private Font standard_Font = new Font(null);
private Font pageHeader_Font;
private Font pageFooter_Font;
private Color pageHeaderFG_Color;
private Color pageHeaderBG_Color;
private Color pageFooterFG_Color;
private Color pageFooterBG_Color;
private Font parameter_Font;
private Color parameter_Color;
private Font header_Font;
private Color headerFG_Color;
private Color headerBG_Color;
private Color hdrLine_Color;
private Stroke header_Stroke; // -
private Font funct_Font;
private Color functFG_Color;
private Color functBG_Color;
private Color lineH_Color;
private Color lineV_Color;
private Stroke lineH_Stroke; // -
private Stroke lineV_Stroke; // |
//
/**************************************************************************
* Set Standard Font to derive other fonts if not defined
* @param standardFont standard font
*/
public void setStandard_Font(Font standardFont)
{
if (standardFont != null)
standard_Font = standardFont;
} // setStandard_Font
/**
* Get Stndard Font
* @return stndard font
*/
public Font getStandard_Font()
{
return standard_Font;
} // getStandard_Font
/**************************************************************************
* Get Table Header Font
* @return table header font or Bold standard font
*/
public Font getHeader_Font()
{
if (header_Font != null)
return header_Font;
int i = getHdr_PrintFont_ID();
if (i != 0)
header_Font = MPrintFont.get(i).getFont();
if (header_Font == null)
header_Font = new Font (standard_Font.getName(), Font.BOLD, standard_Font.getSize());
return header_Font;
} // getHeader_Font
/**
* Get Header Foreground
* @return color or blue black
*/
public Color getHeaderFG_Color()
{
if (headerFG_Color != null)
return headerFG_Color;
int i = getHdrTextFG_PrintColor_ID();
if (i != 0)
headerFG_Color = MPrintColor.get(getCtx(), i).getColor();
if (headerFG_Color == null)
headerFG_Color = MPrintColor.blackBlue;
return headerFG_Color;
} // getHeaderFG_Color
/**
* Get Header BG Color
* @return color or cyan
*/
public Color getHeaderBG_Color()
{
if (headerBG_Color != null)
return headerBG_Color;
int i = getHdrTextBG_PrintColor_ID();
if (i != 0)
headerBG_Color = MPrintColor.get(getCtx(), i).getColor();
if (headerBG_Color == null)
headerBG_Color = Color.cyan;
return headerBG_Color;
} // getHeaderBG_Color
/**
* Get Header Line Color
* @return color or blue black
*/
public Color getHeaderLine_Color()
{
if (hdrLine_Color != null)
return hdrLine_Color;
int i = getHdrLine_PrintColor_ID();
if (i != 0)
hdrLine_Color = MPrintColor.get(getCtx(), i).getColor();
if (hdrLine_Color == null)
hdrLine_Color = MPrintColor.blackBlue;
return hdrLine_Color;
} // getHeaderLine_Color
/**
* Get Header Stroke
* @return Header Stroke (default solid 2pt)
*/
public Stroke getHeader_Stroke()
{
if (header_Stroke == null)
{
float width = getHdrStroke().floatValue();
if (getHdrStrokeType() == null || HDRSTROKETYPE_SolidLine.equals(getHdrStrokeType()))
header_Stroke = new BasicStroke(width); // -
//
else if (HDRSTROKETYPE_DashedLine.equals(getHdrStrokeType()))
header_Stroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL,
1.0f, getPatternDashed(width), 0.0f); // - -
else if (HDRSTROKETYPE_DottedLine.equals(getHdrStrokeType()))
header_Stroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL,
1.0f, getPatternDotted(width), 0.0f); // . . .
else if (HDRSTROKETYPE_Dash_DottedLine.equals(getHdrStrokeType()))
header_Stroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL,
1.0f, getPatternDash_Dotted(width), 0.0f); // - . -
// default / fallback
if (header_Stroke == null)
header_Stroke = new BasicStroke(width); // -
}
return header_Stroke;
} // getHeader_Stroke
/**
* Get Header Stroke for horizontal Lines
* @return stroke in pt (default 2)
*/
public BigDecimal getHdrStroke()
{
BigDecimal retValue = super.getHdrStroke();
if (retValue == null || Env.ZERO.compareTo(retValue) <= 0)
retValue = new BigDecimal (2.0);
return retValue;
} // getHdrStroke
/**************************************************************************
* Get Function Font
* @return function font or BoldItalic standard font
*/
public Font getFunct_Font()
{
if (funct_Font != null)
return funct_Font;
int i = getFunct_PrintFont_ID();
if (i != 0)
funct_Font = MPrintFont.get(i).getFont();
if (funct_Font == null)
funct_Font = new Font (standard_Font.getName(), Font.BOLD|Font.ITALIC, standard_Font.getSize());
return funct_Font;
} // getFunct_Font
/**
* Get Function BG Color
* @return color or white
*/
public Color getFunctBG_Color()
{
if (functBG_Color != null)
return functBG_Color;
int i = getFunctBG_PrintColor_ID();
if (i != 0)
functBG_Color = MPrintColor.get(getCtx(), i).getColor();
if (functBG_Color == null)
functBG_Color = Color.white;
return functBG_Color;
} // getFunctBG_Color
/**
* Get Function FG Color
* @return color or green dark
*/
public Color getFunctFG_Color()
{
if (functFG_Color != null)
return functFG_Color;
int i = getFunctFG_PrintColor_ID();
if (i != 0)
functFG_Color = MPrintColor.get(getCtx(), i).getColor();
if (functFG_Color == null)
functFG_Color = MPrintColor.darkGreen;
return functFG_Color;
} // getFunctFG_Color
/**************************************************************************
* Get Parameter Font
* @return Italic standard font
*/
public Font getParameter_Font()
{
if (parameter_Font == null)
parameter_Font = new Font (standard_Font.getName(), Font.ITALIC, standard_Font.getSize());
return parameter_Font;
} // getParameter_Font
/**
* Get Parameter Color
* @return dark gray
*/
public Color getParameter_Color()
{
if (parameter_Color == null)
parameter_Color = Color.darkGray;
return parameter_Color;
} // getParameter_Color
/**************************************************************************
* Get Top Page Header Font
* @return Bold standard font
*/
public Font getPageHeader_Font()
{
if (pageHeader_Font == null)
pageHeader_Font = new Font (standard_Font.getName(), Font.BOLD, standard_Font.getSize());
return pageHeader_Font;
} // getPageHeader_Font
/**
* Get Page Header FG_Color
* @return color or blue black
*/
public Color getPageHeaderFG_Color()
{
if (pageHeaderFG_Color == null)
pageHeaderFG_Color = MPrintColor.blackBlue;
return pageHeaderFG_Color;
} // getPageHeaderFG_Color
/**
* Get Page Header BG_Color
* @return color or white
*/
public Color getPageHeaderBG_Color()
{
if (pageHeaderBG_Color == null)
pageHeaderBG_Color = Color.white;
return pageHeaderBG_Color;
} // getPageHeaderBG_Color
/**
* Get Page Footer Font
* @return 2pt smaller standard font
*/
public Font getPageFooter_Font()
{
if (pageFooter_Font == null)
pageFooter_Font = new Font (standard_Font.getName(), Font.PLAIN, standard_Font.getSize()-2);
return pageFooter_Font;
} // getPageFooter_Font
/**
* Get PageFooter FG_Color
* @return blue black
*/
public Color getPageFooterFG_Color()
{
if (pageFooterFG_Color == null)
pageFooterFG_Color = MPrintColor.blackBlue;
return pageFooterFG_Color;
} // getPageFooterFG_Color
/**
* Get Page Footer BG_Color
* @return white
*/
public Color getPageFooterBG_Color()
{
if (pageFooterBG_Color == null)
pageFooterBG_Color = Color.white;
return pageFooterBG_Color;
} // getPageFooterBG_Color
/**************************************************************************
* Get Horizontal Line Color.
* (one db attribute for line color)
* @return color or gray light
*/
public Color getHLine_Color()
{
if (lineH_Color != null)
return lineH_Color;
int i = getLine_PrintColor_ID();
if (i != 0)
lineH_Color = MPrintColor.get(getCtx(), i).getColor();
if (lineH_Color == null)
lineH_Color = Color.lightGray;
return lineH_Color;
} // getHLine_Color
/**
* Get Verical Line Color.
* (one db attribute for line color)
* @return color or gray light
*/
public Color getVLine_Color()
{
if (lineV_Color != null)
return lineV_Color;
int i = getLine_PrintColor_ID();
if (i != 0)
lineV_Color = MPrintColor.get(getCtx(), i).getColor();
if (lineV_Color == null)
lineV_Color = Color.lightGray;
return lineV_Color;
} // getVLine_Color
/**
* Get Horizontal Line Stroke -
* (same DB line column)
* @return solid line baded on line width (default solid 1p)
*/
public Stroke getHLine_Stroke()
{
if (lineH_Stroke == null)
{
float width = getLineStroke().floatValue() / 2;
if (getHdrStrokeType() == null || LINESTROKETYPE_DottedLine.equals(getLineStrokeType()))
lineH_Stroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL,
1.0f, getPatternDotted(width), 0.0f); // . . .
//
else if (LINESTROKETYPE_SolidLine.equals(getLineStrokeType()))
lineH_Stroke = new BasicStroke(width); // -
else if (LINESTROKETYPE_DashedLine.equals(getLineStrokeType()))
lineH_Stroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL,
1.0f, getPatternDashed(width), 0.0f); // - -
else if (LINESTROKETYPE_Dash_DottedLine.equals(getLineStrokeType()))
lineH_Stroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL,
1.0f, getPatternDash_Dotted(width), 0.0f); // - . -
// default / fallback
if (lineH_Stroke == null)
lineH_Stroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL,
1.0f, getPatternDotted(width), 0.0f); // . . .
}
return lineH_Stroke;
} // getHLine_Stroke
/**
* Get Vertical Line Stroke |
* (same DB line column)
* @return line based on line (1/2 of) width and stroke (default dotted 1/2p
*/
public Stroke getVLine_Stroke()
{
if (lineV_Stroke == null)
{
float width = getLineStroke().floatValue() / 2;
if (getHdrStrokeType() == null || LINESTROKETYPE_DottedLine.equals(getLineStrokeType()))
lineV_Stroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL,
1.0f, getPatternDotted(width), 0.0f); // . . .
//
else if (LINESTROKETYPE_SolidLine.equals(getLineStrokeType()))
lineV_Stroke = new BasicStroke(width); // -
else if (LINESTROKETYPE_DashedLine.equals(getLineStrokeType()))
lineV_Stroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL,
1.0f, getPatternDashed(width), 0.0f); // - -
else if (LINESTROKETYPE_Dash_DottedLine.equals(getLineStrokeType()))
lineV_Stroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL,
1.0f, getPatternDash_Dotted(width), 0.0f); // - . -
// default / fallback
if (lineV_Stroke == null)
lineV_Stroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL,
1.0f, getPatternDotted(width), 0.0f); // . . .
}
return lineV_Stroke;
} // getVLine_Stroke
/**
* Get Horizontal Stroke for Lines -
* @return stroke in pt (default 1)
*/
public BigDecimal getLineStroke()
{
BigDecimal retValue = super.getLineStroke();
if (retValue == null || Env.ZERO.compareTo(retValue) <= 0)
retValue = new BigDecimal (1.0);
return retValue;
} // getLineStroke
/**
* Get Vertical Stroke for Lines |
* @return stroke in pt (default 1)
*/
public BigDecimal getVLineStroke()
{
BigDecimal retValue = super.getLineStroke();
if (retValue == null || Env.ZERO.compareTo(retValue) <= 0)
retValue = new BigDecimal (1.0);
return retValue;
} // getVLineStroke
/**
* Get Pattern Dotted . . . .
* @param width width of line
* @return pattern
*/
private float[] getPatternDotted (float width)
{
return new float[] {2*width, 2*width};
} // getPatternDotted
/**
* Get Pattern Dashed - - - -
* @param width width of line
* @return pattern
*/
private float[] getPatternDashed (float width)
{
return new float[] {10*width, 4*width};
} // getPatternDashed
/**
* Get Pattern Dash Dotted - . - .
* @param width width of line
* @return pattern
*/
private float[] getPatternDash_Dotted (float width)
{
return new float[] {10*width, 2*width, 2*width, 2*width};
} // getPatternDash_Dotted
/*************************************************************************/
private static CCache<Integer,MPrintTableFormat> s_cache
= new CCache<Integer,MPrintTableFormat>("AD_PrintTableFormat", 3);
/** Static Logger */
private static CLogger s_log = CLogger.getCLogger(MPrintTableFormat.class);
/**
* Get Table Format.
* @param ctx context
* @param AD_PrintTableFormat_ID table format
* @param standard_font standard font
* @return Table Format
*/
static public MPrintTableFormat get (Properties ctx, int AD_PrintTableFormat_ID, Font standard_font)
{
Integer ii = new Integer (AD_PrintTableFormat_ID);
MPrintTableFormat tf = (MPrintTableFormat)s_cache.get(ii);
if (tf == null)
{
if (AD_PrintTableFormat_ID == 0)
tf = getDefault (ctx);
else
tf = new MPrintTableFormat (ctx, AD_PrintTableFormat_ID, null);
s_cache.put(ii, tf);
}
tf.setStandard_Font(standard_font);
return tf;
} // get
/**
* Get Table Format
* @param ctx context
* @param AD_PrintTableFormat_ID table format
* @param AD_PrintFont_ID standard font
* @return Table Format
*/
static public MPrintTableFormat get (Properties ctx, int AD_PrintTableFormat_ID, int AD_PrintFont_ID)
{
return get (ctx, AD_PrintTableFormat_ID, MPrintFont.get (AD_PrintFont_ID).getFont());
} // get
/**
* Get Default Table Format.
* @param ctx context
* @return Default Table Format (need to set standard font)
*/
static public MPrintTableFormat getDefault (Properties ctx)
{
MPrintTableFormat tf = null;
String sql = "SELECT * FROM AD_PrintTableFormat "
+ "WHERE AD_Client_ID IN (0,?) AND IsActive='Y' "
+ "ORDER BY IsDefault DESC, AD_Client_ID DESC";
int AD_Client_ID = Env.getAD_Client_ID(ctx);
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, AD_Client_ID);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
tf = new MPrintTableFormat (ctx, rs, null);
rs.close();
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
s_log.log(Level.SEVERE, sql, e);
}
try
{
if (pstmt != null)
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
return tf;
} // get
} // MPrintTableFormat

View File

@ -0,0 +1,776 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.io.*;
import java.util.*;
import java.util.logging.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.compiere.*;
import org.compiere.util.*;
import org.w3c.dom.*;
/**
* Print Data Structure.
* Created by DataEngine
* A Structure has rows, wich contain elements.
* Elements can be end nodes (PrintDataElements) or data structures (PrintData).
* The row data is sparse - i.e. null if not existing.
* A Structure has optional meta info about content (PrintDataColumn).
*
* @author Jorg Janke
* @version $Id: PrintData.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $
*/
public class PrintData implements Serializable
{
/**
* Data Parent Constructor
* @param ctx context
* @param name data element name
*/
public PrintData (Properties ctx, String name)
{
if (name == null)
throw new IllegalArgumentException("Name cannot be null");
m_ctx = ctx;
m_name = name;
} // PrintData
/**
* Data Parent Constructor
* @param ctx context
* @param name data element name
* @param nodes ArrayList with nodes (content not checked)
*/
public PrintData (Properties ctx, String name, ArrayList<Object> nodes)
{
if (name == null)
throw new IllegalArgumentException("Name cannot be null");
m_ctx = ctx;
m_name = name;
if (nodes != null)
m_nodes = nodes;
} // PrintData
/** Context */
private Properties m_ctx;
/** Data Structure Name */
private String m_name;
/** Data Structure rows */
private ArrayList<ArrayList<Object>> m_rows = new ArrayList<ArrayList<Object>>();
/** Current Row Data Structure elements */
private ArrayList<Object> m_nodes = null;
/** Current Row */
private int m_row = -1;
/** List of Function Rows */
private ArrayList<Integer> m_functionRows = new ArrayList<Integer>();
/** Table has LevelNo */
private boolean m_hasLevelNo = false;
/** Level Number Indicator */
private static final String LEVEL_NO = "LEVELNO";
/** Optional Column Meta Data */
private PrintDataColumn[] m_columnInfo = null;
/** Optional sql */
private String m_sql = null;
/** Optional TableName */
private String m_TableName = null;
/** XML Element Name */
public static final String XML_TAG = "adempiereData";
/** XML Row Name */
public static final String XML_ROW_TAG = "row";
/** XML Attribute Name */
public static final String XML_ATTRIBUTE_NAME = "name";
/** XML Attribute Count */
public static final String XML_ATTRIBUTE_COUNT = "count";
/** XML Attribute Number */
public static final String XML_ATTRIBUTE_NO = "no";
/** XML Attribute Function Row */
public static final String XML_ATTRIBUTE_FUNCTION_ROW = "function_row";
/** Logger */
private static CLogger log = CLogger.getCLogger(PrintData.class);
/**
* Get Context
* @return context
*/
public Properties getCtx()
{
return m_ctx;
} // getName
/**
* Get Name
* @return name
*/
public String getName()
{
return m_name;
} // getName
/*************************************************************************/
/**
* Set optional Column Info
* @param newInfo Column Info
*/
public void setColumnInfo (PrintDataColumn[] newInfo)
{
m_columnInfo = newInfo;
} // setColumnInfo
/**
* Get optional Column Info
* @return Column Info
*/
public PrintDataColumn[] getColumnInfo()
{
return m_columnInfo;
} // getColumnInfo
/**
* Set SQL (optional)
* @param sql SQL
*/
public void setSQL (String sql)
{
m_sql = sql;
} // setSQL
/**
* Get optional SQL
* @return SQL
*/
public String getSQL()
{
return m_sql;
} // getSQL
/**
* Set TableName (optional)
* @param TableName TableName
*/
public void setTableName (String TableName)
{
m_TableName = TableName;
} // setTableName
/**
* Get optional TableName
* @return TableName
*/
public String getTableName()
{
return m_TableName;
} // getTableName
/**
* String representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer("PrintData[");
sb.append(m_name).append(",Rows=").append(m_rows.size());
if (m_TableName != null)
sb.append(",TableName=").append(m_TableName);
sb.append("]");
return sb.toString();
} // toString
/**************************************************************************
* Returns true if no Nodes in row
* @return true if no Nodes in row
*/
public boolean isEmpty()
{
if (m_nodes == null)
return true;
return m_nodes.size() == 0;
} // isEmpty
/**
* Return Number of nodes in row
* @return number of nodes in row
*/
public int getNodeCount()
{
if (m_nodes == null)
return 0;
return m_nodes.size();
} // getNodeCount
/**************************************************************************
* Add Row
* @param functionRow true if function row
* @param levelNo Line detail Level Number 0=Normal
*/
public void addRow (boolean functionRow, int levelNo)
{
m_nodes = new ArrayList<Object>();
m_row = m_rows.size();
m_rows.add (m_nodes);
if (functionRow)
m_functionRows.add(new Integer(m_row));
if (m_hasLevelNo && levelNo != 0)
addNode(new PrintDataElement(LEVEL_NO, new Integer(levelNo), DisplayType.Integer));
} // addRow
/**
* Set Row Index
* @param row row index
* @return true if success
*/
public boolean setRowIndex (int row)
{
if (row < 0 || row >= m_rows.size())
return false;
m_row = row;
m_nodes = (ArrayList<Object>)m_rows.get(m_row);
return true;
}
/**
* Set Row Index to next
* @return true if success
*/
public boolean setRowNext()
{
return setRowIndex(m_row+1);
} // setRowNext
/**
* Get Row Count
* @return row count
*/
public int getRowCount()
{
return m_rows.size();
} // getRowCount
/**
* Get Current Row Index
* @return row index
*/
public int getRowIndex()
{
return m_row;
} // getRowIndex
/**
* Is the Row a Function Row
* @param row row no
* @return true if function row
*/
public boolean isFunctionRow (int row)
{
return m_functionRows.contains(new Integer(row));
} // isFunctionRow
/**
* Is the current Row a Function Row
* @return true if function row
*/
public boolean isFunctionRow ()
{
return m_functionRows.contains(new Integer(m_row));
} // isFunctionRow
/**
* Is the current Row a Function Row
* @return true if function row
*/
public boolean isPageBreak ()
{
// page break requires function and meta data
if (isFunctionRow() && m_nodes != null)
{
for (int i = 0; i < m_nodes.size(); i++)
{
Object o = m_nodes.get(i);
if (o instanceof PrintDataElement)
{
PrintDataElement pde = (PrintDataElement)o;
if (pde.isPageBreak())
return true;
}
}
}
return false;
} // isPageBreak
/**
* PrintData has Level No
* @param hasLevelNo true if sql contains LevelNo
*/
public void setHasLevelNo (boolean hasLevelNo)
{
m_hasLevelNo = hasLevelNo;
} // hasLevelNo
/**
* PrintData has Level No
* @return true if sql contains LevelNo
*/
public boolean hasLevelNo()
{
return m_hasLevelNo;
} // hasLevelNo
/**
* Get Line Level Number for current row
* @return line level no 0 = default
*/
public int getLineLevelNo ()
{
if (m_nodes == null || !m_hasLevelNo)
return 0;
for (int i = 0; i < m_nodes.size(); i++)
{
Object o = m_nodes.get (i);
if (o instanceof PrintDataElement)
{
PrintDataElement pde = (PrintDataElement)o;
if (LEVEL_NO.equals (pde.getColumnName()))
{
Integer ii = (Integer)pde.getValue();
return ii.intValue();
}
}
}
return 0;
} // getLineLevel
/*************************************************************************/
/**
* Add Parent node to Data Structure row
* @param parent parent
*/
public void addNode (PrintData parent)
{
if (parent == null)
throw new IllegalArgumentException("Parent cannot be null");
if (m_nodes == null)
addRow(false, 0);
m_nodes.add (parent);
} // addNode
/**
* Add node to Data Structure row
* @param node node
*/
public void addNode (PrintDataElement node)
{
if (node == null)
throw new IllegalArgumentException("Node cannot be null");
if (m_nodes == null)
addRow(false, 0);
m_nodes.add (node);
} // addNode
/**
* Get Node with index in row
* @param index index
* @return PrintData(Element) of index or null
*/
public Object getNode (int index)
{
if (m_nodes == null || index < 0 || index >= m_nodes.size())
return null;
return m_nodes.get(index);
} // getNode
/**
* Get Node with Name in row
* @param name name
* @return PrintData(Element) with Name or null
*/
public Object getNode (String name)
{
int index = getIndex (name);
if (index < 0)
return null;
return m_nodes.get(index);
} // getNode
/**
* Get Node with AD_Column_ID in row
* @param AD_Column_ID AD_Column_ID
* @return PrintData(Element) with AD_Column_ID or null
*/
public Object getNode (Integer AD_Column_ID)
{
int index = getIndex (AD_Column_ID.intValue());
if (index < 0)
return null;
return m_nodes.get(index);
} // getNode
/**
* Get Primary Key in row
* @return PK or null
*/
public PrintDataElement getPKey()
{
if (m_nodes == null)
return null;
for (int i = 0; i < m_nodes.size(); i++)
{
Object o = m_nodes.get(i);
if (o instanceof PrintDataElement)
{
PrintDataElement pde = (PrintDataElement)o;
if (pde.isPKey())
return pde;
}
}
return null;
} // getPKey
/**
* Get Index of Node in Structure (not recursing) row
* @param columnName name
* @return index or -1
*/
public int getIndex (String columnName)
{
if (m_nodes == null)
return -1;
for (int i = 0; i < m_nodes.size(); i++)
{
Object o = m_nodes.get(i);
if (o instanceof PrintDataElement)
{
if (columnName.equals(((PrintDataElement)o).getColumnName()))
return i;
}
else if (o instanceof PrintData)
{
if (columnName.equals(((PrintData)o).getName()))
return i;
}
else
log.log(Level.SEVERE, "Element not PrintData(Element) " + o.getClass().getName());
}
// As Data is stored sparse, there might be lots of NULL values
// log.log(Level.SEVERE, "PrintData.getIndex - Element not found - " + name);
return -1;
} // getIndex
/**
* Get Index of Node in Structure (not recursing) row
* @param AD_Column_ID AD_Column_ID
* @return index or -1
*/
public int getIndex (int AD_Column_ID)
{
if (m_columnInfo == null)
return -1;
for (int i = 0; i < m_columnInfo.length; i++)
{
if (m_columnInfo[i].getAD_Column_ID() == AD_Column_ID)
return getIndex(m_columnInfo[i].getColumnName());
}
log.log(Level.SEVERE, "Column not found - AD_Column_ID=" + AD_Column_ID);
if (AD_Column_ID == 0)
Trace.printStack();
return -1;
} // getIndex
/**************************************************************************
* Dump All Data - header and rows
*/
public void dump()
{
dump(this);
} // dump
/**
* Dump All Data
*/
public void dumpHeader()
{
dumpHeader(this);
} // dumpHeader
/**
* Dump All Data
*/
public void dumpCurrentRow()
{
dumpRow(this, m_row);
} // dump
/**
* Dump all PrintData - header and rows
* @param pd print data
*/
private static void dump (PrintData pd)
{
dumpHeader(pd);
for (int i = 0; i < pd.getRowCount(); i++)
dumpRow(pd, i);
} // dump
/**
* Dump PrintData Header
* @param pd print data
*/
private static void dumpHeader (PrintData pd)
{
log.info(pd.toString());
if (pd.getColumnInfo() != null)
{
for (int i = 0; i < pd.getColumnInfo().length; i++)
log.config(i + ": " + pd.getColumnInfo()[i]);
}
} // dump
/**
* Dump Row
* @param pd print data
* @param row row
*/
private static void dumpRow (PrintData pd, int row)
{
log.info("Row #" + row);
if (row < 0 || row >= pd.getRowCount())
{
log.warning("- invalid -");
return;
}
pd.setRowIndex(row);
if (pd.getNodeCount() == 0)
{
log.config("- n/a -");
return;
}
for (int i = 0; i < pd.getNodeCount(); i++)
{
Object obj = pd.getNode(i);
if (obj == null)
log.config("- NULL -");
else if (obj instanceof PrintData)
{
log.config("- included -");
dump((PrintData)obj);
}
else if (obj instanceof PrintDataElement)
{
log.config(((PrintDataElement)obj).toStringX());
}
else
log.config("- INVALID: " + obj);
}
} // dumpRow
/**************************************************************************
* Get XML Document representation
* @return XML document
*/
public Document getDocument()
{
Document document = null;
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// System.out.println(factory.getClass().getName());
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.newDocument();
document.appendChild(document.createComment(Adempiere.getSummaryAscii()));
}
catch (Exception e)
{
System.err.println(e);
e.printStackTrace();
}
// Root
Element root = document.createElement(PrintData.XML_TAG);
root.setAttribute(XML_ATTRIBUTE_NAME, getName());
root.setAttribute(XML_ATTRIBUTE_COUNT, String.valueOf(getRowCount()));
document.appendChild(root);
processXML (this, document, root);
return document;
} // getDocument
/**
* Process PrintData Tree
* @param pd Print Data
* @param document document
* @param root element to add to
*/
private static void processXML (PrintData pd, Document document, Element root)
{
for (int r = 0; r < pd.getRowCount(); r++)
{
pd.setRowIndex(r);
Element row = document.createElement(PrintData.XML_ROW_TAG);
row.setAttribute(XML_ATTRIBUTE_NO, String.valueOf(r));
if (pd.isFunctionRow())
row.setAttribute(XML_ATTRIBUTE_FUNCTION_ROW, "yes");
root.appendChild(row);
//
for (int i = 0; i < pd.getNodeCount(); i++)
{
Object o = pd.getNode(i);
if (o instanceof PrintData)
{
PrintData pd_x = (PrintData)o;
Element element = document.createElement(PrintData.XML_TAG);
element.setAttribute(XML_ATTRIBUTE_NAME, pd_x.getName());
element.setAttribute(XML_ATTRIBUTE_COUNT, String.valueOf(pd_x.getRowCount()));
row.appendChild(element);
processXML (pd_x, document, element); // recursive call
}
else if (o instanceof PrintDataElement)
{
PrintDataElement pde = (PrintDataElement)o;
if (!pde.isNull())
{
Element element = document.createElement(PrintDataElement.XML_TAG);
element.setAttribute(PrintDataElement.XML_ATTRIBUTE_NAME, pde.getColumnName());
if (pde.hasKey())
element.setAttribute(PrintDataElement.XML_ATTRIBUTE_KEY, pde.getValueKey());
element.appendChild(document.createTextNode(pde.getValueDisplay(null))); // not formatted
row.appendChild(element);
}
}
else
log.log(Level.SEVERE, "Element not PrintData(Element) " + o.getClass().getName());
} // columns
} // rows
} // processTree
/**
* Create XML representation to StreamResult
* @param result StreamResult
* @return true if success
*/
public boolean createXML (StreamResult result)
{
try
{
DOMSource source = new DOMSource(getDocument());
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.transform (source, result);
}
catch (Exception e)
{
log.log(Level.SEVERE, "(StreamResult)", e);
return false;
}
return true;
} // createXML
/**
* Create XML representation to File
* @param fileName file name
* @return true if success
*/
public boolean createXML (String fileName)
{
try
{
File file = new File(fileName);
file.createNewFile();
StreamResult result = new StreamResult(file);
createXML (result);
}
catch (Exception e)
{
log.log(Level.SEVERE, "(file)", e);
return false;
}
return true;
} // createXMLFile
/**************************************************************************
* Create PrintData from XML
* @param ctx context
* @param input InputSource
* @return PrintData
*/
public static PrintData parseXML (Properties ctx, File input)
{
log.config(input.toString());
PrintData pd = null;
try
{
PrintDataHandler handler = new PrintDataHandler(ctx);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.parse(input, handler);
pd = handler.getPrintData();
}
catch (Exception e)
{
log.log(Level.SEVERE, "", e);
}
return pd;
} // parseXML
/**************************************************************************
* Test
* @param args test
*/
public static void main(String[] args)
{
PrintData pd = new PrintData(new Properties(), "test1");
pd.addNode(new PrintDataElement("test1element1","testvalue<1>",0));
pd.addNode(new PrintDataElement("test1element2","testvalue&2&",0));
PrintData pdx = new PrintData(new Properties(), "test2");
pdx.addNode(new PrintDataElement("test2element1-1","testvalue11",0));
pdx.addNode(new PrintDataElement("test2element1-2","testvalue12",0));
pdx.addRow(false, 0);
pdx.addNode(new PrintDataElement("test2element2-1","testvalue21",0));
pdx.addNode(new PrintDataElement("test2element2-2","testvalue22",0));
pd.addNode(pdx);
pd.addNode(new PrintDataElement("test1element3","testvalue/3/",0));
pd.createXML("C:\\Temp\\printData.xml");
pd.createXML(new StreamResult(System.out));
System.out.println("");
pd.dump();
// parse
System.out.println("");
PrintData pd1 = parseXML (new Properties(), new File("C:\\Temp\\printData.xml"));
pd1.createXML(new StreamResult(System.out));
System.out.println("");
pd1.dump();
} // main
} // PrintData

View File

@ -0,0 +1,137 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
//import java.util.logging.*;
/**
* Print Data Column.
* Optional Meta Data of Columns
*
* @author Jorg Janke
* @version $Id: PrintDataColumn.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $
*/
public class PrintDataColumn
{
/**
* Print Data Column
*
* @param AD_Column_ID Column
* @param columnName Column Name
* @param displayType Display Type
* @param columnSize Column Size
* @param alias Alias in query or the same as column name or null
* @param isPageBreak if true force page break after function
*/
public PrintDataColumn (int AD_Column_ID, String columnName,
int displayType, int columnSize,
String alias, boolean isPageBreak)
{
m_AD_Column_ID = AD_Column_ID;
m_columnName = columnName;
//
m_displayType = displayType;
m_columnSize = columnSize;
//
m_alias = alias;
if (m_alias == null)
m_alias = columnName;
m_pageBreak = isPageBreak;
} // PrintDataColumn
private int m_AD_Column_ID;
private String m_columnName;
private int m_displayType;
private int m_columnSize;
private String m_alias;
private boolean m_pageBreak;
/*************************************************************************/
/**
* Get AD_Column_ID
* @return AD_Column_ID
*/
public int getAD_Column_ID()
{
return m_AD_Column_ID;
} // getAD_Column_ID
/**
* Get Column Name
* @return column name
*/
public String getColumnName()
{
return m_columnName;
} // getColumnName
/**
* Get Display Type
* @return display type
*/
public int getDisplayType()
{
return m_displayType;
} // getDisplayType
/**
* Get Alias Name
* @return alias column name
*/
public String getAlias()
{
return m_alias;
} // getAlias
/**
* Column has Alias.
* (i.e. has a key)
* @return true if Alias
*/
public boolean hasAlias()
{
return !m_columnName.equals(m_alias);
} // hasAlias
/**
* Column value forces page break
* @return true if page break
*/
public boolean isPageBreak()
{
return m_pageBreak;
} // isPageBreak
/**
* String Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer("PrintDataColumn[");
sb.append("ID=").append(m_AD_Column_ID)
.append("-").append(m_columnName);
if (hasAlias())
sb.append("(").append(m_alias).append(")");
sb.append(",DisplayType=").append(m_displayType)
.append(",Size=").append(m_columnSize)
.append("]");
return sb.toString();
} // toString
} // PrintDataColumn

View File

@ -0,0 +1,383 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.math.*;
import java.sql.*;
import org.compiere.model.*;
import org.compiere.util.*;
/**
* Print Data Element
*
* @author Jorg Janke
* @version $Id: PrintDataElement.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $
*/
public class PrintDataElement
{
/**
* Print Data Element Constructor
* @param columnName name
* @param value display value
* @param displayType optional displayType
* @param isPKey is primary key
* @param isPageBreak if true force page break
*/
public PrintDataElement (String columnName, Object value, int displayType, boolean isPKey, boolean isPageBreak)
{
if (columnName == null)
throw new IllegalArgumentException("PrintDataElement - Name cannot be null");
m_columnName = columnName;
m_value = value;
m_displayType = displayType;
m_isPKey = isPKey;
m_isPageBreak = isPageBreak;
} // PrintDataElement
/**
* Print Data Element Constructor
* @param columnName name
* @param value display value
* @param displayType optional displayType
*/
public PrintDataElement(String columnName, Object value, int displayType)
{
this (columnName, value, displayType, false, false);
} // PrintDataElement
/** Data Name */
private String m_columnName;
/** Data Value */
private Object m_value;
/** Display Type */
private int m_displayType;
/** Is Primary Key */
private boolean m_isPKey;
/** Is Page Break */
private boolean m_isPageBreak;
/** XML Element Name */
public static final String XML_TAG = "element";
/** XML Attribute Name */
public static final String XML_ATTRIBUTE_NAME = "name";
/** XML Attribute Key */
public static final String XML_ATTRIBUTE_KEY = "key";
/**
* Get Name
* @return name
*/
public String getColumnName()
{
return m_columnName;
} // getName
/**
* Get Node Value
* @return value
*/
public Object getValue()
{
return m_value;
} // getValue
/**
* Get Function Value
* @return length or numeric value
*/
public BigDecimal getFunctionValue()
{
if (m_value == null)
return Env.ZERO;
// Numbers - return number value
if (m_value instanceof BigDecimal)
return (BigDecimal)m_value;
if (m_value instanceof Number)
return new BigDecimal(((Number)m_value).doubleValue());
// Boolean - return 1 for true 0 for false
if (m_value instanceof Boolean)
{
if (((Boolean)m_value).booleanValue())
return Env.ONE;
else
return Env.ZERO;
}
// Return Length
String s = m_value.toString();
return new BigDecimal(s.length());
} // getFunctionValue
/**
* Get Node Value Display
* @param language optional language - if null nubers/dates are not formatted
* @return display value optionally formatted
*/
public String getValueDisplay (Language language)
{
if (m_value == null)
return "";
String retValue = m_value.toString();
if (m_displayType == DisplayType.Location)
return getValueDisplay_Location();
else if (m_columnName.equals("C_BPartner_Location_ID") || m_columnName.equals("Bill_Location_ID"))
return getValueDisplay_BPLocation();
else if (m_displayType == 0 || m_value instanceof String || m_value instanceof NamePair)
;
else if (language != null) // Optional formatting of Numbers and Dates
{
if (DisplayType.isNumeric(m_displayType))
retValue = DisplayType.getNumberFormat(m_displayType, language).format(m_value);
else if (DisplayType.isDate(m_displayType))
retValue = DisplayType.getDateFormat(m_displayType, language).format(m_value);
}
return retValue;
} // getValueDisplay
/**
* Get Node Data Value as String
* @return data value
*/
public String getValueAsString()
{
if (m_value == null)
return "";
String retValue = m_value.toString();
if (m_value instanceof NamePair)
retValue = ((NamePair)m_value).getID();
return retValue;
} // getValueDisplay
/**
* Return Address String not just name
* @return Address String
*/
private String getValueDisplay_BPLocation ()
{
try
{
int C_BPartner_Location_ID = Integer.parseInt (getValueKey ());
if (C_BPartner_Location_ID != 0)
{
MLocation loc = MLocation.getBPLocation(Env.getCtx(), C_BPartner_Location_ID, null);
if (loc != null)
return loc.toStringCR();
}
}
catch (Exception ex)
{
}
return m_value.toString();
} // getValueDisplay_BPLocation
/**
* Return Address String not just City
* @return Address String
*/
private String getValueDisplay_Location ()
{
try
{
int C_Location_ID = Integer.parseInt (getValueKey ());
if (C_Location_ID != 0)
{
MLocation loc = new MLocation (Env.getCtx(), C_Location_ID, null);
if (loc != null)
return loc.toStringCR();
}
}
catch (Exception ex)
{
}
return m_value.toString();
} // getValueDisplay_Location
/**
* Get Node Value Key
* @return key
*/
public String getValueKey()
{
if (m_value == null)
return "";
if (m_value instanceof NamePair)
return ((NamePair)m_value).getID();
return "";
} // getValueKey
/**
* Is Value Null
* @return true if value is null
*/
public boolean isNull()
{
return m_value == null;
} // isNull
/*************************************************************************/
/**
* Get Display Type
* @return Display Type
*/
public int getDisplayType()
{
return m_displayType;
} // getDisplayType
/**
* Is Value numeric
* @return true if value is a numeric
*/
public boolean isNumeric()
{
if (m_displayType == 0)
return m_value instanceof BigDecimal;
return DisplayType.isNumeric(m_displayType);
} // isNumeric
/**
* Is Value a date
* @return true if value is a date
*/
public boolean isDate()
{
if (m_displayType == 0)
return m_value instanceof Timestamp;
return DisplayType.isDate(m_displayType);
} // isDate
/**
* Is Value an ID
* @return true if value is an ID
*/
public boolean isID()
{
return DisplayType.isID(m_displayType);
} // isID
/**
* Is Value boolean
* @return true if value is a boolean
*/
public boolean isYesNo()
{
if (m_displayType == 0)
return m_value instanceof Boolean;
return DisplayType.YesNo == m_displayType;
} // isYesNo
/**
* Is Value the primary key of row
* @return true if value is the PK
*/
public boolean isPKey()
{
return m_isPKey;
} // isPKey
/**
* Column value forces page break
* @return true if page break
*/
public boolean isPageBreak()
{
return m_isPageBreak;
} // isPageBreak
/*************************************************************************/
/**
* HashCode
* @return hash code
*/
public int hashCode()
{
if (m_value == null)
return m_columnName.hashCode();
return m_columnName.hashCode() + m_value.hashCode();
} // hashCode
/**
* Equals
* @param compare compare object
* @return true if equals
*/
public boolean equals (Object compare)
{
if (compare instanceof PrintDataElement)
{
PrintDataElement pde = (PrintDataElement)compare;
if (pde.getColumnName().equals(m_columnName))
{
if (pde.getValue() != null && pde.getValue().equals(m_value))
return true;
if (pde.getValue() == null && m_value == null)
return true;
}
}
return false;
} // equals
/**
* String representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer(m_columnName).append("=").append(m_value);
if (m_isPKey)
sb.append("(PK)");
return sb.toString();
} // toString
/**
* Value Has Key
* @return true if value has a key
*/
public boolean hasKey()
{
return m_value instanceof NamePair;
} // hasKey
/**
* String representation with key info
* @return info
*/
public String toStringX()
{
if (m_value instanceof NamePair)
{
NamePair pp = (NamePair)m_value;
StringBuffer sb = new StringBuffer(m_columnName);
sb.append("(").append(pp.getID()).append(")")
.append("=").append(pp.getName());
if (m_isPKey)
sb.append("(PK)");
return sb.toString();
}
else
return toString();
} // toStringX
} // PrintDataElement

View File

@ -0,0 +1,228 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.math.*;
import org.compiere.util.*;
/**
* Print Data Function
*
* @author Jorg Janke
* @version $Id: PrintDataFunction.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $
*/
public class PrintDataFunction
{
/**
* Constructor
*/
public PrintDataFunction ()
{
} // PrintDataFunction
/** The Sum */
private BigDecimal m_sum = Env.ZERO;
/** The Count */
private int m_count = 0;
/** Total Count */
private int m_totalCount = 0;
/** Minimum */
private BigDecimal m_min = null;
/** Maximum */
private BigDecimal m_max = null;
/** Sum of Squares */
private BigDecimal m_sumSquare = Env.ZERO;
/** Sum */
static public final char F_SUM = 'S';
/** Mean */
static public final char F_MEAN = 'A'; // Average mu
/** Count */
static public final char F_COUNT = 'C';
/** Min */
static public final char F_MIN = 'm';
/** Max */
static public final char F_MAX = 'M';
/** Variance */
static public final char F_VARIANCE = 'V'; // sigma square
/** Deviation */
static public final char F_DEVIATION = 'D'; // sigma
/** Function Keys */
static private final char[] FUNCTIONS = new char[]
{F_SUM, F_MEAN, F_COUNT, F_MIN, F_MAX, F_VARIANCE, F_DEVIATION};
/** Symbols */
static private final String[] FUNCTION_SYMBOLS = new String[]
{" \u03A3", " \u03BC", " \u2116", " \u2193", " \u2191", " \u03C3\u00B2", " \u03C3"};
/** AD_Message Names of Functions */
static private final String[] FUNCTION_NAMES = new String[]
{"Sum", "Mean", "Count", "Min", "Max", "Variance", "Deviation"};
/**
* Add Value to Counter
* @param bd data
*/
public void addValue (BigDecimal bd)
{
if (bd != null)
{
// Sum
m_sum = m_sum.add(bd);
// Count
m_count++;
// Min
if (m_min == null)
m_min = bd;
m_min = m_min.min(bd);
// Max
if (m_max == null)
m_max = bd;
m_max = m_max.max(bd);
// Sum of Squares
m_sumSquare = m_sumSquare.add (bd.multiply(bd));
}
m_totalCount++;
} // addValue
/**
* Get Function Value
* @param function function
* @return function value
*/
public BigDecimal getValue(char function)
{
// Sum
if (function == F_SUM)
return m_sum;
// Min/Max
if (function == F_MIN)
return m_min;
if (function == F_MAX)
return m_max;
// Count
BigDecimal count = new BigDecimal(m_count);
if (function == F_COUNT)
return count;
// All other functions require count > 0
if (m_count == 0)
return Env.ZERO;
// Mean = sum/count - round to 4 digits
if (function == F_MEAN)
{
BigDecimal mean = m_sum.divide(count, 4, BigDecimal.ROUND_HALF_UP);
if (mean.scale() > 4)
mean = mean.setScale(4, BigDecimal.ROUND_HALF_UP);
return mean;
}
// Variance = sum of squares - (square of sum / count)
BigDecimal ss = m_sum.multiply(m_sum);
ss = ss.divide(count, 4, BigDecimal.ROUND_HALF_UP);
BigDecimal variance = m_sumSquare.subtract(ss);
if (function == F_VARIANCE)
{
if (variance.scale() > 4)
variance = variance.setScale(4, BigDecimal.ROUND_HALF_UP);
return variance;
}
// Standard Deviation
BigDecimal deviation = new BigDecimal(Math.sqrt(variance.doubleValue()));
if (deviation.scale() > 4)
deviation = deviation.setScale(4, BigDecimal.ROUND_HALF_UP);
return deviation;
} // getValue
/**
* Reset Value
*/
public void reset()
{
m_count = 0;
m_totalCount = 0;
m_sum = Env.ZERO;
m_sumSquare = Env.ZERO;
m_min = null;
m_max = null;
} // reset
/**
* String Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer("[")
.append("Count=").append(m_count).append(",").append(m_totalCount)
.append(",Sum=").append(m_sum)
.append(",SumSquare=").append(m_sumSquare)
.append(",Min=").append(m_min)
.append(",Max=").append(m_max);
sb.append("]");
return sb.toString();
} // toString
/*************************************************************************/
/**
* Get Function Symbol of function
* @param function function
* @return function symbol
*/
static public String getFunctionSymbol (char function)
{
for (int i = 0; i < FUNCTIONS.length; i++)
{
if (FUNCTIONS[i] == function)
return FUNCTION_SYMBOLS[i];
}
return "UnknownFunction=" + function;
} // getFunctionSymbol
/**
* Get Function Name of function
* @param function function
* @return function name
*/
static public String getFunctionName (char function)
{
for (int i = 0; i < FUNCTIONS.length; i++)
{
if (FUNCTIONS[i] == function)
return FUNCTION_NAMES[i];
}
return "UnknownFunction=" + function;
} // getFunctionName
/**
* Get Funcuion Name of function
* @param function function
* @return function name
*/
static public int getFunctionDisplayType (char function)
{
if (function == F_SUM || function == F_MIN || function == F_MAX)
return DisplayType.Amount;
if (function == F_COUNT)
return DisplayType.Integer;
// Mean, Variance, Std. Deviation
return DisplayType.Number;
} // getFunctionName
} // PrintDataFunction

View File

@ -0,0 +1,311 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.util.*;
import java.math.*;
/**
* Group By Management
*
* @author Jorg Janke
* @version $Id: PrintDataGroup.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $
*/
public class PrintDataGroup
{
/**
* Constructor
*/
public PrintDataGroup ()
{
} // PrintDataGroup
/** Column-Function Delimiter */
static public final String DELIMITER = "~";
/** Grand Total Indicator */
static public final String TOTAL = "=TOTAL=";
/** NULL substitute value */
static private final Object NULL = new String();
/** List of group columns */
private ArrayList<String> m_groups = new ArrayList<String>();
/** Map of group column & value */
private HashMap<String,Object> m_groupMap = new HashMap<String,Object>();
/** List of column_function */
private ArrayList<String> m_functions = new ArrayList<String>();
/** Map of group_function column & function */
private HashMap<String,PrintDataFunction> m_groupFunction = new HashMap<String,PrintDataFunction>();
/**************************************************************************
* Add Group Column
* @param groupColumnName group column
*/
public void addGroupColumn (String groupColumnName)
{
m_groups.add(groupColumnName);
} // addGroup
/**
* Get Grouyp Column Count.
* TOTAL is included as a column
* @return number of groups
*/
public int getGroupColumnCount()
{
return m_groups.size();
} // getGroupColumnCount
/**
* Column has a function
* @param columnName column name or TOTAL
* @return true if column has function
*/
public boolean isGroupColumn (String columnName)
{
if (columnName == null || m_groups.size() == 0)
return false;
for (int i = 0; i < m_groups.size(); i++)
{
if (columnName.equals(m_groups.get(i)))
return true;
}
return false;
} // isGroupColumn
/**
* Check for Group Change
* @param groupColumnName column name
* @param value column value
* @return null if no group change otherwise old value
*/
public Object groupChange (String groupColumnName, Object value)
{
if (!isGroupColumn(groupColumnName))
return null;
Object newValue = value;
if (newValue == null)
newValue = NULL;
//
if (m_groupMap.containsKey(groupColumnName))
{
Object oldValue = m_groupMap.get(groupColumnName);
if (newValue.equals(oldValue))
return null;
m_groupMap.put(groupColumnName, newValue);
return oldValue;
}
m_groupMap.put(groupColumnName, newValue);
return null;
} // groupChange
/**************************************************************************
* Add Function Column
* @param functionColumnName column name
* @param function function
*/
public void addFunction (String functionColumnName, char function)
{
m_functions.add(functionColumnName + DELIMITER + function);
if (!m_groups.contains(TOTAL))
m_groups.add(TOTAL);
} // addFunction
/**
* Column has a function
* @param columnName column name
* @return true if column has function
*/
public boolean isFunctionColumn (String columnName)
{
if (columnName == null || m_functions.size() == 0)
return false;
for (int i = 0; i < m_functions.size(); i++)
{
String f = (String)m_functions.get(i);
if (f.startsWith(columnName))
return true;
}
return false;
} // isFunctionColumn
/**
* Get calculated functions of column
* @param columnName column name or TOTAL
* @return array of functions
*/
public char[] getFunctions(String columnName)
{
ArrayList<String> list = new ArrayList<String>(); // the final function List
Iterator it = m_groupFunction.keySet().iterator();
while(it.hasNext())
{
String group_function = (String)it.next(); // =TOTAL=~LoadSeq
if (group_function.startsWith(columnName))
{
group_function = group_function.substring(group_function.lastIndexOf(DELIMITER)+1); // LoadSeq
for (int i = 0; i < m_functions.size(); i++)
{
String col_function = ((String)m_functions.get(i)); // LoadSeq~A
if (col_function.startsWith(group_function))
{
String function = col_function.substring(col_function.lastIndexOf(DELIMITER)+1);
if (!list.contains(function))
list.add(function);
}
}
}
}
// Return Value
char[] retValue = new char[list.size()];
for (int i = 0; i < retValue.length; i++)
retValue[i] = ((String)list.get(i)).charAt(0);
// log.finest( "PrintDataGroup.getFunctions for " + columnName + "/" + retValue.length, new String(retValue));
return retValue;
} // getFunctions
/**
* Column has a function
* @param columnName column name
* @param function function
* @return true if column has function
*/
public boolean isFunctionColumn (String columnName, char function)
{
if (columnName == null || m_functions.size() == 0)
return false;
String key = columnName + DELIMITER + function;
for (int i = 0; i < m_functions.size(); i++)
{
String f = (String)m_functions.get(i);
if (f.equals(key))
return true;
}
return false;
} // isFunctionColumn
/**************************************************************************
* Add Value to groups
* @param functionColumnName column name
* @param functionValue value
*/
public void addValue (String functionColumnName, BigDecimal functionValue)
{
if (!isFunctionColumn(functionColumnName))
return;
// Group Breaks
for (int i = 0; i < m_groups.size(); i++)
{
String groupColumnName = (String)m_groups.get(i);
String key = groupColumnName + DELIMITER + functionColumnName;
PrintDataFunction pdf = (PrintDataFunction)m_groupFunction.get(key);
if (pdf == null)
pdf = new PrintDataFunction();
pdf.addValue(functionValue);
m_groupFunction.put(key, pdf);
}
} // addValue
/**
* Get Value
* @param groupColumnName group column name (or TOTAL)
* @param functionColumnName function column name
* @param function function
* @return value
*/
public BigDecimal getValue (String groupColumnName, String functionColumnName,
char function)
{
String key = groupColumnName + DELIMITER + functionColumnName;
PrintDataFunction pdf = (PrintDataFunction)m_groupFunction.get(key);
if (pdf == null)
return null;
return pdf.getValue(function);
} // getValue
/**
* Reset Function values
* @param groupColumnName group column name (or TOTAL)
* @param functionColumnName function column name
*/
public void reset (String groupColumnName, String functionColumnName)
{
String key = groupColumnName + DELIMITER + functionColumnName;
PrintDataFunction pdf = (PrintDataFunction)m_groupFunction.get(key);
if (pdf != null)
pdf.reset();
} // reset
/**************************************************************************
* String Representation
* @return info
*/
public String toString ()
{
return toString(false);
} // toString
/**
* String Representation
* @param withData with data
* @return info
*/
public String toString (boolean withData)
{
StringBuffer sb = new StringBuffer("PrintDataGroup[");
sb.append("Groups=");
for (int i = 0; i < m_groups.size(); i++)
{
if (i != 0)
sb.append(",");
sb.append(m_groups.get(i));
}
if (withData)
{
Iterator it = m_groupMap.keySet().iterator();
while(it.hasNext())
{
Object key = it.next();
Object value = m_groupMap.get(key);
sb.append(":").append(key).append("=").append(value);
}
}
sb.append(";Functions=");
for (int i = 0; i < m_functions.size(); i++)
{
if (i != 0)
sb.append(",");
sb.append(m_functions.get(i));
}
if (withData)
{
Iterator it = m_groupFunction.keySet().iterator();
while(it.hasNext())
{
Object key = it.next();
Object value = m_groupFunction.get(key);
sb.append(":").append(key).append("=").append(value);
}
}
sb.append("]");
return sb.toString();
} // toString
} // PrintDataGroup

View File

@ -0,0 +1,165 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.util.*;
import org.xml.sax.helpers.*;
import org.xml.sax.*;
/**
* SAX Handler for parsing PrintData
*
* @author Jorg Janke
* @version $Id: PrintDataHandler.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $
*/
public class PrintDataHandler extends DefaultHandler
{
/**
* Constructor
* @param ctx context
*/
public PrintDataHandler(Properties ctx)
{
m_ctx = ctx;
} // PrintDataHandler
/** Context */
private Properties m_ctx = null;
/** Final Structure */
private PrintData m_pd = null;
/** Current Active Element Name */
private String m_curPDEname = null;
/** Current Active Element Value */
private StringBuffer m_curPDEvalue = null;
/** Current Active Print Data */
private PrintData m_curPD = null;
/**
* Get PrintData
* @return PrintData
*/
public PrintData getPrintData()
{
return m_pd;
} // getPrintData
/*************************************************************************/
/**
* Receive notification of the start of an element.
*
* @param uri namespace
* @param localName simple name
* @param qName qualified name
* @param attributes attributes
* @throws org.xml.sax.SAXException
*/
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws org.xml.sax.SAXException
{
if (qName.equals(PrintData.XML_TAG))
{
String name = attributes.getValue(PrintData.XML_ATTRIBUTE_NAME);
if (m_pd == null)
{
m_pd = new PrintData(m_ctx, name);
push(m_pd);
}
else
{
PrintData temp = new PrintData(m_ctx, name);
m_curPD.addNode(temp);
push(temp);
}
}
else if (qName.equals(PrintData.XML_ROW_TAG))
{
m_curPD.addRow(false, 0);
}
else if (qName.equals(PrintDataElement.XML_TAG))
{
m_curPDEname = attributes.getValue(PrintDataElement.XML_ATTRIBUTE_NAME);
m_curPDEvalue = new StringBuffer();
}
} // startElement
/**
* Receive notification of character data inside an element.
*
* @param ch buffer
* @param start start
* @param length length
* @throws SAXException
*/
public void characters (char ch[], int start, int length)
throws SAXException
{
m_curPDEvalue.append(ch, start, length);
} // characters
/**
* Receive notification of the end of an element.
* @param uri namespace
* @param localName simple name
* @param qName qualified name
* @throws SAXException
*/
public void endElement (String uri, String localName, String qName)
throws SAXException
{
if (qName.equals(PrintData.XML_TAG))
{
pop();
}
else if (qName.equals(PrintDataElement.XML_TAG))
{
m_curPD.addNode(new PrintDataElement(m_curPDEname, m_curPDEvalue.toString(),0));
}
} // endElement
/*************************************************************************/
/** Stack */
private ArrayList<PrintData> m_stack = new ArrayList<PrintData>();
/**
* Push new PD on Stack and set m_cutPD
* @param newPD new PD
*/
private void push (PrintData newPD)
{
// add
m_stack.add(newPD);
m_curPD = newPD;
} // push
/**
* Pop last PD from Stack and set m_cutPD
*/
private void pop ()
{
// remove last
if (m_stack.size() > 0)
m_stack.remove(m_stack.size()-1);
// get previous
if (m_stack.size() > 0)
m_curPD = (PrintData)m_stack.get(m_stack.size()-1);
} // pop
} // PrintDataHandler

View File

@ -0,0 +1,167 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* Print Format Utilities.
* - Add Missing Columns for all Print Format
*
* @author Jorg Janke
* @version $Id: PrintFormatUtil.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $
*/
public class PrintFormatUtil
{
/**
* Print Format Utility
* @param ctx context
*/
public PrintFormatUtil(Properties ctx)
{
super();
m_ctx = ctx;
} // PrintFormatUtil
/** Logger */
private CLogger log = CLogger.getCLogger (getClass());
/** Context */
private Properties m_ctx;
/**
* Add Missing Columns for all Print Format
*/
public void addMissingColumns ()
{
int total = 0;
String sql = "SELECT * FROM AD_PrintFormat pf "
+ "ORDER BY Name";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, null);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
total += addMissingColumns(new MPrintFormat (m_ctx, rs, null));
rs.close();
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
log.log(Level.SEVERE, sql, e);
}
try
{
if (pstmt != null)
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
log.info ("Total = " + total);
} // addMissingColumns
/**
* Add Missing Columns for Print Format
* @param pf print format
* @return no of columns created
*/
public int addMissingColumns (MPrintFormat pf)
{
log.config(pf.toString());
String sql = "SELECT c.AD_Column_ID, c.ColumnName "
+ "FROM AD_Column c "
+ "WHERE NOT EXISTS "
+ "(SELECT * "
+ "FROM AD_PrintFormatItem pfi"
+ " INNER JOIN AD_PrintFormat pf ON (pfi.AD_PrintFormat_ID=pf.AD_PrintFormat_ID) "
+ "WHERE pf.AD_Table_ID=c.AD_Table_ID"
+ " AND pfi.AD_Column_ID=c.AD_Column_ID"
+ " AND pfi.AD_PrintFormat_ID=?)" // 1
+ " AND c.AD_Table_ID=? " // 2
+ "ORDER BY 1";
PreparedStatement pstmt = null;
int counter = 0;
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, pf.getAD_PrintFormat_ID());
pstmt.setInt(2, pf.getAD_Table_ID());
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
int AD_Column_ID = rs.getInt(1);
String ColumnName = rs.getString(2);
MPrintFormatItem pfi = MPrintFormatItem.createFromColumn (pf, AD_Column_ID, 0);
if (pfi.get_ID() != 0)
log.fine("#" + ++counter + " - added " + ColumnName);
else
log.warning("Not added: " + ColumnName);
}
rs.close();
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
log.log(Level.SEVERE, sql, e);
}
try
{
if (pstmt != null)
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
if (counter == 0)
log.fine("None"
/**
+ " - " + sql
+ " - AD_PrintFormat_ID=" + pf.getAD_PrintFormat_ID()
+ " - AD_Table_ID=" + pf.getAD_Table_ID()
*/
);
else
log.fine("Added=" + counter);
return counter;
} // addMissingColumns
/**************************************************************************
* Main
* @param args arguments
*/
public static void main(String[] args)
{
org.compiere.Adempiere.startupEnvironment(true);
//
PrintFormatUtil pfu = new PrintFormatUtil (Env.getCtx());
pfu.addMissingColumns();
} // main
} // PrintFormatUtils

View File

@ -0,0 +1,519 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.awt.print.*;
import java.util.*;
import java.util.logging.*;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;
import javax.swing.*;
import org.compiere.util.*;
/**
* Print Utilities
*
* @author Jorg Janke
* @version $Id: PrintUtil.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $
*/
public class PrintUtil
{
/** Logger */
private static CLogger log = CLogger.getCLogger(PrintUtil.class);
/** Default Print Request Attribute Set */
private static PrintRequestAttributeSet s_prats = new HashPrintRequestAttributeSet();
/**
* Return Default Print Request Attributes
* @return PrintRequestAttributeSet
*/
public static PrintRequestAttributeSet getDefaultPrintRequestAttributes()
{
return s_prats;
} // getDefaultPrintRequestAttributes
/**
* Get Default Application Flavor
* @return Pageable
*/
public static DocFlavor getDefaultFlavor()
{
return DocFlavor.SERVICE_FORMATTED.PAGEABLE;
} // getDefaultFlavor
/**
* Get Print Services for standard flavor and pratt
* @return print services
*/
public static PrintService[] getPrintServices ()
{
return PrintServiceLookup.lookupPrintServices (getDefaultFlavor(), getDefaultPrintRequestAttributes());
} // getPrintServices
/**
* Get Default Print Service
* @return PrintService
*/
public static PrintService getDefaultPrintService()
{
return PrintServiceLookup.lookupDefaultPrintService();
} // getPrintServices
/*************************************************************************/
/**
* Print (async)
* @param printerName optional printer name
* @param jobName optional printer job name
* @param pageable pageable
* @param copies number of copies
* @param withDialog if true, shows printer dialog
*/
static public void print (Pageable pageable, String printerName, String jobName,
int copies, boolean withDialog)
{
if (pageable == null)
return;
String name = "Adempiere_";
if (jobName != null)
name += jobName;
//
PrinterJob job = CPrinter.getPrinterJob(printerName);
job.setJobName (name);
job.setPageable (pageable);
// Attributes
HashPrintRequestAttributeSet prats = new HashPrintRequestAttributeSet();
prats.add(new Copies(copies));
// Set Orientation
if (pageable.getPageFormat(0).getOrientation() == PageFormat.PORTRAIT)
prats.add(OrientationRequested.PORTRAIT);
else
prats.add(OrientationRequested.LANDSCAPE);
prats.add(new JobName(name, Language.getLoginLanguage().getLocale()));
prats.add(getJobPriority(pageable.getNumberOfPages(), copies, withDialog));
//
print (job, prats, withDialog, false);
} // print
/**
* Print Async
* @param pageable pageable
* @param prats print attribure set
*/
static public void print (Pageable pageable, PrintRequestAttributeSet prats)
{
PrinterJob job = CPrinter.getPrinterJob();
job.setPageable(pageable);
print (job, prats, true, false);
} // print
/**
* Print
* @param job printer job
* @param prats print attribure set
* @param withDialog if true shows Dialog
* @param waitForIt if false print async
*/
static public void print (final PrinterJob job,
final PrintRequestAttributeSet prats,
boolean withDialog, boolean waitForIt)
{
if (job == null)
return;
boolean printed = true;
if (withDialog)
printed = job.printDialog(prats);
if (printed)
{
if (withDialog)
{
Attribute[] atts = prats.toArray();
for (int i = 0; i < atts.length; i++)
log.fine(atts[i].getName() + "=" + atts[i]);
}
//
if (waitForIt)
{
log.fine("(wait) " + job.getPrintService());
try
{
job.print(prats);
}
catch (Exception ex)
{
log.log(Level.SEVERE, "(wait)", ex);
}
}
else // Async
{
// Create Thread
Thread printThread = new Thread()
{
public void run()
{
log.fine("print: " + job.getPrintService());
try
{
job.print(prats);
}
catch (Exception ex)
{
log.log(Level.SEVERE, "print", ex);
}
}
};
printThread.start();
} // Async
} // printed
} // printAsync
/**
* Get Job Priority based on pages printed.
* The more pages, the lower the priority
* @param pages number of pages
* @param copies number of copies
* @param withDialog dialog gets lower priority than direct print
* @return Job Priority
*/
static public JobPriority getJobPriority (int pages, int copies, boolean withDialog)
{
// Set priority (the more pages, the lower the priority)
int priority = copies * pages;
if (withDialog) // prefer direct print
priority *= 2;
priority = 100 - priority; // convert to 1-100 supported range
if (priority < 10)
priority = 10;
else if (priority > 100)
priority = 100;
return new JobPriority(priority);
} // getJobPriority
/*************************************************************************/
/**
* Dump Printer Job info
* @param job printer job
*/
public static void dump (PrinterJob job)
{
StringBuffer sb = new StringBuffer(job.getJobName());
sb.append("/").append(job.getUserName())
.append(" Service=").append(job.getPrintService().getName())
.append(" Copies=").append(job.getCopies());
PageFormat pf = job.defaultPage();
sb.append(" DefaultPage ")
.append("x=").append(pf.getImageableX())
.append(",y=").append(pf.getImageableY())
.append(" w=").append(pf.getImageableWidth())
.append(",h=").append(pf.getImageableHeight());
System.out.println(sb.toString());
} // dump
/**
* Dump Print Service Attribute Set to System.out
* @param psas PS Attribute Set
*/
public static void dump (PrintServiceAttributeSet psas)
{
System.out.println("PrintServiceAttributeSet - length=" + psas.size());
Attribute[] ats = psas.toArray();
for (int i = 0; i < ats.length; i++)
System.out.println(ats[i].getName() + " = " + ats[i] + " (" + ats[i].getCategory() + ")");
} // dump
/**
* Dump Print Request Service Attribute Set to System.out
* @param prats Print Request Attribute Set
*/
public static void dump (PrintRequestAttributeSet prats)
{
System.out.println("PrintRequestAttributeSet - length=" + prats.size());
Attribute[] ats = prats.toArray();
for (int i = 0; i < ats.length; i++)
System.out.println(ats[i].getName() + " = " + ats[i] + " (" + ats[i].getCategory() + ")");
} // dump
/**
* Dump Stream Print Services
* @param docFlavor flavor
* @param outputMimeType mime
*/
public static void dump (DocFlavor docFlavor, String outputMimeType)
{
System.out.println();
System.out.println("DocFlavor=" + docFlavor + ", Output=" + outputMimeType);
StreamPrintServiceFactory[] spsfactories =
StreamPrintServiceFactory.lookupStreamPrintServiceFactories(docFlavor, outputMimeType);
for (int i = 0; i < spsfactories.length; i++)
{
System.out.println("- " + spsfactories[i]);
DocFlavor dfs[] = spsfactories[i].getSupportedDocFlavors();
for (int j = 0; j < dfs.length; j++)
{
System.out.println(" -> " + dfs[j]);
}
}
} // dump
/**
* Dump Stream Print Services
* @param docFlavor flavor
*/
public static void dump (DocFlavor docFlavor)
{
System.out.println();
System.out.println("DocFlavor=" + docFlavor);
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
PrintService[] pss =
PrintServiceLookup.lookupPrintServices(docFlavor, pras);
for (int i = 0; i < pss.length; i++)
{
PrintService ps = pss[i];
System.out.println("- " + ps);
System.out.println(" Factory=" + ps.getServiceUIFactory());
ServiceUIFactory uiF = pss[i].getServiceUIFactory();
if (uiF != null)
{
System.out.println("about");
JDialog about = (JDialog) uiF.getUI (ServiceUIFactory.ABOUT_UIROLE, ServiceUIFactory.JDIALOG_UI);
about.setVisible(true);
System.out.println("admin");
JDialog admin = (JDialog) uiF.getUI (ServiceUIFactory.ADMIN_UIROLE, ServiceUIFactory.JDIALOG_UI);
admin.setVisible(true);
System.out.println("main");
JDialog main = (JDialog) uiF.getUI (ServiceUIFactory.MAIN_UIROLE, ServiceUIFactory.JDIALOG_UI);
main.setVisible(true);
System.out.println("reserved");
JDialog res = (JDialog) uiF.getUI (ServiceUIFactory.RESERVED_UIROLE, ServiceUIFactory.JDIALOG_UI);
res.setVisible(true);
}
//
DocFlavor dfs[] = pss[i].getSupportedDocFlavors();
System.out.println(" - Supported Doc Flavors");
for (int j = 0; j < dfs.length; j++)
System.out.println(" -> " + dfs[j]);
// Attribute
Class[] attCat = pss[i].getSupportedAttributeCategories();
System.out.println(" - Supported Attribute Categories");
for (int j = 0; j < attCat.length; j++)
System.out.println(" -> " + attCat[j].getName()
+ " = " + pss[i].getDefaultAttributeValue((Class<? extends Attribute>)attCat[j]));
//
}
} // dump
/*************************************************************************/
/**
* Test Print Services
*/
private static void testPS()
{
PrintService ps = getDefaultPrintService();
ServiceUIFactory factory = ps.getServiceUIFactory();
System.out.println(factory);
if (factory != null)
{
System.out.println("Factory");
JPanel p0 = (JPanel) factory.getUI(ServiceUIFactory.ABOUT_UIROLE, ServiceUIFactory.JDIALOG_UI);
p0.setVisible(true);
JPanel p1 = (JPanel) factory.getUI(ServiceUIFactory.ADMIN_UIROLE, ServiceUIFactory.JDIALOG_UI);
p1.setVisible(true);
JPanel p2 = (JPanel) factory.getUI(ServiceUIFactory.MAIN_UIROLE, ServiceUIFactory.JDIALOG_UI);
p2.setVisible(true);
}
System.out.println("1----------");
PrinterJob pj = PrinterJob.getPrinterJob();
PrintRequestAttributeSet pratts = getDefaultPrintRequestAttributes();
// Page Dialog
PageFormat pf = pj.pageDialog(pratts);
System.out.println("Pratts Size = " + pratts.size());
Attribute[] atts = pratts.toArray();
for (int i = 0; i < atts.length; i++)
System.out.println(atts[i].getName() + " = " + atts[i] + " - " + atts[i].getCategory());
System.out.println("PageFormat h=" + pf.getHeight() + ",w=" + pf.getWidth() + " - x=" + pf.getImageableX() + ",y=" + pf.getImageableY() + " - ih=" + pf.getImageableHeight() + ",iw=" + pf.getImageableWidth()
+ " - Orient=" + pf.getOrientation());
ps = pj.getPrintService();
System.out.println("PrintService = " + ps.getName());
// Print Dialog
System.out.println("2----------");
pj.printDialog(pratts);
System.out.println("Pratts Size = " + pratts.size());
atts = pratts.toArray();
for (int i = 0; i < atts.length; i++)
System.out.println(atts[i].getName() + " = " + atts[i] + " - " + atts[i].getCategory());
pf = pj.defaultPage();
System.out.println("PageFormat h=" + pf.getHeight() + ",w=" + pf.getWidth() + " - x=" + pf.getImageableX() + ",y=" + pf.getImageableY() + " - ih=" + pf.getImageableHeight() + ",iw=" + pf.getImageableWidth()
+ " - Orient=" + pf.getOrientation());
ps = pj.getPrintService();
System.out.println("PrintService= " + ps.getName());
System.out.println("3----------");
try
{
pj.setPrintService(ps);
}
catch (PrinterException pe)
{
System.out.println(pe);
}
pf = pj.validatePage(pf);
System.out.println("PageFormat h=" + pf.getHeight() + ",w=" + pf.getWidth() + " - x=" + pf.getImageableX() + ",y=" + pf.getImageableY() + " - ih=" + pf.getImageableHeight() + ",iw=" + pf.getImageableWidth()
+ " - Orient=" + pf.getOrientation());
ps = pj.getPrintService();
System.out.println("PrintService= " + ps.getName());
System.out.println("4----------");
pj.printDialog();
} // testPS
/**
* Test Stream Print Services
*/
private static void testSPS()
{
// dump (DocFlavor.INPUT_STREAM.GIF, DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType());
// dump (DocFlavor.SERVICE_FORMATTED.PAGEABLE, DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType());
// dump (DocFlavor.INPUT_STREAM.GIF, DocFlavor.BYTE_ARRAY.PDF.getMimeType());
// dump (DocFlavor.SERVICE_FORMATTED.PAGEABLE, DocFlavor.BYTE_ARRAY.GIF.getMediaSubtype());
// dump (DocFlavor.SERVICE_FORMATTED.PAGEABLE, DocFlavor.BYTE_ARRAY.JPEG.getMediaSubtype());
// dump (DocFlavor.SERVICE_FORMATTED.PAGEABLE); // lists devices able to output pageable
// dump (DocFlavor.SERVICE_FORMATTED.PRINTABLE);
// dump (DocFlavor.INPUT_STREAM.TEXT_PLAIN_HOST);
// dump (DocFlavor.INPUT_STREAM.POSTSCRIPT);
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
PrintService[] pss =
PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, pras);
for (int i = 0; i < pss.length; i++)
{
PrintService ps = pss[i];
String name = ps.getName();
if (name.indexOf("PDF") != -1 || name.indexOf("Acrobat") != -1)
{
System.out.println("----");
System.out.println(ps);
Class[] cat = ps.getSupportedAttributeCategories();
for (int j = 0; j < cat.length; j++)
{
System.out.println("- " + cat[j]);
}
}
}
// dump (null, DocFlavor.BYTE_ARRAY.PDF.getMimeType()); // lists PDF output
// dump (null, DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMediaType()); // lists PS output
// dump(null, null);
} // testSPS
/**************************************************************************
* Create Print Form & Print Formats for a new Client.
* - Order, Invoice, etc.
* Called from VSetup
* @param AD_Client_ID new Client
*/
public static void setupPrintForm (int AD_Client_ID)
{
log.config("AD_Client_ID=" + AD_Client_ID);
Properties ctx = Env.getCtx();
CLogMgt.enable(false);
//
// Order Template
int Order_PrintFormat_ID = MPrintFormat.copyToClient(ctx, 100, AD_Client_ID).get_ID();
int OrderLine_PrintFormat_ID = MPrintFormat.copyToClient(ctx, 101, AD_Client_ID).get_ID();
updatePrintFormatHeader(Order_PrintFormat_ID, OrderLine_PrintFormat_ID);
// Invoice
int Invoice_PrintFormat_ID = MPrintFormat.copyToClient(ctx, 102, AD_Client_ID).get_ID();
int InvoiceLine_PrintFormat_ID = MPrintFormat.copyToClient(ctx, 103, AD_Client_ID).get_ID();
updatePrintFormatHeader(Invoice_PrintFormat_ID, InvoiceLine_PrintFormat_ID);
// Shipment
int Shipment_PrintFormat_ID = MPrintFormat.copyToClient(ctx, 104, AD_Client_ID).get_ID();
int ShipmentLine_PrintFormat_ID = MPrintFormat.copyToClient(ctx, 105, AD_Client_ID).get_ID();
updatePrintFormatHeader(Shipment_PrintFormat_ID, ShipmentLine_PrintFormat_ID);
// Check
int Check_PrintFormat_ID = MPrintFormat.copyToClient(ctx, 106, AD_Client_ID).get_ID();
int RemittanceLine_PrintFormat_ID = MPrintFormat.copyToClient(ctx, 107, AD_Client_ID).get_ID();
updatePrintFormatHeader(Check_PrintFormat_ID, RemittanceLine_PrintFormat_ID);
// Remittance
int Remittance_PrintFormat_ID = MPrintFormat.copyToClient(ctx, 108, AD_Client_ID).get_ID();
updatePrintFormatHeader(Remittance_PrintFormat_ID, RemittanceLine_PrintFormat_ID);
// TODO: MPrintForm
// MPrintForm form = new MPrintForm();
int AD_PrintForm_ID = DB.getNextID (AD_Client_ID, "AD_PrintForm", null);
String sql = "INSERT INTO AD_PrintForm(AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy,AD_PrintForm_ID,"
+ "Name,Order_PrintFormat_ID,Invoice_PrintFormat_ID,Remittance_PrintFormat_ID,Shipment_PrintFormat_ID)"
//
+ " VALUES (" + AD_Client_ID + ",0,'Y',SysDate,0,SysDate,0," + AD_PrintForm_ID + ","
+ "'" + Msg.translate(ctx, "Standard") + "',"
+ Order_PrintFormat_ID + "," + Invoice_PrintFormat_ID + ","
+ Remittance_PrintFormat_ID + "," + Shipment_PrintFormat_ID + ")";
int no = DB.executeUpdate(sql, null);
if (no != 1)
log.log(Level.SEVERE, "PrintForm NOT inserted");
//
CLogMgt.enable(true);
} // createDocuments
/**
* Update the PrintFormat Header lines with Reference to Child Print Format.
* @param Header_ID AD_PrintFormat_ID for Header
* @param Line_ID AD_PrintFormat_ID for Line
*/
static private void updatePrintFormatHeader (int Header_ID, int Line_ID)
{
StringBuffer sb = new StringBuffer();
sb.append("UPDATE AD_PrintFormatItem SET AD_PrintFormatChild_ID=")
.append(Line_ID)
.append(" WHERE AD_PrintFormatChild_ID IS NOT NULL AND AD_PrintFormat_ID=")
.append(Header_ID);
int no = DB.executeUpdate(sb.toString(), null);
} // updatePrintFormatHeader
/*************************************************************************/
/**
* Test
* @param args arg
*/
public static void main(String[] args)
{
// org.compiere.Adempiere.startupClient();
// setupPrintForm (11);
// setupPrintForm (1000000);
testPS(); // Print Services
// testSPS(); // Stream Print Services
// dumpSPS(null, null);
} // main
} // PrintUtil

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,278 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print;
import java.awt.*;
import org.compiere.model.*;
import org.compiere.print.layout.*;
import org.compiere.swing.*;
import org.compiere.util.*;
/**
* View Panel
*
* @author Jorg Janke
* @version $Id: View.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $
*/
public class View extends CPanel
{
/**
* Print Preview
* @param layout Layout
*/
public View (LayoutEngine layout)
{
m_layout = layout;
} // View
/** Layout to be Printed */
private LayoutEngine m_layout;
/** Zoom Level */
private int m_zoomLevel = 0;
/** Zoom Options */
public static final String[] ZOOM_OPTIONS = new String[]
{"100%", "75%", "50%"};
/** Margin around paper */
public static int MARGIN = 5;
/** Margin Background Color */
private static Color COLOR_BACKGROUND = Color.lightGray;
/** Logger */
private static CLogger log = CLogger.getCLogger(View.class);
/*************************************************************************/
/**
* Minimum Size
* @return Max Page Size
*/
public Dimension getMinimumSize()
{
return getMaximumSize();
} // getMinimumSize
/**
* Minimum Size
* @return Max Page Size
*/
public Dimension getMaximumSize()
{
return new Dimension (getPaperWidth()+(2*MARGIN),
(getPaperHeight()+MARGIN)*getPageCount()+MARGIN);
} // getMaximumSize
/**
* Preferred Size
* @return Max Page Size
*/
public Dimension getPreferredSize()
{
return getMaximumSize();
} // getPreferredSize
/**
* Is Archivable
* @return true if archivable
*/
public boolean isArchivable()
{
return ArchiveEngine.isValid(m_layout);
} // IsArchivable
/**
* Paint Component
* @param g Graphics
*/
public void paintComponent (Graphics g)
{
// log.fine( "View.paintComponent", g.getClip());
Graphics2D g2D = (Graphics2D)g;
Rectangle bounds = g2D.getClipBounds();
//
g2D.setColor(COLOR_BACKGROUND);
g2D.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
// for all pages
for (int page = 0; page < m_layout.getPages().size(); page++)
{
Rectangle pageRectangle = getRectangleOfPage(page+1);
if (bounds.intersects(pageRectangle))
{
Page p = (Page)m_layout.getPages().get(page);
p.paint (g2D, pageRectangle, true, false); // sets context
m_layout.getHeaderFooter().paint(g2D, pageRectangle, true);
} // paint page
} // for all pages
} // paintComponent
/**************************************************************************
* Set Zoom Level
* @param level zoom level
*/
public void setZoomLevel(int level)
{
m_zoomLevel = level;
} // setZoomLevel
/**
* Set Zoom Level
* @param levelString zoom level string
*/
public void setZoomLevel(String levelString)
{
for (int i = 0; i < ZOOM_OPTIONS.length; i++)
{
if (ZOOM_OPTIONS[i].equals(levelString))
{
m_zoomLevel = i;
break;
}
}
} // setZoomLevel
/**
* Get Zoom Level
* @return zoom level
*/
public int getZoomLevel()
{
return m_zoomLevel;
} // getZoomLevel
/**
* Get Rectange of Page
* @param pageNo page no
* @return rectangle
*/
public Rectangle getRectangleOfPage(int pageNo)
{
int y = MARGIN + ((pageNo-1) * (getPaperHeight() + MARGIN));
return new Rectangle (MARGIN, y, getPaperWidth(), getPaperHeight());
} // getRectangleOfPage
/**
* Get Page at Point
* @param p Point
* @return page as float to determine also position on page
*/
public float getPageNoAt (Point p)
{
float y = p.y;
float pageHeight = getPaperHeight() + MARGIN;
return 1f + (y/pageHeight);
} // getPageAt
/**
* Get Page Count
* @return page count
*/
public int getPageCount()
{
return m_layout.getPages().size();
} // getPageCount
/**
* Get Page Info for Multi-Page tables
* @param pageNo page
* @return info e.g. (1,1)
*/
public String getPageInfo(int pageNo)
{
return m_layout.getPageInfo(pageNo);
} // getPageInfo
/**
* Get Max Page Info for Multi-Page tables
* @return info e.g. (3,2)
*/
public String getPageInfoMax()
{
return m_layout.getPageInfoMax();
} // getPageInfo
/**
* Get Paper
* @return paper
*/
public CPaper getPaper()
{
return m_layout.getPaper();
} // getPaper
/**
* Get Paper Height
* @return paper height
*/
public int getPaperHeight()
{
return (int)m_layout.getPaper().getHeight(true);
} // getPaperHeight
/**
* Get Paper Height
* @return paper height
*/
public int getPaperWidth()
{
return (int)m_layout.getPaper().getWidth(true);
} // getPaperHeight
/**
* Get Drill Down
* @param absolutePoint point
* @return Drill Down
*/
public MQuery getDrillDown (Point absolutePoint)
{
int pageNo = (int)getPageNoAt(absolutePoint);
Rectangle pageRectangle = getRectangleOfPage(pageNo);
Point relativePoint = new Point (absolutePoint.x-pageRectangle.x,
absolutePoint.y-pageRectangle.y);
Page page = (Page)m_layout.getPages().get(pageNo-1);
//
log.config("Relative=" + relativePoint + ", " + page);
// log.config("AbsolutePoint=" + absolutePoint + ", PageNo=" + pageNo + ", pageRectangle=" + pageRectangle);
MQuery retValue = page.getDrillDown (relativePoint);
if (retValue == null)
retValue = m_layout.getHeaderFooter().getDrillDown (relativePoint);
return retValue;
} // getDrillDown
/**
* Get Drill Across
* @param absolutePoint point
* @return Drill Across
*/
public MQuery getDrillAcross (Point absolutePoint)
{
int pageNo = (int)getPageNoAt(absolutePoint);
Rectangle pageRectangle = getRectangleOfPage(pageNo);
Point relativePoint = new Point (absolutePoint.x-pageRectangle.x,
absolutePoint.y-pageRectangle.y);
Page page = (Page)m_layout.getPages().get(pageNo-1);
//
log.config("Relative=" + relativePoint + ", " + page);
// log.config("AbsolutePoint=" + absolutePoint + ", PageNo=" + pageNo + ", pageRectangle=" + pageRectangle);
return page.getDrillAcross (relativePoint);
} // getDrillAcross
} // View

View File

@ -0,0 +1,216 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print.layout;
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import org.compiere.print.*;
import net.sourceforge.barbecue.*;
import net.sourceforge.barbecue.linear.code128.*;
/**
* Barcode Print Element
*
* @author Jorg Janke
* @version $Id: BarcodeElement.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $
*/
public class BarcodeElement extends PrintElement
{
/**
* Barcode Element Constructor
* @param code barcode data string
* @param item format item
*/
public BarcodeElement (String code, MPrintFormatItem item)
{
super ();
if (code == null || code.length() == 0
|| item == null
|| item.getBarcodeType() == null || item.getBarcodeType().length() == 0)
m_valid = false;
createBarcode(code, item);
if (m_barcode == null)
m_valid = false;
} // BarcodeElement
/** Valid */
private boolean m_valid = true;
/** Barcode */
private Barcode m_barcode = null;
/**
* Create Barcode
* @param code barcode data string
* @param item printformat item
*/
private void createBarcode(String code, MPrintFormatItem item)
{
String type = item.getBarcodeType();
try
{
if (type.equals(MPrintFormatItem.BARCODETYPE_Codabar2Of7Linear))
m_barcode = BarcodeFactory.create2of7(code);
else if (type.equals(MPrintFormatItem.BARCODETYPE_CodabarMonarchLinear))
m_barcode = BarcodeFactory.createMonarch(code);
else if (type.equals(MPrintFormatItem.BARCODETYPE_CodabarNW_7Linear))
m_barcode = BarcodeFactory.createNW7(code);
else if (type.equals(MPrintFormatItem.BARCODETYPE_CodabarUSD_4Linear))
m_barcode = BarcodeFactory.createUSD4(code);
else if (type.equals(MPrintFormatItem.BARCODETYPE_Code128ACharacterSet))
m_barcode = BarcodeFactory.createCode128A(code);
else if (type.equals(MPrintFormatItem.BARCODETYPE_Code128BCharacterSet))
m_barcode = BarcodeFactory.createCode128B(code);
else if (type.equals(MPrintFormatItem.BARCODETYPE_Code128CCharacterSet))
m_barcode = BarcodeFactory.createCode128C(code);
else if (type.equals(MPrintFormatItem.BARCODETYPE_Code128DynamicallySwitching))
m_barcode = BarcodeFactory.createCode128(code);
else if (type.equals(MPrintFormatItem.BARCODETYPE_Code393Of9LinearWithChecksum))
m_barcode = BarcodeFactory.create3of9(code, true);
else if (type.equals(MPrintFormatItem.BARCODETYPE_Code393Of9LinearWOChecksum))
m_barcode = BarcodeFactory.create3of9(code, false);
else if (type.equals(MPrintFormatItem.BARCODETYPE_Code39LinearWithChecksum))
m_barcode = BarcodeFactory.createCode39(code, true);
else if (type.equals(MPrintFormatItem.BARCODETYPE_Code39LinearWOChecksum))
m_barcode = BarcodeFactory.createCode39(code, false);
else if (type.equals(MPrintFormatItem.BARCODETYPE_Code39USD3WithChecksum))
m_barcode = BarcodeFactory.createUSD3(code, true);
else if (type.equals(MPrintFormatItem.BARCODETYPE_Code39USD3WOChecksum))
m_barcode = BarcodeFactory.createUSD3(code, false);
else if (type.equals(MPrintFormatItem.BARCODETYPE_CodeabarLinear))
m_barcode = BarcodeFactory.createCodabar(code);
// http://www.idautomation.com/code128faq.html
else if (type.equals(MPrintFormatItem.BARCODETYPE_EAN128))
m_barcode = BarcodeFactory.createEAN128(code);
else if (type.equals(MPrintFormatItem.BARCODETYPE_GlobalTradeItemNoGTINUCCEAN128))
m_barcode = BarcodeFactory.createGlobalTradeItemNumber(code);
else if (type.equals(MPrintFormatItem.BARCODETYPE_PDF417TwoDimensional))
m_barcode = BarcodeFactory.createPDF417(code);
else if (type.equals(MPrintFormatItem.BARCODETYPE_SCC_14ShippingCodeUCCEAN128))
m_barcode = BarcodeFactory.createSCC14ShippingCode(code);
else if (type.equals(MPrintFormatItem.BARCODETYPE_ShipmentIDNumberUCCEAN128))
m_barcode = BarcodeFactory.createShipmentIdentificationNumber(code);
else if (type.equals(MPrintFormatItem.BARCODETYPE_SSCC_18NumberUCCEAN128))
m_barcode = BarcodeFactory.createSSCC18(code);
else if (type.equals(MPrintFormatItem.BARCODETYPE_UCC128))
m_barcode = BarcodeFactory.createUCC128(UCCEAN128Barcode.EAN128_AI, code);
// http://www.usps.com/cpim/ftp/pubs/pub97/97apxs_006.html#_Toc481397331
else if (type.equals(MPrintFormatItem.BARCODETYPE_USPostalServiceUCCEAN128))
{
m_barcode = BarcodeFactory.createUSPS(code);
m_barcode.setDrawingText(false);
}
else
log.warning("Invalid Type" + type);
}
catch (Exception e)
{
log.warning(code + " - " + e.toString());
m_valid = false;
}
if (m_valid && m_barcode != null)
{
if (item.getAD_PrintFont_ID() != 0)
{
MPrintFont mFont = MPrintFont.get(item.getAD_PrintFont_ID());
if (mFont != null)
m_barcode.setFont(mFont.getFont());
}
if (item.getMaxWidth() > 0)
m_barcode.setBarWidth(item.getMaxWidth());
if (item.getMaxHeight() > 0)
m_barcode.setBarHeight(item.getMaxHeight());
// m_barcode.setResolution(72);
//
p_width = m_barcode.getWidth();
p_height = m_barcode.getHeight();
log.fine(type + " height=" + p_height + ", width=" + p_width);
}
} // createBarcode
/**
* Get Barcode
* @return Barcode
*/
public Barcode getBarcode()
{
return m_barcode;
} // getBarcode
/**
* Is Barcode Valid
* @return true if valid
*/
public boolean isValid()
{
return m_valid;
} // isValid
/**
* Layout and Calculate Size
* Set p_width & p_height
* @return true if calculated
*/
protected boolean calculateSize ()
{
return true;
} // calculateSize
/**
* Paint Element
* @param g2D graphics
* @param pageNo page no
* @param pageStart page start
* @param ctx context
* @param isView view
*/
public void paint (Graphics2D g2D, int pageNo, Point2D pageStart,
Properties ctx, boolean isView)
{
if (!m_valid || m_barcode == null)
return;
// Position
Point2D.Double location = getAbsoluteLocation(pageStart);
int x = (int)location.x;
if (MPrintFormatItem.FIELDALIGNMENTTYPE_TrailingRight.equals(p_FieldAlignmentType))
x += p_maxWidth - p_width;
else if (MPrintFormatItem.FIELDALIGNMENTTYPE_Center.equals(p_FieldAlignmentType))
x += (p_maxWidth - p_width) / 2;
int y = (int)location.y;
m_barcode.draw(g2D, x, y);
} // paint
/**
* String Representation
* @return info
*/
public String toString ()
{
if (m_barcode == null)
return super.toString();
return super.toString() + " " + m_barcode.getData();
} // toString
} // BarcodeElement

View File

@ -0,0 +1,122 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print.layout;
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import org.compiere.print.*;
/**
* Line / Box Element
*
* @author Jorg Janke
* @version $Id: BoxElement.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $
*/
public class BoxElement extends PrintElement
{
/**
* BoxElement
* @param item item
* @param color color
*/
public BoxElement (MPrintFormatItem item, Color color)
{
super ();
if (item != null && item.isTypeBox())
{
m_item = item;
m_color = color;
}
} // BoxElement
/** The Item */
private MPrintFormatItem m_item = null;
private Color m_color = Color.BLACK;
/**
* Calculate Size
* @return true if calculated
*/
protected boolean calculateSize ()
{
p_width = 0;
p_height = 0;
if (m_item == null)
return true;
return true;
} // calculateSize
/**
* Paint
* @param g2D graphics
* @param pageNo page
* @param pageStart page start
* @param ctx context
* @param isView true if Java
*/
public void paint (Graphics2D g2D, int pageNo, Point2D pageStart,
Properties ctx, boolean isView)
{
if (m_item == null)
return;
//
g2D.setColor(m_color);
BasicStroke s = new BasicStroke(m_item.getLineWidth());
g2D.setStroke(s);
//
Point2D.Double location = getAbsoluteLocation(pageStart);
int x = (int)location.x;
int y = (int)location.y;
int width = m_item.getMaxWidth();
int height = m_item.getMaxHeight();
if (m_item.getPrintFormatType().equals(MPrintFormatItem.PRINTFORMATTYPE_Line))
g2D.drawLine(x, y, x+width, y+height);
else
{
String type = m_item.getShapeType();
if (type == null)
type = "";
if (m_item.isFilledRectangle())
{
if (type.equals(MPrintFormatItem.SHAPETYPE_3DRectangle))
g2D.fill3DRect(x, y, width, height, true);
else if (type.equals(MPrintFormatItem.SHAPETYPE_Oval))
g2D.fillOval(x, y, width, height);
else if (type.equals(MPrintFormatItem.SHAPETYPE_RoundRectangle))
g2D.fillRoundRect(x, y, width, height, m_item.getArcDiameter(), m_item.getArcDiameter());
else
g2D.fillRect(x, y, width, height);
}
else
{
if (type.equals(MPrintFormatItem.SHAPETYPE_3DRectangle))
g2D.draw3DRect(x, y, width, height, true);
else if (type.equals(MPrintFormatItem.SHAPETYPE_Oval))
g2D.drawOval(x, y, width, height);
else if (type.equals(MPrintFormatItem.SHAPETYPE_RoundRectangle))
g2D.drawRoundRect(x, y, width, height, m_item.getArcDiameter(), m_item.getArcDiameter());
else
g2D.drawRect(x, y, width, height);
}
}
} // paint
} // BoxElement

View File

@ -0,0 +1,171 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print.layout;
import java.awt.*;
import java.awt.geom.*;
/**
* 2D Dimesnion Implementation
*
* @author Jorg Janke
* @version $Id: Dimension2DImpl.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $
*/
public class Dimension2DImpl extends Dimension2D
{
/**
* Constructor 0/0
*/
public Dimension2DImpl()
{
} // Dimension2DImpl
/**
* Constructor 0/0
* @param dim dimension
*/
public Dimension2DImpl(Dimension dim)
{
setSize (dim);
} // Dimension2DImpl
/**
* Constructor 0/0
* @param Width width
* @param Height height
*/
public Dimension2DImpl(double Width, double Height)
{
setSize (Width, Height);
} // Dimension2DImpl
/** Width */
public double width = 0;
/** Height */
public double height = 0;
/**
* Set Size
* @param Width width
* @param Height height
*/
public void setSize (double Width, double Height)
{
this.width = Width;
this.height = Height;
} // setSize
/**
* Set Size
* @param dim dimension
*/
public void setSize (Dimension dim)
{
this.width = dim.getWidth();
this.height = dim.getHeight();
} // setSize
/**
* Add Size below existing
* @param dWidth width to increase if below
* @param dHeight height to add
*/
public void addBelow (double dWidth, double dHeight)
{
if (this.width < dWidth)
this.width = dWidth;
this.height += dHeight;
} // addBelow
/**
* Add Size below existing
* @param dim add dimension
*/
public void addBelow (Dimension dim)
{
addBelow (dim.width, dim.height);
} // addBelow
/**
* Round to next Int value
*/
public void roundUp()
{
width = Math.ceil(width);
height = Math.ceil(height);
} // roundUp
/**
* Get Width
* @return width
*/
public double getWidth()
{
return width;
} // getWidth
/**
* Get Height
* @return height
*/
public double getHeight()
{
return height;
} // getHeight
/*************************************************************************/
/**
* Hash Code
* @return hash code
*/
public int hashCode()
{
long bits = Double.doubleToLongBits(width);
bits ^= Double.doubleToLongBits(height) * 31;
return (((int) bits) ^ ((int) (bits >> 32)));
} // hashCode
/**
* Equals
* @param obj object
* @return true if w/h is same
*/
public boolean equals (Object obj)
{
if (obj != null && obj instanceof Dimension2D)
{
Dimension2D d = (Dimension2D)obj;
if (d.getWidth() == width && d.getHeight() == height)
return true;
}
return false;
} // equals
/**
* String Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append("Dimension2D[w=").append(width).append(",h=").append(height).append("]");
return sb.toString();
} // toString
} // Dimension2DImpl

View File

@ -0,0 +1,64 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print.layout;
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import org.compiere.print.*;
/**
* Graphic Element
*
* @author Jorg Janke
* @version $Id: GraphElement.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $
*/
public class GraphElement extends PrintElement
{
/**
* Constructor
* @param pg graph model
*/
public GraphElement(MPrintGraph pg)
{
} // GraphElement
/**
* Layout and Calculate Size
* Set p_width & p_height
* @return true if calculated
*/
protected boolean calculateSize()
{
return false;
} // calcluateSize
/**
* Paint/Print.
* @param g2D Graphics
* @param pageNo page number for multi page support (0 = header/footer)
* @param pageStart top left Location of page
* @param ctx context
* @param isView true if online view (IDs are links)
*/
public void paint (Graphics2D g2D, int pageNo, Point2D pageStart, Properties ctx, boolean isView)
{
} // paint
} // GraphElement

View File

@ -0,0 +1,209 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print.layout;
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.text.*;
import java.util.*;
/**
* Grid Element.
* Simple Table with Rows/Columns, but no Headers
*
* @author Jorg Janke
* @version $Id: GridElement.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $
*/
public class GridElement extends PrintElement
{
/**
* Grid Element Constructor
* Call setData to initialize content
* @param rows max rows
* @param cols max cols
*/
public GridElement(int rows, int cols)
{
m_rows = rows;
m_cols = cols;
m_textLayout = new TextLayout[rows][cols];
m_iterator = new AttributedCharacterIterator[rows][cols];
m_rowHeight = new int[rows];
m_colWidth = new int[cols];
// explicit init
for (int r = 0; r < m_rows; r++)
{
m_rowHeight[r] = 0;
for (int c = 0; c < m_cols; c++)
{
m_textLayout[r][c] = null;
m_iterator[r][c] = null;
}
}
for (int c = 0; c < m_cols; c++)
m_colWidth[c] = 0;
} // GridElement
/** Gap between Rows */
private int m_rowGap = 3;
/** Gap between Columns */
private int m_colGap = 5;
/** Rows */
private int m_rows;
/** Columns */
private int m_cols;
/** The Layout Data */
private TextLayout[][] m_textLayout = null;
/** Character Iterator */
private AttributedCharacterIterator[][] m_iterator = null;
/** Row Height */
private int[] m_rowHeight = null;
/** Column Width */
private int[] m_colWidth = null;
/** Context */
private FontRenderContext m_frc = new FontRenderContext(null, true, true);
/**
* Create TextLayout from Data and calculate size.
* Called from ParameterElement and Location
* @param row row
* @param col column
* @param stringData info element
* @param font font
* @param foreground color for foreground
*/
public void setData (int row, int col, String stringData, Font font, Paint foreground)
{
if (stringData == null || stringData.length() == 0)
return;
//
// log.fine("setData - " + row + "/" + col + " - " + stringData);
AttributedString aString = new AttributedString(stringData);
aString.addAttribute(TextAttribute.FONT, font);
aString.addAttribute(TextAttribute.FOREGROUND, foreground);
AttributedCharacterIterator iter = aString.getIterator();
TextLayout layout = new TextLayout(iter, m_frc);
setData (row, col, layout, iter);
} // setData
/**
* Create TextLayout from Data and calculate size
* @param row row
* @param col column
* @param layout single line layout
* @param iter character iterator
*/
private void setData (int row, int col, TextLayout layout, AttributedCharacterIterator iter)
{
if (layout == null)
return;
if (p_sizeCalculated)
throw new IllegalStateException("Size already calculated");
if (row < 0 || row >= m_rows)
throw new ArrayIndexOutOfBoundsException("Row Index=" + row + " Rows=" + m_rows);
if (col < 0 || col >= m_cols)
throw new ArrayIndexOutOfBoundsException("Column Index=" + col + " Cols=" + m_cols);
//
m_textLayout[row][col] = layout;
m_iterator[row][col] = iter;
// Set Size
int height = (int)(layout.getAscent() + layout.getDescent() + layout.getLeading())+1;
int width = (int)layout.getAdvance()+1;
if (m_rowHeight[row] < height)
m_rowHeight[row] = height;
if (m_colWidth[col] < width)
m_colWidth[col] = width;
} // setData
/**
* Set Rpw/Column gap
* @param rowGap row gap
* @param colGap column gap
*/
public void setGap (int rowGap, int colGap)
{
m_rowGap = rowGap;
m_colGap = colGap;
} // setGap
/**************************************************************************
* Layout & Calculate Image Size.
* Set p_width & p_height
* @return true if calculated
*/
protected boolean calculateSize()
{
p_height = 0;
for (int r = 0; r < m_rows; r++)
{
p_height += m_rowHeight[r];
if (m_rowHeight[r] > 0)
p_height += m_rowGap;
}
p_height -= m_rowGap; // remove last
p_width = 0;
for (int c = 0; c < m_cols; c++)
{
p_width += m_colWidth[c];
if (m_colWidth[c] > 0)
p_width += m_colGap;
}
p_width -= m_colGap; // remove last
return true;
} // calculateSize
/**
* Paint it
* @param g2D Graphics
* @param pageStart top left Location of page
* @param pageNo page number for multi page support (0 = header/footer) - ignored
* @param ctx print context
* @param isView true if online view (IDs are links)
*/
public void paint(Graphics2D g2D, int pageNo, Point2D pageStart, Properties ctx, boolean isView)
{
Point2D.Double location = getAbsoluteLocation(pageStart);
float y = (float)location.y;
//
for (int row = 0; row < m_rows; row++)
{
float x = (float)location.x;
for (int col = 0; col < m_cols; col++)
{
if (m_textLayout[row][col] != null)
{
float yy = y + m_textLayout[row][col].getAscent();
// if (m_iterator[row][col] != null)
// g2D.drawString(m_iterator[row][col], x, yy);
// else
m_textLayout[row][col].draw(g2D, x, yy);
}
x += m_colWidth[col];
if (m_colWidth[col] > 0)
x += m_colGap;
}
y += m_rowHeight[row];
if (m_rowHeight[row] > 0)
y += m_rowGap;
}
} // paint
} // GridElement

View File

@ -0,0 +1,146 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print.layout;
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
//import org.compiere.model.*;
/**
* HTML Form Print ELement.
* Restrictions:
* - Label is not printed
* - Alighnment is ignored
*
* @author Jorg Janke
* @version $Id: HTMLElement.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $
*/
public class HTMLElement extends PrintElement
{
/**
* HTML String Constructor
* @param html html code
*/
public HTMLElement (String html)
{
if (html == null || html.equals(""))
throw new IllegalArgumentException("HTMLElement is null");
log.fine("Length=" + html.length());
// Create View
m_renderer = HTMLRenderer.get(html);
} // HTMLElement
/** View for Printing */
private HTMLRenderer m_renderer;
/**************************************************************************
* Layout and Calculate Size.
* Set p_width & p_height
* @return Size
*/
protected boolean calculateSize()
{
if (p_sizeCalculated)
return true;
//
p_height = m_renderer.getHeight();
p_width = m_renderer.getWidth();
// Limits
if (p_maxWidth != 0f)
p_width = p_maxWidth;
if (p_maxHeight != 0f)
{
if (p_maxHeight == -1f) // one line only
p_height = m_renderer.getHeightOneLine();
else
p_height = p_maxHeight;
}
// System.out.println("HTMLElement.calculate size - Width="
// + p_width + "(" + p_maxWidth + ") - Height=" + p_height + "(" + p_maxHeight + ")");
//
m_renderer.setAllocation((int)p_width, (int)p_height);
return true;
} // calculateSize
/*************************************************************************
/**
* Paint/Print.
* Calculate actual Size.
* The text is printed in the topmost left position - i.e. the leading is below the line
* @param g2D Graphics
* @param pageStart top left Location of page
* @param pageNo page number for multi page support (0 = header/footer) - ignored
* @param ctx print context
* @param isView true if online view (IDs are links)
*/
public void paint (Graphics2D g2D, int pageNo, Point2D pageStart, Properties ctx, boolean isView)
{
// 36.0/137.015625, Clip=java.awt.Rectangle[x=0,y=0,width=639,height=804], Translate=1.0/56.0, Scale=1.0/1.0, Shear=0.0/0.0
// log.finest( "HTMLElement.paint", p_pageLocation.x + "/" + p_pageLocation.y
// + ", Clip=" + g2D.getClip()
// + ", Translate=" + g2D.getTransform().getTranslateX() + "/" + g2D.getTransform().getTranslateY()
// + ", Scale=" + g2D.getTransform().getScaleX() + "/" + g2D.getTransform().getScaleY()
// + ", Shear=" + g2D.getTransform().getShearX() + "/" + g2D.getTransform().getShearY());
//
Point2D.Double location = getAbsoluteLocation(pageStart);
// log.finest( "HTMLElement.paint - PageStart=" + pageStart + ", Location=" + location);
//
Rectangle allocation = m_renderer.getAllocation();
g2D.translate(location.x, location.y);
m_renderer.paint(g2D, allocation);
g2D.translate(-location.x, -location.y);
} // paint
/**
* String Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer("HTMLElement[");
sb.append("Bounds=").append(getBounds())
.append(",Height=").append(p_height).append("(").append(p_maxHeight)
.append("),Width=").append(p_width).append("(").append(p_maxHeight)
.append("),PageLocation=").append(p_pageLocation).append(" - ");
sb.append("]");
return sb.toString();
} // toString
/**************************************************************************
* Is content HTML
* @param content content
* @return true if HTML
*/
public static boolean isHTML (Object content)
{
if (content == null)
return false;
String s = content.toString();
if (s.length() < 20) // assumption
return false;
s = s.trim().toUpperCase();
if (s.startsWith("<HTML>"))
return true;
return false;
} // isHTML
} // HTMLElement

View File

@ -0,0 +1,387 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print.layout;
import java.awt.*;
import java.io.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import java.util.logging.*;
import org.compiere.util.*;
/**
* HTML Renderer View
*
* @author Jorg Janke
* @version $Id: HTMLRenderer.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $
*/
public class HTMLRenderer extends View
{
/**
* Get View from HTML String
* @param html html string
* @return renderer view
*/
public static HTMLRenderer get (String html)
{
HTMLEditorKit kit = new HTMLEditorKit();
HTMLDocument doc = (HTMLDocument)kit.createDefaultDocument();
try
{
doc.remove(0, doc.getLength());
Reader r = new StringReader(html);
kit.read(r, doc, 0);
}
catch (Exception e)
{
log.log(Level.SEVERE, "", e);
}
// Create Renderer
Element element = doc.getDefaultRootElement();
ViewFactory factory = kit.getViewFactory();
View view = factory.create(element); // Y_AXIS is main
HTMLRenderer renderer = new HTMLRenderer (factory, view);
renderer.preferenceChanged (null, true, true);
return renderer;
} // get
/** Logger */
private static CLogger log = CLogger.getCLogger(HTMLRenderer.class);
/**************************************************************************
* Constructor
* @param f factory
* @param v root view
*/
public HTMLRenderer (ViewFactory f, View v)
{
super(null);
m_factory = f;
m_view = v;
m_view.setParent(this);
// initially layout to the preferred size
setSize(m_view.getPreferredSpan(X_AXIS), m_view.getPreferredSpan(Y_AXIS));
} // HTMLRenderer
private int m_width;
private View m_view;
private ViewFactory m_factory;
private Rectangle m_allocation;
/**
* Get Width
* @return width
*/
public float getWidth()
{
return getPreferredSpan(javax.swing.text.View.X_AXIS);
} // getWidth
/**
* Get Height
* @return height
*/
public float getHeight()
{
return getPreferredSpan(javax.swing.text.View.Y_AXIS);
} // getHeight
/**
* Get Height for one line
* @return height
*/
public float getHeightOneLine()
{
return 30f; // HARDCODED
} // getHeightOneLine
/**
* Set Allocation (actual print size)
* @param width actual print width
* @param height actual print height
*/
public void setAllocation (int width, int height)
{
setAllocation (new Rectangle(width, height));
} // setAllocation
/**
* Set Allocation (actual size)
* @param allocation actual print size
*/
public void setAllocation(Rectangle allocation)
{
m_allocation = allocation;
} // setAllocation
/**
* Get Allocation
* @return actual print size or if not defined the renderer size
*/
public Rectangle getAllocation()
{
if (m_allocation == null)
return new Rectangle((int)getWidth(), (int)getHeight());
return m_allocation;
} // getAllocation
/**
* Fetches the attributes to use when rendering. At the root
* level there are no attributes. If an attribute is resolved
* up the view hierarchy this is the end of the line.
* @return attribute set
*/
public AttributeSet getAttributes()
{
return null;
}
/**
* Determines the preferred span for this view along an axis.
* @param axis may be either X_AXIS or Y_AXIS
* @return the span the view would like to be rendered into.
* Typically the view is told to render into the span
* that is returned, although there is no guarantee.
* The parent may choose to resize or break the view.
*/
public float getPreferredSpan(int axis)
{
if (axis == X_AXIS)
{
// width currently laid out to
return m_width;
}
return m_view.getPreferredSpan(axis);
}
/**
* Determines the minimum span for this view along an axis.
*
* @param axis may be either X_AXIS or Y_AXIS
* @return the span the view would like to be rendered into.
* Typically the view is told to render into the span
* that is returned, although there is no guarantee.
* The parent may choose to resize or break the view.
*/
public float getMinimumSpan(int axis)
{
return m_view.getMinimumSpan(axis);
}
/**
* Determines the maximum span for this view along an axis.
*
* @param axis may be either X_AXIS or Y_AXIS
* @return the span the view would like to be rendered into.
* Typically the view is told to render into the span
* that is returned, although there is no guarantee.
* The parent may choose to resize or break the view.
*/
public float getMaximumSpan(int axis)
{
return Integer.MAX_VALUE;
}
/**
* Determines the desired alignment for this view along an axis.
*
* @param axis may be either X_AXIS or Y_AXIS
* @return the desired alignment, where 0.0 indicates the origin
* and 1.0 the full span away from the origin
*/
public float getAlignment(int axis)
{
return m_view.getAlignment(axis);
}
/**
* Renders the view.
*
* @param g the graphics context
* @param allocation the region to render into
*/
public void paint(Graphics g, Shape allocation)
{
Rectangle alloc = allocation.getBounds();
m_view.setSize(alloc.width, alloc.height); // layout
Shape oldClip = g.getClip();
g.setClip(alloc); // limit print
m_view.paint(g, allocation);
g.setClip(oldClip);
} // paint
/**
* Sets the view parent.
*
* @param parent the parent view
*/
public void setParent(View parent)
{
throw new Error("Can't set parent on root view");
}
/**
* Returns the number of views in this view. Since
* this view simply wraps the root of the view hierarchy
* it has exactly one child.
*
* @return the number of views
* @see #getView
*/
public int getViewCount()
{
return 1;
}
/**
* Gets the n-th view in this container.
*
* @param n the number of the view to get
* @return the view
*/
public View getView(int n)
{
return m_view;
}
/**
* Provides a mapping from the document model coordinate space
* to the coordinate space of the view mapped to it.
*
* @param pos the position to convert
* @param a the allocated region to render into
* @param b position
* @return the bounding box of the given position
* @throws BadLocationException
*/
public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException
{
return m_view.modelToView(pos, a, b);
}
/**
* Provides a mapping from the document model coordinate space
* to the coordinate space of the view mapped to it.
*
* @param p0 the position to convert >= 0
* @param b0 the bias toward the previous character or the
* next character represented by p0, in case the
* position is a boundary of two views.
* @param p1 the position to convert >= 0
* @param b1 the bias toward the previous character or the
* next character represented by p1, in case the
* position is a boundary of two views.
* @param a the allocated region to render into
* @return the bounding box of the given position is returned
* @exception BadLocationException if the given position does
* not represent a valid location in the associated document
* @exception IllegalArgumentException for an invalid bias argument
* @see javax.swing.text.View#viewToModel(float, float, java.awt.Shape, javax.swing.text.Position.Bias[])
*/
public Shape modelToView(int p0, Position.Bias b0, int p1,
Position.Bias b1, Shape a) throws BadLocationException
{
return m_view.modelToView(p0, b0, p1, b1, a);
}
/**
* Provides a mapping from the view coordinate space to the logical
* coordinate space of the model.
*
* @param x x coordinate of the view location to convert
* @param y y coordinate of the view location to convert
* @param a the allocated region to render into
* @param bias bias
* @return the location within the model that best represents the
* given point in the view
*/
public int viewToModel(float x, float y, Shape a, Position.Bias[] bias)
{
return m_view.viewToModel(x, y, a, bias);
}
/**
* Returns the document model underlying the view.
*
* @return the model
*/
public Document getDocument()
{
return m_view.getDocument();
}
/**
* Returns the starting offset into the model for this view.
*
* @return the starting offset
*/
public int getStartOffset()
{
return m_view.getStartOffset();
}
/**
* Returns the ending offset into the model for this view.
*
* @return the ending offset
*/
public int getEndOffset()
{
return m_view.getEndOffset();
}
/**
* Gets the element that this view is mapped to.
*
* @return the view
*/
public Element getElement()
{
return m_view.getElement();
}
/**
* Sets the view size.
*
* @param width the width
* @param height the height
*/
public void setSize(float width, float height)
{
this.m_width = (int) width;
m_view.setSize(width, height);
}
/**
* Fetches the factory to be used for building the
* various view fragments that make up the view that
* represents the model. This is what determines
* how the model will be represented. This is implemented
* to fetch the factory provided by the associated
* EditorKit.
*
* @return the factory
*/
public ViewFactory getViewFactory()
{
return m_factory;
}
} // HTMLRenderer

View File

@ -0,0 +1,104 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print.layout;
import java.awt.*;
import java.util.*;
import org.compiere.model.*;
/**
* Header Footer
*
* @author Jorg Janke
* @version $Id: HeaderFooter.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $
*/
public class HeaderFooter
{
/**
* Standard Constructor
* @param ctx context
*/
public HeaderFooter (Properties ctx)
{
m_ctx = ctx;
} // HeaderFooter
/** Context */
private Properties m_ctx;
/** Header/Footer content */
private ArrayList<PrintElement> m_elements = new ArrayList<PrintElement>();
/** Header/Footer content as Array */
private PrintElement[] m_pe = null;
/**
* Add Print Element to Page
* @param element print element
*/
public void addElement (PrintElement element)
{
if (element != null)
m_elements.add(element);
m_pe = null;
} // addElement
/**
* Get Elements
* @return array of elements
*/
public PrintElement[] getElements()
{
if (m_pe == null)
{
m_pe = new PrintElement[m_elements.size()];
m_elements.toArray(m_pe);
}
return m_pe;
} // getElements
/**
* Paint Page Header/Footer on Graphics in Bounds
*
* @param g2D graphics
* @param bounds page bounds
* @param isView true if online view (IDs are links)
*/
public void paint (Graphics2D g2D, Rectangle bounds, boolean isView)
{
Point pageStart = new Point(bounds.getLocation());
getElements();
for (int i = 0; i < m_pe.length; i++)
m_pe[i].paint(g2D, 0, pageStart, m_ctx, isView);
} // paint
/**
* Get DrillDown value
* @param relativePoint relative Point
* @return if found NamePait or null
*/
public MQuery getDrillDown (Point relativePoint)
{
MQuery retValue = null;
for (int i = 0; i < m_elements.size() && retValue == null; i++)
{
PrintElement element = (PrintElement)m_elements.get(i);
retValue = element.getDrillDown (relativePoint, 1);
}
return retValue;
} // getDrillDown
} // HeaderFooter

View File

@ -0,0 +1,289 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print.layout;
import java.awt.*;
import java.awt.geom.*;
import java.net.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.model.*;
import org.compiere.print.*;
import org.compiere.util.*;
/**
* Image Element
*
* @author Jorg Janke
* @version $Id: ImageElement.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $
*/
public class ImageElement extends PrintElement
{
/**
* Create Image from URL
* @param imageURLString image url
* @return image element
*/
public static ImageElement get (String imageURLString)
{
Object key = imageURLString;
ImageElement image = (ImageElement)s_cache.get(key);
if (image == null)
{
image = new ImageElement(imageURLString);
s_cache.put(key, image);
}
return new ImageElement(image.getImage());
} // get
/**
* Create Image from URL
* @param imageURL image url
* @return image element
*/
public static ImageElement get (URL imageURL)
{
Object key = imageURL;
ImageElement image = (ImageElement)s_cache.get(key);
if (image == null)
{
image = new ImageElement(imageURL);
s_cache.put(key, image);
}
return new ImageElement(image.getImage());
} // get
/**
* Create Image from Attachment
* @param AD_PrintFormatItem_ID record id
* @return image element
*/
public static ImageElement get (int AD_PrintFormatItem_ID)
{
Object key = new Integer(AD_PrintFormatItem_ID);
ImageElement image = (ImageElement)s_cache.get(key);
if (image == null)
{
image = new ImageElement(AD_PrintFormatItem_ID);
s_cache.put(key, image);
}
return new ImageElement(image.getImage());
} // get
/** 60 minute Cache */
private static CCache<Object,ImageElement> s_cache
= new CCache<Object,ImageElement>("ImageElement", 10, 60);
/**************************************************************************
* Create from existing Image
* @param image image
*/
public ImageElement(Image image)
{
m_image = image;
if (m_image != null)
log.fine("Image=" + image);
else
log.log(Level.WARNING, "Image is NULL");
} // ImageElement
/**
* Create Image from URL
* @param imageURLstring image url
*/
private ImageElement(String imageURLstring)
{
URL imageURL = getURL(imageURLstring);
if (imageURL != null)
{
m_image = Toolkit.getDefaultToolkit().getImage(imageURL);
if (m_image != null)
log.fine("URL=" + imageURL);
else
log.log(Level.WARNING, "Not loaded - URL=" + imageURL);
}
else
log.log(Level.WARNING, "Invalid URL=" + imageURLstring);
} // ImageElement
/**
* Create Image from URL
* @param imageURL image url
*/
private ImageElement(URL imageURL)
{
if (imageURL != null)
{
m_image = Toolkit.getDefaultToolkit().getImage(imageURL);
if (m_image != null)
log.fine("URL=" + imageURL);
else
log.log(Level.WARNING, "Not loaded - URL=" + imageURL);
}
else
log.severe ("ImageURL is NULL");
} // ImageElement
/**
* Create Image from Attachment
* @param AD_PrintFormatItem_ID record id
*/
private ImageElement(int AD_PrintFormatItem_ID)
{
loadAttachment(AD_PrintFormatItem_ID);
} // ImageElement
/** The Image */
private Image m_image = null;
/** Scale */
private double m_scaleFactor = 1;
/**************************************************************************
* Get URL from String
* @param urlString url or resource
* @return URL or null
*/
private URL getURL (String urlString)
{
URL url = null;
// not a URL - may be a resource
if (urlString.indexOf("://") == -1)
{
ClassLoader cl = getClass().getClassLoader();
url = cl.getResource(urlString);
if (url != null)
return url;
log.log(Level.WARNING, "Not found - " + urlString);
return null;
}
// load URL
try
{
url = new URL (urlString);
}
catch (MalformedURLException ex)
{
log.log(Level.WARNING, urlString, ex);
}
return url;
} // getURL;
/**
* Load Attachment
* @param AD_PrintFormatItem_ID record id
*/
private void loadAttachment(int AD_PrintFormatItem_ID)
{
MAttachment attachment = MAttachment.get(Env.getCtx(),
MPrintFormatItem.Table_ID, AD_PrintFormatItem_ID);
if (attachment == null)
{
log.log(Level.WARNING, "No Attachment - AD_PrintFormatItem_ID=" + AD_PrintFormatItem_ID);
return;
}
if (attachment.getEntryCount() != 1)
{
log.log(Level.WARNING, "Need just 1 Attachment Entry = " + attachment.getEntryCount());
return;
}
byte[] imageData = attachment.getEntryData(0);
if (imageData != null)
m_image = Toolkit.getDefaultToolkit().createImage(imageData);
if (m_image != null)
log.fine(attachment.getEntryName(0)
+ " - Size=" + imageData.length);
else
log.log(Level.WARNING, attachment.getEntryName(0)
+ " - not loaded (must be gif or jpg) - AD_PrintFormatItem_ID=" + AD_PrintFormatItem_ID);
} // loadAttachment
/**************************************************************************
* Calculate Image Size.
* Set p_width & p_height
* @return true if calculated
*/
protected boolean calculateSize()
{
p_width = 0;
p_height = 0;
if (m_image == null)
return true;
// we have an image
waitForLoad(m_image);
if (m_image != null)
{
p_width = m_image.getWidth(this);
p_height = m_image.getHeight(this);
if (p_width * p_height == 0)
return true; // don't bother scaling and prevent div by 0
// 0 = unlimited so scale to fit restricted dimension
if (p_maxWidth * p_maxHeight != 0) // scale to maintain aspect ratio
{
if (p_width/p_height > p_maxWidth/p_maxHeight)
// image "fatter" than available area
m_scaleFactor = p_maxWidth/p_width;
else
m_scaleFactor = p_maxHeight/p_height;
}
p_width = (float) m_scaleFactor * p_width;
p_height = (float) m_scaleFactor * p_height;
}
return true;
} // calculateSize
/**
* Get the Image
* @return image
*/
public Image getImage()
{
return m_image;
} // getImage
/**
* Paint Image
* @param g2D Graphics
* @param pageStart top left Location of page
* @param pageNo page number for multi page support (0 = header/footer) - ignored
* @param ctx print context
* @param isView true if online view (IDs are links)
*/
public void paint(Graphics2D g2D, int pageNo, Point2D pageStart, Properties ctx, boolean isView)
{
if (m_image == null)
return;
// Position
Point2D.Double location = getAbsoluteLocation(pageStart);
int x = (int)location.x;
if (MPrintFormatItem.FIELDALIGNMENTTYPE_TrailingRight.equals(p_FieldAlignmentType))
x += p_maxWidth - p_width;
else if (MPrintFormatItem.FIELDALIGNMENTTYPE_Center.equals(p_FieldAlignmentType))
x += (p_maxWidth - p_width) / 2;
int y = (int)location.y;
// map a scaled and shifted version of the image to device space
AffineTransform transform = new AffineTransform();
transform.translate(x,y);
transform.scale(m_scaleFactor, m_scaleFactor);
g2D.drawImage(m_image, transform, this);
} // paint
} // ImageElement

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,83 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print.layout;
import java.awt.*;
import java.util.*;
import java.util.regex.*;
import org.compiere.model.*;
/**
* Location/Address Element.
* Prints Addresses
*
* @author Jorg Janke
* @version $Id: LocationElement.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $
*/
public class LocationElement extends GridElement
{
/**
* Constructor
* @param ctx context
* @param C_Location_ID location
* @param font font
* @param color color
*/
public LocationElement(Properties ctx, int C_Location_ID, Font font, Paint color)
{
super(10,1); // max
setGap(0,0);
MLocation ml = MLocation.get (ctx, C_Location_ID, null);
// log.fine("C_Location_ID=" + C_Location_ID);
if (ml != null)
{
int index = 0;
if (ml.isAddressLinesReverse())
{
setData(index++, 0, ml.getCountry(true), font, color);
String[] lines = Pattern.compile("$", Pattern.MULTILINE).split(ml.getCityRegionPostal());
for (int i = 0; i < lines.length; i++)
setData(index++, 0, lines[i], font, color);
if (ml.getAddress4() != null && ml.getAddress4().length() > 0)
setData(index++, 0, ml.getAddress4(), font, color);
if (ml.getAddress3() != null && ml.getAddress3().length() > 0)
setData(index++, 0, ml.getAddress3(), font, color);
if (ml.getAddress2() != null && ml.getAddress2().length() > 0)
setData(index++, 0, ml.getAddress2(), font, color);
if (ml.getAddress1() != null && ml.getAddress1().length() > 0)
setData(index++, 0, ml.getAddress1(), font, color);
}
else
{
if (ml.getAddress1() != null && ml.getAddress1().length() > 0)
setData(index++, 0, ml.getAddress1(), font, color);
if (ml.getAddress2() != null && ml.getAddress2().length() > 0)
setData(index++, 0, ml.getAddress2(), font, color);
if (ml.getAddress3() != null && ml.getAddress3().length() > 0)
setData(index++, 0, ml.getAddress3(), font, color);
if (ml.getAddress4() != null && ml.getAddress4().length() > 0)
setData(index++, 0, ml.getAddress4(), font, color);
String[] lines = Pattern.compile("$", Pattern.MULTILINE).split(ml.getCityRegionPostal());
for (int i = 0; i < lines.length; i++)
setData(index++, 0, lines[i], font, color);
setData(index++, 0, ml.getCountry(true), font, color);
}
}
} // LocationElement
} // LocationElement

View File

@ -0,0 +1,218 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print.layout;
import java.awt.*;
import java.util.*;
import org.compiere.model.*;
import org.compiere.util.*;
/**
* Layout Page
*
* @author Jorg Janke
* @version $Id: Page.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $
*/
public class Page
{
/**
* Layout for Page
* @param pageNo page
* @param ctx context
*/
public Page (Properties ctx, int pageNo)
{
m_ctx = ctx;
m_pageNo = pageNo;
if (m_pageInfo == null || m_pageInfo.length() == 0)
m_pageInfo = String.valueOf(m_pageNo);
} // Page
/** Current Page No (set here) */
public static final String CONTEXT_PAGE = "*Page";
/** Page Count (set in Layout Emgine */
public static final String CONTEXT_PAGECOUNT = "*PageCount";
/** Multi Page Info (set here) */
public static final String CONTEXT_MULTIPAGE = "*MultiPageInfo";
/** Copy Info (set here) */
public static final String CONTEXT_COPY = "*CopyInfo";
/** Report Name (set in Layout Engine) */
public static final String CONTEXT_REPORTNAME = "*ReportName";
/** Report Header (set in Layout Engine) */
public static final String CONTEXT_HEADER = "*Header";
/** Current Date (set in Layout Engine) */
public static final String CONTEXT_DATE = "*CurrentDate";
/** Current Time (set in Layout Engine) */
public static final String CONTEXT_TIME = "*CurrentDateTime";
/** Page Number */
private int m_pageNo;
/** Page Number */
private int m_pageCount = 1;
/** Page Count */
private String m_pageInfo;
/** Context */
private Properties m_ctx;
/** Page content */
private ArrayList<PrintElement> m_elements = new ArrayList<PrintElement>();
/**
* Get Page No
* @return page no
*/
public int getPageNo()
{
return m_pageNo;
} // getPageNo
/**
* Get Page Info
* @return page info
*/
public String getPageInfo()
{
return m_pageInfo;
} // getPageInfo
/**
* Set Page Info.
* Enhanced pagae no, e.g., 7(2,3)
* @param pageInfo page info
*/
public void setPageInfo (String pageInfo)
{
if (m_pageInfo == null || m_pageInfo.length() == 0)
m_pageInfo = String.valueOf(m_pageNo);
m_pageInfo = pageInfo;
} // getPageInfo
/**
* Set Page Info
* @param pageCount page count
*/
public void setPageCount (int pageCount)
{
m_pageCount = pageCount;
} // setPageCount
/**
* Add Print Element to Page
* @param element print element
*/
public void addElement (PrintElement element)
{
if (element != null)
m_elements.add(element);
} // addElement
/*************************************************************************/
/**
* Paint Page on Graphics in Bounds
*
* @param g2D graphics
* @param bounds page bounds
* @param isView true if online view (IDs are links)
* @param isCopy this print is a copy
*/
public void paint (Graphics2D g2D, Rectangle bounds, boolean isView, boolean isCopy)
{
m_ctx.put (CONTEXT_PAGE, m_pageInfo);
// log.finest( "PrintContext", CONTEXT_PAGE + "=" + m_pageInfo);
//
StringBuffer sb = new StringBuffer();
if (m_pageCount != 1) // set to "Page 1 of 2"
sb.append(Msg.getMsg(m_ctx, "Page")).append(" ")
.append(m_pageNo)
.append(" ").append(Msg.getMsg(m_ctx, "of")).append(" ")
.append(m_pageCount);
else
sb.append(" ");
m_ctx.put(CONTEXT_MULTIPAGE, sb.toString());
// log.finest( "PrintContext", CONTEXT_MULTIPAGE + "=" + sb.toString());
//
sb = new StringBuffer();
if (isCopy) // set to "(Copy)"
sb.append("(")
.append(Msg.getMsg(m_ctx, "DocumentCopy"))
.append(")");
else
sb.append(" ");
m_ctx.put(CONTEXT_COPY, sb.toString());
// log.finest( "PrintContext copy=" + isCopy, CONTEXT_COPY + "=" + sb.toString());
// Paint Background
g2D.setColor(Color.white);
g2D.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
//
Point pageStart = new Point(bounds.getLocation());
for (int i = 0; i < m_elements.size(); i++)
{
PrintElement e = (PrintElement)m_elements.get(i);
e.paint(g2D, m_pageNo, pageStart, m_ctx, isView);
}
} // paint
/*************************************************************************/
/**
* Get DrillDown value
* @param relativePoint relative Point
* @return if found NamePait or null
*/
public MQuery getDrillDown (Point relativePoint)
{
MQuery retValue = null;
for (int i = 0; i < m_elements.size() && retValue == null; i++)
{
PrintElement element = (PrintElement)m_elements.get(i);
retValue = element.getDrillDown (relativePoint, m_pageNo);
}
return retValue;
} // getDrillDown
/**
* Get DrillAcross value
* @param relativePoint relative Point
* @return if found Query or null
*/
public MQuery getDrillAcross (Point relativePoint)
{
MQuery retValue = null;
for (int i = 0; i < m_elements.size() && retValue == null; i++)
{
PrintElement element = (PrintElement)m_elements.get(i);
retValue = element.getDrillAcross (relativePoint, m_pageNo);
}
return retValue;
} // getDrillAcross
/**
* String Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer("Page[");
sb.append(m_pageNo).append(",Elements=").append(m_elements.size());
sb.append("]");
return sb.toString();
} // toString
} // Page

View File

@ -0,0 +1,54 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print.layout;
import java.util.*;
import org.compiere.model.*;
import org.compiere.print.*;
import org.compiere.util.*;
/**
* Parameter Table
*
* @author Jorg Janke
* @version $Id: ParameterElement.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $
*/
public class ParameterElement extends GridElement
{
/**
* Parameter Element.
* <pre>
* Parameter fromValue - toValue
* </pre>
* @param query query
* @param ctx context
* @param tFormat Table Format
*/
public ParameterElement(MQuery query, Properties ctx, MPrintTableFormat tFormat)
{
super (query.getRestrictionCount(), 4);
setData (0, 0, Msg.getMsg(ctx, "Parameter") + ":", tFormat.getPageHeader_Font(), tFormat.getPageHeaderFG_Color());
for (int r = 0; r < query.getRestrictionCount(); r++)
{
setData (r, 1, query.getInfoName(r), tFormat.getParameter_Font(), tFormat.getParameter_Color());
setData (r, 2, query.getInfoOperator(r), tFormat.getParameter_Font(), tFormat.getParameter_Color());
setData (r, 3, query.getInfoDisplayAll(r), tFormat.getParameter_Font(), tFormat.getParameter_Color());
}
} // ParameterElement
} // ParameterElement

View File

@ -0,0 +1,348 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print.layout;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.model.*;
import org.compiere.print.*;
import org.compiere.util.*;
/**
* Print Element
*
* @author Jorg Janke
* @version $Id: PrintElement.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $
*/
public abstract class PrintElement implements ImageObserver
{
/**
* Constructor
*/
protected PrintElement ()
{
} // PrintElement
/** Link Color */
public static final Color LINK_COLOR = Color.blue;
/** Calculated Size of Element */
protected float p_width = 0f;
protected float p_height = 0f;
protected boolean p_sizeCalculated = false;
/** Max Size of Element */
protected float p_maxWidth = 0f;
protected float p_maxHeight = 0f;
/** Field Align Type */
protected String p_FieldAlignmentType;
/** Location on Page */
protected Point2D.Double p_pageLocation = null;
/** Loading Flag */
private boolean m_imageNotLoaded = true;
/** Logger */
protected CLogger log = CLogger.getCLogger(getClass());
/**************************************************************************
* Get Calculated Width
* @return Width
*/
public float getWidth()
{
if (!p_sizeCalculated)
p_sizeCalculated = calculateSize();
return p_width;
} // getWidth
/**
* Get Calculated Height
* @return Height
*/
public float getHeight()
{
if (!p_sizeCalculated)
p_sizeCalculated = calculateSize();
return p_height;
} // getHeight
/**
* Get Calculated Height on page
* @param pageNo page number
* @return Height
*/
public float getHeight (int pageNo)
{
return getHeight();
} // getHeight
/**
* Get number of pages
* @return page count (1)
*/
public int getPageCount()
{
return 1;
} // getPageCount
/**
* Layout and Calculate Size
* Set p_width & p_height
* @return true if calculated
*/
protected abstract boolean calculateSize();
/**
* Layout Element
* @param maxWidth max width
* @param maxHeight max height
* @param isHeightOneLine just one line
* @param FieldAlignmentType alignment type (MPrintFormatItem.FIELD_ALIGN_*)
*/
public void layout (float maxWidth, float maxHeight, boolean isHeightOneLine,
String FieldAlignmentType)
{
if (isHeightOneLine)
p_maxHeight = -1f;
else if (maxHeight > 0f)
p_maxHeight = maxHeight;
p_maxWidth = maxWidth;
//
p_FieldAlignmentType = FieldAlignmentType;
if (p_FieldAlignmentType == null || p_FieldAlignmentType == MPrintFormatItem.FIELDALIGNMENTTYPE_Default)
p_FieldAlignmentType = MPrintFormatItem.FIELDALIGNMENTTYPE_LeadingLeft;
//
p_sizeCalculated = calculateSize();
} // layout
/**
* Set Maximum Height
* @param maxHeight maximum height (0) is no limit
*/
public void setMaxHeight (float maxHeight)
{
p_maxHeight = maxHeight;
} // setMaxHeight
/**
* Set Maximum Width
* @param maxWidth maximum width (0) is no limit
*/
public void setMaxWidth (float maxWidth)
{
p_maxWidth = maxWidth;
} // setMaxWidth
/**
* Set Location within page.
* Called from LayoutEngine.layoutForm(), lauout(), createStandardFooterHeader()
* @param pageLocation location within page
*/
public void setLocation (Point2D pageLocation)
{
p_pageLocation = new Point2D.Double(pageLocation.getX(), pageLocation.getY());
} // setLocation
/**
* Get Location within page
* @return location within page
*/
public Point2D getLocation()
{
return p_pageLocation;
} // getLocation
/**
* Return Absolute Position
* @param pageStart start of page
* @return absolite position
*/
protected Point2D.Double getAbsoluteLocation(Point2D pageStart)
{
Point2D.Double retValue = new Point2D.Double(
p_pageLocation.x + pageStart.getX(), p_pageLocation.y + pageStart.getY());
// log.finest( "PrintElement.getAbsoluteLocation", "PageStart=" + pageStart.getX() + "/" + pageStart.getY()
// + ",PageLocaton=" + p_pageLocation.x + "/" + p_pageLocation.y + " => " + retValue.x + "/" + retValue.y);
return retValue;
} // getAbsoluteLocation
/**
* Get relative Bounds of Element
* @return bounds relative position on page
*/
public Rectangle getBounds()
{
if (p_pageLocation == null)
return new Rectangle (0,0, (int)p_width, (int)p_height);
return new Rectangle ((int)p_pageLocation.x, (int)p_pageLocation.y, (int)p_width, (int)p_height);
} // getBounds
/**
* Get Drill Down value
* @param relativePoint relative Point
* @param pageNo page number
* @return null (subclasses overwrite)
*/
public MQuery getDrillDown (Point relativePoint, int pageNo)
{
return null;
} // getDrillDown
/**
* Get Drill Across value
* @param relativePoint relative Point
* @param pageNo page number
* @return null (subclasses overwrite)
*/
public MQuery getDrillAcross (Point relativePoint, int pageNo)
{
return null;
} // getDrillAcross
/**************************************************************************
* Translate Context if required.
* If content is translated, the element needs to stay in the bounds
* of the originally calculated size and need to align the field.
* @param ctx context
*/
public void translate (Properties ctx)
{
// noop
} // translate
/**
* Content is translated
* @return false
*/
public boolean isTranslated()
{
return false;
} // translate
/**************************************************************************
* Paint/Print.
* @param g2D Graphics
* @param pageNo page number for multi page support (0 = header/footer)
* @param pageStart top left Location of page
* @param ctx context
* @param isView true if online view (IDs are links)
*/
public abstract void paint (Graphics2D g2D, int pageNo, Point2D pageStart, Properties ctx, boolean isView);
/**************************************************************************
* Image Observer
* @param img image
* @param infoflags Observer flags
* @param x x coordinate
* @param y y coordinate
* @param width image width
* @param height image height
* @return false if the infoflags indicate that the image is completely loaded; true otherwise
*/
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height)
{
// copied from java.awt.component
m_imageNotLoaded = (infoflags & (ALLBITS|ABORT)) == 0;
if (CLogMgt.isLevelFinest())
log.finest("Flags=" + infoflags
+ ", x=" + x + ", y=" + y + ", width=" + width + ", height=" + height
+ " - NotLoaded=" + m_imageNotLoaded);
return m_imageNotLoaded;
} // imageUpdate
/**
* Wait until Image is loaded.
* @param image image
* @return true if loaded
*/
public boolean waitForLoad (Image image)
{
long start = System.currentTimeMillis();
Thread.yield();
int count = 0;
try
{
Toolkit toolkit = Toolkit.getDefaultToolkit();
while (!toolkit.prepareImage(image, -1, -1, this)) // ImageObserver calls imageUpdate
{
// Timeout
if (count > 1000) // about 20+ sec overall
{
log.severe (this + " - Timeout - "
+ (System.currentTimeMillis()-start) + "ms - #" + count);
return false;
}
try
{
if (count < 10)
Thread.sleep(10);
else if (count < 100)
Thread.sleep(15);
else
Thread.sleep(20);
}
catch (InterruptedException ex)
{
log.log(Level.SEVERE, "", ex);
break;
}
count++;
}
}
catch (Exception e) // java.lang.SecurityException
{
log.log(Level.SEVERE, "", e);
return false;
}
if (count > 0)
log.fine((System.currentTimeMillis()-start) + "ms - #" + count);
return true;
} // waitForLoad
/**
* Get Detail Info from Sub-Class
* @return detail info
*/
protected String getDetailInfo()
{
return "";
} // getDetailInfo
/**
* String Representation
* @return info
*/
public String toString()
{
String cn = getClass().getName();
StringBuffer sb = new StringBuffer();
sb.append(cn.substring(cn.lastIndexOf('.')+1)).append("[");
sb.append("Bounds=").append(getBounds())
.append(",Height=").append(p_height).append("(").append(p_maxHeight)
.append("),Width=").append(p_width).append("(").append(p_maxHeight)
.append("),PageLocation=").append(p_pageLocation);
sb.append("]");
return sb.toString();
} // toString
} // PrintElement

View File

@ -0,0 +1,606 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.print.layout;
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
import org.compiere.model.*;
import org.compiere.print.*;
import org.compiere.util.*;
/**
* String Form Print ELement.
* The input can be multiple lines. The first tab is expanded.
*
* @author Jorg Janke
* @version $Id: StringElement.java,v 1.2 2006/07/30 00:53:02 jjanke Exp $
*/
public class StringElement extends PrintElement
{
/**
* Standard Field Constructor.
* Created in LayoutEngine
* @param inText text
* @param font font
* @param paint paint
* @param ID optional ID (null if document)
* @param translateText if true, check for optional text translation
*/
public StringElement (String inText, Font font, Paint paint, NamePair ID, boolean translateText)
{
super();
log.finest("Text=" + inText + ", ID=" + ID + ", Translate=" + translateText);
m_font = font;
m_paint = paint;
if (translateText)
{
int count = Util.getCount(inText, '@');
if (count > 0 && count % 2 == 0)
{
m_originalString = inText;
// Translate it to get rough space (not correct context) = may be too small
inText = Msg.parseTranslation(Env.getCtx(), m_originalString);
}
}
m_ID = ID;
String[] lines = Pattern.compile("$", Pattern.MULTILINE).split(inText);
m_string_paper = new AttributedString[lines.length];
m_string_view = new AttributedString[lines.length];
for (int i = 0; i < lines.length; i++)
{
String line = Util.removeCRLF (lines[i]);
m_string_paper[i] = new AttributedString(line);
if (line.length() == 0)
continue;
log.finest(" - line=" + i + " - " + line);
m_string_paper[i].addAttribute(TextAttribute.FONT, font);
m_string_paper[i].addAttribute(TextAttribute.FOREGROUND, paint);
if (m_ID != null && i == 0) // first line only - create special Attributed String
{
m_string_view[i] = new AttributedString(line);
m_string_view[i].addAttribute(TextAttribute.FONT, font);
int endIndex = line.length();
m_string_view[i].addAttribute(TextAttribute.FOREGROUND, LINK_COLOR);
m_string_view[i].addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_LOW_ONE_PIXEL, 0, endIndex);
}
else
m_string_view[i] = m_string_paper[i];
}
// Load Image
waitForLoad(LayoutEngine.IMAGE_TRUE);
waitForLoad(LayoutEngine.IMAGE_FALSE);
} // StringElement
/**
* Attributed String Constructor
* @param string attributed string
*/
public StringElement(AttributedString string)
{
super();
m_string_paper = new AttributedString[] {string};
m_string_view = m_string_paper;
} // StringElement
/**
* Field Constructor.
* Created in LayoutEngine
* @param content text or boolean
* @param font font
* @param paint paint
* @param ID optional ID (null if document)
* @param label optional label
* @param labelSuffix optional label suffix
*/
public StringElement (Object content, Font font, Paint paint, NamePair ID, String label, String labelSuffix)
{
super();
log.finest("Label=" + label + "|" + labelSuffix
+ ", Content=" + content + ", ID=" + ID);
m_font = font;
m_paint = paint;
int startIndex = 0;
int endOffset = 0;
StringBuffer text = new StringBuffer();
if (label != null && label.length() > 0)
{
text.append(label).append(" ");
startIndex = label.length() + 1;
}
if (content instanceof Boolean)
m_check = (Boolean)content;
else
text.append(content);
if (labelSuffix != null && labelSuffix.length() > 0)
{
text.append(labelSuffix);
endOffset = labelSuffix.length();
}
m_ID = ID;
String[] lines = Pattern.compile("$", Pattern.MULTILINE).split(text);
m_string_paper = new AttributedString[lines.length];
m_string_view = new AttributedString[lines.length];
for (int i = 0; i < lines.length; i++)
{
String line = Util.removeCRLF (lines[i]);
m_string_paper[i] = new AttributedString(line);
if (line.length() == 0)
continue;
log.finest(" - line=" + i + " - " + line);
m_string_paper[i].addAttribute(TextAttribute.FONT, font);
m_string_paper[i].addAttribute(TextAttribute.FOREGROUND, paint);
if (m_ID != null && i == 0) // first line only - create special Attributed String
{
m_string_view[i] = new AttributedString(line);
m_string_view[i].addAttribute(TextAttribute.FONT, font);
m_string_view[i].addAttribute(TextAttribute.FOREGROUND, paint);
int endIndex = line.length() - endOffset;
if (endIndex > startIndex)
{
m_string_view[i].addAttribute (TextAttribute.FOREGROUND, LINK_COLOR, startIndex, endIndex);
m_string_view[i].addAttribute (TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_LOW_ONE_PIXEL, startIndex, endIndex);
}
}
else
m_string_view[i] = m_string_paper[i];
}
} // StringElement
/** Actual Elements - Viewer */
private AttributedString[] m_string_view = null;
/** Actual Elements - Printer */
private AttributedString[] m_string_paper = null;
/** To be translated String */
private String m_originalString = null;
/** Font used */
private Font m_font = null;
/** Paint used */
private Paint m_paint = null;
/** Optional ID of String */
private NamePair m_ID = null;
/** Optional CheckBox */
private Boolean m_check = null;
/**
* Get optional ID
* @return ID or null
*/
public NamePair getID()
{
return m_ID;
} // getID
/**
* Get Original String
* @return original (may be null)
*/
public String getOriginalString()
{
return m_originalString;
} // getOrig
/**
* Translate Context if required
* If content is translated, the element needs to stay in the bounds
* of the originally calculated size and need to align the field.
* @param ctx context
*/
public void translate(Properties ctx)
{
if (m_originalString == null)
return;
String inText = Msg.parseTranslation(ctx, m_originalString);
// log.fine( "StringElement.translate", inText);
String[] lines = Pattern.compile("$", Pattern.MULTILINE).split(inText);
m_string_paper = new AttributedString[lines.length];
for (int i = 0; i < lines.length; i++)
{
String line = Util.removeCRLF (lines[i]);
m_string_paper[i] = new AttributedString(line);
if (line.length() > 0)
{
m_string_paper[i].addAttribute(TextAttribute.FONT, m_font);
m_string_paper[i].addAttribute(TextAttribute.FOREGROUND, m_paint);
}
}
m_string_view = m_string_paper;
} // translate
/**************************************************************************
* Layout and Calculate Size.
* Set p_width & p_height
* @return Size
*/
protected boolean calculateSize()
{
if (p_sizeCalculated)
return true;
//
FontRenderContext frc = new FontRenderContext(null, true, true);
TextLayout layout = null;
p_height = 0f;
p_width = 0f;
// No Limit
if (p_maxWidth == 0f && p_maxHeight == 0f)
{
for (int i = 0; i < m_string_paper.length; i++)
{
AttributedCharacterIterator iter = m_string_paper[i].getIterator();
if (iter.getBeginIndex() == iter.getEndIndex())
continue;
// Check for Tab (just first)
int tabPos = -1;
for (char c = iter.first(); c != CharacterIterator.DONE && tabPos == -1; c = iter.next())
{
if (c == '\t')
tabPos = iter.getIndex();
}
if (tabPos == -1)
{
layout = new TextLayout (iter, frc);
p_height += layout.getAscent() + layout.getDescent() + layout.getLeading();
if (p_width < layout.getAdvance())
p_width = layout.getAdvance();
}
else // with tab
{
LineBreakMeasurer measurer = new LineBreakMeasurer(iter, frc);
layout = measurer.nextLayout(9999, tabPos, false);
p_height += layout.getAscent() + layout.getDescent() + layout.getLeading();
float width = getTabPos (0, layout.getAdvance());
layout = measurer.nextLayout(9999, iter.getEndIndex(), true);
width += layout.getAdvance();
if (p_width < width)
p_width = width;
}
} // for all strings
// Add CheckBox Size
if (m_check != null)
{
p_width += LayoutEngine.IMAGE_SIZE.width;
if (p_height < LayoutEngine.IMAGE_SIZE.height)
p_height = LayoutEngine.IMAGE_SIZE.height;
}
}
// Size Limits
else
{
p_width = p_maxWidth;
for (int i = 0; i < m_string_paper.length; i++)
{
AttributedCharacterIterator iter = m_string_paper[i].getIterator();
if (iter.getBeginIndex() == iter.getEndIndex())
continue;
LineBreakMeasurer measurer = new LineBreakMeasurer(iter, frc);
// System.out.println("StringLength=" + m_originalString.length() + " MaxWidth=" + p_maxWidth + " MaxHeight=" + p_maxHeight);
while (measurer.getPosition() < iter.getEndIndex())
{
// no need to expand tab space for limited space
layout = measurer.nextLayout(p_maxWidth);
float lineHeight = layout.getAscent() + layout.getDescent() + layout.getLeading();
// System.out.println(" LineWidth=" + layout.getAdvance() + " LineHeight=" + lineHeight);
if (p_maxHeight == -1f && i == 0) // one line only
p_maxHeight = lineHeight;
if (p_maxHeight == 0f || (p_height + lineHeight) <= p_maxHeight)
p_height += lineHeight;
}
} // for all strings
// Add CheckBox Size
if (m_check != null)
{
// p_width += LayoutEngine.IMAGE_SIZE.width;
if (p_height < LayoutEngine.IMAGE_SIZE.height)
p_height = LayoutEngine.IMAGE_SIZE.height;
}
// System.out.println(" Width=" + p_width + " Height=" + p_height);
}
// System.out.println("StringElement.calculate size - Width="
// + p_width + "(" + p_maxWidth + ") - Height=" + p_height + "(" + p_maxHeight + ")");
// Enlarge Size when aligned and max size is given
if (p_FieldAlignmentType != null)
{
boolean changed = false;
if (p_height < p_maxHeight)
{
p_height = p_maxHeight;
changed = true;
}
if (p_width < p_maxWidth)
{
p_width = p_maxWidth;
changed = true;
}
// if (changed)
// System.out.println("StringElement.calculate size - Width="
// + p_width + "(" + p_maxWidth + ") - Height=" + p_height + "(" + p_maxHeight + ")");
}
return true;
} // calculateSize
/**************************************************************************
* Get Drill Down value
* @param relativePoint relative Point
* @param pageNo page number (ignored)
* @return if found query or null
*/
public MQuery getDrillDown (Point relativePoint, int pageNo)
{
if (m_ID != null && getBounds().contains(relativePoint))
{
log.fine(toString());
String columnName = MQuery.getZoomColumnName(m_ID.getName());
String tableName = MQuery.getZoomTableName(columnName);
Object code = m_ID.getID();
if (m_ID instanceof KeyNamePair)
code = new Integer(((KeyNamePair)m_ID).getKey());
//
MQuery query = new MQuery(tableName);
query.addRestriction(columnName, MQuery.EQUAL, code);
return query;
}
return null;
} // getDrillDown
/**
* Get Drill Across value
* @param relativePoint relative Point
* @param pageNo page number (ignored)
* @return null - not implemented
*/
public MQuery getDrillAcross (Point relativePoint, int pageNo)
{
// log.fine( "StringElement.getDrillAcross");
// if (getBounds().contains(relativePoint));
return null;
} // getDrillAcross
/**************************************************************************
* Paint/Print.
* Calculate actual Size.
* The text is printed in the topmost left position - i.e. the leading is below the line
* @param g2D Graphics
* @param pageStart top left Location of page
* @param pageNo page number for multi page support (0 = header/footer) - ignored
* @param ctx print context
* @param isView true if online view (IDs are links)
*/
public void paint (Graphics2D g2D, int pageNo, Point2D pageStart, Properties ctx, boolean isView)
{
// log.finest( "StringElement.paint", "<" + m_originalString + "> " + p_pageLocation.x + "/" + p_pageLocation.y
// + ", Clip=" + g2D.getClip()
// + ", Translate=" + g2D.getTransform().getTranslateX() + "/" + g2D.getTransform().getTranslateY()
// + ", Scale=" + g2D.getTransform().getScaleX() + "/" + g2D.getTransform().getScaleY()
// + ", Shear=" + g2D.getTransform().getShearX() + "/" + g2D.getTransform().getShearY());
Point2D.Double location = getAbsoluteLocation(pageStart);
//
if (m_originalString != null)
translate(ctx);
AttributedString aString = null;
AttributedCharacterIterator iter = null;
AttributedCharacterIterator iter2 = null;
float xPos = (float)location.x;
float yPos = (float)location.y;
float yPen = 0f;
float height = 0f;
float width = 0f;
// for all lines
for (int i = 0; i < m_string_paper.length; i++)
{
// Get Text
if (isView)
{
if (m_string_view[i] == null)
continue;
aString = m_string_view[i];
}
else
{
if (m_string_paper[i] == null)
continue;
aString = m_string_paper[i];
}
iter = aString.getIterator();
// Zero Length
if (iter.getBeginIndex() == iter.getEndIndex())
continue;
// Check for Tab (just first) and 16 bit characters
int tabPos = -1;
boolean is8Bit = true;
for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next())
{
if (c == '\t' && tabPos == -1)
tabPos = iter.getIndex();
if (c > 255)
is8Bit = false;
}
TextLayout layout = null;
float xPen = xPos;
// No Limit
if (p_maxWidth == 0f)
{
if (tabPos == -1)
{
layout = new TextLayout (iter, g2D.getFontRenderContext());
yPen = yPos + layout.getAscent();
// layout.draw(g2D, xPen, yPen);
g2D.setFont(m_font);
g2D.setPaint(m_paint);
g2D.drawString(iter, xPen, yPen);
//
yPos += layout.getAscent() + layout.getDescent() + layout.getLeading();
if (width < layout.getAdvance())
width = layout.getAdvance();
}
else // we have a tab
{
LineBreakMeasurer measurer = new LineBreakMeasurer(iter, g2D.getFontRenderContext());
layout = measurer.nextLayout(9999, tabPos, false);
float lineHeight_1 = layout.getAscent() + layout.getDescent() + layout.getLeading();
yPen = yPos + layout.getAscent();
layout.draw(g2D, xPen, yPen); // first part before tab
xPen = getTabPos (xPos, layout.getAdvance());
float lineWidth = xPen - xPos;
layout = measurer.nextLayout(9999);//, iter.getEndIndex(), true);
float lineHeight_2 = layout.getAscent() + layout.getDescent() + layout.getLeading();
layout.draw(g2D, xPen, yPen); // second part after tab
//
yPos += Math.max(lineHeight_1, lineHeight_2);
lineWidth += layout.getAdvance();
if (width < lineWidth)
width = lineWidth;
}
// log.finest( "StringElement.paint - No Limit - " + location.x + "/" + yPos
// + " w=" + layout.getAdvance() + ",h=" + lineHeight + ", Bounds=" + layout.getBounds());
}
// Size Limits
else
{
boolean fastDraw = LayoutEngine.s_FASTDRAW;
if (fastDraw && !isView && !is8Bit)
fastDraw = false;
LineBreakMeasurer measurer = new LineBreakMeasurer(iter, g2D.getFontRenderContext());
while (measurer.getPosition() < iter.getEndIndex())
{
if (tabPos == -1)
{
layout = measurer.nextLayout(p_maxWidth);
if (iter.getEndIndex() != measurer.nextOffset(p_maxWidth))
fastDraw = false;
}
else // tab
{
fastDraw = false;
layout = measurer.nextLayout(p_maxWidth, tabPos, false);
}
// Line Height
float lineHeight = layout.getAscent() + layout.getDescent() + layout.getLeading();
if (p_maxHeight == -1f && i == 0) // one line only
p_maxHeight = lineHeight;
// If we have hight left over
if (p_maxHeight == 0f || (height + lineHeight) <= p_maxHeight)
{
yPen = (float)location.y + height + layout.getAscent();
// Tab in Text
if (tabPos != -1)
{
layout.draw(g2D, xPen, yPen); // first part before tab
xPen = getTabPos (xPos, layout.getAdvance());
layout = measurer.nextLayout(p_width, iter.getEndIndex(), true);
tabPos = -1; // reset (just one tab)
}
else if ((MPrintFormatItem.FIELDALIGNMENTTYPE_TrailingRight.equals(p_FieldAlignmentType) && layout.isLeftToRight())
|| (MPrintFormatItem.FIELDALIGNMENTTYPE_LeadingLeft.equals(p_FieldAlignmentType) && !layout.isLeftToRight()))
xPen += p_maxWidth - layout.getAdvance();
else if (MPrintFormatItem.FIELDALIGNMENTTYPE_Center.equals(p_FieldAlignmentType))
xPen += (p_maxWidth - layout.getAdvance()) / 2;
else if (MPrintFormatItem.FIELDALIGNMENTTYPE_Block.equals(p_FieldAlignmentType) && measurer.getPosition() < iter.getEndIndex())
{
layout = layout.getJustifiedLayout(p_maxWidth);
fastDraw = false;
}
if (fastDraw)
{
g2D.setFont(m_font);
g2D.setPaint(m_paint);
g2D.drawString(iter, xPen, yPen);
}
else
{
layout.draw(g2D, xPen, yPen);
}
height += lineHeight;
// log.finest( "StringElement.paint - Limit - " + xPen + "/" + yPen
// + " w=" + layout.getAdvance() + ",h=" + lineHeight + ", Align=" + p_FieldAlignmentType + ", Max w=" + p_maxWidth + ",h=" + p_maxHeight + ", Bounds=" + layout.getBounds());
}
}
width = p_maxWidth;
} // size limits
} // for all strings
if (m_check != null)
{
int x = (int)(location.x + width + 1);
int y = (int)(location.y);
g2D.drawImage(m_check.booleanValue() ? LayoutEngine.IMAGE_TRUE : LayoutEngine.IMAGE_FALSE, x, y, this);
}
} // paint
/**
* Get Tab Position.
* The Tab position is relative to the string itself, not the absolute
* position; i.e. to have the same tab position on a page, strings need
* to start at the same position.
* The Tab is rounded up to the next 30 dividable position.
* @param xPos starting x position
* @param length length of segment
* @return new x Position (xPos + length + tabSpace)
*/
private float getTabPos (float xPos, float length)
{
float retValue = xPos + length;
int iLength = (int)Math.ceil(length);
int tabSpace = iLength % 30;
retValue += (30 - tabSpace);
return retValue;
} // getTabPos
/**
* String Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer("StringElement[");
sb.append("Bounds=").append(getBounds())
.append(",Height=").append(p_height).append("(").append(p_maxHeight)
.append("),Width=").append(p_width).append("(").append(p_maxHeight)
.append("),PageLocation=").append(p_pageLocation).append(" - ");
for (int i = 0; i < m_string_paper.length; i++)
{
if (m_string_paper.length > 1)
sb.append(Env.NL).append(i).append(":");
AttributedCharacterIterator iter = m_string_paper[i].getIterator();
for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next())
sb.append(c);
}
if (m_ID != null)
sb.append(",ID=(").append(m_ID.toStringX()).append(")");
sb.append("]");
return sb.toString();
} // toString
} // StringElement

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 471 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 400 B

View File

@ -0,0 +1,34 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!--
$Id: package.html,v 1.1 2006/04/21 18:03:06 jjanke Exp $
Copyright 1999-2002 Jorg Janke, Inc.
40 Old Tannery Rd, Monroe, CT 06468, U.S.A.
All Rights Reserved.
-->
</head>
<body>
Provides for....
<h2>Package Specification</h2>
<ul>
<li><a href="http://www.adempiere.org">http://www.adempiere.org</a>
</ul>
<h2>Related Documentation</h2>
For overviews, tutorials, examples, guides, and tool documentation, please see:
<ul>
<li><a href="http://www.adempiere.org">http://www.adempiere.org</a>
</ul>
<!-- Put @see and @since tags down here. -->
</body>
</html>