# BrowseJasperDataSource.java

    /*
    ** Module   : BrowseJasperDataSource.java
    ** Abstract : Data source for a FWD Jasper report backed by a browse.
    **
    ** Copyright (c) 2018-2022, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------Description----------------------------------
    ** 001 SVL 20180207 Created initial version.
    ** 002 SVL 20181004 Support for arbitrary fonts and colors.
    ** 003 SVL 20181006 Implemented arbitrary colors and fonts for column labels.
    ** 004 IAS 20171019 Use getters to access ColorTable.EnvironmentColorTable fields.
    ** 005 AL2 20211011 Use row display triggers when getting browse rows.
    **     SVL 20220620 Changed readDefaultFonts() signature.
    **     SVL 20220720 Enhanced color can be defined by an index in the color table.
    */
    /*
    ** This program is free software: you can redistribute it and/or modify
    ** it under the terms of the GNU Affero General Public License as
    ** published by the Free Software Foundation, either version 3 of the
    ** License, or (at your option) any later version.
    **
    ** This program is distributed in the hope that it will be useful,
    ** but WITHOUT ANY WARRANTY; without even the implied warranty of
    ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    ** GNU Affero General Public License for more details.
    **
    ** You may find a copy of the GNU Affero GPL version 3 at the following
    ** location: https://www.gnu.org/licenses/agpl-3.0.en.html
    **
    ** Additional terms under GNU Affero GPL version 3 section 7:
    **
    **   Under Section 7 of the GNU Affero GPL version 3, the following additional
    **   terms apply to the works covered under the License.  These additional terms
    **   are non-permissive additional terms allowed under Section 7 of the GNU
    **   Affero GPL version 3 and may not be removed by you.
    **
    **   0. Attribution Requirement.
    **
    **     You must preserve all legal notices or author attributions in the covered
    **     work or Appropriate Legal Notices displayed by works containing the covered
    **     work.  You may not remove from the covered work any author or developer
    **     credit already included within the covered work.
    **
    **   1. No License To Use Trademarks.
    **
    **     This license does not grant any license or rights to use the trademarks
    **     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
    **     of Golden Code Development Corporation. You are not authorized to use the
    **     name Golden Code, FWD, or the names of any author or contributor, for
    **     publicity purposes without written authorization.
    **
    **   2. No Misrepresentation of Affiliation.
    **
    **     You may not represent yourself as Golden Code Development Corporation or FWD.
    **
    **     You may not represent yourself for publicity purposes as associated with
    **     Golden Code Development Corporation, FWD, or any author or contributor to
    **     the covered work, without written authorization.
    **
    **   3. No Misrepresentation of Source or Origin.
    **
    **     You may not represent the covered work as solely your work.  All modified
    **     versions of the covered work must be marked in a reasonable way to make it
    **     clear that the modified work is not originating from Golden Code Development
    **     Corporation or FWD.  All modified versions must contain the notices of
    **     attribution required in this license.
    */

    package com.goldencode.p2j.reporting;

    import com.goldencode.p2j.persist.*;
    import com.goldencode.p2j.ui.*;
    import com.goldencode.p2j.ui.client.*;
    import com.goldencode.p2j.util.*;
    import net.sf.jasperreports.engine.*;

    import java.awt.*;
    import java.util.*;

    import static com.goldencode.p2j.reporting.ReportFactory.showError;

    /**
     * Data source for a FWD Jasper report backed by a browse. Rows are passed to the report in the
     * same way they look in browse (with the same formatting, after ROW-DISPLAY trigger has been
     * applied (if any)).
     */
    class BrowseJasperDataSource
    implements JasperDataSource
    {
       /** Font families available for JVM. */
       private static final Set<String> availableJavaFontFamilies;

       /** Browse which provides data for the report. */
       private final BrowseWidget browse;

       /**
        * Map of the names of jasper report fields representing cell data (like "column33") to browse
        * column ordinals (0-based).
        */
       private Map<String, Integer> fieldMapping;

       /**
        * Map of the names of jasper report fields representing cell attributes (like
        * "column33.fontName") to default values of these attributes for specific column.
        */
       private Map<String, String> attributeMapping;

       /** Browse rows which represent the report data. */
       private BrowseRow[] browseRows;

       /** Index of the current browse row in {@link #browseRows} while iterating the data set. */
       private int browseRowIndex;

       static
       {
          String[] fontNames =
                GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
          availableJavaFontFamilies = new HashSet<>(Arrays.asList(fontNames));
       }

       /**
        * Constructs a data source object for the given browse.
        *
        * @param browse
        *        Underlying browse.
        */
       BrowseJasperDataSource(BrowseWidget browse)
       {
          this.browse = browse;
       }

       /**
        * Get compiled Jasper report for the given report template design file.
        *
        * @param  designTemplateFileName
        *         File name of the Jasper report design template file.
        *
        * @return compiled Jasper report for the given report design template file.
        */
       @Override
       public JasperReport getReport(String designTemplateFileName)
       {
          return ReportFactory.getBrowseReport(browse, designTemplateFileName);
       }

       /**
        * Executed before report is filled from the data source.
        *
        * @param  report
        *         Jasper report to be filled.
        *
        * @return <code>true</code> on success, <code>false</code> if the data source cannot provide
        *         data.
        */
       @Override
       public boolean reportStarted(JasperReport report)
       {
          P2JQuery query = browse.getQuery();

          if (query == null)
          {
             showError("A query is not assigned to the browse.");
             return false;
          }

          if (!query.isOpen().booleanValue())
          {
             showError("Browse query should be open before the report is run.");
             return false;
          }

          if (!buildFieldMapping(report))
          {
             return false;
          }

          TriggerMatch match = LogicalTerminal.findTrigger(Keyboard.eventCode(Keyboard.ROW_DISPLAY), browse.getId());
          browseRows = browse.getRows(0, -1, true, match.triggerId, null, null);
          browseRowIndex = -1;
          return true;
       }

       /**
        * Executed after report was filled from the data source.
        *
        * @param  error
        *         <code>true</code> if there were problems while getting data from the data source.
        *         <code>false</code> on success,
        */
       @Override
       public void reportFinished(boolean error)
       {
          browseRows = null;
       }

       /**
        * Get underlying 4GL browse object which provides data for the report.
        *
        * @return handle to the underlying 4GL browse object which provides data for the report.
        */
       @Override
       public handle asProgressObject()
       {
          return new handle(browse);
       }

       /**
        * Tries to position the cursor on the next element in the data source.
        *
        * @return <code>true</code> if there is a next record, <code>false</code> otherwise.
        *
        * @throws JRException
        *         if any error occurs while trying to move to the next element.
        */
       @Override
       public boolean next()
       throws JRException
       {
          return browseRows != null && ++browseRowIndex < browseRows.length;
       }

       /**
        * Gets the field value for the current position.
        *
        * @param  field
        *         Field to get.
        *
        * @return an object containing the field value. The object type must be the field object type.
        *
        * @throws JRException
        *         if any error occurs while trying to get the field value.
        */
       @Override
       public Object getFieldValue(JRField field)
       throws JRException
       {
          if (browseRows == null || browseRowIndex < 0 || browseRowIndex >= browseRows.length)
          {
             throw new JRException("Cannot access browse row at index " + browseRowIndex);
          }

          String fieldName = field.getName();
          if (fieldName.contains("."))
          {
             if (fieldName.endsWith(".fgcolor"))
             {
                // check cell-specific color values set in a ROW-DISPLAY trigger
                int columnOrdinal = fieldMapping.get(fieldName.replace(".fgcolor", ""));
                Integer cellColor =
                      ((GuiCellAttributes) browseRows[browseRowIndex].attr[columnOrdinal]).fgColor;
                if (cellColor != null)
                {
                   return getJasperColor(getTableColor(browse, cellColor));
                }
             }
             return attributeMapping.get(fieldName); // OK to return null
          }

          int columnOrdinal = fieldMapping.get(fieldName);
          return browseRows[browseRowIndex].text[columnOrdinal];
       }

       /**
        * Checks is the given font available for the JVM.
        *
        * @param  font
        *         Font to check.
        *
        * @return <code>true</code> if the given font available for the JVM.
        */
       static boolean isFontFamilyAvailable(FontDetails font)
       {
          return availableJavaFontFamilies.contains(font.fontName);
       }

       /**
        * Get color of the browse element following general color application rules.
        *
        * @param  browse
        *         Parent browse.
        * @param  ehColumnColor
        *         Enhanced column-specific color.
        * @param  columnColor
        *         Column-specific color.
        * @param  ehBrowseColor
        *         Enhanced browse-specific color.
        * @param  browseColor
        *         Browse-specific color.
        *
        * @return color of the browse element in Jasper report format.
        */
       static String getElementColor(BrowseWidget browse,
                                     EnhancedColor ehColumnColor,
                                     int columnColor,
                                     EnhancedColor ehBrowseColor,
                                     int browseColor)
       {

          ColorRgb color = resolveEnhancedColor(browse, ehColumnColor);
          if (color == null)
          {
             if (columnColor != -1)
             {
                color = getTableColor(browse, columnColor);
             }
             else
             {
                color = resolveEnhancedColor(browse, ehBrowseColor);

                if (color == null && browseColor != -1)
                {
                   color = getTableColor(browse, browseColor);
                }
             }
          }

          return color != null ? getJasperColor(color) : null;
       }

       /**
        * Get effective column font.
        *
        * @param  column
        *         Browse column.
        * @param  label
        *         <code>true</code> for label font, <code>false</code> for cells font.
        *
        * @return effective label or cells font of the specified column.
        */
       static FontDetails getColumnFont(BrowseColumnWidget column, boolean label)
       {
          BrowseWidget browse = column.getBrowse();
          FontDetails font = null;

          if (label)
          {
             font = getElementFont(column.config().ehLabelFont,
                   column.config().labelFont,
                   browse.config().ehLabelFont,
                   browse.config().labelFont);
          }

          if (font == null)
          {
             font = getElementFont(column.config().ehFont,
                   column.config().font,
                   browse.config().ehFont,
                   browse.config().font);
          }

          if (font == null)
          {
             font = LogicalTerminal.readDefaultFonts(false)[0];
          }

          if (font.fontAlias != null)
          {
             font = font.fontAlias;
          }

          return font;
       }

       /**
        * Get string representation of the color in Jasper report format.
        *
        * @param  color
        *         Color.
        *
        * @return string representation of the color in Jasper report format.
        */
       private static String getJasperColor(ColorRgb color)
       {
          return color != null ?
                String.format("#%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue()) :
                null;
       }

       /**
        * Return RGB color defined by the enhanced color.
        *
        * @param  browse
        *         Parent browse of the element which color is resolved.
        * @param  enhancedColor
        *         Enhanced color. Can be <code>null</code>.
        *
        * @return RGB color defined by the enhanced color.
        */
       private static ColorRgb resolveEnhancedColor(BrowseWidget browse, EnhancedColor enhancedColor)
       {
          if (enhancedColor == null)
          {
             return null;
          }

          if (enhancedColor.colorRgb != null)
          {
             return enhancedColor.colorRgb;
          }

          return getTableColor(browse, enhancedColor.colorIndex);
       }

       /**
        * Get color at the specified index in the system color table.
        *
        * @param  browse
        *         Parent browse of the element which color is resolved.
        * @param  colorIndex
        *         Index of the color.
        *
        * @return color at the specified index in the system color table.
        */
       private static ColorRgb getTableColor(BrowseWidget browse, int colorIndex)
       {
          WindowWidget window = (WindowWidget) browse.getWindow().unwrapWindow();
          ColorTable.EnvironmentColorTable colorTable =
                LogicalTerminal.readColorTable(window.config().envName);

          return colorIndex < colorTable.getColors().size() ?
                 colorTable.getColors().get(colorIndex) :
                 null;
       }

       /**
        * Get font of the browse element following general font application rules.
        *
        * @param  ehColumnFont
        *         Enhanced column-specific font.
        * @param  columnFont
        *         Column-specific font.
        * @param  ehBrowseFont
        *         Enhanced browse-specific font.
        * @param  browseFont
        *         Browse-specific font.
        *
        * @return font of the browse element.
        */
       private static FontDetails getElementFont(FontDetails ehColumnFont,
                                                 int columnFont,
                                                 FontDetails ehBrowseFont,
                                                 int browseFont)
       {
          FontDetails[] fontTable = LogicalTerminal.readFontTable();
          FontDetails font = null;

          if (ehColumnFont != null)
          {
             font = ehColumnFont;
          }
          else if (columnFont >= 0)
          {
             if (columnFont < fontTable.length)
             {
                font = fontTable[columnFont];
             }
          }
          else if (ehBrowseFont != null)
          {
             font = ehBrowseFont;
          }
          else if (browseFont >= 0)
          {
             if (browseFont < fontTable.length)
             {
                font = fontTable[browseFont];
             }
          }

          return font;
       }

       /**
        * Build and store field mapping (Jasper report field names to 1-based browse column index) for
        * the given report.
        *
        * @param  report
        *         Jasper report for which we need to build a field mapping.
        *
        * @return <code>true</code> on success.
        */
       private boolean buildFieldMapping(JasperReport report)
       {
          fieldMapping = new HashMap<>();
          attributeMapping = new HashMap<>();
          for (JRField jrField : report.getFields())
          {
             String name = jrField.getName();

             if (name.contains("."))
             {
               if (!putAttributeValue(name))
               {
                  return false;
               }
             }

             int ordinal = getColumnOrdinal(name);
             if (ordinal == -1)
             {
                return false;
             }

             fieldMapping.put(name, ordinal);
          }

          return true;
       }

       /**
        * Get 0-based ordinal of the browse column referenced by the given field.
        *
        * @param  fieldName
        *         Name of the field.
        *
        * @return 0-based ordinal of the browse column referenced by the given field.
        */
       private int getColumnOrdinal(String fieldName)
       {
          int index = fieldName.indexOf(".");
          if (index >= 0)
          {
             fieldName = fieldName.substring(0, index);
          }

          fieldName = fieldName.replace("column", "");
          int res;
          try
          {
             res = Integer.valueOf(fieldName);
          }
          catch (NumberFormatException e)
          {
             showError("Invalid column name inside the browse report: " + fieldName, e);
             return -1;
          }

          return res;
       }

       /**
        * Put the default column-specific value of the corresponding attribute into
        * {@link #attributeMapping} map.
        *
        * @param  fieldName
        *         Name of the report field representing the specific attribute of the specific column
        *         (like "column33.fontName").
        *
        * @return <code>true</code> of success. <code>false</code> if the field name is invalid.
        */
       private boolean putAttributeValue(String fieldName)
       {
          int ordinal = getColumnOrdinal(fieldName);
          if (ordinal == -1)
          {
             return false;
          }

          BrowseColumnWidget column =
                (BrowseColumnWidget) browse.getBrowseColumn(ordinal + 1).unwrapBrowseColumn();

          if (fieldName.endsWith(".forecolor"))
          {
             String color = getElementColor(browse,
                                            column.config().ehFgColor,
                                            column.config().columnFgColor,
                                            browse.config().ehFgColor,
                                            browse.config().fgcolor);
             if (color != null)
             {
                attributeMapping.put(fieldName, color);
             }
          }
          else if (fieldName.endsWith(".fontName"))
          {
             FontDetails font = getColumnFont(column, false);
             // don't let Jasper throw "font not available" exception
             if (isFontFamilyAvailable(font))
             {
                attributeMapping.put(fieldName, font.fontName);
             }
          }
          else if (fieldName.endsWith(".fontSize"))
          {
             FontDetails font = getColumnFont(column, false);
             attributeMapping.put(fieldName, String.valueOf(font.pointSize));
          }
          else if (fieldName.endsWith(".isBold"))
          {
             FontDetails font = getColumnFont(column, false);
             attributeMapping.put(fieldName, Boolean.toString(font.style.isBold()));
          }
          else if (fieldName.endsWith(".isItalic"))
          {
             FontDetails font = getColumnFont(column, false);
             attributeMapping.put(fieldName, Boolean.toString(font.style.isItalic()));
          }
          else if (fieldName.endsWith(".isUnderline"))
          {
             FontDetails font = getColumnFont(column, false);
             attributeMapping.put(fieldName, Boolean.toString(font.style.isUnderline()));
          }
          else
          {
             showError("Invalid attribute field inside the browse report: " + fieldName);
          }

          return true;
       }
    }