<commit_before>#ifdef __APPLE__

#include <iostream>
int main(int argc, char* argv[])
{
    std::clog << "OS X is not currently supported by topcube\n";
    return 0;
}

#else

#include <gtk/gtk.h>
#include <webkit/webkit.h>
#include <webkit/webkitwebview.h>

GtkWidget *window;
GtkWidget *scrolled_window;
GtkWidget *web_view;
WebKitWebSettings *settings;

void destroy (void)
{
  gtk_main_quit ();
}

void title_change (void)
{
  gtk_window_set_title(GTK_WINDOW (window), webkit_web_view_get_title(WEBKIT_WEB_VIEW (web_view)));
}

void new_window (
  WebKitWebView *web_view,
  WebKitWebFrame *frame,
  WebKitNetworkRequest *request)
{
  gchar *argv[3];
  argv[0] = const_cast<char*>("/usr/bin/xdg-open");
  argv[1] = const_cast<char*>(webkit_network_request_get_uri(request));
  argv[2] = NULL;
  g_spawn_async(NULL, argv, NULL, G_SPAWN_LEAVE_DESCRIPTORS_OPEN, NULL, NULL, NULL, NULL);
}

static gboolean download (
  WebKitWebView *web_view,
  WebKitWebFrame *frame,
  WebKitNetworkRequest *request,
  const char *mime_type,
  WebKitWebPolicyDecision *decision,
  gpointer user_data)
{
  // Any other mime types we should handle?
  if (strcmp(mime_type, "text/html") != 0) {
    WebKitDownload *download = webkit_download_new(request);
    GtkWidget *window = gtk_widget_get_toplevel (GTK_WIDGET(web_view));
    GtkWidget *dialog = gtk_file_chooser_dialog_new ("Save file",
      GTK_WINDOW(window),
      GTK_FILE_CHOOSER_ACTION_SAVE,
      GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
      GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
      NULL);
    gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog), TRUE);
    gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (dialog), webkit_download_get_suggested_filename(download));

    // @TODO getting a warning 'Unable to retrieve the file info' for the
    // file as it does not exist yet... track down why?
    if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT) {
      gchar *destination = g_filename_to_uri(gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog)), NULL, NULL);
      webkit_download_set_destination_uri (download, destination);
      webkit_download_start(download);
      g_free(destination);
    } else {
      webkit_download_cancel(download);
      g_object_unref(download);
    }

    gtk_widget_destroy (dialog);
    webkit_web_policy_decision_ignore(decision);
  }
  return TRUE;
}

int main(int argc, char* argv[])
{
  static gchar *url = const_cast<char*>("http://google.com");
  static gchar *name = const_cast<char*>("TopCube");
  static gint width = 800;
  static gint height = 600;
  static gint minwidth = 600;
  static gint minheight = 400;
  static GOptionEntry entries[] = {
    { "url", 'u', 0, G_OPTION_ARG_STRING, &url, "URL" },
    { "name", 'n', 0, G_OPTION_ARG_STRING, &name, "Window name" },
    { "width", 'W', 0, G_OPTION_ARG_INT, &width, "Width" },
    { "height", 'H', 0, G_OPTION_ARG_INT, &height, "Height" },
    { "minwidth", 'w', 0, G_OPTION_ARG_INT, &minwidth, "Minimum width" },
    { "minheight", 'h', 0, G_OPTION_ARG_INT, &minheight, "Minimum height" }
  };
  GError *error = NULL;
  GOptionContext *options;
  options = g_option_context_new("topcube options");
  g_option_context_add_main_entries (options, entries, NULL);
  g_option_context_add_group (options, gtk_get_option_group(TRUE));
  if (!g_option_context_parse (options, &argc, &argv, &error)) {
    g_print ("Error parsing options: %s\n", error->message);
    exit (1);
  }

  gtk_init (&argc, &argv);
  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  scrolled_window = gtk_scrolled_window_new (NULL, NULL);
  web_view = webkit_web_view_new ();

  // Modify default settings - disable right click menus.
  settings = webkit_web_view_get_settings (WEBKIT_WEB_VIEW(web_view));
  g_object_set(settings, "enable-default-context-menu", FALSE, NULL);

  gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (destroy), NULL);
  gtk_signal_connect (GTK_OBJECT (web_view), "title-changed", GTK_SIGNAL_FUNC (title_change), NULL);
  gtk_signal_connect (GTK_OBJECT (web_view), "mime-type-policy-decision-requested", GTK_SIGNAL_FUNC (download), NULL);
  gtk_signal_connect (GTK_OBJECT (web_view), "new-window-policy-decision-requested", GTK_SIGNAL_FUNC (new_window), NULL);

  gtk_container_add (GTK_CONTAINER (scrolled_window), web_view);
  gtk_container_add (GTK_CONTAINER (window), scrolled_window);

  webkit_web_view_load_uri (WEBKIT_WEB_VIEW (web_view), url);

  gtk_window_set_wmclass (GTK_WINDOW (window), name, name);
  gtk_window_set_default_size (GTK_WINDOW (window), width, height);

  GdkGeometry hints;
  hints.min_width = minwidth;
  hints.min_height = minheight;
  gtk_window_set_geometry_hints(GTK_WINDOW (window), GTK_WIDGET (scrolled_window), &hints, GDK_HINT_MIN_SIZE);

  gtk_widget_grab_focus (GTK_WIDGET(web_view));
  gtk_widget_show_all (window);
  gtk_main ();

  return 0;
}

#endif // linux
<commit_msg>Add back necessary headers<commit_after>#ifdef __APPLE__

#include <iostream>
int main(int argc, char* argv[])
{
    std::clog << "OS X is not currently supported by topcube\n";
    return 0;
}

#else

#include <string.h> // for strcmp
#include <cstdlib> // for exit
#include <gtk/gtk.h>
#include <webkit/webkit.h>
#include <webkit/webkitwebview.h>

GtkWidget *window;
GtkWidget *scrolled_window;
GtkWidget *web_view;
WebKitWebSettings *settings;

void destroy (void)
{
  gtk_main_quit ();
}

void title_change (void)
{
  gtk_window_set_title(GTK_WINDOW (window), webkit_web_view_get_title(WEBKIT_WEB_VIEW (web_view)));
}

void new_window (
  WebKitWebView *web_view,
  WebKitWebFrame *frame,
  WebKitNetworkRequest *request)
{
  gchar *argv[3];
  argv[0] = const_cast<char*>("/usr/bin/xdg-open");
  argv[1] = const_cast<char*>(webkit_network_request_get_uri(request));
  argv[2] = NULL;
  g_spawn_async(NULL, argv, NULL, G_SPAWN_LEAVE_DESCRIPTORS_OPEN, NULL, NULL, NULL, NULL);
}

static gboolean download (
  WebKitWebView *web_view,
  WebKitWebFrame *frame,
  WebKitNetworkRequest *request,
  const char *mime_type,
  WebKitWebPolicyDecision *decision,
  gpointer user_data)
{
  // Any other mime types we should handle?
  if (strcmp(mime_type, "text/html") != 0) {
    WebKitDownload *download = webkit_download_new(request);
    GtkWidget *window = gtk_widget_get_toplevel (GTK_WIDGET(web_view));
    GtkWidget *dialog = gtk_file_chooser_dialog_new ("Save file",
      GTK_WINDOW(window),
      GTK_FILE_CHOOSER_ACTION_SAVE,
      GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
      GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
      NULL);
    gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog), TRUE);
    gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (dialog), webkit_download_get_suggested_filename(download));

    // @TODO getting a warning 'Unable to retrieve the file info' for the
    // file as it does not exist yet... track down why?
    if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT) {
      gchar *destination = g_filename_to_uri(gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog)), NULL, NULL);
      webkit_download_set_destination_uri (download, destination);
      webkit_download_start(download);
      g_free(destination);
    } else {
      webkit_download_cancel(download);
      g_object_unref(download);
    }

    gtk_widget_destroy (dialog);
    webkit_web_policy_decision_ignore(decision);
  }
  return TRUE;
}

int main(int argc, char* argv[])
{
  static gchar *url = const_cast<char*>("http://google.com");
  static gchar *name = const_cast<char*>("TopCube");
  static gint width = 800;
  static gint height = 600;
  static gint minwidth = 600;
  static gint minheight = 400;
  static GOptionEntry entries[] = {
    { "url", 'u', 0, G_OPTION_ARG_STRING, &url, "URL" },
    { "name", 'n', 0, G_OPTION_ARG_STRING, &name, "Window name" },
    { "width", 'W', 0, G_OPTION_ARG_INT, &width, "Width" },
    { "height", 'H', 0, G_OPTION_ARG_INT, &height, "Height" },
    { "minwidth", 'w', 0, G_OPTION_ARG_INT, &minwidth, "Minimum width" },
    { "minheight", 'h', 0, G_OPTION_ARG_INT, &minheight, "Minimum height" }
  };
  GError *error = NULL;
  GOptionContext *options;
  options = g_option_context_new("topcube options");
  g_option_context_add_main_entries (options, entries, NULL);
  g_option_context_add_group (options, gtk_get_option_group(TRUE));
  if (!g_option_context_parse (options, &argc, &argv, &error)) {
    g_print ("Error parsing options: %s\n", error->message);
    exit (1);
  }

  gtk_init (&argc, &argv);
  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  scrolled_window = gtk_scrolled_window_new (NULL, NULL);
  web_view = webkit_web_view_new ();

  // Modify default settings - disable right click menus.
  settings = webkit_web_view_get_settings (WEBKIT_WEB_VIEW(web_view));
  g_object_set(settings, "enable-default-context-menu", FALSE, NULL);

  gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (destroy), NULL);
  gtk_signal_connect (GTK_OBJECT (web_view), "title-changed", GTK_SIGNAL_FUNC (title_change), NULL);
  gtk_signal_connect (GTK_OBJECT (web_view), "mime-type-policy-decision-requested", GTK_SIGNAL_FUNC (download), NULL);
  gtk_signal_connect (GTK_OBJECT (web_view), "new-window-policy-decision-requested", GTK_SIGNAL_FUNC (new_window), NULL);

  gtk_container_add (GTK_CONTAINER (scrolled_window), web_view);
  gtk_container_add (GTK_CONTAINER (window), scrolled_window);

  webkit_web_view_load_uri (WEBKIT_WEB_VIEW (web_view), url);

  gtk_window_set_wmclass (GTK_WINDOW (window), name, name);
  gtk_window_set_default_size (GTK_WINDOW (window), width, height);

  GdkGeometry hints;
  hints.min_width = minwidth;
  hints.min_height = minheight;
  gtk_window_set_geometry_hints(GTK_WINDOW (window), GTK_WIDGET (scrolled_window), &hints, GDK_HINT_MIN_SIZE);

  gtk_widget_grab_focus (GTK_WIDGET(web_view));
  gtk_widget_show_all (window);
  gtk_main ();

  return 0;
}

#endif // linux
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: bmpconv.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-27 17:57:56 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <bitmap.hxx>
#include <impbmpconv.hxx>
#include <svapp.hxx>
#include <vos/mutex.hxx>

#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _COM_SUN_STAR_SCRIPT_XINVOCATION_HPP_
#include <com/sun/star/script/XInvocation.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XBITMAP_HPP_
#include <com/sun/star/awt/XBitmap.hpp>
#endif

#ifndef _CPPUHELPER_COMPBASE1_HXX_
#include <cppuhelper/compbase1.hxx>
#endif

using namespace com::sun::star::uno;
using namespace com::sun::star::script;
using namespace com::sun::star::beans;
using namespace com::sun::star::reflection;
using namespace com::sun::star::awt;
using namespace rtl;

namespace vcl {

class BmpTransporter :
        public cppu::WeakImplHelper1< com::sun::star::awt::XBitmap >
{
    Sequence<sal_Int8>          m_aBM;
    com::sun::star::awt::Size   m_aSize;
public:
    BmpTransporter( const Bitmap& rBM );
    virtual  ~BmpTransporter();

    virtual com::sun::star::awt::Size SAL_CALL getSize() throw();
    virtual Sequence< sal_Int8 > SAL_CALL getDIB() throw();
    virtual Sequence< sal_Int8 > SAL_CALL getMaskDIB() throw();
};

class BmpConverter :
        public cppu::WeakImplHelper1< com::sun::star::script::XInvocation >
{
public:
    BmpConverter();
    virtual ~BmpConverter();

    virtual Reference< XIntrospectionAccess > SAL_CALL getIntrospection() throw();
    virtual void SAL_CALL setValue( const OUString& rProperty, const Any& rValue )
        throw( UnknownPropertyException );
    virtual Any SAL_CALL getValue( const OUString& rProperty )
        throw( UnknownPropertyException );
    virtual sal_Bool SAL_CALL hasMethod( const OUString& rName ) throw();
    virtual sal_Bool SAL_CALL hasProperty( const OUString& rProp ) throw();

    virtual Any SAL_CALL invoke( const OUString& rFunction,
                                 const Sequence< Any >& rParams,
                                 Sequence< sal_Int16 >& rOutParamIndex,
                                 Sequence< Any >& rOutParam
                                 )
        throw( CannotConvertException, InvocationTargetException );
};

}

using namespace vcl;

Reference< XInvocation > vcl::createBmpConverter()
{
    return static_cast<XInvocation*>(new BmpConverter());
}

BmpConverter::BmpConverter()
{
}

BmpConverter::~BmpConverter()
{
}

Reference< XIntrospectionAccess > SAL_CALL BmpConverter::getIntrospection() throw()
{
    return Reference< XIntrospectionAccess >();
}

void SAL_CALL BmpConverter::setValue( const OUString& rProperty, const Any& rValue ) throw( UnknownPropertyException )
{
    throw UnknownPropertyException();
}

Any SAL_CALL BmpConverter::getValue( const OUString& rProperty ) throw( UnknownPropertyException )
{
    throw UnknownPropertyException();
}

sal_Bool SAL_CALL BmpConverter::hasMethod( const OUString& rName ) throw()
{
    return rName.equalsIgnoreAsciiCase( OUString::createFromAscii( "convert-bitmap-depth" ) );
}

sal_Bool SAL_CALL BmpConverter::hasProperty( const OUString& rName ) throw()
{
    return sal_False;
}

Any SAL_CALL BmpConverter::invoke(
                                  const OUString& rFunction,
                                  const Sequence< Any >& rParams,
                                  Sequence< sal_Int16 >& rOutParamIndex,
                                  Sequence< Any >& rOutParam )
    throw( CannotConvertException, InvocationTargetException )
{
    Any aRet;

    if( rFunction.equalsIgnoreAsciiCase( OUString::createFromAscii( "convert-bitmap-depth" ) ) )
    {
        Reference< XBitmap > xBM;
        sal_uInt16 nTargetDepth = 0;
        if( rParams.getLength() != 2 )
            throw CannotConvertException();

        if( ! (rParams.getConstArray()[0] >>= xBM ) ||
            ! ( rParams.getConstArray()[1] >>= nTargetDepth ) )
            throw CannotConvertException();

        Sequence< sal_Int8 > aDIB = xBM->getDIB();

        // call into vcl not thread safe
        vos::OGuard aGuard( Application::GetSolarMutex() );

        SvMemoryStream aStream( aDIB.getArray(), aDIB.getLength(), STREAM_READ | STREAM_WRITE );
        Bitmap aBM;
        aBM.Read( aStream, TRUE );
        if( nTargetDepth < 4 )
            nTargetDepth = 1;
        else if( nTargetDepth < 8 )
            nTargetDepth = 4;
        else if( nTargetDepth >8 && nTargetDepth < 24 )
            nTargetDepth = 24;

        if( aBM.GetBitCount() == 24 && nTargetDepth <= 8 )
            aBM.Dither( BMP_DITHER_FLOYD );

        if( aBM.GetBitCount() != nTargetDepth )
        {
            switch( nTargetDepth )
            {
                case 1:     aBM.Convert( BMP_CONVERSION_1BIT_THRESHOLD );break;
                case 4:     aBM.ReduceColors( BMP_CONVERSION_4BIT_COLORS );break;
                case 8:     aBM.ReduceColors( BMP_CONVERSION_8BIT_COLORS );break;
                case 24:    aBM.Convert( BMP_CONVERSION_24BIT );break;
            }
        }
        xBM = new BmpTransporter( aBM );
        aRet <<= xBM;
    }
    else
        throw InvocationTargetException();

    return aRet;
}

BmpTransporter::BmpTransporter( const Bitmap& rBM )
{
    m_aSize.Width = rBM.GetSizePixel().Width();
    m_aSize.Height = rBM.GetSizePixel().Height();
    SvMemoryStream aStream;
    rBM.Write( aStream, FALSE, TRUE );
    m_aBM = Sequence<sal_Int8>((const sal_Int8*)aStream.GetData(), aStream.GetSize() );
}

BmpTransporter::~BmpTransporter()
{
}

com::sun::star::awt::Size SAL_CALL BmpTransporter::getSize() throw()
{
    return m_aSize;
}

Sequence< sal_Int8 > SAL_CALL BmpTransporter::getDIB() throw()
{
    return m_aBM;
}

Sequence< sal_Int8 > SAL_CALL BmpTransporter::getMaskDIB() throw()
{
    return Sequence< sal_Int8 >();
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.836); FILE MERGED 2005/09/05 14:44:47 rt 1.2.836.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: bmpconv.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 11:55:10 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <bitmap.hxx>
#include <impbmpconv.hxx>
#include <svapp.hxx>
#include <vos/mutex.hxx>

#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _COM_SUN_STAR_SCRIPT_XINVOCATION_HPP_
#include <com/sun/star/script/XInvocation.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XBITMAP_HPP_
#include <com/sun/star/awt/XBitmap.hpp>
#endif

#ifndef _CPPUHELPER_COMPBASE1_HXX_
#include <cppuhelper/compbase1.hxx>
#endif

using namespace com::sun::star::uno;
using namespace com::sun::star::script;
using namespace com::sun::star::beans;
using namespace com::sun::star::reflection;
using namespace com::sun::star::awt;
using namespace rtl;

namespace vcl {

class BmpTransporter :
        public cppu::WeakImplHelper1< com::sun::star::awt::XBitmap >
{
    Sequence<sal_Int8>          m_aBM;
    com::sun::star::awt::Size   m_aSize;
public:
    BmpTransporter( const Bitmap& rBM );
    virtual  ~BmpTransporter();

    virtual com::sun::star::awt::Size SAL_CALL getSize() throw();
    virtual Sequence< sal_Int8 > SAL_CALL getDIB() throw();
    virtual Sequence< sal_Int8 > SAL_CALL getMaskDIB() throw();
};

class BmpConverter :
        public cppu::WeakImplHelper1< com::sun::star::script::XInvocation >
{
public:
    BmpConverter();
    virtual ~BmpConverter();

    virtual Reference< XIntrospectionAccess > SAL_CALL getIntrospection() throw();
    virtual void SAL_CALL setValue( const OUString& rProperty, const Any& rValue )
        throw( UnknownPropertyException );
    virtual Any SAL_CALL getValue( const OUString& rProperty )
        throw( UnknownPropertyException );
    virtual sal_Bool SAL_CALL hasMethod( const OUString& rName ) throw();
    virtual sal_Bool SAL_CALL hasProperty( const OUString& rProp ) throw();

    virtual Any SAL_CALL invoke( const OUString& rFunction,
                                 const Sequence< Any >& rParams,
                                 Sequence< sal_Int16 >& rOutParamIndex,
                                 Sequence< Any >& rOutParam
                                 )
        throw( CannotConvertException, InvocationTargetException );
};

}

using namespace vcl;

Reference< XInvocation > vcl::createBmpConverter()
{
    return static_cast<XInvocation*>(new BmpConverter());
}

BmpConverter::BmpConverter()
{
}

BmpConverter::~BmpConverter()
{
}

Reference< XIntrospectionAccess > SAL_CALL BmpConverter::getIntrospection() throw()
{
    return Reference< XIntrospectionAccess >();
}

void SAL_CALL BmpConverter::setValue( const OUString& rProperty, const Any& rValue ) throw( UnknownPropertyException )
{
    throw UnknownPropertyException();
}

Any SAL_CALL BmpConverter::getValue( const OUString& rProperty ) throw( UnknownPropertyException )
{
    throw UnknownPropertyException();
}

sal_Bool SAL_CALL BmpConverter::hasMethod( const OUString& rName ) throw()
{
    return rName.equalsIgnoreAsciiCase( OUString::createFromAscii( "convert-bitmap-depth" ) );
}

sal_Bool SAL_CALL BmpConverter::hasProperty( const OUString& rName ) throw()
{
    return sal_False;
}

Any SAL_CALL BmpConverter::invoke(
                                  const OUString& rFunction,
                                  const Sequence< Any >& rParams,
                                  Sequence< sal_Int16 >& rOutParamIndex,
                                  Sequence< Any >& rOutParam )
    throw( CannotConvertException, InvocationTargetException )
{
    Any aRet;

    if( rFunction.equalsIgnoreAsciiCase( OUString::createFromAscii( "convert-bitmap-depth" ) ) )
    {
        Reference< XBitmap > xBM;
        sal_uInt16 nTargetDepth = 0;
        if( rParams.getLength() != 2 )
            throw CannotConvertException();

        if( ! (rParams.getConstArray()[0] >>= xBM ) ||
            ! ( rParams.getConstArray()[1] >>= nTargetDepth ) )
            throw CannotConvertException();

        Sequence< sal_Int8 > aDIB = xBM->getDIB();

        // call into vcl not thread safe
        vos::OGuard aGuard( Application::GetSolarMutex() );

        SvMemoryStream aStream( aDIB.getArray(), aDIB.getLength(), STREAM_READ | STREAM_WRITE );
        Bitmap aBM;
        aBM.Read( aStream, TRUE );
        if( nTargetDepth < 4 )
            nTargetDepth = 1;
        else if( nTargetDepth < 8 )
            nTargetDepth = 4;
        else if( nTargetDepth >8 && nTargetDepth < 24 )
            nTargetDepth = 24;

        if( aBM.GetBitCount() == 24 && nTargetDepth <= 8 )
            aBM.Dither( BMP_DITHER_FLOYD );

        if( aBM.GetBitCount() != nTargetDepth )
        {
            switch( nTargetDepth )
            {
                case 1:     aBM.Convert( BMP_CONVERSION_1BIT_THRESHOLD );break;
                case 4:     aBM.ReduceColors( BMP_CONVERSION_4BIT_COLORS );break;
                case 8:     aBM.ReduceColors( BMP_CONVERSION_8BIT_COLORS );break;
                case 24:    aBM.Convert( BMP_CONVERSION_24BIT );break;
            }
        }
        xBM = new BmpTransporter( aBM );
        aRet <<= xBM;
    }
    else
        throw InvocationTargetException();

    return aRet;
}

BmpTransporter::BmpTransporter( const Bitmap& rBM )
{
    m_aSize.Width = rBM.GetSizePixel().Width();
    m_aSize.Height = rBM.GetSizePixel().Height();
    SvMemoryStream aStream;
    rBM.Write( aStream, FALSE, TRUE );
    m_aBM = Sequence<sal_Int8>((const sal_Int8*)aStream.GetData(), aStream.GetSize() );
}

BmpTransporter::~BmpTransporter()
{
}

com::sun::star::awt::Size SAL_CALL BmpTransporter::getSize() throw()
{
    return m_aSize;
}

Sequence< sal_Int8 > SAL_CALL BmpTransporter::getDIB() throw()
{
    return m_aBM;
}

Sequence< sal_Int8 > SAL_CALL BmpTransporter::getMaskDIB() throw()
{
    return Sequence< sal_Int8 >();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: gfxlink.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: rt $ $Date: 2006-05-04 07:51:42 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <tools/vcompat.hxx>
#include <tools/urlobj.hxx>
#include <tools/debug.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/tempfile.hxx>
#include <ucbhelper/content.hxx>
#include "graph.hxx"
#include "gfxlink.hxx"
#include "cvtgrf.hxx"

#ifndef _COM_SUN_STAR_UCB_COMMANDABORTEDEXCEPTION_HPP_
#include <com/sun/star/ucb/CommandAbortedException.hpp>
#endif

// -----------
// - GfxLink -
// -----------

GfxLink::GfxLink() :
    meType      ( GFX_LINK_TYPE_NONE ),
    mpBuf       ( NULL ),
    mpSwap      ( NULL ),
    mnBufSize   ( 0 ),
    mnUserId    ( 0UL ),
    mpImpData   ( new ImpGfxLink )
{
}

// ------------------------------------------------------------------------

GfxLink::GfxLink( const GfxLink& rGfxLink ) :
    mpImpData( new ImpGfxLink )
{
    ImplCopy( rGfxLink );
}

// ------------------------------------------------------------------------

GfxLink::GfxLink( BYTE* pBuf, sal_uInt32 nSize, GfxLinkType nType, BOOL bOwns ) :
    mpImpData( new ImpGfxLink )
{
    DBG_ASSERT( (pBuf != NULL && nSize) || (!bOwns && nSize == 0),
                "GfxLink::GfxLink(): empty/NULL buffer given" );

    meType = nType;
    mnBufSize = nSize;
    mpSwap = NULL;
    mnUserId = 0UL;

    if( bOwns )
        mpBuf = new ImpBuffer( pBuf );
    else if( nSize )
    {
        mpBuf = new ImpBuffer( nSize );
        memcpy( mpBuf->mpBuffer, pBuf, nSize );
    }
    else
        mpBuf = NULL;
}

// ------------------------------------------------------------------------

GfxLink::~GfxLink()
{
    if( mpBuf && !( --mpBuf->mnRefCount ) )
        delete mpBuf;

    if( mpSwap && !( --mpSwap->mnRefCount ) )
        delete mpSwap;

    delete mpImpData;
}

// ------------------------------------------------------------------------

GfxLink& GfxLink::operator=( const GfxLink& rGfxLink )
{
    if( &rGfxLink != this )
    {
        if ( mpBuf && !( --mpBuf->mnRefCount ) )
            delete mpBuf;

        if( mpSwap && !( --mpSwap->mnRefCount ) )
            delete mpSwap;

        ImplCopy( rGfxLink );
    }

    return *this;
}

// ------------------------------------------------------------------------

sal_Bool GfxLink::IsEqual( const GfxLink& rGfxLink ) const
{
    sal_Bool bIsEqual = sal_False;

    if ( ( mnBufSize == rGfxLink.mnBufSize ) && ( meType == rGfxLink.meType ) )
    {
        const sal_uInt8* pSource = GetData();
        const sal_uInt8* pDest = rGfxLink.GetData();
        sal_uInt32 nSourceSize = GetDataSize();
        sal_uInt32 nDestSize = rGfxLink.GetDataSize();
        if ( pSource && pDest && ( nSourceSize == nDestSize ) )
        {
            bIsEqual = memcmp( pSource, pDest, nSourceSize ) == 0;
        }
        else if ( ( pSource == 0 ) && ( pDest == 0 ) )
            bIsEqual = sal_True;
    }
    return bIsEqual;
}

// ------------------------------------------------------------------------

void GfxLink::ImplCopy( const GfxLink& rGfxLink )
{
    mnBufSize = rGfxLink.mnBufSize;
    meType = rGfxLink.meType;
    mpBuf = rGfxLink.mpBuf;
    mpSwap = rGfxLink.mpSwap;
    mnUserId = rGfxLink.mnUserId;
    *mpImpData = *rGfxLink.mpImpData;

    if( mpBuf )
        mpBuf->mnRefCount++;

    if( mpSwap )
        mpSwap->mnRefCount++;
}

// ------------------------------------------------------------------------

GfxLinkType GfxLink::GetType() const
{
    return meType;
}

// ------------------------------------------------------------------------

BOOL GfxLink::IsNative() const
{
    return( meType >= GFX_LINK_FIRST_NATIVE_ID && meType <= GFX_LINK_LAST_NATIVE_ID );
}

// ------------------------------------------------------------------------

sal_uInt32 GfxLink::GetDataSize() const
{
    return mnBufSize;
}

// ------------------------------------------------------------------------

const BYTE* GfxLink::GetData() const
{
    if( IsSwappedOut() )
        ( (GfxLink*) this )->SwapIn();

    return( mpBuf ? mpBuf->mpBuffer : NULL );
}

// ------------------------------------------------------------------------

const Size& GfxLink::GetPrefSize() const
{
    return mpImpData->maPrefSize;
}

// ------------------------------------------------------------------------

void GfxLink::SetPrefSize( const Size& rPrefSize )
{
    mpImpData->maPrefSize = rPrefSize;
    mpImpData->mbPrefSizeValid = true;
}

// ------------------------------------------------------------------------

bool GfxLink::IsPrefSizeValid()
{
    return mpImpData->mbPrefSizeValid;
}

// ------------------------------------------------------------------------

const MapMode& GfxLink::GetPrefMapMode() const
{
    return mpImpData->maPrefMapMode;
}

// ------------------------------------------------------------------------

void GfxLink::SetPrefMapMode( const MapMode& rPrefMapMode )
{
    mpImpData->maPrefMapMode = rPrefMapMode;
    mpImpData->mbPrefMapModeValid = true;
}

// ------------------------------------------------------------------------

bool GfxLink::IsPrefMapModeValid()
{
    return mpImpData->mbPrefMapModeValid;
}

// ------------------------------------------------------------------------

BOOL GfxLink::LoadNative( Graphic& rGraphic )
{
    BOOL bRet = FALSE;

    if( IsNative() && mnBufSize )
    {
        const BYTE* pData = GetData();

        if( pData )
        {
            SvMemoryStream  aMemStm;
            ULONG           nCvtType;

            aMemStm.SetBuffer( (char*) pData, mnBufSize, FALSE, mnBufSize );

            switch( meType )
            {
                case( GFX_LINK_TYPE_NATIVE_GIF ): nCvtType = CVT_GIF; break;
                case( GFX_LINK_TYPE_NATIVE_JPG ): nCvtType = CVT_JPG; break;
                case( GFX_LINK_TYPE_NATIVE_PNG ): nCvtType = CVT_PNG; break;
                case( GFX_LINK_TYPE_NATIVE_TIF ): nCvtType = CVT_TIF; break;
                case( GFX_LINK_TYPE_NATIVE_WMF ): nCvtType = CVT_WMF; break;
                case( GFX_LINK_TYPE_NATIVE_MET ): nCvtType = CVT_MET; break;
                case( GFX_LINK_TYPE_NATIVE_PCT ): nCvtType = CVT_PCT; break;

                default: nCvtType = CVT_UNKNOWN; break;
            }

            if( nCvtType && ( GraphicConverter::Import( aMemStm, rGraphic, nCvtType ) == ERRCODE_NONE ) )
                bRet = TRUE;
        }
    }

    return bRet;
}

// ------------------------------------------------------------------------

void GfxLink::SwapOut()
{
    if( !IsSwappedOut() && mpBuf )
    {
        mpSwap = new ImpSwap( mpBuf->mpBuffer, mnBufSize );

        if( !mpSwap->IsSwapped() )
        {
            delete mpSwap;
            mpSwap = NULL;
        }
        else
        {
            if( !( --mpBuf->mnRefCount ) )
                delete mpBuf;

            mpBuf = NULL;
        }
    }
}

// ------------------------------------------------------------------------

void GfxLink::SwapIn()
{
    if( IsSwappedOut() )
    {
        mpBuf = new ImpBuffer( mpSwap->GetData() );

        if( !( --mpSwap->mnRefCount ) )
            delete mpSwap;

        mpSwap = NULL;
    }
}

// ------------------------------------------------------------------------

BOOL GfxLink::ExportNative( SvStream& rOStream ) const
{
    if( GetDataSize() )
    {
        if( IsSwappedOut() )
            mpSwap->WriteTo( rOStream );
        else if( GetData() )
            rOStream.Write( GetData(), GetDataSize() );
    }

    return ( rOStream.GetError() == ERRCODE_NONE );
}

// ------------------------------------------------------------------------

SvStream& operator<<( SvStream& rOStream, const GfxLink& rGfxLink )
{
    VersionCompat* pCompat = new VersionCompat( rOStream, STREAM_WRITE, 2 );

    // Version 1
    rOStream << (UINT16) rGfxLink.GetType() << rGfxLink.GetDataSize() << rGfxLink.GetUserId();

    // Version 2
    rOStream << rGfxLink.GetPrefSize() << rGfxLink.GetPrefMapMode();

    delete pCompat;

    if( rGfxLink.GetDataSize() )
    {
        if( rGfxLink.IsSwappedOut() )
            rGfxLink.mpSwap->WriteTo( rOStream );
        else if( rGfxLink.GetData() )
            rOStream.Write( rGfxLink.GetData(), rGfxLink.GetDataSize() );
    }

    return rOStream;
}

// ------------------------------------------------------------------------

SvStream& operator>>( SvStream& rIStream, GfxLink& rGfxLink)
{
    Size            aSize;
    MapMode         aMapMode;
    sal_uInt32      nSize;
    sal_uInt32      nUserId;
    UINT16          nType;
    BYTE*           pBuf;
    bool            bMapAndSizeValid( false );
    VersionCompat*  pCompat = new VersionCompat( rIStream, STREAM_READ );

    // Version 1
    rIStream >> nType >> nSize >> nUserId;

    if( pCompat->GetVersion() >= 2 )
    {
        rIStream >> aSize >> aMapMode;
        bMapAndSizeValid = true;
    }

    delete pCompat;

    pBuf = new BYTE[ nSize ];
    rIStream.Read( pBuf, nSize );

    rGfxLink = GfxLink( pBuf, nSize, (GfxLinkType) nType, TRUE );
    rGfxLink.SetUserId( nUserId );

    if( bMapAndSizeValid )
    {
        rGfxLink.SetPrefSize( aSize );
        rGfxLink.SetPrefMapMode( aMapMode );
    }

    return rIStream;
}

// -----------
// - ImpSwap -
// -----------

ImpSwap::ImpSwap( BYTE* pData, ULONG nDataSize ) :
            mnDataSize( nDataSize ),
            mnRefCount( 1UL )
{
    if( pData && mnDataSize )
    {
        ::utl::TempFile aTempFile;

        maURL = INetURLObject(aTempFile.GetURL());

        if( maURL.GetMainURL( INetURLObject::NO_DECODE ).getLength() )
        {
            SvStream* pOStm = ::utl::UcbStreamHelper::CreateStream( maURL.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READWRITE | STREAM_SHARE_DENYWRITE );

            if( pOStm )
            {
                pOStm->Write( pData, mnDataSize );
                sal_Bool bError = ( ERRCODE_NONE != pOStm->GetError() );
                delete pOStm;

                if( bError )
                {
                    try
                    {
                        ::ucb::Content aCnt( maURL.GetMainURL( INetURLObject::NO_DECODE ),
                                             ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >() );

                        aCnt.executeCommand( ::rtl::OUString::createFromAscii( "delete" ),
                                             ::com::sun::star::uno::makeAny( sal_Bool( sal_True ) ) );
                    }
                    catch( const ::com::sun::star::ucb::ContentCreationException& )
                    {
                    }
                    catch( const ::com::sun::star::uno::RuntimeException& )
                    {
                    }
                    catch( const ::com::sun::star::ucb::CommandAbortedException& )
                    {
                    }
                    catch( const ::com::sun::star::uno::Exception& )
                    {
                    }

                    maURL = INetURLObject();
                }
            }
        }
    }
}

// ------------------------------------------------------------------------

ImpSwap::~ImpSwap()
{
    if( IsSwapped() )
    {
        try
        {
            ::ucb::Content aCnt( maURL.GetMainURL( INetURLObject::NO_DECODE ),
                                 ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >() );

            aCnt.executeCommand( ::rtl::OUString::createFromAscii( "delete" ),
                                 ::com::sun::star::uno::makeAny( sal_Bool( sal_True ) ) );
        }
        catch( const ::com::sun::star::ucb::ContentCreationException& )
        {
        }
        catch( const ::com::sun::star::uno::RuntimeException& )
        {
        }
        catch( const ::com::sun::star::ucb::CommandAbortedException& )
        {
        }
        catch( const ::com::sun::star::uno::Exception& )
        {
        }
    }
}

// ------------------------------------------------------------------------

BYTE* ImpSwap::GetData() const
{
    BYTE* pData;

    if( IsSwapped() )
    {
        SvStream* pIStm = ::utl::UcbStreamHelper::CreateStream( maURL.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READWRITE );

        if( pIStm )
        {
            pData = new BYTE[ mnDataSize ];
            pIStm->Read( pData, mnDataSize );
            sal_Bool bError = ( ERRCODE_NONE != pIStm->GetError() );
            delete pIStm;

            if( bError )
                delete[] pData, pData = NULL;
        }
        else
            pData = NULL;
    }
    else
        pData = NULL;

    return pData;
}

// ------------------------------------------------------------------------

void ImpSwap::WriteTo( SvStream& rOStm ) const
{
    BYTE* pData = GetData();

    if( pData )
    {
        rOStm.Write( pData, mnDataSize );
        delete[] pData;
    }
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.15.160); FILE MERGED 2006/09/01 17:57:42 kaib 1.15.160.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: gfxlink.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 12:00:51 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#include <tools/vcompat.hxx>
#include <tools/urlobj.hxx>
#include <tools/debug.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/tempfile.hxx>
#include <ucbhelper/content.hxx>
#include "graph.hxx"
#include "gfxlink.hxx"
#include "cvtgrf.hxx"

#ifndef _COM_SUN_STAR_UCB_COMMANDABORTEDEXCEPTION_HPP_
#include <com/sun/star/ucb/CommandAbortedException.hpp>
#endif

// -----------
// - GfxLink -
// -----------

GfxLink::GfxLink() :
    meType      ( GFX_LINK_TYPE_NONE ),
    mpBuf       ( NULL ),
    mpSwap      ( NULL ),
    mnBufSize   ( 0 ),
    mnUserId    ( 0UL ),
    mpImpData   ( new ImpGfxLink )
{
}

// ------------------------------------------------------------------------

GfxLink::GfxLink( const GfxLink& rGfxLink ) :
    mpImpData( new ImpGfxLink )
{
    ImplCopy( rGfxLink );
}

// ------------------------------------------------------------------------

GfxLink::GfxLink( BYTE* pBuf, sal_uInt32 nSize, GfxLinkType nType, BOOL bOwns ) :
    mpImpData( new ImpGfxLink )
{
    DBG_ASSERT( (pBuf != NULL && nSize) || (!bOwns && nSize == 0),
                "GfxLink::GfxLink(): empty/NULL buffer given" );

    meType = nType;
    mnBufSize = nSize;
    mpSwap = NULL;
    mnUserId = 0UL;

    if( bOwns )
        mpBuf = new ImpBuffer( pBuf );
    else if( nSize )
    {
        mpBuf = new ImpBuffer( nSize );
        memcpy( mpBuf->mpBuffer, pBuf, nSize );
    }
    else
        mpBuf = NULL;
}

// ------------------------------------------------------------------------

GfxLink::~GfxLink()
{
    if( mpBuf && !( --mpBuf->mnRefCount ) )
        delete mpBuf;

    if( mpSwap && !( --mpSwap->mnRefCount ) )
        delete mpSwap;

    delete mpImpData;
}

// ------------------------------------------------------------------------

GfxLink& GfxLink::operator=( const GfxLink& rGfxLink )
{
    if( &rGfxLink != this )
    {
        if ( mpBuf && !( --mpBuf->mnRefCount ) )
            delete mpBuf;

        if( mpSwap && !( --mpSwap->mnRefCount ) )
            delete mpSwap;

        ImplCopy( rGfxLink );
    }

    return *this;
}

// ------------------------------------------------------------------------

sal_Bool GfxLink::IsEqual( const GfxLink& rGfxLink ) const
{
    sal_Bool bIsEqual = sal_False;

    if ( ( mnBufSize == rGfxLink.mnBufSize ) && ( meType == rGfxLink.meType ) )
    {
        const sal_uInt8* pSource = GetData();
        const sal_uInt8* pDest = rGfxLink.GetData();
        sal_uInt32 nSourceSize = GetDataSize();
        sal_uInt32 nDestSize = rGfxLink.GetDataSize();
        if ( pSource && pDest && ( nSourceSize == nDestSize ) )
        {
            bIsEqual = memcmp( pSource, pDest, nSourceSize ) == 0;
        }
        else if ( ( pSource == 0 ) && ( pDest == 0 ) )
            bIsEqual = sal_True;
    }
    return bIsEqual;
}

// ------------------------------------------------------------------------

void GfxLink::ImplCopy( const GfxLink& rGfxLink )
{
    mnBufSize = rGfxLink.mnBufSize;
    meType = rGfxLink.meType;
    mpBuf = rGfxLink.mpBuf;
    mpSwap = rGfxLink.mpSwap;
    mnUserId = rGfxLink.mnUserId;
    *mpImpData = *rGfxLink.mpImpData;

    if( mpBuf )
        mpBuf->mnRefCount++;

    if( mpSwap )
        mpSwap->mnRefCount++;
}

// ------------------------------------------------------------------------

GfxLinkType GfxLink::GetType() const
{
    return meType;
}

// ------------------------------------------------------------------------

BOOL GfxLink::IsNative() const
{
    return( meType >= GFX_LINK_FIRST_NATIVE_ID && meType <= GFX_LINK_LAST_NATIVE_ID );
}

// ------------------------------------------------------------------------

sal_uInt32 GfxLink::GetDataSize() const
{
    return mnBufSize;
}

// ------------------------------------------------------------------------

const BYTE* GfxLink::GetData() const
{
    if( IsSwappedOut() )
        ( (GfxLink*) this )->SwapIn();

    return( mpBuf ? mpBuf->mpBuffer : NULL );
}

// ------------------------------------------------------------------------

const Size& GfxLink::GetPrefSize() const
{
    return mpImpData->maPrefSize;
}

// ------------------------------------------------------------------------

void GfxLink::SetPrefSize( const Size& rPrefSize )
{
    mpImpData->maPrefSize = rPrefSize;
    mpImpData->mbPrefSizeValid = true;
}

// ------------------------------------------------------------------------

bool GfxLink::IsPrefSizeValid()
{
    return mpImpData->mbPrefSizeValid;
}

// ------------------------------------------------------------------------

const MapMode& GfxLink::GetPrefMapMode() const
{
    return mpImpData->maPrefMapMode;
}

// ------------------------------------------------------------------------

void GfxLink::SetPrefMapMode( const MapMode& rPrefMapMode )
{
    mpImpData->maPrefMapMode = rPrefMapMode;
    mpImpData->mbPrefMapModeValid = true;
}

// ------------------------------------------------------------------------

bool GfxLink::IsPrefMapModeValid()
{
    return mpImpData->mbPrefMapModeValid;
}

// ------------------------------------------------------------------------

BOOL GfxLink::LoadNative( Graphic& rGraphic )
{
    BOOL bRet = FALSE;

    if( IsNative() && mnBufSize )
    {
        const BYTE* pData = GetData();

        if( pData )
        {
            SvMemoryStream  aMemStm;
            ULONG           nCvtType;

            aMemStm.SetBuffer( (char*) pData, mnBufSize, FALSE, mnBufSize );

            switch( meType )
            {
                case( GFX_LINK_TYPE_NATIVE_GIF ): nCvtType = CVT_GIF; break;
                case( GFX_LINK_TYPE_NATIVE_JPG ): nCvtType = CVT_JPG; break;
                case( GFX_LINK_TYPE_NATIVE_PNG ): nCvtType = CVT_PNG; break;
                case( GFX_LINK_TYPE_NATIVE_TIF ): nCvtType = CVT_TIF; break;
                case( GFX_LINK_TYPE_NATIVE_WMF ): nCvtType = CVT_WMF; break;
                case( GFX_LINK_TYPE_NATIVE_MET ): nCvtType = CVT_MET; break;
                case( GFX_LINK_TYPE_NATIVE_PCT ): nCvtType = CVT_PCT; break;

                default: nCvtType = CVT_UNKNOWN; break;
            }

            if( nCvtType && ( GraphicConverter::Import( aMemStm, rGraphic, nCvtType ) == ERRCODE_NONE ) )
                bRet = TRUE;
        }
    }

    return bRet;
}

// ------------------------------------------------------------------------

void GfxLink::SwapOut()
{
    if( !IsSwappedOut() && mpBuf )
    {
        mpSwap = new ImpSwap( mpBuf->mpBuffer, mnBufSize );

        if( !mpSwap->IsSwapped() )
        {
            delete mpSwap;
            mpSwap = NULL;
        }
        else
        {
            if( !( --mpBuf->mnRefCount ) )
                delete mpBuf;

            mpBuf = NULL;
        }
    }
}

// ------------------------------------------------------------------------

void GfxLink::SwapIn()
{
    if( IsSwappedOut() )
    {
        mpBuf = new ImpBuffer( mpSwap->GetData() );

        if( !( --mpSwap->mnRefCount ) )
            delete mpSwap;

        mpSwap = NULL;
    }
}

// ------------------------------------------------------------------------

BOOL GfxLink::ExportNative( SvStream& rOStream ) const
{
    if( GetDataSize() )
    {
        if( IsSwappedOut() )
            mpSwap->WriteTo( rOStream );
        else if( GetData() )
            rOStream.Write( GetData(), GetDataSize() );
    }

    return ( rOStream.GetError() == ERRCODE_NONE );
}

// ------------------------------------------------------------------------

SvStream& operator<<( SvStream& rOStream, const GfxLink& rGfxLink )
{
    VersionCompat* pCompat = new VersionCompat( rOStream, STREAM_WRITE, 2 );

    // Version 1
    rOStream << (UINT16) rGfxLink.GetType() << rGfxLink.GetDataSize() << rGfxLink.GetUserId();

    // Version 2
    rOStream << rGfxLink.GetPrefSize() << rGfxLink.GetPrefMapMode();

    delete pCompat;

    if( rGfxLink.GetDataSize() )
    {
        if( rGfxLink.IsSwappedOut() )
            rGfxLink.mpSwap->WriteTo( rOStream );
        else if( rGfxLink.GetData() )
            rOStream.Write( rGfxLink.GetData(), rGfxLink.GetDataSize() );
    }

    return rOStream;
}

// ------------------------------------------------------------------------

SvStream& operator>>( SvStream& rIStream, GfxLink& rGfxLink)
{
    Size            aSize;
    MapMode         aMapMode;
    sal_uInt32      nSize;
    sal_uInt32      nUserId;
    UINT16          nType;
    BYTE*           pBuf;
    bool            bMapAndSizeValid( false );
    VersionCompat*  pCompat = new VersionCompat( rIStream, STREAM_READ );

    // Version 1
    rIStream >> nType >> nSize >> nUserId;

    if( pCompat->GetVersion() >= 2 )
    {
        rIStream >> aSize >> aMapMode;
        bMapAndSizeValid = true;
    }

    delete pCompat;

    pBuf = new BYTE[ nSize ];
    rIStream.Read( pBuf, nSize );

    rGfxLink = GfxLink( pBuf, nSize, (GfxLinkType) nType, TRUE );
    rGfxLink.SetUserId( nUserId );

    if( bMapAndSizeValid )
    {
        rGfxLink.SetPrefSize( aSize );
        rGfxLink.SetPrefMapMode( aMapMode );
    }

    return rIStream;
}

// -----------
// - ImpSwap -
// -----------

ImpSwap::ImpSwap( BYTE* pData, ULONG nDataSize ) :
            mnDataSize( nDataSize ),
            mnRefCount( 1UL )
{
    if( pData && mnDataSize )
    {
        ::utl::TempFile aTempFile;

        maURL = INetURLObject(aTempFile.GetURL());

        if( maURL.GetMainURL( INetURLObject::NO_DECODE ).getLength() )
        {
            SvStream* pOStm = ::utl::UcbStreamHelper::CreateStream( maURL.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READWRITE | STREAM_SHARE_DENYWRITE );

            if( pOStm )
            {
                pOStm->Write( pData, mnDataSize );
                sal_Bool bError = ( ERRCODE_NONE != pOStm->GetError() );
                delete pOStm;

                if( bError )
                {
                    try
                    {
                        ::ucb::Content aCnt( maURL.GetMainURL( INetURLObject::NO_DECODE ),
                                             ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >() );

                        aCnt.executeCommand( ::rtl::OUString::createFromAscii( "delete" ),
                                             ::com::sun::star::uno::makeAny( sal_Bool( sal_True ) ) );
                    }
                    catch( const ::com::sun::star::ucb::ContentCreationException& )
                    {
                    }
                    catch( const ::com::sun::star::uno::RuntimeException& )
                    {
                    }
                    catch( const ::com::sun::star::ucb::CommandAbortedException& )
                    {
                    }
                    catch( const ::com::sun::star::uno::Exception& )
                    {
                    }

                    maURL = INetURLObject();
                }
            }
        }
    }
}

// ------------------------------------------------------------------------

ImpSwap::~ImpSwap()
{
    if( IsSwapped() )
    {
        try
        {
            ::ucb::Content aCnt( maURL.GetMainURL( INetURLObject::NO_DECODE ),
                                 ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >() );

            aCnt.executeCommand( ::rtl::OUString::createFromAscii( "delete" ),
                                 ::com::sun::star::uno::makeAny( sal_Bool( sal_True ) ) );
        }
        catch( const ::com::sun::star::ucb::ContentCreationException& )
        {
        }
        catch( const ::com::sun::star::uno::RuntimeException& )
        {
        }
        catch( const ::com::sun::star::ucb::CommandAbortedException& )
        {
        }
        catch( const ::com::sun::star::uno::Exception& )
        {
        }
    }
}

// ------------------------------------------------------------------------

BYTE* ImpSwap::GetData() const
{
    BYTE* pData;

    if( IsSwapped() )
    {
        SvStream* pIStm = ::utl::UcbStreamHelper::CreateStream( maURL.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READWRITE );

        if( pIStm )
        {
            pData = new BYTE[ mnDataSize ];
            pIStm->Read( pData, mnDataSize );
            sal_Bool bError = ( ERRCODE_NONE != pIStm->GetError() );
            delete pIStm;

            if( bError )
                delete[] pData, pData = NULL;
        }
        else
            pData = NULL;
    }
    else
        pData = NULL;

    return pData;
}

// ------------------------------------------------------------------------

void ImpSwap::WriteTo( SvStream& rOStm ) const
{
    BYTE* pData = GetData();

    if( pData )
    {
        rOStm.Write( pData, mnDataSize );
        delete[] pData;
    }
}
<|endoftext|>


<commit_before>/** Copyright (C) 2017 European Spallation Source ERIC */

#include <algorithm>
#include <memory>
#include <sonde/Geometry.h>
#include <sonde/ideas/Data.h>
#include <sonde/ideas/TestData.h>
#include <test/TestBase.h>

using namespace Sonde;

class IDEASDataTest : public TestBase {
protected:
  Geometry geometry;
  IDEASData *readout;
  void SetUp() override {
    readout = new IDEASData(&geometry);
    memset(readout->data, 0, sizeof(readout->data));
  }
  void TearDown() override {
    delete readout;
  }
};

/** Test cases below */
TEST_F(IDEASDataTest, ErrNoData) {
  int res = readout->parse_buffer(0, 20);
  ASSERT_EQ(res, -IDEASData::EBUFFER);
}

TEST_F(IDEASDataTest, ErrHeaderFields) {
  int i = 0;
  for (auto v : err_hdr) {
    MESSAGE() << "err_hdr[" << i++ << "]\n";
    int res = readout->parse_buffer((char *)&v[0], v.size());
    ASSERT_EQ(res, -IDEASData::EHEADER);
  }
}

TEST_F(IDEASDataTest, ErrShortHeader) {
  int size = err_short_header.size();
  int res = readout->parse_buffer((char *)&err_short_header[0], size);
  ASSERT_EQ(res, -IDEASData::EBADSIZE);
}

TEST_F(IDEASDataTest, ErrUnknownDataFormat) {
  int size = err_unknown_data_format.size();
  int res = readout->parse_buffer((char *)&err_unknown_data_format[0], size);
  ASSERT_EQ(res, -IDEASData::EUNSUPP);
}

TEST_F(IDEASDataTest, ErrInvalidGeometry) {
  int size = err_invalid_geometry.size();
  int res = readout->parse_buffer((char *)&err_invalid_geometry[0], size);
  ASSERT_EQ(res, 0);
  ASSERT_EQ(readout->errors, 1);
}

TEST_F(IDEASDataTest, OkHeaderOnly) {
  int size = ok_header_only.size();
  int res = readout->parse_buffer((char *)&ok_header_only[0], size);
  ASSERT_EQ(res, 0);
  ASSERT_EQ(readout->events, 0);
}

TEST_F(IDEASDataTest, OkOneEvent) {
  int size = ok_events_1.size();
  int res = readout->parse_buffer((char *)&ok_events_1[0], size);
  ASSERT_EQ(res, 1);
  ASSERT_EQ(readout->events, 1);
}

TEST_F(IDEASDataTest, OkThreeEvents) {
  int size = ok_events_3.size();
  int res = readout->parse_buffer((char *)&ok_events_3[0], size);
  ASSERT_EQ(res, 3);
  ASSERT_EQ(readout->events, 3);

  for (int i = 0; i < res; i++) {
    ASSERT_NE(0, readout->data[i].Time);
    ASSERT_NE(0, readout->data[i].PixelId);
  }
}

TEST_F(IDEASDataTest, SEPHOkOneSample) {
  int size = type_0xd5_seph_ok_1.size();
  int res = readout->parse_buffer((char *)&type_0xd5_seph_ok_1[0], size);
  ASSERT_EQ(res, 1);
  ASSERT_EQ(readout->samples, 1);
}

TEST_F(IDEASDataTest, SEPHOkThreeSamples) {
  int size = type_0xd5_seph_ok_3.size();
  int res = readout->parse_buffer((char *)&type_0xd5_seph_ok_3[0], size);
  ASSERT_EQ(res, 3); // Currently returns one event per sample
  ASSERT_EQ(readout->samples, 3);
  ASSERT_EQ(readout->data[0].Adc, 0x1234);
  ASSERT_EQ(readout->data[1].Adc, 0x5678);
  ASSERT_EQ(readout->data[2].Adc, 0x9abc);
}

TEST_F(IDEASDataTest, SEPHErrHdrLenMismatch) {
  int size = type_0xd5_seph_err_hdr_len_mismatch.size();
  int res = readout->parse_buffer(
      (char *)&type_0xd5_seph_err_hdr_len_mismatch[0], size);
  ASSERT_EQ(res, -IDEASData::EHEADER);
}

TEST_F(IDEASDataTest, MEPHErrHdrLen) {
  int size = type_0xd4_meph_err_hdr_len.size();
  int res = readout->parse_buffer((char *)&type_0xd4_meph_err_hdr_len[0], size);
  ASSERT_EQ(res, -IDEASData::EBADSIZE);
}

TEST_F(IDEASDataTest, MEPHErrHdrLenMismatch) {
  int size = type_0xd4_meph_err_hdr_len_mismatch.size();
  int res = readout->parse_buffer(
      (char *)&type_0xd4_meph_err_hdr_len_mismatch[0], size);
  ASSERT_EQ(res, -IDEASData::EHEADER);
}

TEST_F(IDEASDataTest, MEPHOkOneSample) {
  int size = type_0xd4_meph_ok_1.size();
  int res = readout->parse_buffer((char *)&type_0xd4_meph_ok_1[0], size);
  ASSERT_EQ(res, 1);
  ASSERT_EQ(readout->samples, 1);
}

TEST_F(IDEASDataTest, MEPHOkN3M1) {
  int size = type_0xd4_meph_ok_n3m1.size();
  int res = readout->parse_buffer((char *)&type_0xd4_meph_ok_n3m1[0], size);
  ASSERT_EQ(res, 3); // Should always return 3 events
  // This also implicitly testes the data endianness
  ASSERT_EQ(readout->samples, 3);
  ASSERT_EQ(readout->data[0].Time, 0x00000001);
  ASSERT_EQ(readout->data[0].Adc, 0x1234);
  ASSERT_EQ(readout->data[1].Time, 0x00000005);
  ASSERT_EQ(readout->data[1].Adc, 0x5678);
  ASSERT_EQ(readout->data[2].Time, 0x00000009);
  ASSERT_EQ(readout->data[2].Adc, 0x9abc);
}

TEST_F(IDEASDataTest, SCRO_pkt) {
  int size = scro_pkt.size();
  int res = readout->parse_buffer((char *)&scro_pkt[0], size);
  ASSERT_EQ(res, 150); // There is really only one event but 150 samples
}

TEST_F(IDEASDataTest, ACRO_pkt) {
  int size = acro_pkt.size();
  int res = readout->parse_buffer((char *)&acro_pkt[0], size);
  ASSERT_EQ(res, 64); // There is really only one event but 1 sample per channel
}

int main(int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>filedumping enabled for sonde unit test<commit_after>/** Copyright (C) 2017 European Spallation Source ERIC */

#include <algorithm>
#include <memory>
#include <sonde/Geometry.h>
#include <sonde/ideas/Data.h>
#include <sonde/ideas/TestData.h>
#include <test/TestBase.h>

using namespace Sonde;

class IDEASDataTest : public TestBase {
protected:
  Geometry geometry;
  IDEASData *readout;
  void SetUp() override {
    readout = new IDEASData(&geometry, "deleteme_sonde_test_");
    memset(readout->data, 0, sizeof(readout->data));
  }
  void TearDown() override {
    delete readout;
  }
};

/** Test cases below */
TEST_F(IDEASDataTest, ErrNoData) {
  int res = readout->parse_buffer(0, 20);
  ASSERT_EQ(res, -IDEASData::EBUFFER);
}

TEST_F(IDEASDataTest, ErrHeaderFields) {
  int i = 0;
  for (auto v : err_hdr) {
    MESSAGE() << "err_hdr[" << i++ << "]\n";
    int res = readout->parse_buffer((char *)&v[0], v.size());
    ASSERT_EQ(res, -IDEASData::EHEADER);
  }
}

TEST_F(IDEASDataTest, ErrShortHeader) {
  int size = err_short_header.size();
  int res = readout->parse_buffer((char *)&err_short_header[0], size);
  ASSERT_EQ(res, -IDEASData::EBADSIZE);
}

TEST_F(IDEASDataTest, ErrUnknownDataFormat) {
  int size = err_unknown_data_format.size();
  int res = readout->parse_buffer((char *)&err_unknown_data_format[0], size);
  ASSERT_EQ(res, -IDEASData::EUNSUPP);
}

TEST_F(IDEASDataTest, ErrInvalidGeometry) {
  int size = err_invalid_geometry.size();
  int res = readout->parse_buffer((char *)&err_invalid_geometry[0], size);
  ASSERT_EQ(res, 0);
  ASSERT_EQ(readout->errors, 1);
}

TEST_F(IDEASDataTest, OkHeaderOnly) {
  int size = ok_header_only.size();
  int res = readout->parse_buffer((char *)&ok_header_only[0], size);
  ASSERT_EQ(res, 0);
  ASSERT_EQ(readout->events, 0);
}

TEST_F(IDEASDataTest, OkOneEvent) {
  int size = ok_events_1.size();
  int res = readout->parse_buffer((char *)&ok_events_1[0], size);
  ASSERT_EQ(res, 1);
  ASSERT_EQ(readout->events, 1);
}

TEST_F(IDEASDataTest, OkThreeEvents) {
  int size = ok_events_3.size();
  int res = readout->parse_buffer((char *)&ok_events_3[0], size);
  ASSERT_EQ(res, 3);
  ASSERT_EQ(readout->events, 3);

  for (int i = 0; i < res; i++) {
    ASSERT_NE(0, readout->data[i].Time);
    ASSERT_NE(0, readout->data[i].PixelId);
  }
}

TEST_F(IDEASDataTest, SEPHOkOneSample) {
  int size = type_0xd5_seph_ok_1.size();
  int res = readout->parse_buffer((char *)&type_0xd5_seph_ok_1[0], size);
  ASSERT_EQ(res, 1);
  ASSERT_EQ(readout->samples, 1);
}

TEST_F(IDEASDataTest, SEPHOkThreeSamples) {
  int size = type_0xd5_seph_ok_3.size();
  int res = readout->parse_buffer((char *)&type_0xd5_seph_ok_3[0], size);
  ASSERT_EQ(res, 3); // Currently returns one event per sample
  ASSERT_EQ(readout->samples, 3);
  ASSERT_EQ(readout->data[0].Adc, 0x1234);
  ASSERT_EQ(readout->data[1].Adc, 0x5678);
  ASSERT_EQ(readout->data[2].Adc, 0x9abc);
}

TEST_F(IDEASDataTest, SEPHErrHdrLenMismatch) {
  int size = type_0xd5_seph_err_hdr_len_mismatch.size();
  int res = readout->parse_buffer(
      (char *)&type_0xd5_seph_err_hdr_len_mismatch[0], size);
  ASSERT_EQ(res, -IDEASData::EHEADER);
}

TEST_F(IDEASDataTest, MEPHErrHdrLen) {
  int size = type_0xd4_meph_err_hdr_len.size();
  int res = readout->parse_buffer((char *)&type_0xd4_meph_err_hdr_len[0], size);
  ASSERT_EQ(res, -IDEASData::EBADSIZE);
}

TEST_F(IDEASDataTest, MEPHErrHdrLenMismatch) {
  int size = type_0xd4_meph_err_hdr_len_mismatch.size();
  int res = readout->parse_buffer(
      (char *)&type_0xd4_meph_err_hdr_len_mismatch[0], size);
  ASSERT_EQ(res, -IDEASData::EHEADER);
}

TEST_F(IDEASDataTest, MEPHOkOneSample) {
  int size = type_0xd4_meph_ok_1.size();
  int res = readout->parse_buffer((char *)&type_0xd4_meph_ok_1[0], size);
  ASSERT_EQ(res, 1);
  ASSERT_EQ(readout->samples, 1);
}

TEST_F(IDEASDataTest, MEPHOkN3M1) {
  int size = type_0xd4_meph_ok_n3m1.size();
  int res = readout->parse_buffer((char *)&type_0xd4_meph_ok_n3m1[0], size);
  ASSERT_EQ(res, 3); // Should always return 3 events
  // This also implicitly testes the data endianness
  ASSERT_EQ(readout->samples, 3);
  ASSERT_EQ(readout->data[0].Time, 0x00000001);
  ASSERT_EQ(readout->data[0].Adc, 0x1234);
  ASSERT_EQ(readout->data[1].Time, 0x00000005);
  ASSERT_EQ(readout->data[1].Adc, 0x5678);
  ASSERT_EQ(readout->data[2].Time, 0x00000009);
  ASSERT_EQ(readout->data[2].Adc, 0x9abc);
}

TEST_F(IDEASDataTest, SCRO_pkt) {
  int size = scro_pkt.size();
  int res = readout->parse_buffer((char *)&scro_pkt[0], size);
  ASSERT_EQ(res, 150); // There is really only one event but 150 samples
}

TEST_F(IDEASDataTest, ACRO_pkt) {
  int size = acro_pkt.size();
  int res = readout->parse_buffer((char *)&acro_pkt[0], size);
  ASSERT_EQ(res, 64); // There is really only one event but 1 sample per channel
}

int main(int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#ifndef VIENNAGRID_PLC_HPP
#define VIENNAGRID_PLC_HPP

/* =======================================================================
   Copyright (c) 2011-2012, Institute for Microelectronics,
                            Institute for Analysis and Scientific Computing,
                            TU Wien.

                            -----------------
                     ViennaGrid - The Vienna Grid Library
                            -----------------

   Authors:      Karl Rupp                           rupp@iue.tuwien.ac.at
                 Josef Weinbub                    weinbub@iue.tuwien.ac.at

   (A list of additional contributors can be found in the PDF manual)

   License:      MIT (X11), see file LICENSE in the base directory
======================================================================= */

#include "viennagrid/forwards.hpp"

/** @file element.hpp
    @brief Provides the main n-cell type
*/

namespace viennagrid
{

    struct plc_tag
    {
        typedef viennameta::null_type facet_type;

        enum{ dim = 2 };
        static std::string name() { return "PLC"; }
    };

    template<typename bounding_polygon_view_type_, typename hole_polygon_view_type_, typename line_view_type_, typename vertex_view_type_, typename id_tag_>
    class plc_t : public viennagrid::storage::id_handler<
                    typename viennagrid::storage::result_of::id< plc_t<bounding_polygon_view_type_, hole_polygon_view_type_, line_view_type_, vertex_view_type_, id_tag_>, id_tag_>::type
                >
    {
    public:

        typedef plc_tag tag;

        typedef bounding_polygon_view_type_ bounding_polygon_view_type;
        typedef typename bounding_polygon_view_type::value_type bounding_polygon_type;
        typedef typename bounding_polygon_view_type::hook_type bounding_polygon_hook_type;

        typedef hole_polygon_view_type_ hole_polygon_view_type;
        typedef typename hole_polygon_view_type::value_type hole_polygon_type;
        typedef typename hole_polygon_view_type::hook_type hole_polygon_hook_type;

        typedef line_view_type_ line_view_type;
        typedef typename line_view_type::value_type line_type;
        typedef typename line_view_type::hook_type line_hook_type;

        typedef vertex_view_type_ vertex_view_type;
        typedef typename vertex_view_type::value_type vertex_type;
        typedef typename vertex_view_type::hook_type vertex_hook_type;

        void set_bounding_polygon( bounding_polygon_hook_type bounding_polygon_hook )
        {
            bounding_polygon.set_hook( bounding_polygon_hook, 0 );

            typedef typename viennagrid::result_of::element_range<bounding_polygon_type, line_type>::type line_range_type;
            typedef typename viennagrid::result_of::hook_iterator<line_range_type>::type line_hook_iterator;

            line_range_type line_range = viennagrid::elements<line_type>( get_bounding_polygon() );
            for (line_hook_iterator it = line_range.hook_begin(); it != line_range.hook_end(); ++it)
                lines.insert_hook( *it );

            typedef typename viennagrid::result_of::element_range<bounding_polygon_type, vertex_type>::type vertex_range_type;
            typedef typename viennagrid::result_of::hook_iterator<vertex_range_type>::type vertex_hook_iterator;

            vertex_range_type vertex_range = viennagrid::elements<vertex_type>( get_bounding_polygon() );
            for (vertex_hook_iterator it = vertex_range.hook_begin(); it != vertex_range.hook_end(); ++it)
                vertices.insert_hook( *it );
        }

        bounding_polygon_type & get_bounding_polygon() { return bounding_polygon[0]; }
        const bounding_polygon_type & get_bounding_polygon() const { return bounding_polygon[0]; }

        template<typename hook_array_iterator_type>
        void add_hole_polygons(hook_array_iterator_type array_start, const hook_array_iterator_type & array_end)
        {
            for ( ; array_start != array_end; ++array_start )
            {
                hole_polygons.insert_hook( *array_start );
                hole_polygon_type & poly = hole_polygons.dereference_hook( *array_start );

                typedef typename viennagrid::result_of::element_range<hole_polygon_type, line_type>::type line_range_type;
                typedef typename viennagrid::result_of::hook_iterator<line_range_type>::type line_hook_iterator;

                line_range_type line_range = viennagrid::elements<line_type>( poly );
                for (line_hook_iterator it = line_range.hook_begin(); it != line_range.hook_end(); ++it)
                    lines.insert_hook( *it );

                typedef typename viennagrid::result_of::element_range<hole_polygon_type, vertex_type>::type vertex_range_type;
                typedef typename viennagrid::result_of::hook_iterator<vertex_range_type>::type vertex_hook_iterator;

                vertex_range_type vertex_range = viennagrid::elements<vertex_type>( poly );
                for (vertex_hook_iterator it = vertex_range.hook_begin(); it != vertex_range.hook_end(); ++it)
                    vertices.insert_hook( *it );
            }
        }

        hole_polygon_view_type & get_hole_polygons() { return hole_polygons; }
        const hole_polygon_view_type & get_hole_polygons() const { return hole_polygons; }

        template<typename hook_array_iterator_type>
        void add_lines(hook_array_iterator_type array_start, const hook_array_iterator_type & array_end)
        {
            for ( ; array_start != array_end; ++array_start )
            {
                lines.insert_hook( *array_start );
                line_type & line = lines.dereference_hook( *array_start );

                typedef typename viennagrid::result_of::element_range<line_type, vertex_type>::type vertex_range_type;
                typedef typename viennagrid::result_of::hook_iterator<vertex_range_type>::type vertex_hook_iterator;

                vertex_range_type vertex_range = viennagrid::elements<vertex_type>( line );
                for (vertex_hook_iterator it = vertex_range.hook_begin(); it != vertex_range.hook_end(); ++it)
                    vertices.insert_hook( *it );
            }
        }

        line_view_type & get_lines() { return lines; }
        const line_view_type & get_lines() const { return lines; }

        template<typename hook_array_iterator_type>
        void add_vertices(hook_array_iterator_type array_start, const hook_array_iterator_type & array_end)
        {
            for ( ; array_start != array_end; ++array_start )
            {
                vertices.insert_hook( *array_start );
            }
        }

        vertex_view_type & get_vertices() { return vertices; }
        const vertex_view_type & get_vertices() const { return vertices; }

        template<typename container_collection_type>
        void set_container_collection(container_collection_type & container_collection)
        {
            bounding_polygon.set_base_container( viennagrid::storage::collection::get<bounding_polygon_type>(container_collection) );

            hole_polygons.set_base_container( viennagrid::storage::collection::get<hole_polygon_type>(container_collection) );
            lines.set_base_container( viennagrid::storage::collection::get<line_type>(container_collection) );
            vertices.set_base_container( viennagrid::storage::collection::get<vertex_type>(container_collection) );
        }

        template<typename inserter_type>
        void insert_callback( inserter_type & inserter, bool inserted )
        {}

    private:
        bounding_polygon_view_type bounding_polygon;

        hole_polygon_view_type hole_polygons;
        line_view_type lines;
        vertex_view_type vertices;
    };

    /** @brief Overload for the output streaming operator */
    template<typename bounding_polygon_view_type, typename hole_polygon_view_type, typename line_view_type, typename vertex_view_type, typename id_tag>
    std::ostream & operator<<(std::ostream & os, plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag> & plc)
    {
        typedef plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag> element_type;
        typedef typename viennagrid::result_of::const_element_range< element_type, vertex_tag >::type vertex_range;
        typedef typename viennagrid::result_of::const_iterator< vertex_range >::type const_vertex_iterator;

        os << "-- " << plc_tag::name() << ", ID: " << plc.id() << " --";
        const vertex_range & vertices = elements<vertex_tag>(plc);
        for (const_vertex_iterator vit  = vertices.begin();
                            vit != vertices.end();
                        ++vit)
            os << std::endl << "  " << *vit;

        return os;
    }

    namespace result_of
    {
        template<typename bounding_polygon_view_type, typename hole_polygon_view_type, typename line_view_type, typename vertex_view_type, typename id_tag>
        struct element_tag< plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag> >
        {
            typedef plc_tag type;
        };
    }

    namespace result_of
    {
        template<typename bounding_polygon_view_type, typename hole_polygon_view_type, typename line_view_type, typename vertex_view_type, typename id_tag>
        struct element_range< plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag>, vertex_tag >
        {
            typedef typename viennagrid::storage::container_range_wrapper<vertex_view_type> type;
        };

        template<typename bounding_polygon_view_type, typename hole_polygon_view_type, typename line_view_type, typename vertex_view_type, typename id_tag>
        struct const_element_range< plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag>, vertex_tag >
        {
            typedef typename viennagrid::storage::container_range_wrapper<const vertex_view_type> type;
        };

        template<typename bounding_polygon_view_type, typename hole_polygon_view_type, typename line_view_type, typename vertex_view_type, typename id_tag>
        struct element_range< plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag>, line_tag >
        {
            typedef typename viennagrid::storage::container_range_wrapper<line_view_type> type;
        };

        template<typename bounding_polygon_view_type, typename hole_polygon_view_type, typename line_view_type, typename vertex_view_type, typename id_tag>
        struct const_element_range< plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag>, line_tag >
        {
            typedef typename viennagrid::storage::container_range_wrapper<const line_view_type> type;
        };

        template<typename bounding_polygon_view_type, typename hole_polygon_view_type, typename line_view_type, typename vertex_view_type, typename id_tag>
        struct element_range< plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag>, hole_polygon_tag >
        {
            typedef typename viennagrid::storage::container_range_wrapper<hole_polygon_view_type> type;
        };

        template<typename bounding_polygon_view_type, typename hole_polygon_view_type, typename line_view_type, typename vertex_view_type, typename id_tag>
        struct const_element_range< plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag>, hole_polygon_tag >
        {
            typedef typename viennagrid::storage::container_range_wrapper<const hole_polygon_view_type> type;
        };

        template<typename bounding_polygon_view_type, typename hole_polygon_view_type, typename line_view_type, typename vertex_view_type, typename id_tag, typename element_type_or_tag>
        struct element_range< plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag>, element_type_or_tag >
        {
            typedef typename element_tag<element_type_or_tag>::type element_tag_;
            typedef typename element_range<plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag>, element_tag_>::type type;
        };

        template<typename bounding_polygon_view_type, typename hole_polygon_view_type, typename line_view_type, typename vertex_view_type, typename id_tag, typename element_type_or_tag>
        struct const_element_range< plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag>, element_type_or_tag >
        {
            typedef typename element_tag<element_type_or_tag>::type element_tag_;
            typedef typename const_element_range<plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag>, element_tag_>::type type;
        };
    }

    template<typename element_tag>
    struct plc_elements_helper;

    template<>
    struct plc_elements_helper<vertex_tag>
    {
        template<typename bounding_polygon_view_type, typename hole_polygon_view_type, typename line_view_type, typename vertex_view_type, typename id_tag>
        static typename result_of::element_range< plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag>, vertex_tag >::type
            elements(  plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag> & plc )
        {
            return plc.get_vertices();
        }
    };

    template<>
    struct plc_elements_helper<line_tag>
    {
        template<typename bounding_polygon_view_type, typename hole_polygon_view_type, typename line_view_type, typename vertex_view_type, typename id_tag>
        static typename result_of::element_range< plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag>, line_tag >::type
            elements(  plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag> & plc )
        {
            return plc.get_lines();
        }
    };

    template<>
    struct plc_elements_helper<hole_polygon_tag>
    {
        template<typename bounding_polygon_view_type, typename hole_polygon_view_type, typename line_view_type, typename vertex_view_type, typename id_tag>
        static typename result_of::element_range< plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag>, hole_polygon_tag >::type
            elements(  plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag> & plc )
        {
            return plc.get_hole_polygons();
        }
    };

    template<typename element_type_or_tag, typename bounding_polygon_view_type, typename hole_polygon_view_type, typename line_view_type, typename vertex_view_type, typename id_tag>
    typename result_of::element_range< plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag>, element_type_or_tag >::type
        elements( plc_t<bounding_polygon_view_type, hole_polygon_view_type, line_view_type, vertex_view_type, id_tag> & plc )
    {
        typedef typename viennagrid::result_of::element_tag<element_type_or_tag>::type element_tag;
        return plc_elements_helper<element_tag>::elements(plc);
    }

}

#endif
<commit_msg>PLC is not a type anymore, element_t is used for PLCs<commit_after><|endoftext|>


<commit_before>/******************************************************************************
    nomlib.hpp

  SDL-based Game Engine Library

  Copyright (c) 2013 Jeffrey Carpenter

******************************************************************************/
#ifndef NOMLIB_HEADERS
#define NOMLIB_HEADERS

#define DEBUG_TRANSFORMABLE
//#define DEBUG_TRANSFORMABLE_OBJ

#define DEBUG_COLOR
//#define DEBUG_COLOR_OBJ

#define DEBUG_COORDS
//#define DEBUG_COORDS_OBJ

#define DEBUG_AUDIO
#define DEBUG_AUDIO_OBJ

#define DEBUG_SDL_FONT
#define DEBUG_SDL_FONT_OBJ

#define DEBUG_BITMAP_FONT
#define DEBUG_BITMAP_FONT_OBJ

#define DEBUG_GFX
#define DEBUG_GFX_OBJ

//#define DEBUG_SDL_GRADIENT
#define DEBUG_SDL_GRADIENT_OBJ

#define DEBUG_SPRITE
#define DEBUG_SPRITE_OBJ

#define DEBUG_SDL_INPUT
#define DEBUG_SDL_INPUT_OBJ

//#define DEBUG_ISTATE
#define DEBUG_ISTATE_OBJ

#define DEBUG_OSXFS
//#define DEBUG_OSXFS_OBJ

#define DEBUG_SDL_TIMER
//#define DEBUG_SDL_TIMER_OBJ

#define DEBUG_TIMER_FPS
//#define DEBUG_TIMER_FPS_OBJ

#define DEBUG_SDL_MESSAGEBOX
#define DEBUG_SDL_MESSAGEBOX_OBJ

#define DEBUG_WINDOWFRAME
#define DEBUG_WINDOWFRAME_OBJ

#define DEBUG_SDL_CURSOR
//#define DEBUG_SDL_CURSOR_OBJ

//#define DEBUG_IDRAWABLE_OBJ
//#define DEBUG_SDL_DRAWABLE_OBJ

#define DEBUG_SDL_PIXEL
//#define DEBUG_SDL_PIXEL_OBJ

#define DEBUG_SDL_LINE
//#define DEBUG_SDL_LINE_OBJ

#define DEBUG_SDL_RECT
//#define DEBUG_SDL_RECT_OBJ

#define DEBUG_FONT
#define DEBUG_FONT_OBJ

#define DEBUG_SDL_DISPLAY
#define DEBUG_SDL_DISPLAY_OBJ

#define DEBUG_SDL_CANVAS
#define DEBUG_SDL_CANVAS_OBJ

#define DEBUG_GAMESTATES
#define DEBUG_GAMESTATES_OBJ

#define DEBUG_SDL_APP
#define DEBUG_SDL_APP_OBJ

#define DEBUG_SDL_IMAGE
#define DEBUG_SDL_IMAGE_OBJ

#endif // NOMLIB_HEADERS defined
<commit_msg>Removal of un-used / abandoned DEBUG preprocessors<commit_after>/******************************************************************************
    nomlib.hpp

  SDL-based Game Engine Library

  Copyright (c) 2013 Jeffrey Carpenter

******************************************************************************/
#ifndef NOMLIB_HEADERS
#define NOMLIB_HEADERS

#define DEBUG_TRANSFORMABLE
//#define DEBUG_TRANSFORMABLE_OBJ

#define DEBUG_COLOR
//#define DEBUG_COLOR_OBJ

#define DEBUG_COORDS
//#define DEBUG_COORDS_OBJ

#define DEBUG_AUDIO
#define DEBUG_AUDIO_OBJ

#define DEBUG_SDL_FONT
#define DEBUG_SDL_FONT_OBJ

#define DEBUG_BITMAP_FONT
#define DEBUG_BITMAP_FONT_OBJ

//#define DEBUG_SDL_GRADIENT
#define DEBUG_SDL_GRADIENT_OBJ

#define DEBUG_SPRITE
#define DEBUG_SPRITE_OBJ

#define DEBUG_SDL_INPUT
#define DEBUG_SDL_INPUT_OBJ

//#define DEBUG_ISTATE
#define DEBUG_ISTATE_OBJ

#define DEBUG_OSXFS
//#define DEBUG_OSXFS_OBJ

#define DEBUG_SDL_TIMER
//#define DEBUG_SDL_TIMER_OBJ

#define DEBUG_TIMER_FPS
//#define DEBUG_TIMER_FPS_OBJ

#define DEBUG_SDL_MESSAGEBOX
#define DEBUG_SDL_MESSAGEBOX_OBJ

#define DEBUG_SDL_CURSOR
//#define DEBUG_SDL_CURSOR_OBJ

//#define DEBUG_IDRAWABLE_OBJ
//#define DEBUG_SDL_DRAWABLE_OBJ

#define DEBUG_SDL_PIXEL
//#define DEBUG_SDL_PIXEL_OBJ

#define DEBUG_SDL_LINE
//#define DEBUG_SDL_LINE_OBJ

#define DEBUG_SDL_RECT
//#define DEBUG_SDL_RECT_OBJ

#define DEBUG_FONT
#define DEBUG_FONT_OBJ

#define DEBUG_SDL_DISPLAY
#define DEBUG_SDL_DISPLAY_OBJ

#define DEBUG_SDL_CANVAS
#define DEBUG_SDL_CANVAS_OBJ

#define DEBUG_GAMESTATES
#define DEBUG_GAMESTATES_OBJ

#define DEBUG_SDL_APP
#define DEBUG_SDL_APP_OBJ

#define DEBUG_SDL_IMAGE
#define DEBUG_SDL_IMAGE_OBJ

#endif // NOMLIB_HEADERS defined
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>

using namespace std;

#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1

typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;

const double eps = 1e-6;
const ll  LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;

#define x first
#define y second

#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);

int dp[200005];
int q[200005];
int a[200005];
int g[200005];
int n;

void Init(){
	print(1);
    REP(i,1,n){scanf("%d",&(a[i]));g[i]=a[i]+i;}
    REP(i,n+1,n+n/2){a[i]=a[i-n];g[i]=a[i]+i;}
	return ;
}

void Solve(){

	q[1]=1;
    int head=1,tail=1;
    for(int i=2;i<=n+n/2;i++)
    {
        while(i-q[head]>n/2)head++;
        dp[i]=g[i]+a[q[head]]-q[head];
        while(a[i]-i>=a[q[tail]]-q[tail]&&tail>=head)tail--;
        q[++tail]=i;
    }
    int ans=0;
    for(int i=2;i<=n+n/2;i++)
        ans=max(ans,dp[i]);
    printf("%d",(ans));
	return ;
}
int main(){

	freopen("uoj8613.in","r",stdin);

	while((scanf("%d",&n))&&n)
	Init(),Solve();
	return 0;
}<commit_msg>update uoj8613<commit_after>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>

using namespace std;

#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1

typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;

const double eps = 1e-6;
const ll  LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;

#define x first
#define y second

#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);

int dp[200005];
int q[200005];
int a[200005];
int g[200005];
int n;

void Init(){

    REP(i,1,n){scanf("%d",&(a[i]));g[i]=a[i]+i;}
    REP(i,n+1,n+n/2){a[i]=a[i-n];g[i]=a[i]+i;}
	return ;
}

void Solve(){

	q[1]=1;
    int head=1,tail=1;
    REP(i,2,n+n/2)
    {
        while(i-q[head]>n/2)head++;
        dp[i]=g[i]+a[q[head]]-q[head];
        while(a[i]-i>=a[q[tail]]-q[tail]&&tail>=head)tail--;
        q[++tail]=i;
    }
    int ans=0;
    REP(i,2,n+n/2)
        ans=max(ans,dp[i]);
    printf("%d",(ans));
	return ;
}
int main(){

	freopen("uoj8613.in","r",stdin);

	while((scanf("%d",&n))&&n)
	Init(),Solve();
	return 0;
}<|endoftext|>