<commit_before>// Module:  Log4CPLUS
// File:    layout.cxx
// Created: 6/2001
// Author:  Tad E. Smith
//
//
// Copyright 2001-2010 Tad E. Smith
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <log4cplus/layout.h>
#include <log4cplus/helpers/stringhelper.h>
#include <log4cplus/helpers/timehelper.h>
#include <log4cplus/spi/loggingevent.h>
#include <log4cplus/helpers/property.h>
#include <ostream>
#include <iomanip>

namespace log4cplus
{

void
formatRelativeTimestamp (log4cplus::tostream & output,
    log4cplus::spi::InternalLoggingEvent const & event)
{
    helpers::Time const rel_time
        = event.getTimestamp () - getTTCCLayoutTimeBase ();
    tchar const old_fill = output.fill ();
    helpers::time_t const sec = rel_time.sec ();

    if (sec != 0)
        output << sec << std::setfill (LOG4CPLUS_TEXT ('0')) << std::setw (3);

    output << rel_time.usec () / 1000;
    output.fill (old_fill);
}

//
//
//

Layout::Layout ()
    : llmCache(getLogLevelManager())
{ }

Layout::Layout (const log4cplus::helpers::Properties&)
    : llmCache(getLogLevelManager())
{ }

Layout::~Layout()
{ }

///////////////////////////////////////////////////////////////////////////////
// log4cplus::SimpleLayout public methods
///////////////////////////////////////////////////////////////////////////////

SimpleLayout::SimpleLayout ()
{ }

SimpleLayout::SimpleLayout (const helpers::Properties& properties)
    : Layout (properties)
{ }

SimpleLayout::~SimpleLayout()
{ }

void
SimpleLayout::formatAndAppend(log4cplus::tostream& output,
                              const log4cplus::spi::InternalLoggingEvent& event)
{
    output << llmCache.toString(event.getLogLevel())
           << LOG4CPLUS_TEXT(" - ")
           << event.getMessage()
           << LOG4CPLUS_TEXT("\n");
}

///////////////////////////////////////////////////////////////////////////////
// log4cplus::TTCCLayout ctors and dtor
///////////////////////////////////////////////////////////////////////////////

TTCCLayout::TTCCLayout(bool use_gmtime_)
    : dateFormat( LOG4CPLUS_TEXT("%m-%d-%y %H:%M:%S,%q") )
    , use_gmtime(use_gmtime_)
{
}

TTCCLayout::TTCCLayout(const log4cplus::helpers::Properties& properties)
    : Layout(properties)
    , dateFormat (properties.getProperty (LOG4CPLUS_TEXT("DateFormat"),
        LOG4CPLUS_TEXT ("%m-%d-%y %H:%M:%S,%q")))
    , use_gmtime(false)
{
    properties.getBool (use_gmtime, LOG4CPLUS_TEXT("Use_gmtime"));
}

TTCCLayout::~TTCCLayout()
{
}

///////////////////////////////////////////////////////////////////////////////
// log4cplus::TTCCLayout public methods
///////////////////////////////////////////////////////////////////////////////

void
TTCCLayout::formatAndAppend(log4cplus::tostream& output,
                            const log4cplus::spi::InternalLoggingEvent& event)
{
     if (dateFormat.empty ())
         formatRelativeTimestamp (output, event);
     else
         output << event.getTimestamp().getFormattedTime(dateFormat,
             use_gmtime);

    output << LOG4CPLUS_TEXT(" [")
           << event.getThread()
           << LOG4CPLUS_TEXT("] ")
           << llmCache.toString(event.getLogLevel())
           << LOG4CPLUS_TEXT(" ")
           << event.getLoggerName()
           << LOG4CPLUS_TEXT(" <")
           << event.getNDC()
           << LOG4CPLUS_TEXT("> - ")
           << event.getMessage()
           << LOG4CPLUS_TEXT("\n");
}

} // namespace log4cplus
<commit_msg>layout.cxx: Fix occurence of bug #3101459 on trunk. TTCCLayout is printing formatted date instead of miliseconds since start.<commit_after>// Module:  Log4CPLUS
// File:    layout.cxx
// Created: 6/2001
// Author:  Tad E. Smith
//
//
// Copyright 2001-2010 Tad E. Smith
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <log4cplus/layout.h>
#include <log4cplus/helpers/stringhelper.h>
#include <log4cplus/helpers/timehelper.h>
#include <log4cplus/spi/loggingevent.h>
#include <log4cplus/helpers/property.h>
#include <log4cplus/internal/internal.h>
#include <ostream>
#include <iomanip>

namespace log4cplus
{

void
formatRelativeTimestamp (log4cplus::tostream & output,
    log4cplus::spi::InternalLoggingEvent const & event)
{
    helpers::Time const rel_time
        = event.getTimestamp () - getTTCCLayoutTimeBase ();
    tchar const old_fill = output.fill ();
    helpers::time_t const sec = rel_time.sec ();

    if (sec != 0)
        output << sec << std::setfill (LOG4CPLUS_TEXT ('0')) << std::setw (3);

    output << rel_time.usec () / 1000;
    output.fill (old_fill);
}

//
//
//

Layout::Layout ()
    : llmCache(getLogLevelManager())
{ }

Layout::Layout (const log4cplus::helpers::Properties&)
    : llmCache(getLogLevelManager())
{ }

Layout::~Layout()
{ }

///////////////////////////////////////////////////////////////////////////////
// log4cplus::SimpleLayout public methods
///////////////////////////////////////////////////////////////////////////////

SimpleLayout::SimpleLayout ()
{ }

SimpleLayout::SimpleLayout (const helpers::Properties& properties)
    : Layout (properties)
{ }

SimpleLayout::~SimpleLayout()
{ }

void
SimpleLayout::formatAndAppend(log4cplus::tostream& output,
                              const log4cplus::spi::InternalLoggingEvent& event)
{
    output << llmCache.toString(event.getLogLevel())
           << LOG4CPLUS_TEXT(" - ")
           << event.getMessage()
           << LOG4CPLUS_TEXT("\n");
}

///////////////////////////////////////////////////////////////////////////////
// log4cplus::TTCCLayout ctors and dtor
///////////////////////////////////////////////////////////////////////////////

TTCCLayout::TTCCLayout(bool use_gmtime_)
    : dateFormat()
    , use_gmtime(use_gmtime_)
{
}

TTCCLayout::TTCCLayout(const log4cplus::helpers::Properties& properties)
    : Layout(properties)
    , dateFormat(properties.getProperty (LOG4CPLUS_TEXT("DateFormat"),
            internal::empty_str))
    , use_gmtime(false)
{
    properties.getBool (use_gmtime, LOG4CPLUS_TEXT("Use_gmtime"));
}

TTCCLayout::~TTCCLayout()
{ }

///////////////////////////////////////////////////////////////////////////////
// log4cplus::TTCCLayout public methods
///////////////////////////////////////////////////////////////////////////////

void
TTCCLayout::formatAndAppend(log4cplus::tostream& output,
                            const log4cplus::spi::InternalLoggingEvent& event)
{
     if (dateFormat.empty ())
         formatRelativeTimestamp (output, event);
     else
         output << event.getTimestamp().getFormattedTime(dateFormat,
             use_gmtime);

    output << LOG4CPLUS_TEXT(" [")
           << event.getThread()
           << LOG4CPLUS_TEXT("] ")
           << llmCache.toString(event.getLogLevel())
           << LOG4CPLUS_TEXT(" ")
           << event.getLoggerName()
           << LOG4CPLUS_TEXT(" <")
           << event.getNDC()
           << LOG4CPLUS_TEXT("> - ")
           << event.getMessage()
           << LOG4CPLUS_TEXT("\n");
}

} // namespace log4cplus
<|endoftext|>


<commit_before>#include "core.h"
#include "chip.h"

#include "network_mesh_analytical.h"

using namespace std;

int Core::coreInit(Chip *chip, int tid, int num_mod)
{
   the_chip = chip;
   core_tid = tid;
   core_num_mod = num_mod;

   //Switch which line is commented to choose the different
   //network models
   //FIXME: Make this runtime configurable
   //NetworkModel net_model = NETWORK_BUS;
   NetworkModel net_model = NETWORK_ANALYTICAL_MESH;

   switch(net_model)
   {
       case NETWORK_BUS:
           network = new Network(this, num_mod);
           break;
       case NETWORK_ANALYTICAL_MESH:
           network = new NetworkMeshAnalytical(this, num_mod);
           break;
       case NUM_NETWORK_TYPES:
       default:
           cout << "ERROR: Unknown Network Model!";
           break;
   }

   if ( g_knob_enable_performance_modeling )
   {
      perf_model = new PerfModel("performance modeler");
      cout << "Core[" << tid << "]: instantiated performance model" << endl;
   } else
   {
      perf_model = (PerfModel *) NULL;
   }

   if ( g_knob_enable_dcache_modeling || g_knob_enable_icache_modeling )
   {
      ocache = new OCache("organic cache",
                          g_knob_cache_size.Value() * k_KILO,
                          g_knob_line_size.Value(),
                          g_knob_associativity.Value(),
                          g_knob_mutation_interval.Value(),
                          g_knob_dcache_threshold_hit.Value(),
                          g_knob_dcache_threshold_miss.Value(),
                          g_knob_dcache_size.Value() * k_KILO,
                          g_knob_dcache_associativity.Value(),
                          g_knob_dcache_max_search_depth.Value(),
                          g_knob_icache_threshold_hit.Value(),
                          g_knob_icache_threshold_miss.Value(),
                          g_knob_icache_size.Value() * k_KILO,
                          g_knob_icache_associativity.Value(),
                          g_knob_icache_max_search_depth.Value());

//       cout << "Core[" << tid << "]: instantiated organic cache model" << endl;
//       cout << ocache->statsLong() << endl;
   } else
   {
      ocache = (OCache *) NULL;
   }

   syscall_model = new SyscallMdl(network);
   sync_client = new SyncClient(this);

   return 0;
}

int Core::coreCommID() { return network->netCommID(); }

int Core::coreSendW(int sender, int receiver, char *buffer, int size)
{
   // Create a net packet
   NetPacket packet;
   packet.sender= sender;
   packet.receiver= receiver;
   packet.type = USER;
   packet.length = size;
   packet.data = buffer;

   /*
   packet.data = new char[size];
   for(int i = 0; i < size; i++)
      packet.data[i] = buffer[i];
   */

   network->netSend(packet);
   return 0;
}

int Core::coreRecvW(int sender, int receiver, char *buffer, int size)
{
   NetPacket packet;
   NetMatch match;

   match.sender = sender;
   match.sender_flag = true;
   match.type = USER;
   match.type_flag = true;

   packet = network->netRecv(match);

#ifdef DEBUG
   cout << "Got packet: "
	<< "Send=" << packet.sender
	<< ", Recv=" << packet.receiver
	<< ", Type=" << packet.type
	<< ", Len=" << packet.length << endl;
#endif

   if((unsigned)size != packet.length){
      cerr << "ERROR (comm_id: " << coreCommID() << "):" << endl
           << "Received packet length (" << packet.length
	   << ") is not as expected (" << size << ")" << endl;
      exit(-1);
   }

   for(int i = 0; i < size; i++)
      buffer[i] = packet.data[i];

   // De-allocate dynamic memory
   delete [] packet.data;

   return 0;
}

VOID Core::fini(int code, VOID *v, ofstream& out)
{
   delete network;

   if ( g_knob_enable_performance_modeling )
      perf_model->fini(code, v, out);

   if ( g_knob_enable_dcache_modeling || g_knob_enable_icache_modeling )
      ocache->fini(code,v,out);
}

void Core::setProcTime(UInt64 time)
{
  the_chip->setProcTime(core_tid, time);
}

void Core::updateProcTime(UInt64 time)
{
  if (time > getProcTime())
    setProcTime(time);
}

UInt64 Core::getProcTime()
{
  return the_chip->getProcTime(core_tid);
}
<commit_msg>[core] Output cycle count and delete members.<commit_after>#include "core.h"
#include "chip.h"

#include "network_mesh_analytical.h"

using namespace std;

int Core::coreInit(Chip *chip, int tid, int num_mod)
{
   the_chip = chip;
   core_tid = tid;
   core_num_mod = num_mod;

   //Switch which line is commented to choose the different
   //network models
   //FIXME: Make this runtime configurable
   //NetworkModel net_model = NETWORK_BUS;
   NetworkModel net_model = NETWORK_ANALYTICAL_MESH;

   switch(net_model)
   {
       case NETWORK_BUS:
           network = new Network(this, num_mod);
           break;
       case NETWORK_ANALYTICAL_MESH:
           network = new NetworkMeshAnalytical(this, num_mod);
           break;
       case NUM_NETWORK_TYPES:
       default:
           cout << "ERROR: Unknown Network Model!";
           break;
   }

   if ( g_knob_enable_performance_modeling )
   {
      perf_model = new PerfModel("performance modeler");
      cout << "Core[" << tid << "]: instantiated performance model" << endl;
   } else
   {
      perf_model = (PerfModel *) NULL;
   }

   if ( g_knob_enable_dcache_modeling || g_knob_enable_icache_modeling )
   {
      ocache = new OCache("organic cache",
                          g_knob_cache_size.Value() * k_KILO,
                          g_knob_line_size.Value(),
                          g_knob_associativity.Value(),
                          g_knob_mutation_interval.Value(),
                          g_knob_dcache_threshold_hit.Value(),
                          g_knob_dcache_threshold_miss.Value(),
                          g_knob_dcache_size.Value() * k_KILO,
                          g_knob_dcache_associativity.Value(),
                          g_knob_dcache_max_search_depth.Value(),
                          g_knob_icache_threshold_hit.Value(),
                          g_knob_icache_threshold_miss.Value(),
                          g_knob_icache_size.Value() * k_KILO,
                          g_knob_icache_associativity.Value(),
                          g_knob_icache_max_search_depth.Value());

//       cout << "Core[" << tid << "]: instantiated organic cache model" << endl;
//       cout << ocache->statsLong() << endl;
   } else
   {
      ocache = (OCache *) NULL;
   }

   syscall_model = new SyscallMdl(network);
   sync_client = new SyncClient(this);

   return 0;
}

int Core::coreCommID() { return network->netCommID(); }

int Core::coreSendW(int sender, int receiver, char *buffer, int size)
{
   // Create a net packet
   NetPacket packet;
   packet.sender= sender;
   packet.receiver= receiver;
   packet.type = USER;
   packet.length = size;
   packet.data = buffer;

   /*
   packet.data = new char[size];
   for(int i = 0; i < size; i++)
      packet.data[i] = buffer[i];
   */

   network->netSend(packet);
   return 0;
}

int Core::coreRecvW(int sender, int receiver, char *buffer, int size)
{
   NetPacket packet;
   NetMatch match;

   match.sender = sender;
   match.sender_flag = true;
   match.type = USER;
   match.type_flag = true;

   packet = network->netRecv(match);

#ifdef DEBUG
   cout << "Got packet: "
	<< "Send=" << packet.sender
	<< ", Recv=" << packet.receiver
	<< ", Type=" << packet.type
	<< ", Len=" << packet.length << endl;
#endif

   if((unsigned)size != packet.length){
      cerr << "ERROR (comm_id: " << coreCommID() << "):" << endl
           << "Received packet length (" << packet.length
	   << ") is not as expected (" << size << ")" << endl;
      exit(-1);
   }

   for(int i = 0; i < size; i++)
      buffer[i] = packet.data[i];

   // De-allocate dynamic memory
   delete [] packet.data;

   return 0;
}

VOID Core::fini(int code, VOID *v, ofstream& out)
{
   if ( g_knob_enable_performance_modeling )
     {
       out << "Total cycles: " << getProcTime() << endl;
       cout << "Total cycles: " << getProcTime() << endl; // copy to stdout (stupid)
       perf_model->fini(code, v, out);
     }

   if ( g_knob_enable_dcache_modeling || g_knob_enable_icache_modeling )
      ocache->fini(code,v,out);

   delete sync_client;
   delete syscall_model;
   delete ocache;
   delete perf_model;
   delete network;
}

void Core::setProcTime(UInt64 time)
{
  the_chip->setProcTime(core_tid, time);
}

void Core::updateProcTime(UInt64 time)
{
  if (time > getProcTime())
    setProcTime(time);
}

UInt64 Core::getProcTime()
{
  return the_chip->getProcTime(core_tid);
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestImageDAtaToUniformGrid.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// .NAME TestImageDAtaToUniformGrid.cxx --Test vtkImageDataToUniformGrid
//
// .SECTION Description
// Serial tests for converting an image data to a uniform grid with blanking.

// VTK includes
#include <vtkDataSet.h>
#include <vtkElevationFilter.h>
#include <vtkImageDataToUniformGrid.h>
#include <vtkMultiBlockDataSet.h>
#include <vtkMultiBlockDataGroupFilter.h>
#include <vtkNew.h>
#include <vtkPointDataToCellData.h>
#include <vtkRTAnalyticSource.h>
#include <vtkSphereSource.h>
#include <vtkThreshold.h>
#include <vtkUnstructuredGrid.h>

// C++ includes
#include <iostream>

namespace
{

// returns 0 for success.
int TestSingleGridBlanking(bool pointBlanking, bool reverse, int expectedNumberOfCells)
{
  vtkNew<vtkRTAnalyticSource> source;
  vtkNew<vtkElevationFilter> elevation;
  elevation->SetInputConnection(source->GetOutputPort());
  elevation->SetLowPoint(-10, 0, 0);
  elevation->SetHighPoint(10, 0, 0);
  elevation->SetScalarRange(-3, 3);
  vtkNew<vtkPointDataToCellData> pointDataToCellData;
  pointDataToCellData->SetInputConnection(elevation->GetOutputPort());
  pointDataToCellData->PassPointDataOn();

  pointDataToCellData->Update();

  vtkNew<vtkImageDataToUniformGrid> imageDataToUniformGrid;
  if(reverse)
    {
    imageDataToUniformGrid->ReverseOn();
    }
  imageDataToUniformGrid->SetInputConnection(pointDataToCellData->GetOutputPort());
  if(pointBlanking)
    {
    imageDataToUniformGrid->SetInputArrayToProcess(
      0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "Elevation");
    }
  else
    {
    imageDataToUniformGrid->SetInputArrayToProcess(
      0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, "Elevation");
    }
  imageDataToUniformGrid->Update();

  // the threshold filter is really meant to create an unstructured
  // grid. The threshold is set to include the range of RTData so that
  // the only cells that aren't outputted from the threshold filter
  // are the blanked cells.
  vtkNew<vtkThreshold> threshold;
  threshold->SetInputArrayToProcess( 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS,
                                     "RTData");
  threshold->ThresholdBetween(-1000, 1000);
  threshold->SetInputConnection(imageDataToUniformGrid->GetOutputPort());
  threshold->Update();
  vtkUnstructuredGrid* outputGrid = threshold->GetOutput();

  if(outputGrid->GetNumberOfCells() == expectedNumberOfCells)
    {
    return 0;
    }
  vtkGenericWarningMacro("Expecting " << expectedNumberOfCells << " but getting "
                         << outputGrid->GetNumberOfCells());
  return 1;
}

// returns 0 for success. only tests point blanking
int TestMultiBlockBlanking(int expectedNumberOfCells)
{
  vtkNew<vtkRTAnalyticSource> source;
  vtkNew<vtkElevationFilter> elevation;
  elevation->SetInputConnection(source->GetOutputPort());
  elevation->SetLowPoint(-10, 0, 0);
  elevation->SetHighPoint(10, 0, 0);
  elevation->SetScalarRange(-3, 3);
  vtkNew<vtkPointDataToCellData> pointDataToCellData;
  pointDataToCellData->SetInputConnection(elevation->GetOutputPort());
  pointDataToCellData->PassPointDataOn();

  vtkNew<vtkSphereSource> sphereSource;
  vtkNew<vtkMultiBlockDataGroupFilter> groupFilter;
  groupFilter->SetInputConnection(pointDataToCellData->GetOutputPort());
  groupFilter->SetInputConnection(pointDataToCellData->GetOutputPort());
  groupFilter->AddInputConnection(sphereSource->GetOutputPort());

  vtkNew<vtkImageDataToUniformGrid> imageDataToUniformGrid;
  imageDataToUniformGrid->SetInputConnection(groupFilter->GetOutputPort());
  imageDataToUniformGrid->SetInputArrayToProcess(
    0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "Elevation");
  imageDataToUniformGrid->Update();
  vtkMultiBlockDataSet* output =
    vtkMultiBlockDataSet::SafeDownCast(imageDataToUniformGrid->GetOutput());

  vtkNew<vtkThreshold> threshold;
  threshold->SetInputArrayToProcess( 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS,
                                     "RTData");
  threshold->ThresholdBetween(50, 150);
  threshold->SetInputData(output->GetBlock(0));
  threshold->Update();
  vtkUnstructuredGrid* outputGrid = threshold->GetOutput();

  if(outputGrid->GetNumberOfCells() == expectedNumberOfCells)
    {
    return 0;
    }
  vtkGenericWarningMacro("Expecting " << expectedNumberOfCells << " but getting "
                         << outputGrid->GetNumberOfCells());
  return 1;
}

} // end anonymous namespace

//------------------------------------------------------------------------------
// Program main
int TestImageDataToUniformGrid( int, char* [] )
{
  int rc = TestSingleGridBlanking(true, false, 4800);
  rc += TestSingleGridBlanking(false, false, 5600);

  rc += TestSingleGridBlanking(true, true, 2400);
  // note that this and the the second call to TestSingleGridBlanking
  // are opposites so they should add up to 8000 cells.
  rc += TestSingleGridBlanking(false, true, 2400);

  rc += TestMultiBlockBlanking(1638);

  return rc;
}
<commit_msg>Fixed a bug where negative numbers were being converted to uchar.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestImageDAtaToUniformGrid.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// .NAME TestImageDAtaToUniformGrid.cxx --Test vtkImageDataToUniformGrid
//
// .SECTION Description
// Serial tests for converting an image data to a uniform grid with blanking.

// VTK includes
#include <vtkDataSet.h>
#include <vtkElevationFilter.h>
#include <vtkImageDataToUniformGrid.h>
#include <vtkMultiBlockDataSet.h>
#include <vtkMultiBlockDataGroupFilter.h>
#include <vtkNew.h>
#include <vtkPointDataToCellData.h>
#include <vtkRTAnalyticSource.h>
#include <vtkSphereSource.h>
#include <vtkThreshold.h>
#include <vtkUnstructuredGrid.h>

// C++ includes
#include <iostream>

namespace
{

// returns 0 for success.
int TestSingleGridBlanking(bool pointBlanking, bool reverse, int expectedNumberOfCells)
{
  vtkNew<vtkRTAnalyticSource> source;
  vtkNew<vtkElevationFilter> elevation;
  elevation->SetInputConnection(source->GetOutputPort());
  elevation->SetLowPoint(-10, 0, 0);
  elevation->SetHighPoint(10, 0, 0);
  elevation->SetScalarRange(0, 3);
  vtkNew<vtkPointDataToCellData> pointDataToCellData;
  pointDataToCellData->SetInputConnection(elevation->GetOutputPort());
  pointDataToCellData->PassPointDataOn();

  pointDataToCellData->Update();

  vtkNew<vtkImageDataToUniformGrid> imageDataToUniformGrid;
  if(reverse)
    {
    imageDataToUniformGrid->ReverseOn();
    }
  imageDataToUniformGrid->SetInputConnection(pointDataToCellData->GetOutputPort());
  if(pointBlanking)
    {
    imageDataToUniformGrid->SetInputArrayToProcess(
      0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "Elevation");
    }
  else
    {
    imageDataToUniformGrid->SetInputArrayToProcess(
      0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, "Elevation");
    }
  imageDataToUniformGrid->Update();

  // the threshold filter is really meant to create an unstructured
  // grid. The threshold is set to include the range of RTData so that
  // the only cells that aren't outputted from the threshold filter
  // are the blanked cells.
  vtkNew<vtkThreshold> threshold;
  threshold->SetInputArrayToProcess( 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS,
                                     "RTData");
  threshold->ThresholdBetween(-1000, 1000);
  threshold->SetInputConnection(imageDataToUniformGrid->GetOutputPort());
  threshold->Update();
  vtkUnstructuredGrid* outputGrid = threshold->GetOutput();

  if(outputGrid->GetNumberOfCells() == expectedNumberOfCells)
    {
    return 0;
    }
  vtkGenericWarningMacro("Expecting " << expectedNumberOfCells << " but getting "
                         << outputGrid->GetNumberOfCells());
  return 1;
}

// returns 0 for success. only tests point blanking
int TestMultiBlockBlanking(int expectedNumberOfCells)
{
  vtkNew<vtkRTAnalyticSource> source;
  vtkNew<vtkElevationFilter> elevation;
  elevation->SetInputConnection(source->GetOutputPort());
  elevation->SetLowPoint(-10, 0, 0);
  elevation->SetHighPoint(10, 0, 0);
  elevation->SetScalarRange(0, 3);
  vtkNew<vtkPointDataToCellData> pointDataToCellData;
  pointDataToCellData->SetInputConnection(elevation->GetOutputPort());
  pointDataToCellData->PassPointDataOn();

  vtkNew<vtkSphereSource> sphereSource;
  vtkNew<vtkMultiBlockDataGroupFilter> groupFilter;
  groupFilter->SetInputConnection(pointDataToCellData->GetOutputPort());
  groupFilter->SetInputConnection(pointDataToCellData->GetOutputPort());
  groupFilter->AddInputConnection(sphereSource->GetOutputPort());

  vtkNew<vtkImageDataToUniformGrid> imageDataToUniformGrid;
  imageDataToUniformGrid->SetInputConnection(groupFilter->GetOutputPort());
  imageDataToUniformGrid->SetInputArrayToProcess(
    0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, "Elevation");
  imageDataToUniformGrid->Update();
  vtkMultiBlockDataSet* output =
    vtkMultiBlockDataSet::SafeDownCast(imageDataToUniformGrid->GetOutput());

  vtkNew<vtkThreshold> threshold;
  threshold->SetInputArrayToProcess( 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS,
                                     "RTData");
  threshold->ThresholdBetween(50, 150);
  threshold->SetInputData(output->GetBlock(0));
  threshold->Update();
  vtkUnstructuredGrid* outputGrid = threshold->GetOutput();

  if(outputGrid->GetNumberOfCells() == expectedNumberOfCells)
    {
    return 0;
    }
  vtkGenericWarningMacro("Expecting " << expectedNumberOfCells << " but getting "
                         << outputGrid->GetNumberOfCells());
  return 1;
}

} // end anonymous namespace

//------------------------------------------------------------------------------
// Program main
int TestImageDataToUniformGrid( int, char* [] )
{
  int rc = TestSingleGridBlanking(true, false, 5200);
  rc += TestSingleGridBlanking(false, false, 5200);

  rc += TestSingleGridBlanking(true, true, 2400);
  // note that this and the the second call to TestSingleGridBlanking
  // are opposites so they should add up to 8000 cells.
  rc += TestSingleGridBlanking(false, true, 2800);

  rc += TestMultiBlockBlanking(1102);

  return rc;
}
<|endoftext|>


<commit_before>/*==================================================================

  Program:   Visualization Toolkit
  Module:    TestHyperTreeGridBinary2D.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

===================================================================*/
// .SECTION Thanks
// This test was written by Philippe Pebay, Kitware 2012
// This work was supported in part by Commissariat a l'Energie Atomique (CEA/DIF)

#include "vtkHyperTreeGridGeometry.h"
#include "vtkHyperTreeGridSource.h"

#include "vtkCamera.h"
#include "vtkCellData.h"
#include "vtkContourFilter.h"
#include "vtkDataSetMapper.h"
#include "vtkNew.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"

int TestHyperTreeGridBinary2D( int argc, char* argv[] )
{
  // Hyper tree grid
  vtkNew<vtkHyperTreeGridSource> htGrid;
  int maxLevel = 6;
  htGrid->SetMaximumLevel( maxLevel );
  htGrid->SetGridSize( 2, 3, 1 );
  htGrid->SetGridScale( 1.5, 1., .7 );
  htGrid->SetDimension( 2 );
  htGrid->SetBranchFactor( 2 );
  htGrid->SetDescriptor( "RRRRR.|.... .R.. RRRR R... R...|.R.. ...R ..RR .R.. R... .... ....|.... ...R ..R. .... .R.. R...|.... .... .R.. ....|...." );

  // Geometry
  vtkNew<vtkHyperTreeGridGeometry> geometry;
  geometry->SetInputConnection( htGrid->GetOutputPort() );
  geometry->Update();
  vtkPolyData* pd = geometry->GetOutput();

  // Contour
  vtkNew<vtkContourFilter> contour;
  int nContours = 3;
  contour->SetNumberOfContours( nContours );
  contour->SetInputConnection( htGrid->GetOutputPort() );
  double resolution = ( maxLevel - 1 ) / ( nContours + 1. );
  double isovalue = resolution;
  for ( int i = 0; i < nContours; ++ i, isovalue += resolution )
    {
    contour->SetValue( i, isovalue );
    }

  // Mappers
  vtkMapper::SetResolveCoincidentTopologyToPolygonOffset();
  vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters( 1, 1 );
  vtkNew<vtkPolyDataMapper> mapper1;
  mapper1->SetInputConnection( geometry->GetOutputPort() );
  mapper1->SetScalarRange( pd->GetCellData()->GetScalars()->GetRange() );
  vtkNew<vtkPolyDataMapper> mapper2;
  mapper2->SetInputConnection( geometry->GetOutputPort() );
  mapper2->ScalarVisibilityOff();
  vtkNew<vtkPolyDataMapper> mapper3;
  mapper3->SetInputConnection( contour->GetOutputPort() );
  mapper3->ScalarVisibilityOff();
  vtkNew<vtkDataSetMapper> mapper4;
  mapper4->SetInputConnection( htGrid->GetOutputPort() );
  mapper4->ScalarVisibilityOff();

  // Actors
  vtkNew<vtkActor> actor1;
  actor1->SetMapper( mapper1.GetPointer() );
  vtkNew<vtkActor> actor2;
  actor2->SetMapper( mapper2.GetPointer() );
  actor2->GetProperty()->SetRepresentationToWireframe();
  actor2->GetProperty()->SetColor( .7, .7, .7 );
  vtkNew<vtkActor> actor3;
  actor3->SetMapper( mapper3.GetPointer() );
  actor3->GetProperty()->SetColor( .8, .4, .3 );
  actor3->GetProperty()->SetLineWidth( 3 );
  vtkNew<vtkActor> actor4;
  actor4->SetMapper( mapper4.GetPointer() );
  actor4->GetProperty()->SetRepresentationToWireframe();
  actor4->GetProperty()->SetColor( .0, .0, .0 );

  // Camera
  double bd[6];
  pd->GetBounds( bd );
  vtkNew<vtkCamera> camera;
  camera->SetClippingRange( 1., 100. );
  camera->SetFocalPoint( pd->GetCenter() );
  camera->SetPosition( .5 * bd[1], .5 * bd[3], 6. );

  // Renderer
  vtkNew<vtkRenderer> renderer;
  renderer->SetActiveCamera( camera.GetPointer() );
  renderer->SetBackground( 1., 1., 1. );
  renderer->AddActor( actor1.GetPointer() );
  renderer->AddActor( actor2.GetPointer() );
  renderer->AddActor( actor3.GetPointer() );
  renderer->AddActor( actor4.GetPointer() );

  // Render window
  vtkNew<vtkRenderWindow> renWin;
  renWin->AddRenderer( renderer.GetPointer() );
  renWin->SetSize( 400, 400 );
  renWin->SetMultiSamples( 0 );

  // Interactor
  vtkNew<vtkRenderWindowInteractor> iren;
  iren->SetRenderWindow( renWin.GetPointer() );

  // Render and test
  renWin->Render();

  int retVal = vtkRegressionTestImage( renWin.GetPointer() );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR )
    {
    iren->Start();
    }

  return !retVal;
}
<commit_msg>White space clean up<commit_after>/*==================================================================

  Program:   Visualization Toolkit
  Module:    TestHyperTreeGridBinary2D.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

===================================================================*/
// .SECTION Thanks
// This test was written by Philippe Pebay, Kitware 2012
// This work was supported in part by Commissariat a l'Energie Atomique (CEA/DIF)

#include "vtkHyperTreeGridGeometry.h"
#include "vtkHyperTreeGridSource.h"

#include "vtkCamera.h"
#include "vtkCellData.h"
#include "vtkContourFilter.h"
#include "vtkDataSetMapper.h"
#include "vtkNew.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"

int TestHyperTreeGridBinary2D( int argc, char* argv[] )
{
  // Hyper tree grid
  vtkNew<vtkHyperTreeGridSource> htGrid;
  int maxLevel = 6;
  htGrid->SetMaximumLevel( maxLevel );
  htGrid->SetGridSize( 2, 3, 1 );
  htGrid->SetGridScale( 1.5, 1., .7 );
  htGrid->SetDimension( 2 );
  htGrid->SetBranchFactor( 2 );
  htGrid->SetDescriptor( "RRRRR.|.... .R.. RRRR R... R...|.R.. ...R ..RR .R.. R... .... ....|.... ...R ..R. .... .R.. R...|.... .... .R.. ....|...." );

  // Geometry
  vtkNew<vtkHyperTreeGridGeometry> geometry;
  geometry->SetInputConnection( htGrid->GetOutputPort() );
  geometry->Update();
  vtkPolyData* pd = geometry->GetOutput();

  // Contour
  vtkNew<vtkContourFilter> contour;
  int nContours = 3;
  contour->SetNumberOfContours( nContours );
  contour->SetInputConnection( htGrid->GetOutputPort() );
  double resolution = ( maxLevel - 1 ) / ( nContours + 1. );
  double isovalue = resolution;
  for ( int i = 0; i < nContours; ++ i, isovalue += resolution )
    {
    contour->SetValue( i, isovalue );
    }

  // Mappers
  vtkMapper::SetResolveCoincidentTopologyToPolygonOffset();
  vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters( 1, 1 );
  vtkNew<vtkPolyDataMapper> mapper1;
  mapper1->SetInputConnection( geometry->GetOutputPort() );
  mapper1->SetScalarRange( pd->GetCellData()->GetScalars()->GetRange() );
  vtkNew<vtkPolyDataMapper> mapper2;
  mapper2->SetInputConnection( geometry->GetOutputPort() );
  mapper2->ScalarVisibilityOff();
  vtkNew<vtkPolyDataMapper> mapper3;
  mapper3->SetInputConnection( contour->GetOutputPort() );
  mapper3->ScalarVisibilityOff();
  vtkNew<vtkDataSetMapper> mapper4;
  mapper4->SetInputConnection( htGrid->GetOutputPort() );
  mapper4->ScalarVisibilityOff();

  // Actors
  vtkNew<vtkActor> actor1;
  actor1->SetMapper( mapper1.GetPointer() );
  vtkNew<vtkActor> actor2;
  actor2->SetMapper( mapper2.GetPointer() );
  actor2->GetProperty()->SetRepresentationToWireframe();
  actor2->GetProperty()->SetColor( .7, .7, .7 );
  vtkNew<vtkActor> actor3;
  actor3->SetMapper( mapper3.GetPointer() );
  actor3->GetProperty()->SetColor( .8, .4, .3 );
  actor3->GetProperty()->SetLineWidth( 3 );
  vtkNew<vtkActor> actor4;
  actor4->SetMapper( mapper4.GetPointer() );
  actor4->GetProperty()->SetRepresentationToWireframe();
  actor4->GetProperty()->SetColor( .0, .0, .0 );

  // Camera
  double bd[6];
  pd->GetBounds( bd );
  vtkNew<vtkCamera> camera;
  camera->SetClippingRange( 1., 100. );
  camera->SetFocalPoint( pd->GetCenter() );
  camera->SetPosition( .5 * bd[1], .5 * bd[3], 6. );

  // Renderer
  vtkNew<vtkRenderer> renderer;
  renderer->SetActiveCamera( camera.GetPointer() );
  renderer->SetBackground( 1., 1., 1. );
  renderer->AddActor( actor1.GetPointer() );
  renderer->AddActor( actor2.GetPointer() );
  renderer->AddActor( actor3.GetPointer() );
  renderer->AddActor( actor4.GetPointer() );

  // Render window
  vtkNew<vtkRenderWindow> renWin;
  renWin->AddRenderer( renderer.GetPointer() );
  renWin->SetSize( 400, 400 );
  renWin->SetMultiSamples( 0 );

  // Interactor
  vtkNew<vtkRenderWindowInteractor> iren;
  iren->SetRenderWindow( renWin.GetPointer() );

  // Render and test
  renWin->Render();

  int retVal = vtkRegressionTestImage( renWin.GetPointer() );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR )
    {
    iren->Start();
    }

  return !retVal;
}
<|endoftext|>


<commit_before>/*
    Copyright 2011 Google Inc.

    Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

#include "GrTypes.h"
#include "GrGLInterface.h"
#include "GrGLDefines.h"

#include <stdio.h>

GrGLInterface* gGLInterface = NULL;

void gl_version_from_string(int* major, int* minor,
                            const char* versionString) {
    if (NULL == versionString) {
        GrAssert(0);
        *major = 0;
        *minor = 0;
        return;
    }

    int n = sscanf(versionString, "%d.%d", major, minor);
    if (2 == n) {
      return;
    }

    char profile[2];
    n = sscanf(versionString, "OpenGL ES-%c%c %d.%d", profile, profile+1,
               major, minor);
    bool ok = 4 == n;
    if (!ok) {
        n = sscanf(versionString, "OpenGL ES %d.%d", major, minor);
        ok = 2 == n;
    }

    if (!ok) {
        GrAssert(0);
        *major = 0;
        *minor = 0;
        return;
    }
}

bool has_gl_extension_from_string(const char* ext,
                                  const char* extensionString) {
    int extLength = strlen(ext);

    while (true) {
        int n = strcspn(extensionString, " ");
        if (n == extLength && 0 == strncmp(ext, extensionString, n)) {
            return true;
        }
        if (0 == extensionString[n]) {
            return false;
        }
        extensionString += n+1;
    }

    return false;
}

GR_API void GrGLSetGLInterface(GrGLInterface* gl_interface) {
    gGLInterface = gl_interface;
}

GR_API GrGLInterface* GrGLGetGLInterface() {
    return gGLInterface;
}

bool has_gl_extension(const char* ext) {
    const char* glstr = reinterpret_cast<const char*>(
                GrGLGetGLInterface()->fGetString(GR_GL_EXTENSIONS));

    return has_gl_extension_from_string(ext, glstr);
}

void gl_version(int* major, int* minor) {
    const char* v = reinterpret_cast<const char*>(
                GrGLGetGLInterface()->fGetString(GR_GL_VERSION));
    gl_version_from_string(major, minor, v);
}

bool GrGLInterface::validateShaderFunctions() const {
    // required for GrGpuGLShaders
    if (NULL == fAttachShader ||
        NULL == fBindAttribLocation ||
        NULL == fCompileShader ||
        NULL == fCreateProgram ||
        NULL == fCreateShader ||
        NULL == fDeleteProgram ||
        NULL == fDeleteShader ||
        NULL == fDisableVertexAttribArray ||
        NULL == fEnableVertexAttribArray ||
        NULL == fGetProgramInfoLog ||
        NULL == fGetProgramiv ||
        NULL == fGetShaderInfoLog ||
        NULL == fGetShaderiv ||
        NULL == fGetUniformLocation ||
        NULL == fLinkProgram ||
        NULL == fShaderSource ||
        NULL == fUniform1f ||
        NULL == fUniform1i ||
        NULL == fUniform1fv ||
        NULL == fUniform1iv ||
        NULL == fUniform2f ||
        NULL == fUniform2i ||
        NULL == fUniform2fv ||
        NULL == fUniform2iv ||
        NULL == fUniform3f ||
        NULL == fUniform3i ||
        NULL == fUniform3fv ||
        NULL == fUniform3iv ||
        NULL == fUniform4f ||
        NULL == fUniform4i ||
        NULL == fUniform4fv ||
        NULL == fUniform4iv ||
        NULL == fUniformMatrix2fv ||
        NULL == fUniformMatrix3fv ||
        NULL == fUniformMatrix4fv ||
        NULL == fUseProgram ||
        NULL == fVertexAttrib4fv ||
        NULL == fVertexAttribPointer) {
        return false;
    }
    return true;
}

bool GrGLInterface::validateFixedFunctions() const {
    if (NULL == fClientActiveTexture ||
        NULL == fColor4ub ||
        NULL == fColorPointer ||
        NULL == fDisableClientState ||
        NULL == fEnableClientState ||
        NULL == fLoadMatrixf ||
        NULL == fMatrixMode ||
        NULL == fPointSize ||
        NULL == fShadeModel ||
        NULL == fTexCoordPointer ||
        NULL == fVertexPointer) {
        return false;
    }
    return true;
}

bool GrGLInterface::validate(GrEngine engine) const {

    bool isDesktop = kDesktop_GrGLBinding == fBindingsExported;

    // ES1 and 2 can be supported in the same interface
    bool isES = ((kES1_GrGLBinding | kES2_GrGLBinding) & fBindingsExported &&
                 !(~(kES1_GrGLBinding | kES2_GrGLBinding) & fBindingsExported));

    if (!isDesktop && !isES) {
        return false;
    }

    // functions that are always required
    if (NULL == fActiveTexture ||
        NULL == fBindBuffer ||
        NULL == fBindTexture ||
        NULL == fBlendFunc ||
        NULL == fBufferData ||
        NULL == fBufferSubData ||
        NULL == fClear ||
        NULL == fClearColor ||
        NULL == fClearStencil ||
        NULL == fColorMask ||
        NULL == fCullFace ||
        NULL == fDeleteBuffers ||
        NULL == fDeleteTextures ||
        NULL == fDepthMask ||
        NULL == fDisable ||
        NULL == fDrawArrays ||
        NULL == fDrawElements ||
        NULL == fEnable ||
        NULL == fFrontFace ||
        NULL == fGenBuffers ||
        NULL == fGenTextures ||
        NULL == fGetBufferParameteriv ||
        NULL == fGetError ||
        NULL == fGetIntegerv ||
        NULL == fGetString ||
        NULL == fPixelStorei ||
        NULL == fReadPixels ||
        NULL == fScissor ||
        NULL == fStencilFunc ||
        NULL == fStencilMask ||
        NULL == fStencilOp ||
        NULL == fTexEnvi ||
        NULL == fTexImage2D ||
        NULL == fTexParameteri ||
        NULL == fTexSubImage2D ||
        NULL == fViewport ||
        NULL == fBindFramebuffer ||
        NULL == fBindRenderbuffer ||
        NULL == fCheckFramebufferStatus ||
        NULL == fDeleteFramebuffers ||
        NULL == fDeleteRenderbuffers ||
        NULL == fFramebufferRenderbuffer ||
        NULL == fFramebufferTexture2D ||
        NULL == fGenFramebuffers ||
        NULL == fGenRenderbuffers ||
        NULL == fRenderbufferStorage) {
        return false;
    }

    switch (engine) {
        case kOpenGL_Shaders_GrEngine:
            if (kES1_GrGLBinding == fBindingsExported) {
                return false;
            }
            if (!this->validateShaderFunctions()) {
                return false;
            }
            break;
        case kOpenGL_Fixed_GrEngine:
            if (kES1_GrGLBinding == fBindingsExported) {
                return false;
            }
            if (!this->validateFixedFunctions()) {
                return false;
            }
            break;
        default:
            return false;
    }

    int major, minor;
    const char* ext;

    gl_version(&major, &minor);
    ext = (const char*)fGetString(GR_GL_EXTENSIONS);

    // Now check that baseline ES/Desktop fns not covered above are present
    // and that we have fn pointers for any advertised extensions that we will
    // try to use.

    // these functions are part of ES2, we assume they are available
    // On the desktop we assume they are available if the extension
    // is present or GL version is high enough.
    if ((kES2_GrGLBinding & fBindingsExported)) {
        if (NULL == fBlendColor ||
            NULL == fStencilFuncSeparate ||
            NULL == fStencilMaskSeparate ||
            NULL == fStencilOpSeparate) {
            return false;
        }
    } else if (kDesktop_GrGLBinding == fBindingsExported) {
        if (major >= 2) {
            if (NULL == fStencilFuncSeparate ||
                NULL == fStencilMaskSeparate ||
                NULL == fStencilOpSeparate) {
                return false;
            }
        }
        if (1 < major || (1 == major && 4 <= minor) ||
            has_gl_extension_from_string("GL_EXT_blend_color", ext)) {
            if (NULL == fBlendColor) {
                return false;
            }
        }
    }

    // optional function on desktop before 1.3
    if (kDesktop_GrGLBinding != fBindingsExported ||
        (1 < major || (1 == major && 3 <= minor)) ||
        has_gl_extension_from_string("GL_ARB_texture_compression", ext)) {
        if (NULL == fCompressedTexImage2D) {
            return false;
        }
    }

    // part of desktop GL
    if (kDesktop_GrGLBinding == fBindingsExported &&
        NULL == fLineWidth) {
        return false;
    }
    // FBO MSAA
    if (kDesktop_GrGLBinding == fBindingsExported) {
        // GL 3.0 and the ARB extension have multisample + blit
        if ((major >= 3) || has_gl_extension_from_string("GL_ARB_framebuffer_object", ext)) {
            if (NULL == fRenderbufferStorageMultisample ||
                NULL == fBlitFramebuffer) {
                return false;
            }
        } else {
            if (has_gl_extension_from_string("GL_EXT_framebuffer_blit", ext) &&
                NULL == fBlitFramebuffer) {
                return false;
            }
            if (has_gl_extension_from_string("GL_EXT_framebuffer_multisample", ext) &&
                NULL == fRenderbufferStorageMultisample) {
                return false;
            }
        }
    } else {
        if (has_gl_extension_from_string("GL_CHROMIUM_framebuffer_multisample", ext)) {
            if (NULL == fRenderbufferStorageMultisample ||
                NULL == fBlitFramebuffer) {
                return false;
            }
        }
        if (has_gl_extension_from_string("GL_APPLE_framebuffer_multisample", ext)) {
            if (NULL == fRenderbufferStorageMultisample ||
                NULL == fResolveMultisampleFramebuffer) {
                return false;
            }
        }
    }

    // On ES buffer mapping is an extension. On Desktop
    // buffer mapping was part of original VBO extension
    // which we require.
    if (kDesktop_GrGLBinding == fBindingsExported  ||
        has_gl_extension_from_string("GL_OES_mapbuffer", ext)) {
        if (NULL == fMapBuffer ||
            NULL == fUnmapBuffer) {
            return false;
        }
    }

    return true;
}

<commit_msg>Fix validation (glTexEnvi is fixed pipe only)<commit_after>/*
    Copyright 2011 Google Inc.

    Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

#include "GrTypes.h"
#include "GrGLInterface.h"
#include "GrGLDefines.h"

#include <stdio.h>

GrGLInterface* gGLInterface = NULL;

void gl_version_from_string(int* major, int* minor,
                            const char* versionString) {
    if (NULL == versionString) {
        GrAssert(0);
        *major = 0;
        *minor = 0;
        return;
    }

    int n = sscanf(versionString, "%d.%d", major, minor);
    if (2 == n) {
      return;
    }

    char profile[2];
    n = sscanf(versionString, "OpenGL ES-%c%c %d.%d", profile, profile+1,
               major, minor);
    bool ok = 4 == n;
    if (!ok) {
        n = sscanf(versionString, "OpenGL ES %d.%d", major, minor);
        ok = 2 == n;
    }

    if (!ok) {
        GrAssert(0);
        *major = 0;
        *minor = 0;
        return;
    }
}

bool has_gl_extension_from_string(const char* ext,
                                  const char* extensionString) {
    int extLength = strlen(ext);

    while (true) {
        int n = strcspn(extensionString, " ");
        if (n == extLength && 0 == strncmp(ext, extensionString, n)) {
            return true;
        }
        if (0 == extensionString[n]) {
            return false;
        }
        extensionString += n+1;
    }

    return false;
}

GR_API void GrGLSetGLInterface(GrGLInterface* gl_interface) {
    gGLInterface = gl_interface;
}

GR_API GrGLInterface* GrGLGetGLInterface() {
    return gGLInterface;
}

bool has_gl_extension(const char* ext) {
    const char* glstr = reinterpret_cast<const char*>(
                GrGLGetGLInterface()->fGetString(GR_GL_EXTENSIONS));

    return has_gl_extension_from_string(ext, glstr);
}

void gl_version(int* major, int* minor) {
    const char* v = reinterpret_cast<const char*>(
                GrGLGetGLInterface()->fGetString(GR_GL_VERSION));
    gl_version_from_string(major, minor, v);
}

bool GrGLInterface::validateShaderFunctions() const {
    // required for GrGpuGLShaders
    if (NULL == fAttachShader ||
        NULL == fBindAttribLocation ||
        NULL == fCompileShader ||
        NULL == fCreateProgram ||
        NULL == fCreateShader ||
        NULL == fDeleteProgram ||
        NULL == fDeleteShader ||
        NULL == fDisableVertexAttribArray ||
        NULL == fEnableVertexAttribArray ||
        NULL == fGetProgramInfoLog ||
        NULL == fGetProgramiv ||
        NULL == fGetShaderInfoLog ||
        NULL == fGetShaderiv ||
        NULL == fGetUniformLocation ||
        NULL == fLinkProgram ||
        NULL == fShaderSource ||
        NULL == fUniform1f ||
        NULL == fUniform1i ||
        NULL == fUniform1fv ||
        NULL == fUniform1iv ||
        NULL == fUniform2f ||
        NULL == fUniform2i ||
        NULL == fUniform2fv ||
        NULL == fUniform2iv ||
        NULL == fUniform3f ||
        NULL == fUniform3i ||
        NULL == fUniform3fv ||
        NULL == fUniform3iv ||
        NULL == fUniform4f ||
        NULL == fUniform4i ||
        NULL == fUniform4fv ||
        NULL == fUniform4iv ||
        NULL == fUniformMatrix2fv ||
        NULL == fUniformMatrix3fv ||
        NULL == fUniformMatrix4fv ||
        NULL == fUseProgram ||
        NULL == fVertexAttrib4fv ||
        NULL == fVertexAttribPointer) {
        return false;
    }
    return true;
}

bool GrGLInterface::validateFixedFunctions() const {
    if (NULL == fClientActiveTexture ||
        NULL == fColor4ub ||
        NULL == fColorPointer ||
        NULL == fDisableClientState ||
        NULL == fEnableClientState ||
        NULL == fLoadMatrixf ||
        NULL == fMatrixMode ||
        NULL == fPointSize ||
        NULL == fShadeModel ||
        NULL == fTexCoordPointer ||
        NULL == fTexEnvi ||
        NULL == fVertexPointer) {
        return false;
    }
    return true;
}

bool GrGLInterface::validate(GrEngine engine) const {

    bool isDesktop = kDesktop_GrGLBinding == fBindingsExported;

    // ES1 and 2 can be supported in the same interface
    bool isES = ((kES1_GrGLBinding | kES2_GrGLBinding) & fBindingsExported &&
                 !(~(kES1_GrGLBinding | kES2_GrGLBinding) & fBindingsExported));

    if (!isDesktop && !isES) {
        return false;
    }

    // functions that are always required
    if (NULL == fActiveTexture ||
        NULL == fBindBuffer ||
        NULL == fBindTexture ||
        NULL == fBlendFunc ||
        NULL == fBufferData ||
        NULL == fBufferSubData ||
        NULL == fClear ||
        NULL == fClearColor ||
        NULL == fClearStencil ||
        NULL == fColorMask ||
        NULL == fCullFace ||
        NULL == fDeleteBuffers ||
        NULL == fDeleteTextures ||
        NULL == fDepthMask ||
        NULL == fDisable ||
        NULL == fDrawArrays ||
        NULL == fDrawElements ||
        NULL == fEnable ||
        NULL == fFrontFace ||
        NULL == fGenBuffers ||
        NULL == fGenTextures ||
        NULL == fGetBufferParameteriv ||
        NULL == fGetError ||
        NULL == fGetIntegerv ||
        NULL == fGetString ||
        NULL == fPixelStorei ||
        NULL == fReadPixels ||
        NULL == fScissor ||
        NULL == fStencilFunc ||
        NULL == fStencilMask ||
        NULL == fStencilOp ||
        NULL == fTexImage2D ||
        NULL == fTexParameteri ||
        NULL == fTexSubImage2D ||
        NULL == fViewport ||
        NULL == fBindFramebuffer ||
        NULL == fBindRenderbuffer ||
        NULL == fCheckFramebufferStatus ||
        NULL == fDeleteFramebuffers ||
        NULL == fDeleteRenderbuffers ||
        NULL == fFramebufferRenderbuffer ||
        NULL == fFramebufferTexture2D ||
        NULL == fGenFramebuffers ||
        NULL == fGenRenderbuffers ||
        NULL == fRenderbufferStorage) {
        return false;
    }

    switch (engine) {
        case kOpenGL_Shaders_GrEngine:
            if (kES1_GrGLBinding == fBindingsExported) {
                return false;
            }
            if (!this->validateShaderFunctions()) {
                return false;
            }
            break;
        case kOpenGL_Fixed_GrEngine:
            if (kES1_GrGLBinding == fBindingsExported) {
                return false;
            }
            if (!this->validateFixedFunctions()) {
                return false;
            }
            break;
        default:
            return false;
    }

    int major, minor;
    const char* ext;

    gl_version(&major, &minor);
    ext = (const char*)fGetString(GR_GL_EXTENSIONS);

    // Now check that baseline ES/Desktop fns not covered above are present
    // and that we have fn pointers for any advertised extensions that we will
    // try to use.

    // these functions are part of ES2, we assume they are available
    // On the desktop we assume they are available if the extension
    // is present or GL version is high enough.
    if ((kES2_GrGLBinding & fBindingsExported)) {
        if (NULL == fBlendColor ||
            NULL == fStencilFuncSeparate ||
            NULL == fStencilMaskSeparate ||
            NULL == fStencilOpSeparate) {
            return false;
        }
    } else if (kDesktop_GrGLBinding == fBindingsExported) {
        if (major >= 2) {
            if (NULL == fStencilFuncSeparate ||
                NULL == fStencilMaskSeparate ||
                NULL == fStencilOpSeparate) {
                return false;
            }
        }
        if (1 < major || (1 == major && 4 <= minor) ||
            has_gl_extension_from_string("GL_EXT_blend_color", ext)) {
            if (NULL == fBlendColor) {
                return false;
            }
        }
    }

    // optional function on desktop before 1.3
    if (kDesktop_GrGLBinding != fBindingsExported ||
        (1 < major || (1 == major && 3 <= minor)) ||
        has_gl_extension_from_string("GL_ARB_texture_compression", ext)) {
        if (NULL == fCompressedTexImage2D) {
            return false;
        }
    }

    // part of desktop GL
    if (kDesktop_GrGLBinding == fBindingsExported &&
        NULL == fLineWidth) {
        return false;
    }
    // FBO MSAA
    if (kDesktop_GrGLBinding == fBindingsExported) {
        // GL 3.0 and the ARB extension have multisample + blit
        if ((major >= 3) || has_gl_extension_from_string("GL_ARB_framebuffer_object", ext)) {
            if (NULL == fRenderbufferStorageMultisample ||
                NULL == fBlitFramebuffer) {
                return false;
            }
        } else {
            if (has_gl_extension_from_string("GL_EXT_framebuffer_blit", ext) &&
                NULL == fBlitFramebuffer) {
                return false;
            }
            if (has_gl_extension_from_string("GL_EXT_framebuffer_multisample", ext) &&
                NULL == fRenderbufferStorageMultisample) {
                return false;
            }
        }
    } else {
        if (has_gl_extension_from_string("GL_CHROMIUM_framebuffer_multisample", ext)) {
            if (NULL == fRenderbufferStorageMultisample ||
                NULL == fBlitFramebuffer) {
                return false;
            }
        }
        if (has_gl_extension_from_string("GL_APPLE_framebuffer_multisample", ext)) {
            if (NULL == fRenderbufferStorageMultisample ||
                NULL == fResolveMultisampleFramebuffer) {
                return false;
            }
        }
    }

    // On ES buffer mapping is an extension. On Desktop
    // buffer mapping was part of original VBO extension
    // which we require.
    if (kDesktop_GrGLBinding == fBindingsExported  ||
        has_gl_extension_from_string("GL_OES_mapbuffer", ext)) {
        if (NULL == fMapBuffer ||
            NULL == fUnmapBuffer) {
            return false;
        }
    }

    return true;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 * REALM CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2012] Realm Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Realm Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Realm Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Realm Incorporated.
 *
 **************************************************************************/
#ifndef REALM_COLUMN_FWD_HPP
#define REALM_COLUMN_FWD_HPP

#include <cstdint>

namespace realm {

// Regular classes
class ColumnBase;
class StringColumn;
class StringEnumColumn;
class BinaryColumn;
class SubtableColumn;
class MixedColumn;
class LinkColumn;
class LinkListColumn;

// Templated classes
template <class T, bool Nullable = false> class Column;
template<class T> class BasicColumn;

// Shortcuts, aka typedefs.
using IntegerColumn = Column<std::int64_t, false>;
using IntNullColumn = Column<std::int64_t, true>;
using DoubleColumn = BasicColumn<double>;
using FloatColumn = BasicColumn<float>;

} // namespace realm

#endif // REALM_COLUMN_FWD_HPP
<commit_msg>std::int* -> int*<commit_after>/*************************************************************************
 *
 * REALM CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2012] Realm Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Realm Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Realm Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Realm Incorporated.
 *
 **************************************************************************/
#ifndef REALM_COLUMN_FWD_HPP
#define REALM_COLUMN_FWD_HPP

#include <cstdint>

namespace realm {

// Regular classes
class ColumnBase;
class StringColumn;
class StringEnumColumn;
class BinaryColumn;
class SubtableColumn;
class MixedColumn;
class LinkColumn;
class LinkListColumn;

// Templated classes
template <class T, bool Nullable = false> class Column;
template<class T> class BasicColumn;

// Shortcuts, aka typedefs.
using IntegerColumn = Column<int64_t, false>;
using IntNullColumn = Column<int64_t, true>;
using DoubleColumn = BasicColumn<double>;
using FloatColumn = BasicColumn<float>;

} // namespace realm

#endif // REALM_COLUMN_FWD_HPP
<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012   Torsten Rahn      <tackat@kde.org>
// Copyright 2012   Mohammed Nafees   <nafees.technocool@gmail.com>
// Copyright 2012   Dennis Nienhüser  <earthwings@gentoo.org>
// Copyright 2012   Illya Kovalevskyy <illya.kovalevskyy@gmail.com>
//

#include "PopupItem.h"
#include "MarbleWidget.h"

#include <QtWebKit/QWebView>
#include <QtGui/QMouseEvent>
#include <QtGui/QApplication>
#include <QtGui/QVBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QPixmapCache>
#include <qdrawutil.h>

namespace Marble
{

PopupItem::PopupItem( QObject* parent ) :
    QObject( parent ),
    BillboardGraphicsItem(),
    m_widget( new QWidget ),
    m_webView( new QWebView ( m_widget ) ),
    m_textColor( QColor(Qt::black) ),
    m_backColor( QColor(Qt::white) ),
    m_needMouseRelease(false)
{
    setVisible( false );

    QGridLayout *childLayout = new QGridLayout;
    m_titleText = new QLabel( m_widget );
    childLayout->addWidget( m_titleText, 0, 0 );
    QPushButton *hideButton = new QPushButton( m_widget );
    hideButton->setIcon( QIcon( ":/marble/webpopup/icon-remove.png" ) );
    hideButton->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
    hideButton->setCursor( QCursor( Qt::PointingHandCursor ) );
    hideButton->setFlat( true );
    childLayout->addWidget( hideButton, 0, 1 );
    QVBoxLayout *layout = new QVBoxLayout( m_widget );
    layout->addLayout( childLayout );
    layout->addWidget( m_webView );
    m_widget->setLayout( layout );
    m_widget->setAttribute( Qt::WA_NoSystemBackground, true );
    QPalette palette = m_webView->palette();
    palette.setBrush(QPalette::Base, Qt::transparent);
    m_webView->setPalette(palette);
    m_webView->page()->setPalette(palette);
    m_webView->setAttribute(Qt::WA_OpaquePaintEvent, false);

    connect( m_webView, SIGNAL(titleChanged(QString)), m_titleText, SLOT(setText(QString)) );
    connect( hideButton, SIGNAL(clicked()), this, SIGNAL(hide()) );
}

PopupItem::~PopupItem()
{
    delete m_widget;
}

void PopupItem::setUrl( const QUrl &url )
{
    if ( m_webView ) {
        m_webView->setUrl( url );
        setVisible( true );

	QPalette palette = m_webView->palette();
	palette.setBrush(QPalette::Base, Qt::transparent);
	m_webView->setPalette(palette);
	m_webView->page()->setPalette(palette);
	m_webView->setAttribute(Qt::WA_OpaquePaintEvent, false);

        emit dirty();
    }
}

void PopupItem::setContent( const QString &html )
{
    m_content = html;
    m_webView->setHtml(html);
}

void PopupItem::setTextColor(const QColor &color)
{
    if(color.isValid() && m_titleText != 0) {
        m_textColor = color;
        QPalette palette(m_titleText->palette());
        palette.setColor(QPalette::WindowText, m_textColor);
        m_titleText->setPalette(palette);
    }
}
void PopupItem::setBackgroundColor(const QColor &color)
{
    if(color.isValid()) {
        m_backColor = color;
        QPixmapCache::remove( "marble/webpopup/webpopup2" );
        QPixmapCache::remove( "marble/webpopup/arrow2_topleft" );
        QPixmapCache::remove( "marble/webpopup/arrow2_bottomleft" );
        QPixmapCache::remove( "marble/webpopup/arrow2_topright" );
        QPixmapCache::remove( "marble/webpopup/arrow2_bottomright" );
    }
}

void PopupItem::colorize( QImage &img, const QColor &col )
{
    if (img.depth() <= 8) return;
    int pixels = img.width()*img.height();
    unsigned int *data = (unsigned int *) img.bits();
    for (int i=0; i < pixels; ++i) {
        int val = qGray(data[i]);
        data[i] = qRgba(col.red()*val/255,col.green()*val/255, col.blue()*val/255, qAlpha(data[i]));
    }
}

void PopupItem::paint( QPainter *painter )
{
    QRect popupRect;
    QPixmap image = pixmap("marble/webpopup/arrow2_vertical_topright");

    if ( alignment() & Qt::AlignRight ) {
        popupRect.setRect( image.width() - 13, -10,
                           size().width() - ( image.width() - 23 ),
                           size().height() + 20 );
        qDrawBorderPixmap(painter, popupRect, QMargins( 20, 20, 20, 20 ),
                          pixmap("marble/webpopup/webpopup2"));
        if ( alignment() & Qt::AlignTop ) {
            image = pixmap("marble/webpopup/arrow2_bottomleft");
            painter->drawPixmap( 0, size().height() - image.height(), image );
        } else if ( alignment() & Qt::AlignBottom ) {
            image = pixmap("marble/webpopup/arrow2_topleft");
            painter->drawPixmap( 0, 0, image );
        } else { // for no horizontal align value and Qt::AlignVCenter
            image = pixmap("marble/webpopup/arrow2_topleft");
            painter->drawPixmap( 0, size().height() / 2, image );
        }
        m_widget->render( painter, QPoint( image.width() - 3, 0 ), QRegion() );
    } else if ( alignment() & Qt::AlignLeft ) {
        popupRect.setRect( -10, -10,
                           size().width() - ( image.width() - 23 ),
                           size().height() + 20 );
        qDrawBorderPixmap(painter, popupRect, QMargins( 20, 20, 20, 20 ),
                          pixmap("marble/webpopup/webpopup2"));
        if ( alignment() & Qt::AlignTop ) {
            image = pixmap("marble/webpopup/arrow2_bottomright");
            painter->drawPixmap( size().width() - image.width(),
                                 size().height() - image.height(), image );
        } else if ( alignment() & Qt::AlignBottom ) {
            image = pixmap("marble/webpopup/arrow2_topright");
            painter->drawPixmap( size().width() - image.width(),
                                 0, image );
        } else { // for no horizontal align value and Qt::AlignVCenter
            image = pixmap("marble/webpopup/arrow2_topright");
            painter->drawPixmap( size().width() - image.width(),
                                 size().height() / 2 - image.height() / 2 + 23, image );
        }
        m_widget->render( painter, QPoint( 5, 0 ), QRegion() );
    } else if ( alignment() & Qt::AlignHCenter )
    {
        if ( alignment() & Qt::AlignTop )
        {
            image = pixmap("marble/webpopup/arrow2_vertical_bottomright");
            popupRect.setRect( -10, -10, size().width() + 20,
                               size().height() - image.height() + 23 );
            qDrawBorderPixmap(painter, popupRect, QMargins( 20, 20, 20, 20 ),
                              pixmap("marble/webpopup/webpopup2"));
            painter->drawPixmap( size().width() / 2 - image.width(),
                                 size().height() - image.height(), image );
            m_widget->render( painter, QPoint( 0, 0 ), QRegion() );
        } else if ( alignment() & Qt::AlignBottom ) {
            image = pixmap("marble/webpopup/arrow2_vertical_topleft");
            popupRect.setRect( -10, image.height() - 13, size().width() + 20,
                               size().height() - image.height() + 23 );
            qDrawBorderPixmap(painter, popupRect, QMargins( 20, 20, 20, 20 ),
                              pixmap("marble/webpopup/webpopup2"));
            painter->drawPixmap( size().width() / 2, 0, image );
            m_widget->render( painter, QPoint( 5, image.height() - 7 ), QRegion() );
        } else { // for no horizontal align value and Qt::AlignVCenter
            popupRect.setRect( -10, -10, size().width() + 20,
                               size().height() + 20 );
            qDrawBorderPixmap(painter, popupRect, QMargins( 20, 20, 20, 20 ),
                              pixmap("marble/webpopup/webpopup2"));
            m_widget->render( painter, QPoint( 0, 0 ), QRegion() );
        }
    }
    m_widget->setFixedSize( popupRect.width() - 20,
                            popupRect.height() - 20 );
}

bool PopupItem::eventFilter( QObject *object, QEvent *e )
{
    MarbleWidget *widget = dynamic_cast<MarbleWidget*> ( object );
    if ( !widget ) {
        return BillboardGraphicsItem::eventFilter( object, e );
    }

    if ( e->type() == QEvent::MouseButtonDblClick
            || e->type() == QEvent::MouseMove
            || e->type() == QEvent::MouseButtonPress
            || e->type() == QEvent::MouseButtonRelease )
    {
        // Mouse events are forwarded to the underlying widget
        QMouseEvent *event = static_cast<QMouseEvent*> ( e );
        QPoint shiftedPos = event->pos();
        QWidget* child = transform( shiftedPos );
        bool const forcedMouseRelease = m_needMouseRelease && e->type() == QEvent::MouseButtonRelease;
        if ( child || forcedMouseRelease ) {
            if ( !m_needMouseRelease && e->type() == QEvent::MouseButtonPress ) {
                m_needMouseRelease = true;
            } else if ( forcedMouseRelease ) {
                m_needMouseRelease = false;
            }
            if ( !child ) {
                child = m_webView;
            }
            widget->setCursor( Qt::ArrowCursor );
            QMouseEvent shiftedEvent = QMouseEvent( e->type(), shiftedPos,
                                                    event->globalPos(), event->button(), event->buttons(),
                                                    event->modifiers() );
            if ( QApplication::sendEvent( child, &shiftedEvent ) ) {
                widget->setCursor( child->cursor() );
                emit dirty();
                return true;
            }
        }
    } else if ( e->type() == QEvent::Wheel ) {
        // Wheel events are forwarded to the underlying widget
        QWheelEvent *event = static_cast<QWheelEvent*> ( e );
        QPoint shiftedPos = event->pos();
        QWidget* child = transform( shiftedPos );
        if ( child ) {
            widget->setCursor( Qt::ArrowCursor );
            QWheelEvent shiftedEvent = QWheelEvent( shiftedPos,
                                                    event->globalPos(), event->delta(), event->buttons(),
                                                    event->modifiers() );
            if ( QApplication::sendEvent( child, &shiftedEvent ) ) {
                widget->setCursor( child->cursor() );
                emit dirty();
                return true;
            }
        }
    }

    return BillboardGraphicsItem::eventFilter( object, e );
}

QWidget* PopupItem::transform( QPoint &point ) const
{
    /*
     * Fixes for mouse events to trigger when the web popup
     * is shifted in accordance with the horizontal alignment
     */
    if ( alignment() & Qt::AlignRight )
        point -= QPoint( 117, 0 );
    else if ( alignment() & Qt::AlignLeft )
        point -= QPoint( 5, 0 );
    else if ( alignment() & Qt::AlignHCenter )
    {
        if ( alignment() & Qt::AlignTop )
        {
            point -= QPoint( 0, 0 );
        } else if ( alignment() & Qt::AlignBottom )
        {
            point-= QPoint( 5, 57 );
        } else {
            point -= QPoint( 0, 0 );
        }
    }

    QList<QPointF> widgetPositions = positions();
    QList<QPointF>::const_iterator it = widgetPositions.constBegin();
    for( ; it != widgetPositions.constEnd(); ++it ) {
        if ( QRectF( *it, size() ).contains( point ) ) {
            point -= it->toPoint();
            QWidget* child = m_widget->childAt( point );
            if ( child ) {
                point -= child->pos();
            }
            return child;
        }
    }
    return 0;
}

QPixmap PopupItem::pixmap( const QString &imageId )
{
  QPixmap result;
  if ( !QPixmapCache::find( imageId, result ) ) {
    QImage bottom = QImage( QString( ":/%1_shadow.png" ).arg( imageId) );
    QImage top = QImage( QString( ":/%1.png" ).arg( imageId) );
    colorize( top, m_backColor );
    QPainter painter( &bottom );
    painter.drawImage( QPoint(0,0), top );

    result = QPixmap::fromImage( bottom );
    QPixmapCache::insert( imageId, result );
  }

  return result;
}

}

#include "PopupItem.moc"
<commit_msg>Restrict width (fixes alignment)<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012   Torsten Rahn      <tackat@kde.org>
// Copyright 2012   Mohammed Nafees   <nafees.technocool@gmail.com>
// Copyright 2012   Dennis Nienhüser  <earthwings@gentoo.org>
// Copyright 2012   Illya Kovalevskyy <illya.kovalevskyy@gmail.com>
//

#include "PopupItem.h"
#include "MarbleWidget.h"

#include <QtWebKit/QWebView>
#include <QtGui/QMouseEvent>
#include <QtGui/QApplication>
#include <QtGui/QVBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QPixmapCache>
#include <qdrawutil.h>

namespace Marble
{

PopupItem::PopupItem( QObject* parent ) :
    QObject( parent ),
    BillboardGraphicsItem(),
    m_widget( new QWidget ),
    m_webView( new QWebView ( m_widget ) ),
    m_textColor( QColor(Qt::black) ),
    m_backColor( QColor(Qt::white) ),
    m_needMouseRelease(false)
{
    setVisible( false );

    QGridLayout *childLayout = new QGridLayout;
    m_titleText = new QLabel( m_widget );
    childLayout->addWidget( m_titleText, 0, 0 );
    QPushButton *hideButton = new QPushButton( m_widget );
    hideButton->setIcon( QIcon( ":/marble/webpopup/icon-remove.png" ) );
    hideButton->setMaximumWidth( 24 );
    hideButton->setCursor( QCursor( Qt::PointingHandCursor ) );
    hideButton->setFlat( true );
    childLayout->addWidget( hideButton, 0, 1 );
    QVBoxLayout *layout = new QVBoxLayout( m_widget );
    layout->addLayout( childLayout );
    layout->addWidget( m_webView );
    m_widget->setLayout( layout );
    m_widget->setAttribute( Qt::WA_NoSystemBackground, true );
    QPalette palette = m_webView->palette();
    palette.setBrush(QPalette::Base, Qt::transparent);
    m_webView->setPalette(palette);
    m_webView->page()->setPalette(palette);
    m_webView->setAttribute(Qt::WA_OpaquePaintEvent, false);

    connect( m_webView, SIGNAL(titleChanged(QString)), m_titleText, SLOT(setText(QString)) );
    connect( hideButton, SIGNAL(clicked()), this, SIGNAL(hide()) );
}

PopupItem::~PopupItem()
{
    delete m_widget;
}

void PopupItem::setUrl( const QUrl &url )
{
    if ( m_webView ) {
        m_webView->setUrl( url );
        setVisible( true );

	QPalette palette = m_webView->palette();
	palette.setBrush(QPalette::Base, Qt::transparent);
	m_webView->setPalette(palette);
	m_webView->page()->setPalette(palette);
	m_webView->setAttribute(Qt::WA_OpaquePaintEvent, false);

        emit dirty();
    }
}

void PopupItem::setContent( const QString &html )
{
    m_content = html;
    m_webView->setHtml(html);
}

void PopupItem::setTextColor(const QColor &color)
{
    if(color.isValid() && m_titleText != 0) {
        m_textColor = color;
        QPalette palette(m_titleText->palette());
        palette.setColor(QPalette::WindowText, m_textColor);
        m_titleText->setPalette(palette);
    }
}
void PopupItem::setBackgroundColor(const QColor &color)
{
    if(color.isValid()) {
        m_backColor = color;
        QPixmapCache::remove( "marble/webpopup/webpopup2" );
        QPixmapCache::remove( "marble/webpopup/arrow2_topleft" );
        QPixmapCache::remove( "marble/webpopup/arrow2_bottomleft" );
        QPixmapCache::remove( "marble/webpopup/arrow2_topright" );
        QPixmapCache::remove( "marble/webpopup/arrow2_bottomright" );
    }
}

void PopupItem::colorize( QImage &img, const QColor &col )
{
    if (img.depth() <= 8) return;
    int pixels = img.width()*img.height();
    unsigned int *data = (unsigned int *) img.bits();
    for (int i=0; i < pixels; ++i) {
        int val = qGray(data[i]);
        data[i] = qRgba(col.red()*val/255,col.green()*val/255, col.blue()*val/255, qAlpha(data[i]));
    }
}

void PopupItem::paint( QPainter *painter )
{
    QRect popupRect;
    QPixmap image = pixmap("marble/webpopup/arrow2_vertical_topright");

    if ( alignment() & Qt::AlignRight ) {
        popupRect.setRect( image.width() - 13, -10,
                           size().width() - ( image.width() - 23 ),
                           size().height() + 20 );
        qDrawBorderPixmap(painter, popupRect, QMargins( 20, 20, 20, 20 ),
                          pixmap("marble/webpopup/webpopup2"));
        if ( alignment() & Qt::AlignTop ) {
            image = pixmap("marble/webpopup/arrow2_bottomleft");
            painter->drawPixmap( 0, size().height() - image.height(), image );
        } else if ( alignment() & Qt::AlignBottom ) {
            image = pixmap("marble/webpopup/arrow2_topleft");
            painter->drawPixmap( 0, 0, image );
        } else { // for no horizontal align value and Qt::AlignVCenter
            image = pixmap("marble/webpopup/arrow2_topleft");
            painter->drawPixmap( 0, size().height() / 2, image );
        }
        m_widget->render( painter, QPoint( image.width() - 3, 0 ), QRegion() );
    } else if ( alignment() & Qt::AlignLeft ) {
        popupRect.setRect( -10, -10,
                           size().width() - ( image.width() - 23 ),
                           size().height() + 20 );
        qDrawBorderPixmap(painter, popupRect, QMargins( 20, 20, 20, 20 ),
                          pixmap("marble/webpopup/webpopup2"));
        if ( alignment() & Qt::AlignTop ) {
            image = pixmap("marble/webpopup/arrow2_bottomright");
            painter->drawPixmap( size().width() - image.width(),
                                 size().height() - image.height(), image );
        } else if ( alignment() & Qt::AlignBottom ) {
            image = pixmap("marble/webpopup/arrow2_topright");
            painter->drawPixmap( size().width() - image.width(),
                                 0, image );
        } else { // for no horizontal align value and Qt::AlignVCenter
            image = pixmap("marble/webpopup/arrow2_topright");
            painter->drawPixmap( size().width() - image.width(),
                                 size().height() / 2 - image.height() / 2 + 23, image );
        }
        m_widget->render( painter, QPoint( 5, 0 ), QRegion() );
    } else if ( alignment() & Qt::AlignHCenter )
    {
        if ( alignment() & Qt::AlignTop )
        {
            image = pixmap("marble/webpopup/arrow2_vertical_bottomright");
            popupRect.setRect( -10, -10, size().width() + 20,
                               size().height() - image.height() + 23 );
            qDrawBorderPixmap(painter, popupRect, QMargins( 20, 20, 20, 20 ),
                              pixmap("marble/webpopup/webpopup2"));
            painter->drawPixmap( size().width() / 2 - image.width(),
                                 size().height() - image.height(), image );
            m_widget->render( painter, QPoint( 0, 0 ), QRegion() );
        } else if ( alignment() & Qt::AlignBottom ) {
            image = pixmap("marble/webpopup/arrow2_vertical_topleft");
            popupRect.setRect( -10, image.height() - 13, size().width() + 20,
                               size().height() - image.height() + 23 );
            qDrawBorderPixmap(painter, popupRect, QMargins( 20, 20, 20, 20 ),
                              pixmap("marble/webpopup/webpopup2"));
            painter->drawPixmap( size().width() / 2, 0, image );
            m_widget->render( painter, QPoint( 5, image.height() - 7 ), QRegion() );
        } else { // for no horizontal align value and Qt::AlignVCenter
            popupRect.setRect( -10, -10, size().width() + 20,
                               size().height() + 20 );
            qDrawBorderPixmap(painter, popupRect, QMargins( 20, 20, 20, 20 ),
                              pixmap("marble/webpopup/webpopup2"));
            m_widget->render( painter, QPoint( 0, 0 ), QRegion() );
        }
    }
    m_widget->setFixedSize( popupRect.width() - 20,
                            popupRect.height() - 20 );
}

bool PopupItem::eventFilter( QObject *object, QEvent *e )
{
    MarbleWidget *widget = dynamic_cast<MarbleWidget*> ( object );
    if ( !widget ) {
        return BillboardGraphicsItem::eventFilter( object, e );
    }

    if ( e->type() == QEvent::MouseButtonDblClick
            || e->type() == QEvent::MouseMove
            || e->type() == QEvent::MouseButtonPress
            || e->type() == QEvent::MouseButtonRelease )
    {
        // Mouse events are forwarded to the underlying widget
        QMouseEvent *event = static_cast<QMouseEvent*> ( e );
        QPoint shiftedPos = event->pos();
        QWidget* child = transform( shiftedPos );
        bool const forcedMouseRelease = m_needMouseRelease && e->type() == QEvent::MouseButtonRelease;
        if ( child || forcedMouseRelease ) {
            if ( !m_needMouseRelease && e->type() == QEvent::MouseButtonPress ) {
                m_needMouseRelease = true;
            } else if ( forcedMouseRelease ) {
                m_needMouseRelease = false;
            }
            if ( !child ) {
                child = m_webView;
            }
            widget->setCursor( Qt::ArrowCursor );
            QMouseEvent shiftedEvent = QMouseEvent( e->type(), shiftedPos,
                                                    event->globalPos(), event->button(), event->buttons(),
                                                    event->modifiers() );
            if ( QApplication::sendEvent( child, &shiftedEvent ) ) {
                widget->setCursor( child->cursor() );
                emit dirty();
                return true;
            }
        }
    } else if ( e->type() == QEvent::Wheel ) {
        // Wheel events are forwarded to the underlying widget
        QWheelEvent *event = static_cast<QWheelEvent*> ( e );
        QPoint shiftedPos = event->pos();
        QWidget* child = transform( shiftedPos );
        if ( child ) {
            widget->setCursor( Qt::ArrowCursor );
            QWheelEvent shiftedEvent = QWheelEvent( shiftedPos,
                                                    event->globalPos(), event->delta(), event->buttons(),
                                                    event->modifiers() );
            if ( QApplication::sendEvent( child, &shiftedEvent ) ) {
                widget->setCursor( child->cursor() );
                emit dirty();
                return true;
            }
        }
    }

    return BillboardGraphicsItem::eventFilter( object, e );
}

QWidget* PopupItem::transform( QPoint &point ) const
{
    /*
     * Fixes for mouse events to trigger when the web popup
     * is shifted in accordance with the horizontal alignment
     */
    if ( alignment() & Qt::AlignRight )
        point -= QPoint( 117, 0 );
    else if ( alignment() & Qt::AlignLeft )
        point -= QPoint( 5, 0 );
    else if ( alignment() & Qt::AlignHCenter )
    {
        if ( alignment() & Qt::AlignTop )
        {
            point -= QPoint( 0, 0 );
        } else if ( alignment() & Qt::AlignBottom )
        {
            point-= QPoint( 5, 57 );
        } else {
            point -= QPoint( 0, 0 );
        }
    }

    QList<QPointF> widgetPositions = positions();
    QList<QPointF>::const_iterator it = widgetPositions.constBegin();
    for( ; it != widgetPositions.constEnd(); ++it ) {
        if ( QRectF( *it, size() ).contains( point ) ) {
            point -= it->toPoint();
            QWidget* child = m_widget->childAt( point );
            if ( child ) {
                point -= child->pos();
            }
            return child;
        }
    }
    return 0;
}

QPixmap PopupItem::pixmap( const QString &imageId )
{
  QPixmap result;
  if ( !QPixmapCache::find( imageId, result ) ) {
    QImage bottom = QImage( QString( ":/%1_shadow.png" ).arg( imageId) );
    QImage top = QImage( QString( ":/%1.png" ).arg( imageId) );
    colorize( top, m_backColor );
    QPainter painter( &bottom );
    painter.drawImage( QPoint(0,0), top );

    result = QPixmap::fromImage( bottom );
    QPixmapCache::insert( imageId, result );
  }

  return result;
}

}

#include "PopupItem.moc"
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
 * This file is part of the libpagemaker project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <cstdio>

#include <libpagemaker/libpagemaker.h>

#include <boost/scoped_ptr.hpp>

#include "PMDCollector.h"
#include "PMDParser.h"
#include "yaml_utils.h"
#include "libpagemaker_utils.h"

namespace libpagemaker
{

bool PMDocument::isSupported(librevenge::RVNGInputStream * /*input*/) try
{
  // TODO: Fix this.
  return true;
}
catch (...)
{
  return false;
}

bool PMDocument::parseToYaml(librevenge::RVNGInputStream *input)
{
  PMDCollector collector;
  PMD_DEBUG_MSG(("About to start parsing...\n"));
  PMDParser(input->getSubStreamByName("PageMaker"), &collector).parse();
  PMD_DEBUG_MSG(("About to start printing...\n"));
  dumpAsYaml(stdout, collector);
  return true;
}

bool PMDocument::parse(librevenge::RVNGInputStream *input, librevenge::RVNGDrawingInterface *painter)
{
  PMDCollector collector;
  PMD_DEBUG_MSG(("About to start parsing...\n"));
  boost::scoped_ptr<librevenge::RVNGInputStream>
  pmdStream(input->getSubStreamByName("PageMaker"));
  PMDParser(pmdStream.get(), &collector).parse();
  PMD_DEBUG_MSG(("About to start drawing...\n"));
  collector.draw(painter);
  return true;
}

}

/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>Use boost::scoped_ptr in parseToYaml too<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
 * This file is part of the libpagemaker project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <cstdio>

#include <libpagemaker/libpagemaker.h>

#include <boost/scoped_ptr.hpp>

#include "PMDCollector.h"
#include "PMDParser.h"
#include "yaml_utils.h"
#include "libpagemaker_utils.h"

namespace libpagemaker
{

bool PMDocument::isSupported(librevenge::RVNGInputStream * /*input*/) try
{
  // TODO: Fix this.
  return true;
}
catch (...)
{
  return false;
}

bool PMDocument::parseToYaml(librevenge::RVNGInputStream *input)
{
  PMDCollector collector;
  PMD_DEBUG_MSG(("About to start parsing...\n"));
  boost::scoped_ptr<librevenge::RVNGInputStream>
    pmdStream(input->getSubStreamByName("PageMaker"));
  PMDParser(pmdStream.get(), &collector).parse();
  PMD_DEBUG_MSG(("About to start printing...\n"));
  dumpAsYaml(stdout, collector);
  return true;
}

bool PMDocument::parse(librevenge::RVNGInputStream *input, librevenge::RVNGDrawingInterface *painter)
{
  PMDCollector collector;
  PMD_DEBUG_MSG(("About to start parsing...\n"));
  boost::scoped_ptr<librevenge::RVNGInputStream>
  pmdStream(input->getSubStreamByName("PageMaker"));
  PMDParser(pmdStream.get(), &collector).parse();
  PMD_DEBUG_MSG(("About to start drawing...\n"));
  collector.draw(painter);
  return true;
}

}

/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|>