<commit_before>/* Copyright (C) 2003 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#define DBTUP_C
#include "Dbtup.hpp"
#include <RefConvert.hpp>
#include <ndb_limits.h>
#include <pc.hpp>
#include <signaldata/TransIdAI.hpp>

#define ljam() { jamLine(2000 + __LINE__); }
#define ljamEntry() { jamEntryLine(2000 + __LINE__); }

void Dbtup::execSEND_PACKED(Signal* signal)
{
  Uint16 hostId;
  Uint32 i;
  Uint32 TpackedListIndex = cpackedListIndex;
  ljamEntry();
  for (i = 0; i < TpackedListIndex; i++) {
    ljam();
    hostId = cpackedList[i];
    ndbrequire((hostId - 1) < (MAX_NODES - 1)); // Also check not zero
    Uint32 TpacketTA = hostBuffer[hostId].noOfPacketsTA;
    if (TpacketTA != 0) {
      ljam();
      BlockReference TBref = numberToRef(API_PACKED, hostId);
      Uint32 TpacketLen = hostBuffer[hostId].packetLenTA;
      MEMCOPY_NO_WORDS(&signal->theData[0],
                       &hostBuffer[hostId].packetBufferTA[0],
                       TpacketLen);
      sendSignal(TBref, GSN_TRANSID_AI, signal, TpacketLen, JBB);
      hostBuffer[hostId].noOfPacketsTA = 0;
      hostBuffer[hostId].packetLenTA = 0;
    }//if
    hostBuffer[hostId].inPackedList = false;
  }//for
  cpackedListIndex = 0;
}//Dbtup::execSEND_PACKED()

void Dbtup::bufferTRANSID_AI(Signal* signal, BlockReference aRef,
                             Uint32 Tlen)
{
  if(Tlen == 3)
    return;

  Uint32 hostId = refToNode(aRef);
  Uint32 Theader = ((refToBlock(aRef) << 16)+(Tlen-3));

  ndbrequire(hostId < MAX_NODES);
  Uint32 TpacketLen = hostBuffer[hostId].packetLenTA;
  Uint32 TnoOfPackets = hostBuffer[hostId].noOfPacketsTA;
  Uint32 sig0 = signal->theData[0];
  Uint32 sig1 = signal->theData[1];
  Uint32 sig2 = signal->theData[2];

  BlockReference TBref = numberToRef(API_PACKED, hostId);

  if ((Tlen + TpacketLen + 1) <= 25) {
// ----------------------------------------------------------------
// There is still space in the buffer. We will copy it into the
// buffer.
// ----------------------------------------------------------------
    ljam();
    updatePackedList(signal, hostId);
  } else if (false && TnoOfPackets == 1) {
// ----------------------------------------------------------------
// The buffer is full and there was only one packet buffered. We
// will send this as a normal signal.
// ----------------------------------------------------------------
    Uint32 TnewRef = numberToRef((hostBuffer[hostId].packetBufferTA[0] >> 16),
                                 hostId);
    MEMCOPY_NO_WORDS(&signal->theData[0],
                     &hostBuffer[hostId].packetBufferTA[1],
                     TpacketLen - 1);
    sendSignal(TnewRef, GSN_TRANSID_AI, signal, (TpacketLen - 1), JBB);
    TpacketLen = 0;
    TnoOfPackets = 0;
  } else {
// ----------------------------------------------------------------
// The buffer is full but at least two packets. Send those in
// packed form.
// ----------------------------------------------------------------
    MEMCOPY_NO_WORDS(&signal->theData[0],
                     &hostBuffer[hostId].packetBufferTA[0],
                     TpacketLen);
    sendSignal(TBref, GSN_TRANSID_AI, signal, TpacketLen, JBB);
    TpacketLen = 0;
    TnoOfPackets = 0;
  }//if
// ----------------------------------------------------------------
// Copy the signal into the buffer
// ----------------------------------------------------------------
  hostBuffer[hostId].packetBufferTA[TpacketLen + 0] = Theader;
  hostBuffer[hostId].packetBufferTA[TpacketLen + 1] = sig0;
  hostBuffer[hostId].packetBufferTA[TpacketLen + 2] = sig1;
  hostBuffer[hostId].packetBufferTA[TpacketLen + 3] = sig2;
  hostBuffer[hostId].noOfPacketsTA = TnoOfPackets + 1;
  hostBuffer[hostId].packetLenTA = Tlen + TpacketLen + 1;
  MEMCOPY_NO_WORDS(&hostBuffer[hostId].packetBufferTA[TpacketLen + 4],
                   &signal->theData[25],
                   Tlen - 3);
}//Dbtup::bufferTRANSID_AI()

void Dbtup::updatePackedList(Signal* signal, Uint16 hostId)
{
  if (hostBuffer[hostId].inPackedList == false) {
    Uint32 TpackedListIndex = cpackedListIndex;
    ljam();
    hostBuffer[hostId].inPackedList = true;
    cpackedList[TpackedListIndex] = hostId;
    cpackedListIndex = TpackedListIndex + 1;
  }//if
}//Dbtup::updatePackedList()

/* ---------------------------------------------------------------- */
/* ----------------------- SEND READ ATTRINFO --------------------- */
/* ---------------------------------------------------------------- */
void Dbtup::sendReadAttrinfo(Signal* signal,
                             Uint32 ToutBufIndex,
                             const Operationrec * const regOperPtr)
{
  const BlockReference recBlockref = regOperPtr->recBlockref;
  const Uint32 block = refToBlock(recBlockref);
  const Uint32 nodeId = refToNode(recBlockref);

  bool connectedToNode = getNodeInfo(nodeId).m_connected;
  const Uint32 type = getNodeInfo(nodeId).m_type;
  bool is_api = (type >= NodeInfo::API && type <= NodeInfo::REP);
  bool old_dest = (getNodeInfo(nodeId).m_version < MAKE_VERSION(3,5,0));

  if (ERROR_INSERTED(4006) && (nodeId != getOwnNodeId())){
    // Use error insert to turn routing on
    ljam();
    connectedToNode = false;
  }

  Uint32 sig0 = regOperPtr->tcOperationPtr;
  Uint32 sig1 = regOperPtr->transid1;
  Uint32 sig2 = regOperPtr->transid2;

  TransIdAI * transIdAI =  (TransIdAI *)signal->getDataPtrSend();
  transIdAI->connectPtr = sig0;
  transIdAI->transId[0] = sig1;
  transIdAI->transId[1] = sig2;

  if (connectedToNode){
    /**
     * Own node -> execute direct
     */
    if(nodeId != getOwnNodeId()){
      ljam();

      /**
       * Send long sig
       */
      if(ToutBufIndex >= 22 && is_api && !old_dest) {
	ljam();
	LinearSectionPtr ptr[3];
	ptr[0].p = &signal->theData[25];
	ptr[0].sz = ToutBufIndex;
	sendSignal(recBlockref, GSN_TRANSID_AI, signal, 3, JBB, ptr, 1);
	return;
      }

      /**
       * short sig + api -> buffer
       */
#ifndef NDB_NO_DROPPED_SIGNAL
      if (ToutBufIndex < 22 && is_api){
	ljam();
	bufferTRANSID_AI(signal, recBlockref, 3+ToutBufIndex);
	return;
      }//if
#endif

      /**
       * rest -> old send sig
       */
      Uint32 * src = signal->theData+25;
      if(ToutBufIndex >= 22){
	do {
	  ljam();
	  MEMCOPY_NO_WORDS(&signal->theData[3], src, 22);
	  sendSignal(recBlockref, GSN_TRANSID_AI, signal, 25, JBB);
	  ToutBufIndex -= 22;
	  src += 22;
	} while(ToutBufIndex >= 22);
      }

      if(ToutBufIndex > 0){
	ljam();
	MEMCOPY_NO_WORDS(&signal->theData[3], src, ToutBufIndex);
	sendSignal(recBlockref, GSN_TRANSID_AI, signal, 3+ToutBufIndex, JBB);
      }
      return;
    }
    EXECUTE_DIRECT(block, GSN_TRANSID_AI, signal, 3 + ToutBufIndex);
    ljamEntry();
    return;
  }

  /**
   * If this node does not have a direct connection
   * to the receiving node we want to send the signals
   * routed via the node that controls this read
   */
  Uint32 routeBlockref = regOperPtr->coordinatorTC;

  if(true){ // TODO is_api && !old_dest){
    ljam();
    transIdAI->attrData[0] = recBlockref;
    LinearSectionPtr ptr[3];
    ptr[0].p = &signal->theData[25];
    ptr[0].sz = ToutBufIndex;
    sendSignal(routeBlockref, GSN_TRANSID_AI_R, signal, 4, JBB, ptr, 1);
    return;
  }

  /**
   * Fill in a TRANSID_AI signal, use last word to store
   * final destination and send it to route node
   * as signal TRANSID_AI_R (R as in Routed)
   */
  Uint32 tot = ToutBufIndex;
  Uint32 sent = 0;
  Uint32 maxLen = TransIdAI::DataLength - 1;
  while (sent < tot) {
    ljam();
    Uint32 dataLen = (tot - sent > maxLen) ? maxLen : tot - sent;
    Uint32 sigLen = dataLen + TransIdAI::HeaderLength + 1;
    MEMCOPY_NO_WORDS(&transIdAI->attrData,
		     &signal->theData[25+sent],
		     dataLen);
    // Set final destination in last word
    transIdAI->attrData[dataLen] = recBlockref;

    sendSignal(routeBlockref, GSN_TRANSID_AI_R,
	       signal, sigLen, JBB);
    sent += dataLen;
  }
}//Dbtup::sendReadAttrinfo()
<commit_msg>BUG#ndb_blob on 1 node Make sure to flush buffer when sending long sig so that order is maintained<commit_after>/* Copyright (C) 2003 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#define DBTUP_C
#include "Dbtup.hpp"
#include <RefConvert.hpp>
#include <ndb_limits.h>
#include <pc.hpp>
#include <signaldata/TransIdAI.hpp>

#define ljam() { jamLine(2000 + __LINE__); }
#define ljamEntry() { jamEntryLine(2000 + __LINE__); }

void Dbtup::execSEND_PACKED(Signal* signal)
{
  Uint16 hostId;
  Uint32 i;
  Uint32 TpackedListIndex = cpackedListIndex;
  ljamEntry();
  for (i = 0; i < TpackedListIndex; i++) {
    ljam();
    hostId = cpackedList[i];
    ndbrequire((hostId - 1) < (MAX_NODES - 1)); // Also check not zero
    Uint32 TpacketTA = hostBuffer[hostId].noOfPacketsTA;
    if (TpacketTA != 0) {
      ljam();
      BlockReference TBref = numberToRef(API_PACKED, hostId);
      Uint32 TpacketLen = hostBuffer[hostId].packetLenTA;
      MEMCOPY_NO_WORDS(&signal->theData[0],
                       &hostBuffer[hostId].packetBufferTA[0],
                       TpacketLen);
      sendSignal(TBref, GSN_TRANSID_AI, signal, TpacketLen, JBB);
      hostBuffer[hostId].noOfPacketsTA = 0;
      hostBuffer[hostId].packetLenTA = 0;
    }//if
    hostBuffer[hostId].inPackedList = false;
  }//for
  cpackedListIndex = 0;
}//Dbtup::execSEND_PACKED()

void Dbtup::bufferTRANSID_AI(Signal* signal, BlockReference aRef,
                             Uint32 Tlen)
{
  if(Tlen == 3)
    return;

  Uint32 hostId = refToNode(aRef);
  Uint32 Theader = ((refToBlock(aRef) << 16)+(Tlen-3));

  ndbrequire(hostId < MAX_NODES);
  Uint32 TpacketLen = hostBuffer[hostId].packetLenTA;
  Uint32 TnoOfPackets = hostBuffer[hostId].noOfPacketsTA;
  Uint32 sig0 = signal->theData[0];
  Uint32 sig1 = signal->theData[1];
  Uint32 sig2 = signal->theData[2];

  BlockReference TBref = numberToRef(API_PACKED, hostId);

  if ((Tlen + TpacketLen + 1) <= 25) {
// ----------------------------------------------------------------
// There is still space in the buffer. We will copy it into the
// buffer.
// ----------------------------------------------------------------
    ljam();
    updatePackedList(signal, hostId);
  } else if (false && TnoOfPackets == 1) {
// ----------------------------------------------------------------
// The buffer is full and there was only one packet buffered. We
// will send this as a normal signal.
// ----------------------------------------------------------------
    Uint32 TnewRef = numberToRef((hostBuffer[hostId].packetBufferTA[0] >> 16),
                                 hostId);
    MEMCOPY_NO_WORDS(&signal->theData[0],
                     &hostBuffer[hostId].packetBufferTA[1],
                     TpacketLen - 1);
    sendSignal(TnewRef, GSN_TRANSID_AI, signal, (TpacketLen - 1), JBB);
    TpacketLen = 0;
    TnoOfPackets = 0;
  } else {
// ----------------------------------------------------------------
// The buffer is full but at least two packets. Send those in
// packed form.
// ----------------------------------------------------------------
    MEMCOPY_NO_WORDS(&signal->theData[0],
                     &hostBuffer[hostId].packetBufferTA[0],
                     TpacketLen);
    sendSignal(TBref, GSN_TRANSID_AI, signal, TpacketLen, JBB);
    TpacketLen = 0;
    TnoOfPackets = 0;
  }//if
// ----------------------------------------------------------------
// Copy the signal into the buffer
// ----------------------------------------------------------------
  hostBuffer[hostId].packetBufferTA[TpacketLen + 0] = Theader;
  hostBuffer[hostId].packetBufferTA[TpacketLen + 1] = sig0;
  hostBuffer[hostId].packetBufferTA[TpacketLen + 2] = sig1;
  hostBuffer[hostId].packetBufferTA[TpacketLen + 3] = sig2;
  hostBuffer[hostId].noOfPacketsTA = TnoOfPackets + 1;
  hostBuffer[hostId].packetLenTA = Tlen + TpacketLen + 1;
  MEMCOPY_NO_WORDS(&hostBuffer[hostId].packetBufferTA[TpacketLen + 4],
                   &signal->theData[25],
                   Tlen - 3);
}//Dbtup::bufferTRANSID_AI()

void Dbtup::updatePackedList(Signal* signal, Uint16 hostId)
{
  if (hostBuffer[hostId].inPackedList == false) {
    Uint32 TpackedListIndex = cpackedListIndex;
    ljam();
    hostBuffer[hostId].inPackedList = true;
    cpackedList[TpackedListIndex] = hostId;
    cpackedListIndex = TpackedListIndex + 1;
  }//if
}//Dbtup::updatePackedList()

/* ---------------------------------------------------------------- */
/* ----------------------- SEND READ ATTRINFO --------------------- */
/* ---------------------------------------------------------------- */
void Dbtup::sendReadAttrinfo(Signal* signal,
                             Uint32 ToutBufIndex,
                             const Operationrec * const regOperPtr)
{
  const BlockReference recBlockref = regOperPtr->recBlockref;
  const Uint32 block = refToBlock(recBlockref);
  const Uint32 nodeId = refToNode(recBlockref);

  bool connectedToNode = getNodeInfo(nodeId).m_connected;
  const Uint32 type = getNodeInfo(nodeId).m_type;
  bool is_api = (type >= NodeInfo::API && type <= NodeInfo::REP);
  bool old_dest = (getNodeInfo(nodeId).m_version < MAKE_VERSION(3,5,0));
  Uint32 TpacketTA = hostBuffer[nodeId].noOfPacketsTA;
  Uint32 TpacketLen = hostBuffer[nodeId].packetLenTA;

  if (ERROR_INSERTED(4006) && (nodeId != getOwnNodeId())){
    // Use error insert to turn routing on
    ljam();
    connectedToNode = false;
  }

  Uint32 sig0 = regOperPtr->tcOperationPtr;
  Uint32 sig1 = regOperPtr->transid1;
  Uint32 sig2 = regOperPtr->transid2;

  TransIdAI * transIdAI =  (TransIdAI *)signal->getDataPtrSend();
  transIdAI->connectPtr = sig0;
  transIdAI->transId[0] = sig1;
  transIdAI->transId[1] = sig2;

  if (connectedToNode){
    /**
     * Own node -> execute direct
     */
    if(nodeId != getOwnNodeId()){
      ljam();

      /**
       * Send long sig
       */
      if(ToutBufIndex >= 22 && is_api && !old_dest) {
	ljam();
	/**
	 * Flush buffer so that order is maintained
	 */
	if (TpacketTA != 0) {
	  ljam();
	  BlockReference TBref = numberToRef(API_PACKED, nodeId);
	  MEMCOPY_NO_WORDS(&signal->theData[0],
			   &hostBuffer[nodeId].packetBufferTA[0],
			   TpacketLen);
	  sendSignal(TBref, GSN_TRANSID_AI, signal, TpacketLen, JBB);
	  hostBuffer[nodeId].noOfPacketsTA = 0;
	  hostBuffer[nodeId].packetLenTA = 0;
	}//if
	LinearSectionPtr ptr[3];
	ptr[0].p = &signal->theData[25];
	ptr[0].sz = ToutBufIndex;
	sendSignal(recBlockref, GSN_TRANSID_AI, signal, 3, JBB, ptr, 1);
	return;
      }

      /**
       * short sig + api -> buffer
       */
#ifndef NDB_NO_DROPPED_SIGNAL
      if (ToutBufIndex < 22 && is_api){
	ljam();
	bufferTRANSID_AI(signal, recBlockref, 3+ToutBufIndex);
	return;
      }//if
#endif

      /**
       * rest -> old send sig
       */
      Uint32 * src = signal->theData+25;
      if(ToutBufIndex >= 22){
	do {
	  ljam();
	  MEMCOPY_NO_WORDS(&signal->theData[3], src, 22);
	  sendSignal(recBlockref, GSN_TRANSID_AI, signal, 25, JBB);
	  ToutBufIndex -= 22;
	  src += 22;
	} while(ToutBufIndex >= 22);
      }

      if(ToutBufIndex > 0){
	ljam();
	MEMCOPY_NO_WORDS(&signal->theData[3], src, ToutBufIndex);
	sendSignal(recBlockref, GSN_TRANSID_AI, signal, 3+ToutBufIndex, JBB);
      }
      return;
    }
    EXECUTE_DIRECT(block, GSN_TRANSID_AI, signal, 3 + ToutBufIndex);
    ljamEntry();
    return;
  }

  /**
   * If this node does not have a direct connection
   * to the receiving node we want to send the signals
   * routed via the node that controls this read
   */
  Uint32 routeBlockref = regOperPtr->coordinatorTC;

  if(true){ // TODO is_api && !old_dest){
    ljam();
    transIdAI->attrData[0] = recBlockref;
    LinearSectionPtr ptr[3];
    ptr[0].p = &signal->theData[25];
    ptr[0].sz = ToutBufIndex;
    sendSignal(routeBlockref, GSN_TRANSID_AI_R, signal, 4, JBB, ptr, 1);
    return;
  }

  /**
   * Fill in a TRANSID_AI signal, use last word to store
   * final destination and send it to route node
   * as signal TRANSID_AI_R (R as in Routed)
   */
  Uint32 tot = ToutBufIndex;
  Uint32 sent = 0;
  Uint32 maxLen = TransIdAI::DataLength - 1;
  while (sent < tot) {
    ljam();
    Uint32 dataLen = (tot - sent > maxLen) ? maxLen : tot - sent;
    Uint32 sigLen = dataLen + TransIdAI::HeaderLength + 1;
    MEMCOPY_NO_WORDS(&transIdAI->attrData,
		     &signal->theData[25+sent],
		     dataLen);
    // Set final destination in last word
    transIdAI->attrData[dataLen] = recBlockref;

    sendSignal(routeBlockref, GSN_TRANSID_AI_R,
	       signal, sigLen, JBB);
    sent += dataLen;
  }
}//Dbtup::sendReadAttrinfo()
<|endoftext|>


<commit_before>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
* Copyright (c) 2010 Ruslan Kabatsayev <b7.10110111@gmail.com>
*
* This  library is free  software; you can  redistribute it and/or
* modify it  under  the terms  of the  GNU Lesser  General  Public
* License  as published  by the Free  Software  Foundation; either
* version 2 of the License, or(at your option ) any later version.
*
* 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., 51  Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#include <gtk/gtk.h>
#include "oxygeninnershadowdata.h"
#include "../oxygengtkutils.h"
#include "../config.h"
#include "../oxygencairocontext.h"
#include "oxygenanimations.h"
#include "../oxygenstyle.h"

#include <cassert>
#include <iostream>

#undef OXYGEN_DEBUG
#define OXYGEN_DEBUG 1

namespace Oxygen
{

    gboolean InnerShadowData::targetExposeEvent( GtkWidget* widget, GdkEventExpose* event, gpointer )
    {
        GtkWidget* child=gtk_bin_get_child(GTK_BIN(widget));
        GdkWindow* window=gtk_widget_get_window(child);

        #if OXYGEN_DEBUG
        std::cerr << "InnerShadowData::targetExposeEvent( " << G_OBJECT_TYPE_NAME(widget) << " ); child: " ;
        char* path;
        gtk_widget_path(child,NULL,&path,NULL);
        std::cerr << path << std::endl;
        g_free(path);
        #endif

        // don't do anything if the window isn't composited
        if(!gdk_window_get_composited(window))
        {
            #if OXYGEN_DEBUG
            std::cerr << "Window isn't composited, so not doing anything\n";
            #endif
            return FALSE;
        }
        Cairo::Context context(gtk_widget_get_window(widget));

        // set up clipping independently of GTK version
        GtkAllocation alloc;
        gtk_widget_get_allocation(child,&alloc);
        cairo_rectangle(context,alloc.x,alloc.y,alloc.width,alloc.height);
        cairo_clip(context);
        gdk_cairo_region(context,event->region);
        cairo_clip(context);

        // first make sure the child window doesn't contain garbage
        gdk_window_process_updates(window,TRUE);

        // now draw the child
        gdk_cairo_set_source_window(context,window,alloc.x,alloc.y);
        cairo_paint(context);

        // draw the shadow

        int basicOffset=2;
        // we only draw SHADOW_IN here
        if(gtk_scrolled_window_get_shadow_type(GTK_SCROLLED_WINDOW(widget)) != GTK_SHADOW_IN )
        {
            if( GTK_IS_VIEWPORT(child) && gtk_viewport_get_shadow_type(GTK_VIEWPORT(child)) == GTK_SHADOW_IN )
            {
                basicOffset=0;
            }
            else
            {
                #if OXYGEN_DEBUG
                std::cerr << "Shadow type isn't GTK_SHADOW_IN, so not drawing the shadow in expose-event handler\n";
                #endif
                return FALSE;
            }
        }

        StyleOptions options(widget,gtk_widget_get_state(widget));
        options|=NoFill;
        options &= ~(Hover|Focus);
        if( Style::instance().animations().scrolledWindowEngine().contains( widget ) )
        {
            if( Style::instance().animations().scrolledWindowEngine().focused( widget ) ) options |= Focus;
            if( Style::instance().animations().scrolledWindowEngine().hovered( widget ) ) options |= Hover;
        }
        const AnimationData data( Style::instance().animations().widgetStateEngine().get( widget, options, AnimationHover|AnimationFocus, AnimationFocus ) );

        int offsetX=basicOffset+Style::Entry_SideMargin;
        int offsetY=basicOffset;

        GdkRectangle clipRect={alloc.x,alloc.y,alloc.width,alloc.height};

        Style::instance().renderHoleBackground( gtk_widget_get_window(widget), &clipRect, alloc.x-offsetX, alloc.y-offsetY, alloc.width+offsetX*2, alloc.height+offsetY*2 );
        offsetX-=Style::Entry_SideMargin;
        Style::instance().renderHole( gtk_widget_get_window(widget), &clipRect, alloc.x-offsetX, alloc.y-offsetY, alloc.width+offsetX*2, alloc.height+offsetY*2, options, data );

        // let the event propagate
        return FALSE;
    }

    //_____________________________________________
    void InnerShadowData::connect( GtkWidget* widget )
    {
        assert( GTK_IS_SCROLLED_WINDOW( widget ) );
        assert( !_target );

        // store target
        _target = widget;

        if(gdk_display_supports_composite(gdk_display_get_default()))
        {
            _compositeEnabled=true;
            _exposeId.connect( G_OBJECT(_target), "expose-event", G_CALLBACK( targetExposeEvent ), this, true );
        }

        // check child
        GtkWidget* child( gtk_bin_get_child( GTK_BIN( widget ) ) );
        if( !child ) return;

        #if OXYGEN_DEBUG
        std::cerr
            << "Oxygen::InnerShadowData::connect -"
            << " child: " << child << " (" << G_OBJECT_TYPE_NAME( child ) << ")"
            << std::endl;
        #endif

        registerChild( child );
    }

    //_____________________________________________
    void InnerShadowData::disconnect( GtkWidget* widget )
    {
        _target = 0;
        for( ChildDataMap::iterator iter = _childrenData.begin(); iter != _childrenData.end(); ++iter )
        { iter->second.disconnect( iter->first ); }

        if(_compositeEnabled)
        {
            _exposeId.disconnect();
        }

        _childrenData.clear();
    }

    //_____________________________________________
    void InnerShadowData::registerChild( GtkWidget* widget )
    {
        // make sure widget is not already in map
        if( _childrenData.find( widget ) == _childrenData.end() )
        {

            #if OXYGEN_DEBUG
            std::cerr
                << "Oxygen::InnerShadowData::registerChild -"
                << " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
                << std::endl;
            #endif

            ChildData data;
            data._unrealizeId.connect( G_OBJECT(widget), "unrealize", G_CALLBACK( childUnrealizeNotifyEvent ), this );

            GdkWindow* window(gtk_widget_get_window(widget));
            if(window && gdk_display_supports_composite(gdk_display_get_default()))
            {
                data.initiallyComposited=gdk_window_get_composited(window);
                gdk_window_set_composited(window,TRUE);
            }

            _childrenData.insert( std::make_pair( widget, data ) );

        }

    }

    //________________________________________________________________________________
    void InnerShadowData::unregisterChild( GtkWidget* widget )
    {

        ChildDataMap::iterator iter( _childrenData.find( widget ) );
        if( iter == _childrenData.end() ) return;

        #if OXYGEN_DEBUG
        std::cerr
            << "Oxygen::InnerShadowData::unregisterChild -"
            << " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
            << std::endl;
        #endif

        iter->second.disconnect( widget );
        _childrenData.erase( iter );

    }

    //________________________________________________________________________________
    void InnerShadowData::ChildData::disconnect( GtkWidget* widget )
    {

        #if OXYGEN_DEBUG
        std::cerr
            << "Oxygen::InnerShadowData::ChildData::disconnect -"
            << " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
            << std::endl;
        #endif

        _unrealizeId.disconnect();
        GdkWindow* window(gtk_widget_get_window(widget));
        if(GTK_IS_WINDOW(window))
            gdk_window_set_composited(window,initiallyComposited);
    }

    //____________________________________________________________________________________________
    gboolean InnerShadowData::childUnrealizeNotifyEvent( GtkWidget* widget, gpointer data )
    {
        #if OXYGEN_DEBUG
        std::cerr
            << "Oxygen::InnerShadowData::childUnrealizeNotifyEvent -"
            << " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
            << std::endl;
        #endif
        static_cast<InnerShadowData*>(data)->unregisterChild( widget );
        return FALSE;
    }

}
<commit_msg>Remove debug force enabling<commit_after>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
* Copyright (c) 2010 Ruslan Kabatsayev <b7.10110111@gmail.com>
*
* This  library is free  software; you can  redistribute it and/or
* modify it  under  the terms  of the  GNU Lesser  General  Public
* License  as published  by the Free  Software  Foundation; either
* version 2 of the License, or(at your option ) any later version.
*
* 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., 51  Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#include <gtk/gtk.h>
#include "oxygeninnershadowdata.h"
#include "../oxygengtkutils.h"
#include "../config.h"
#include "../oxygencairocontext.h"
#include "oxygenanimations.h"
#include "../oxygenstyle.h"

#include <cassert>
#include <iostream>

namespace Oxygen
{

    gboolean InnerShadowData::targetExposeEvent( GtkWidget* widget, GdkEventExpose* event, gpointer )
    {
        GtkWidget* child=gtk_bin_get_child(GTK_BIN(widget));
        GdkWindow* window=gtk_widget_get_window(child);

        #if OXYGEN_DEBUG
        std::cerr << "InnerShadowData::targetExposeEvent( " << G_OBJECT_TYPE_NAME(widget) << " ); child: " ;
        char* path;
        gtk_widget_path(child,NULL,&path,NULL);
        std::cerr << path << std::endl;
        g_free(path);
        #endif

        // don't do anything if the window isn't composited
        if(!gdk_window_get_composited(window))
        {
            #if OXYGEN_DEBUG
            std::cerr << "Window isn't composited, so not doing anything\n";
            #endif
            return FALSE;
        }
        Cairo::Context context(gtk_widget_get_window(widget));

        // set up clipping independently of GTK version
        GtkAllocation alloc;
        gtk_widget_get_allocation(child,&alloc);
        cairo_rectangle(context,alloc.x,alloc.y,alloc.width,alloc.height);
        cairo_clip(context);
        gdk_cairo_region(context,event->region);
        cairo_clip(context);

        // first make sure the child window doesn't contain garbage
        gdk_window_process_updates(window,TRUE);

        // now draw the child
        gdk_cairo_set_source_window(context,window,alloc.x,alloc.y);
        cairo_paint(context);

        // draw the shadow

        int basicOffset=2;
        // we only draw SHADOW_IN here
        if(gtk_scrolled_window_get_shadow_type(GTK_SCROLLED_WINDOW(widget)) != GTK_SHADOW_IN )
        {
            if( GTK_IS_VIEWPORT(child) && gtk_viewport_get_shadow_type(GTK_VIEWPORT(child)) == GTK_SHADOW_IN )
            {
                basicOffset=0;
            }
            else
            {
                #if OXYGEN_DEBUG
                std::cerr << "Shadow type isn't GTK_SHADOW_IN, so not drawing the shadow in expose-event handler\n";
                #endif
                return FALSE;
            }
        }

        StyleOptions options(widget,gtk_widget_get_state(widget));
        options|=NoFill;
        options &= ~(Hover|Focus);
        if( Style::instance().animations().scrolledWindowEngine().contains( widget ) )
        {
            if( Style::instance().animations().scrolledWindowEngine().focused( widget ) ) options |= Focus;
            if( Style::instance().animations().scrolledWindowEngine().hovered( widget ) ) options |= Hover;
        }
        const AnimationData data( Style::instance().animations().widgetStateEngine().get( widget, options, AnimationHover|AnimationFocus, AnimationFocus ) );

        int offsetX=basicOffset+Style::Entry_SideMargin;
        int offsetY=basicOffset;

        GdkRectangle clipRect={alloc.x,alloc.y,alloc.width,alloc.height};

        Style::instance().renderHoleBackground( gtk_widget_get_window(widget), &clipRect, alloc.x-offsetX, alloc.y-offsetY, alloc.width+offsetX*2, alloc.height+offsetY*2 );
        offsetX-=Style::Entry_SideMargin;
        Style::instance().renderHole( gtk_widget_get_window(widget), &clipRect, alloc.x-offsetX, alloc.y-offsetY, alloc.width+offsetX*2, alloc.height+offsetY*2, options, data );

        // let the event propagate
        return FALSE;
    }

    //_____________________________________________
    void InnerShadowData::connect( GtkWidget* widget )
    {
        assert( GTK_IS_SCROLLED_WINDOW( widget ) );
        assert( !_target );

        // store target
        _target = widget;

        if(gdk_display_supports_composite(gdk_display_get_default()))
        {
            _compositeEnabled=true;
            _exposeId.connect( G_OBJECT(_target), "expose-event", G_CALLBACK( targetExposeEvent ), this, true );
        }

        // check child
        GtkWidget* child( gtk_bin_get_child( GTK_BIN( widget ) ) );
        if( !child ) return;

        #if OXYGEN_DEBUG
        std::cerr
            << "Oxygen::InnerShadowData::connect -"
            << " child: " << child << " (" << G_OBJECT_TYPE_NAME( child ) << ")"
            << std::endl;
        #endif

        registerChild( child );
    }

    //_____________________________________________
    void InnerShadowData::disconnect( GtkWidget* widget )
    {
        _target = 0;
        for( ChildDataMap::iterator iter = _childrenData.begin(); iter != _childrenData.end(); ++iter )
        { iter->second.disconnect( iter->first ); }

        if(_compositeEnabled)
        {
            _exposeId.disconnect();
        }

        _childrenData.clear();
    }

    //_____________________________________________
    void InnerShadowData::registerChild( GtkWidget* widget )
    {
        // make sure widget is not already in map
        if( _childrenData.find( widget ) == _childrenData.end() )
        {

            #if OXYGEN_DEBUG
            std::cerr
                << "Oxygen::InnerShadowData::registerChild -"
                << " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
                << std::endl;
            #endif

            ChildData data;
            data._unrealizeId.connect( G_OBJECT(widget), "unrealize", G_CALLBACK( childUnrealizeNotifyEvent ), this );

            GdkWindow* window(gtk_widget_get_window(widget));
            if(window && gdk_display_supports_composite(gdk_display_get_default()))
            {
                data.initiallyComposited=gdk_window_get_composited(window);
                gdk_window_set_composited(window,TRUE);
            }

            _childrenData.insert( std::make_pair( widget, data ) );

        }

    }

    //________________________________________________________________________________
    void InnerShadowData::unregisterChild( GtkWidget* widget )
    {

        ChildDataMap::iterator iter( _childrenData.find( widget ) );
        if( iter == _childrenData.end() ) return;

        #if OXYGEN_DEBUG
        std::cerr
            << "Oxygen::InnerShadowData::unregisterChild -"
            << " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
            << std::endl;
        #endif

        iter->second.disconnect( widget );
        _childrenData.erase( iter );

    }

    //________________________________________________________________________________
    void InnerShadowData::ChildData::disconnect( GtkWidget* widget )
    {

        #if OXYGEN_DEBUG
        std::cerr
            << "Oxygen::InnerShadowData::ChildData::disconnect -"
            << " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
            << std::endl;
        #endif

        _unrealizeId.disconnect();
        GdkWindow* window(gtk_widget_get_window(widget));
        if(GTK_IS_WINDOW(window))
            gdk_window_set_composited(window,initiallyComposited);
    }

    //____________________________________________________________________________________________
    gboolean InnerShadowData::childUnrealizeNotifyEvent( GtkWidget* widget, gpointer data )
    {
        #if OXYGEN_DEBUG
        std::cerr
            << "Oxygen::InnerShadowData::childUnrealizeNotifyEvent -"
            << " " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")"
            << std::endl;
        #endif
        static_cast<InnerShadowData*>(data)->unregisterChild( widget );
        return FALSE;
    }

}
<|endoftext|>


<commit_before>#include "cyclelist.h"
#include <iostream>

using namespace std;

struct CycleListElement {
    int value;
    CycleListElement* next;
};

struct CycleList {
    CycleListElement* head;
    int size;
};

CycleList* createCycle()
{
    return new CycleList{nullptr, 0};
}

void deleteCycle(CycleList* cycle)
{
    while (cycle->size) {
        remove(cycle->head, cycle);
        (cycle->size)--;
    }
    delete cycle;
}

void addFirst(int value, CycleList* cycle)
{
    CycleListElement* newElement = new CycleListElement{value, nullptr};
    newElement->next = newElement;
    cycle->head = newElement;
    (cycle->size)++;
}

void insert(int value, CycleListElement* current, CycleList* cycle)
{
    CycleListElement* tempNext = current->next;
    CycleListElement* newElement = new CycleListElement{value, tempNext};
    current->next = newElement;
    (cycle->size)++;
}

void remove(CycleListElement* current, CycleList* cycle)
{
    CycleListElement* previous = moveSeveralTimes(current, cycle->size - 1);
    previous->next = current->next;
    delete current;
    (cycle->size)--;
}

int getValue(CycleListElement* current)
{
    return current->value;
}

CycleListElement* next(CycleListElement* current)
{
    return current->next;
}

CycleListElement* moveSeveralTimes(CycleListElement* current, int step)
{
    CycleListElement* newCurrent = current;
    for (int i = 0; i < step; ++i) {
        newCurrent = next(newCurrent);
    }
    return newCurrent;
}

CycleListElement* getFirst(CycleList* cycle)
{
    return cycle->head;
}

void printCycle(CycleList *cycle)
{
    CycleListElement* current = cycle->head;
    for (int i = 0; i < cycle->size; ++i) {
        cout << current->value << ' ';
        current = next(current);
    }
    cout << endl;
}

int getSize(CycleList* cycle)
{
    return cycle->size;
}

<commit_msg>fixed wrong behavior (cycle->head problem)<commit_after>#include "cyclelist.h"
#include <iostream>

using namespace std;

struct CycleListElement {
    int value;
    CycleListElement* next;
};

struct CycleList {
    CycleListElement* head;
    int size;
};

CycleList* createCycle()
{
    return new CycleList{nullptr, 0};
}

void deleteCycle(CycleList* cycle)
{
    while (cycle->size) {
        remove(cycle->head, cycle);
        (cycle->size)--;
    }
    delete cycle;
}

void addFirst(int value, CycleList* cycle)
{
    CycleListElement* newElement = new CycleListElement{value, nullptr};
    newElement->next = newElement;
    cycle->head = newElement;
    (cycle->size)++;
}

void insert(int value, CycleListElement* current, CycleList* cycle)
{
    CycleListElement* tempNext = current->next;
    CycleListElement* newElement = new CycleListElement{value, tempNext};
    current->next = newElement;
    (cycle->size)++;
}

void remove(CycleListElement* current, CycleList* cycle)
{

    CycleListElement* previous = moveSeveralTimes(current, cycle->size - 1);
    previous->next = current->next;
    if (cycle->head == current) {
        cycle->head = current->next;
    }
    delete current;
    (cycle->size)--;
}

int getValue(CycleListElement* current)
{
    return current->value;
}

CycleListElement* next(CycleListElement* current)
{
    return current->next;
}

CycleListElement* moveSeveralTimes(CycleListElement* current, int step)
{
    CycleListElement* newCurrent = current;
    for (int i = 0; i < step; ++i) {
        newCurrent = next(newCurrent);
    }
    return newCurrent;
}

CycleListElement* getFirst(CycleList* cycle)
{
    return cycle->head;
}

void printCycle(CycleList *cycle)
{
    CycleListElement* current = cycle->head;
    for (int i = 0; i < cycle->size; ++i) {
        cout << current->value << ' ';
        current = next(current);
    }
    cout << endl;
}

int getSize(CycleList* cycle)
{
    return cycle->size;
}

<|endoftext|>


<commit_before>#include <cstdlib>
#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
	int n, m;
	int *q;

	scanf("%d", &n);

	q = (int *)malloc(n * sizeof(int));

	for (int i = 0; i < n; ++i) {
		scanf("%d", &q[i]);
	}

	sort(q, q + n);

	scanf("%d", &m);

	for (int i = 0; i < m; ++i) {
		int ans;
		//            vector<int>::iterator iter;

		scanf("%d", &ans);

		//            iter = find(q.begin(), q.end(), ans);
		//
		//            if(iter != q.end())
		//                printf("1\n");
		//            else
		//                printf("0\n");

		if (binary_search(q, q + n, ans))
			printf("1\n");
		else
			printf("0\n");
	}
}<commit_msg>modify 1920<commit_after>#include <cstdio>
#include <cstdlib>
using namespace std;

int n, m, q;
int arr[100001];

int comp(const void* x, const void* y) {
	if (*(int*)x < *(int*)y) {
		return -1;
	} else if (*(int*)x > *(int*)y) {
		return 1;
	} else {
		return 0;
	}
}

bool rbinary(int s, int e, int target) {
	int mid = (s + e) / 2;

	while (s <= e) {
		if (arr[mid] == target) {
			return true;
		} else if (arr[mid] > target) {
			return rbinary(s, mid - 1, target);
		} else if (arr[mid] < target) {
			return rbinary(mid + 1, e, target);
		}
	}

	return false;
}

bool binary(int s, int e, int target) {
	while (s <= e) {
		int mid = (s + e) / 2;

		if (arr[mid] == target) {
			return true;
		} else if (arr[mid] > target) {
			e = mid - 1;
		} else if (arr[mid] < target) {
			s = mid + 1;
		}
	}

	return false;
}

int main() {
	scanf("%d", &n);

	for (int i = 0; i < n; i++) {
		scanf("%d", &arr[i]);
	}

	// sort(q, q + n);
	qsort(arr, n, sizeof(int), comp);

	scanf("%d", &m);

	for (int i = 0; i < m; i++) {
		scanf("%d", &q);

		if (binary(0, n - 1, q))
			printf("1\n");
		else
			printf("0\n");
	}
}<|endoftext|>


<commit_before>#include "AM2320.h"
#include < Wire.h >

// AM2320 Temperature & Humidity Sensor library for Arduino
// Modified by Timofeev E.N. from https://github.com/thakshak/AM2320/

unsigned int CRC16(byte * ptr, byte length) {
        unsigned int crc = 0xFFFF;
        uint8_t s = 0x00;

        while (length--) {
                crc ^ = * ptr++;
                for (s = 0; s < 8; s++) {
                        if ((crc & 0x01) ! = 0) {
                                crc >> = 1;
                                crc ^ = 0xA001;
                        } else crc >> = 1;
                }
        }
        return crc;
}

AM2320::AM2320() {}

int AM2320::Read() {
        byte buf[8];
        for (int s = 0; s < 8; s++) buf[s] = 0x00;

        Wire.beginTransmission(AM2320_address);
        Wire.endTransmission();
        // request 4 bytes (temperature and humidity)
        Wire.beginTransmission(AM2320_address);
        Wire.write(0x03); // request
        Wire.write(0x00); // from the 0th address
        Wire.write(0x04); // 4 bytes
        if (Wire.endTransmission(1) ! = 0) return 1;
        delayMicroseconds(1600); //>1.5ms
        // read the query results
        Wire.requestFrom(AM2320_address, 0x08);
        for (int i = 0; i < 0x08; i++) buf[i] = Wire.read();

        // CRC check
        unsigned int Rcrc = buf[7] << 8;
        Rcrc + = buf[6];
        if (Rcrc == CRC16(buf, 6)) {
                unsigned int temperature = ((buf[4] & 0x7F) << 8) + buf[5];
                t = temperature / 10.0;
                t = ((buf[4] & 0x80) >> 7) == 1 ? t * (-1) : t;

                unsigned int humidity = (buf[2] << 8) + buf[3];
                h = humidity / 10.0;
                return 0;
        }
        return 2;
}
<commit_msg>removed extra spaces from include directive<commit_after>#include "AM2320.h"
#include <Wire.h>

// AM2320 Temperature & Humidity Sensor library for Arduino
// Modified by Timofeev E.N. from https://github.com/thakshak/AM2320/

unsigned int CRC16(byte * ptr, byte length) {
        unsigned int crc = 0xFFFF;
        uint8_t s = 0x00;

        while (length--) {
                crc ^ = * ptr++;
                for (s = 0; s < 8; s++) {
                        if ((crc & 0x01) ! = 0) {
                                crc >> = 1;
                                crc ^ = 0xA001;
                        } else crc >> = 1;
                }
        }
        return crc;
}

AM2320::AM2320() {}

int AM2320::Read() {
        byte buf[8];
        for (int s = 0; s < 8; s++) buf[s] = 0x00;

        Wire.beginTransmission(AM2320_address);
        Wire.endTransmission();
        // request 4 bytes (temperature and humidity)
        Wire.beginTransmission(AM2320_address);
        Wire.write(0x03); // request
        Wire.write(0x00); // from the 0th address
        Wire.write(0x04); // 4 bytes
        if (Wire.endTransmission(1) ! = 0) return 1;
        delayMicroseconds(1600); //>1.5ms
        // read the query results
        Wire.requestFrom(AM2320_address, 0x08);
        for (int i = 0; i < 0x08; i++) buf[i] = Wire.read();

        // CRC check
        unsigned int Rcrc = buf[7] << 8;
        Rcrc + = buf[6];
        if (Rcrc == CRC16(buf, 6)) {
                unsigned int temperature = ((buf[4] & 0x7F) << 8) + buf[5];
                t = temperature / 10.0;
                t = ((buf[4] & 0x80) >> 7) == 1 ? t * (-1) : t;

                unsigned int humidity = (buf[2] << 8) + buf[3];
                h = humidity / 10.0;
                return 0;
        }
        return 2;
}
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2014 - 2017)
//   Rene Milk       (2014, 2016 - 2017)
//   Tobias Leibner  (2014, 2016)

#ifndef DUNE_GDT_PLAYGROUND_SPACES_DG_DUNE_PDELAB_WRAPPER_HH
#define DUNE_GDT_PLAYGROUND_SPACES_DG_DUNE_PDELAB_WRAPPER_HH

#include <memory>
#include <tuple>

#include <dune/common/fvector.hh>
#include <dune/common/deprecated.hh>

#include <dune/geometry/type.hh>

#if HAVE_DUNE_PDELAB
#include <dune/pdelab/finiteelementmap/qkdg.hh>
#include <dune/pdelab/gridfunctionspace/gridfunctionspace.hh>
#include <dune/pdelab/constraints/conforming.hh>
#endif // HAVE_DUNE_PDELAB

#include <dune/xt/common/tuple.hh>
#include <dune/xt/common/type_traits.hh>
#include <dune/xt/la/container/istl.hh>
#include <dune/xt/grid/type_traits.hh>

#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/parallel.hh>
#include <dune/gdt/spaces/dg/interface.hh>
#include <dune/gdt/spaces/basefunctionset/dune-pdelab-wrapper.hh>
#include <dune/gdt/playground/spaces/mapper/dune-pdelab-wrapper.hh>

namespace Dune {
namespace GDT {

#if HAVE_DUNE_PDELAB

// forward, to be used in the traits and to allow for specialization
template <class GridLayerImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1>
class DunePdelabDgSpaceWrapper
{
  static_assert(Dune::AlwaysFalse<GridLayerImp>::value, "Untested for this combination of dimensions!");
};

// forward, to be used in the traits and to allow for specialization
template <class GridLayerImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1>
class DunePdelabDgProductSpaceWrapper
{
  static_assert(Dune::AlwaysFalse<GridLayerImp>::value, "Untested for these dimensions!");
};

namespace internal {

template <class GridLayerImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1>
class DunePdelabDgSpaceWrapperTraits
{
public:
  typedef DunePdelabDgSpaceWrapper<GridLayerImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols> derived_type;
  typedef GridLayerImp GridLayerType;
  static const int polOrder = polynomialOrder;
  static const bool continuous = false;
  static const constexpr Backends backend_type{Backends::pdelab};

private:
  typedef typename GridLayerType::ctype DomainFieldType;
  static const size_t dimDomain = GridLayerType::dimension;

public:
  typedef RangeFieldImp RangeFieldType;

private:
  template <class G, bool single_geom, bool is_simplex, bool is_cube>
  struct FeMap
  {
    static_assert(Dune::AlwaysFalse<G>::value,
                  "This space is only implemented for either fully simplicial or fully cubic grids!");
  };
  template <class G>
  struct FeMap<G, true, true, false>
  {
    static_assert(Dune::AlwaysFalse<G>::value, "Not yet implemented for simplicial grids!");
  };
  template <class G>
  struct FeMap<G, true, false, true>
  {
    typedef PDELab::QkDGLocalFiniteElementMap<DomainFieldType, RangeFieldType, polOrder, dimDomain> Type;
  };

  static const bool single_geom_ = Dune::Capabilities::hasSingleGeometryType<GridType>::v;
  static const bool simplicial_ =
      (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId == Impl::SimplexTopology<dimDomain>::type::id);
  static const bool cubic_ =
      (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId == Impl::CubeTopology<dimDomain>::type::id);
  typedef typename FeMap<GridType, single_geom_, simplicial_, cubic_>::Type FEMapType;

public:
  typedef PDELab::GridFunctionSpace<GridLayerType, FEMapType, PDELab::OverlappingConformingDirichletConstraints>
      BackendType;
  typedef DunePdelabDgMapperWrapper<BackendType> MapperType;
  using EntityType = XT::Grid::extract_entity_t<GridLayerType>;
  typedef BaseFunctionSet::
      DunePdelabWrapper<BackendType, EntityType, DomainFieldType, dimDomain, RangeFieldType, rangeDim, rangeDimCols>
          BaseFunctionSetType;
  static const XT::Grid::Backends layer_backend = XT::Grid::Backends::view;
  static const bool needs_grid_view = true;
  typedef CommunicationChooser<GridLayerType> CommunicationChooserType;
  typedef typename CommunicationChooserType::Type CommunicatorType;

private:
  friend class DunePdelabDgSpaceWrapper<GridLayerImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols>;
}; // class DunePdelabDgSpaceWrapperTraits

template <class GridLayerImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols>
class DunePdelabDgProductSpaceWrapperTraits
    : public DunePdelabDgSpaceWrapperTraits<GridLayerImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols>
{
  typedef DunePdelabDgSpaceWrapperTraits<GridLayerImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols> BaseType;

public:
  typedef DunePdelabDgProductSpaceWrapper<GridLayerImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols>
      derived_type;
  using typename BaseType::GridLayerType;
  static const int polOrder = BaseType::polOrder;
  static const size_t dimDomain = GridLayerType::dimension;
  static const size_t dimRange = rangeDim;
  static const size_t dimRangeCols = rangeDimCols;
  using typename BaseType::BackendType;
  using typename BaseType::EntityType;
  using typename BaseType::RangeFieldType;
  typedef ProductDgMapper<BackendType, rangeDim, rangeDimCols> MapperType;
  using BaseType::layer_backend;
  using BaseType::needs_grid_view;

  typedef typename Dune::GDT::DunePdelabDgSpaceWrapper<GridLayerType, polOrder, RangeFieldType, 1, dimRangeCols>
      FactorSpaceType;
  typedef typename Dune::XT::Common::make_identical_tuple<FactorSpaceType, dimRange>::type SpaceTupleType;
};

} // namespace internal

template <class GridLayerImp, int polynomialOrder, class RangeFieldImp>
class DunePdelabDgSpaceWrapper<GridLayerImp, polynomialOrder, RangeFieldImp, 1, 1>
    : public DgSpaceInterface<internal::
                                  DunePdelabDgSpaceWrapperTraits<GridLayerImp, polynomialOrder, RangeFieldImp, 1, 1>,
                              GridLayerImp::dimension,
                              1,
                              1>
{
  typedef DunePdelabDgSpaceWrapper<GridLayerImp, polynomialOrder, RangeFieldImp, 1, 1> ThisType;
  typedef DgSpaceInterface<internal::DunePdelabDgSpaceWrapperTraits<GridLayerImp, polynomialOrder, RangeFieldImp, 1, 1>,
                           GridLayerImp::dimension,
                           1,
                           1>
      BaseType;

public:
  using typename BaseType::Traits;

  using typename BaseType::GridLayerType;
  using typename BaseType::BackendType;
  using typename BaseType::MapperType;
  using typename BaseType::EntityType;
  using typename BaseType::BaseFunctionSetType;

private:
  typedef typename Traits::CommunicationChooserType CommunicationChooserType;
  typedef typename Traits::FEMapType FEMapType;

public:
  using typename BaseType::CommunicatorType;

  DunePdelabDgSpaceWrapper(GridLayerType grd_vw)
    : grid_layer_(grd_vw)
    , fe_map_()
    , backend_(grid_layer_, fe_map_)
    , mapper_(backend_)
    , communicator_(CommunicationChooser<GridLayerImp>::create(grid_layer_))
    , communicator_prepared_(false)
  {
  }

  /**
   * \brief Copy ctor.
   * \note  Manually implemented bc of the std::mutex + communicator_  unique_ptr
   */
  DunePdelabDgSpaceWrapper(const ThisType& other)
    : grid_layer_(other.grid_layer_)
    , fe_map_()
    , backend_(grid_layer_, fe_map_)
    , mapper_(backend_)
    , communicator_(CommunicationChooser<GridLayerImp>::create(grid_layer_))
    , communicator_prepared_(false)
  {
    // make sure our new communicator is prepared if other's was
    if (other.communicator_prepared_)
      const auto& comm DUNE_UNUSED = this->communicator();
  }

  /**
   * \brief Move ctor.
   * \note  Manually implemented bc of the std::mutex.
   */
  DunePdelabDgSpaceWrapper(ThisType&& source)
    : grid_layer_(source.grid_layer_)
    , fe_map_(source.fe_map_)
    , backend_(source.backend_)
    , mapper_(source.mapper_)
    , communicator_(std::move(source.communicator_))
    , communicator_prepared_(source.communicator_prepared_)
  {
  }

  ThisType& operator=(const ThisType& other) = delete;

  ThisType& operator=(ThisType&& source) = delete;

  const GridLayerType& grid_layer() const
  {
    return grid_layer_;
  }

  GridLayerType& grid_layer()
  {
    return grid_layer_;
  }

  const BackendType& backend() const
  {
    return backend_;
  }

  const MapperType& mapper() const
  {
    return mapper_;
  }

  BaseFunctionSetType base_function_set(const EntityType& entity) const
  {
    return BaseFunctionSetType(backend_, entity);
  }

  CommunicatorType& communicator() const
  {
    DUNE_UNUSED std::lock_guard<std::mutex> gg(communicator_mutex_);
    if (!communicator_prepared_)
      communicator_prepared_ = CommunicationChooser<GridLayerType>::prepare(*this, *communicator_);
    return *communicator_;
  } // ... communicator(...)

private:
  GridLayerType grid_layer_;
  const FEMapType fe_map_;
  const BackendType backend_;
  const MapperType mapper_;
  mutable std::unique_ptr<CommunicatorType> communicator_;
  mutable bool communicator_prepared_;
  mutable std::mutex communicator_mutex_;
}; // class DunePdelabDgSpaceWrapper< ..., 1 >

template <class GridLayerImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim>
class DunePdelabDgProductSpaceWrapper<GridLayerImp, polynomialOrder, RangeFieldImp, rangeDim, 1>
    : public Dune::GDT::SpaceInterface<internal::DunePdelabDgProductSpaceWrapperTraits<GridLayerImp,
                                                                                polynomialOrder,
                                                                                RangeFieldImp,
                                                                                rangeDim,
                                                                                1>,
                                       GridLayerImp::dimension,
                                       rangeDim,
                                       1>,
      public Dune::GDT::ProductSpaceInterface<internal::DunePdelabDgProductSpaceWrapperTraits<GridLayerImp,
                                                                                polynomialOrder,
                                                                                RangeFieldImp,
                                                                                rangeDim,
                                                                                1>,
                                              GridLayerImp::dimension,
                                              rangeDim,
                                              1>
{
  typedef DunePdelabDgProductSpaceWrapper<GridLayerImp, polynomialOrder, RangeFieldImp, rangeDim, 1> ThisType;
  typedef typename Dune::GDT::SpaceInterface<internal::DunePdelabDgProductSpaceWrapperTraits<GridLayerImp,
                                                                                polynomialOrder,
                                                                                RangeFieldImp,
                                                                                rangeDim,
                                                                                1>,
                                             GridLayerImp::dimension,
                                             rangeDim,
                                             1>
      BaseType;

public:
  typedef typename internal::
      DunePdelabDgProductSpaceWrapperTraits<GridLayerImp, polynomialOrder, RangeFieldImp, rangeDim, 1>
          Traits;
  using typename BaseType::GridLayerType;
  using typename BaseType::EntityType;
  using typename BaseType::BaseFunctionSetType;
  using typename BaseType::MapperType;
  using typename BaseType::CommunicatorType;
  using typename BaseType::BackendType;
  using BaseType::dimDomain;
  using BaseType::dimRange;
  using BaseType::dimRangeCols;
  typedef typename Traits::SpaceTupleType SpaceTupleType;
  typedef typename Traits::FactorSpaceType FactorSpaceType;

  DunePdelabDgProductSpaceWrapper(GridLayerType grd_vw)
    : grid_layer_(grd_vw)
    , factor_space_(grid_layer_)
    , factor_mapper_(factor_space_.backend())
    , communicator_(CommunicationChooser<GridLayerImp>::create(grid_layer_))
    , communicator_prepared_(false)
  {
  }

  DunePdelabDgProductSpaceWrapper(const ThisType& other)
    : grid_layer_(other.grid_layer_)
    , factor_space_(other.factor_space_)
    , factor_mapper_(other.factor_mapper_)
    , communicator_(CommunicationChooser<GridLayerImp>::create(grid_layer_))
    , communicator_prepared_(false)
  {
    // make sure our new communicator is prepared if other's was
    if (other.communicator_prepared_)
      const auto& comm DUNE_UNUSED = this->communicator();
  }

  DunePdelabDgProductSpaceWrapper(ThisType&& source) = default;

  ThisType& operator=(const ThisType& other) = delete;

  ThisType& operator=(ThisType&& source) = delete;

  const GridLayerType& grid_layer() const
  {
    return grid_layer_;
  }

  GridLayerType& grid_layer()
  {
    return grid_layer_;
  }

  const BackendType& backend() const
  {
    return factor_space_.backend();
  }

  const MapperType& mapper() const
  {
    return factor_mapper_;
  }

  BaseFunctionSetType base_function_set(const EntityType& entity) const
  {
    return BaseFunctionSetType(backend(), entity);
  }

  CommunicatorType& communicator() const
  {
    DUNE_UNUSED std::lock_guard<std::mutex> gg(communicator_mutex_);
    if (!communicator_prepared_)
      communicator_prepared_ = CommunicationChooser<GridLayerType>::prepare(*this, *communicator_);
    return *communicator_;
  } // ... communicator(...)

  template <size_t ii>
  const FactorSpaceType& factor() const
  {
    return factor_space_;
  }

private:
  GridLayerType grid_layer_;
  const FactorSpaceType factor_space_;
  const MapperType factor_mapper_;
  mutable std::unique_ptr<CommunicatorType> communicator_;
  mutable bool communicator_prepared_;
  mutable std::mutex communicator_mutex_;
}; // class DefaultProduct< ..., 1 >

#else // HAVE_DUNE_PDELAB

template <class GridLayerImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1>
class DunePdelabDgSpaceWrapper
{
  static_assert(Dune::AlwaysFalse<GridLayerImp>::value, "You are missing dune-pdelab!");
};

#endif // HAVE_DUNE_PDELAB

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_PLAYGROUND_SPACES_DG_DUNE_PDELAB_WRAPPER_HH
<commit_msg>[spaces] simplify pdelab dg femap switch<commit_after>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2014 - 2017)
//   Rene Milk       (2014, 2016 - 2017)
//   Tobias Leibner  (2014, 2016)

#ifndef DUNE_GDT_PLAYGROUND_SPACES_DG_DUNE_PDELAB_WRAPPER_HH
#define DUNE_GDT_PLAYGROUND_SPACES_DG_DUNE_PDELAB_WRAPPER_HH

#include <memory>
#include <tuple>

#include <dune/common/fvector.hh>
#include <dune/common/deprecated.hh>

#include <dune/geometry/type.hh>

#if HAVE_DUNE_PDELAB
#include <dune/pdelab/finiteelementmap/qkdg.hh>
#include <dune/pdelab/gridfunctionspace/gridfunctionspace.hh>
#include <dune/pdelab/constraints/conforming.hh>
#endif // HAVE_DUNE_PDELAB

#include <dune/xt/common/tuple.hh>
#include <dune/xt/common/type_traits.hh>
#include <dune/xt/la/container/istl.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/grid/grids.hh>

#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/parallel.hh>
#include <dune/gdt/spaces/dg/interface.hh>
#include <dune/gdt/spaces/basefunctionset/dune-pdelab-wrapper.hh>
#include <dune/gdt/playground/spaces/mapper/dune-pdelab-wrapper.hh>

namespace Dune {
namespace GDT {

#if HAVE_DUNE_PDELAB

// forward, to be used in the traits and to allow for specialization
template <class GridLayerImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1>
class DunePdelabDgSpaceWrapper
{
  static_assert(Dune::AlwaysFalse<GridLayerImp>::value, "Untested for this combination of dimensions!");
};

// forward, to be used in the traits and to allow for specialization
template <class GridLayerImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1>
class DunePdelabDgProductSpaceWrapper
{
  static_assert(Dune::AlwaysFalse<GridLayerImp>::value, "Untested for these dimensions!");
};

namespace internal {

template <class GridLayerImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1>
class DunePdelabDgSpaceWrapperTraits
{
public:
  typedef DunePdelabDgSpaceWrapper<GridLayerImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols> derived_type;
  typedef GridLayerImp GridLayerType;
  static const int polOrder = polynomialOrder;
  static const bool continuous = false;
  static const constexpr Backends backend_type{Backends::pdelab};

private:
  typedef typename GridLayerType::ctype DomainFieldType;
  static const size_t dimDomain = GridLayerType::dimension;

public:
  typedef RangeFieldImp RangeFieldType;

private:
  template <class G, bool single_geom, bool is_simplex, bool is_cube>
  struct FeMap
  {
    static_assert(single_geom, "This space is only implemented for grids with a single geometry type!");
    static_assert(is_simplex != is_cube,
                  "This space is only implemented for either fully simplicial or fully cubic grids!");
    using Type = PDELab::QkDGLocalFiniteElementMap<DomainFieldType, RangeFieldType, polOrder, dimDomain>;
  };

  static const bool single_geom_ = Dune::Capabilities::hasSingleGeometryType<GridType>::v;
  static const bool simplicial_ =
      (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId == Impl::SimplexTopology<dimDomain>::type::id);
  static const bool cubic_ =
      (Dune::Capabilities::hasSingleGeometryType<GridType>::topologyId == Impl::CubeTopology<dimDomain>::type::id);
  typedef typename FeMap<GridType, single_geom_, simplicial_, cubic_>::Type FEMapType;

public:
  typedef PDELab::GridFunctionSpace<GridLayerType, FEMapType, PDELab::OverlappingConformingDirichletConstraints>
      BackendType;
  typedef DunePdelabDgMapperWrapper<BackendType> MapperType;
  using EntityType = XT::Grid::extract_entity_t<GridLayerType>;
  typedef BaseFunctionSet::
      DunePdelabWrapper<BackendType, EntityType, DomainFieldType, dimDomain, RangeFieldType, rangeDim, rangeDimCols>
          BaseFunctionSetType;
  static const XT::Grid::Backends layer_backend = XT::Grid::Backends::view;
  static const bool needs_grid_view = true;
  typedef CommunicationChooser<GridLayerType> CommunicationChooserType;
  typedef typename CommunicationChooserType::Type CommunicatorType;

private:
  friend class DunePdelabDgSpaceWrapper<GridLayerImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols>;
}; // class DunePdelabDgSpaceWrapperTraits

template <class GridLayerImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols>
class DunePdelabDgProductSpaceWrapperTraits
    : public DunePdelabDgSpaceWrapperTraits<GridLayerImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols>
{
  typedef DunePdelabDgSpaceWrapperTraits<GridLayerImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols> BaseType;

public:
  typedef DunePdelabDgProductSpaceWrapper<GridLayerImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols>
      derived_type;
  using typename BaseType::GridLayerType;
  static const int polOrder = BaseType::polOrder;
  static const size_t dimDomain = GridLayerType::dimension;
  static const size_t dimRange = rangeDim;
  static const size_t dimRangeCols = rangeDimCols;
  using typename BaseType::BackendType;
  using typename BaseType::EntityType;
  using typename BaseType::RangeFieldType;
  typedef ProductDgMapper<BackendType, rangeDim, rangeDimCols> MapperType;
  using BaseType::layer_backend;
  using BaseType::needs_grid_view;

  typedef typename Dune::GDT::DunePdelabDgSpaceWrapper<GridLayerType, polOrder, RangeFieldType, 1, dimRangeCols>
      FactorSpaceType;
  typedef typename Dune::XT::Common::make_identical_tuple<FactorSpaceType, dimRange>::type SpaceTupleType;
};

} // namespace internal

template <class GridLayerImp, int polynomialOrder, class RangeFieldImp>
class DunePdelabDgSpaceWrapper<GridLayerImp, polynomialOrder, RangeFieldImp, 1, 1>
    : public DgSpaceInterface<internal::
                                  DunePdelabDgSpaceWrapperTraits<GridLayerImp, polynomialOrder, RangeFieldImp, 1, 1>,
                              GridLayerImp::dimension,
                              1,
                              1>
{
  typedef DunePdelabDgSpaceWrapper<GridLayerImp, polynomialOrder, RangeFieldImp, 1, 1> ThisType;
  typedef DgSpaceInterface<internal::DunePdelabDgSpaceWrapperTraits<GridLayerImp, polynomialOrder, RangeFieldImp, 1, 1>,
                           GridLayerImp::dimension,
                           1,
                           1>
      BaseType;

public:
  using typename BaseType::Traits;

  using typename BaseType::GridLayerType;
  using typename BaseType::BackendType;
  using typename BaseType::MapperType;
  using typename BaseType::EntityType;
  using typename BaseType::BaseFunctionSetType;

private:
  typedef typename Traits::CommunicationChooserType CommunicationChooserType;
  typedef typename Traits::FEMapType FEMapType;

public:
  using typename BaseType::CommunicatorType;

  DunePdelabDgSpaceWrapper(GridLayerType grd_vw)
    : grid_layer_(grd_vw)
    , fe_map_()
    , backend_(grid_layer_, fe_map_)
    , mapper_(backend_)
    , communicator_(CommunicationChooser<GridLayerImp>::create(grid_layer_))
    , communicator_prepared_(false)
  {
  }

  /**
   * \brief Copy ctor.
   * \note  Manually implemented bc of the std::mutex + communicator_  unique_ptr
   */
  DunePdelabDgSpaceWrapper(const ThisType& other)
    : grid_layer_(other.grid_layer_)
    , fe_map_()
    , backend_(grid_layer_, fe_map_)
    , mapper_(backend_)
    , communicator_(CommunicationChooser<GridLayerImp>::create(grid_layer_))
    , communicator_prepared_(false)
  {
    // make sure our new communicator is prepared if other's was
    if (other.communicator_prepared_)
      const auto& comm DUNE_UNUSED = this->communicator();
  }

  /**
   * \brief Move ctor.
   * \note  Manually implemented bc of the std::mutex.
   */
  DunePdelabDgSpaceWrapper(ThisType&& source)
    : grid_layer_(source.grid_layer_)
    , fe_map_(source.fe_map_)
    , backend_(source.backend_)
    , mapper_(source.mapper_)
    , communicator_(std::move(source.communicator_))
    , communicator_prepared_(source.communicator_prepared_)
  {
  }

  ThisType& operator=(const ThisType& other) = delete;

  ThisType& operator=(ThisType&& source) = delete;

  const GridLayerType& grid_layer() const
  {
    return grid_layer_;
  }

  GridLayerType& grid_layer()
  {
    return grid_layer_;
  }

  const BackendType& backend() const
  {
    return backend_;
  }

  const MapperType& mapper() const
  {
    return mapper_;
  }

  BaseFunctionSetType base_function_set(const EntityType& entity) const
  {
    return BaseFunctionSetType(backend_, entity);
  }

  CommunicatorType& communicator() const
  {
    DUNE_UNUSED std::lock_guard<std::mutex> gg(communicator_mutex_);
    if (!communicator_prepared_)
      communicator_prepared_ = CommunicationChooser<GridLayerType>::prepare(*this, *communicator_);
    return *communicator_;
  } // ... communicator(...)

private:
  GridLayerType grid_layer_;
  const FEMapType fe_map_;
  const BackendType backend_;
  const MapperType mapper_;
  mutable std::unique_ptr<CommunicatorType> communicator_;
  mutable bool communicator_prepared_;
  mutable std::mutex communicator_mutex_;
}; // class DunePdelabDgSpaceWrapper< ..., 1 >

template <class GridLayerImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim>
class DunePdelabDgProductSpaceWrapper<GridLayerImp, polynomialOrder, RangeFieldImp, rangeDim, 1>
    : public Dune::GDT::SpaceInterface<internal::DunePdelabDgProductSpaceWrapperTraits<GridLayerImp,
                                                                                polynomialOrder,
                                                                                RangeFieldImp,
                                                                                rangeDim,
                                                                                1>,
                                       GridLayerImp::dimension,
                                       rangeDim,
                                       1>,
      public Dune::GDT::ProductSpaceInterface<internal::DunePdelabDgProductSpaceWrapperTraits<GridLayerImp,
                                                                                polynomialOrder,
                                                                                RangeFieldImp,
                                                                                rangeDim,
                                                                                1>,
                                              GridLayerImp::dimension,
                                              rangeDim,
                                              1>
{
  typedef DunePdelabDgProductSpaceWrapper<GridLayerImp, polynomialOrder, RangeFieldImp, rangeDim, 1> ThisType;
  typedef typename Dune::GDT::SpaceInterface<internal::DunePdelabDgProductSpaceWrapperTraits<GridLayerImp,
                                                                                polynomialOrder,
                                                                                RangeFieldImp,
                                                                                rangeDim,
                                                                                1>,
                                             GridLayerImp::dimension,
                                             rangeDim,
                                             1>
      BaseType;

public:
  typedef typename internal::
      DunePdelabDgProductSpaceWrapperTraits<GridLayerImp, polynomialOrder, RangeFieldImp, rangeDim, 1>
          Traits;
  using typename BaseType::GridLayerType;
  using typename BaseType::EntityType;
  using typename BaseType::BaseFunctionSetType;
  using typename BaseType::MapperType;
  using typename BaseType::CommunicatorType;
  using typename BaseType::BackendType;
  using BaseType::dimDomain;
  using BaseType::dimRange;
  using BaseType::dimRangeCols;
  typedef typename Traits::SpaceTupleType SpaceTupleType;
  typedef typename Traits::FactorSpaceType FactorSpaceType;

  DunePdelabDgProductSpaceWrapper(GridLayerType grd_vw)
    : grid_layer_(grd_vw)
    , factor_space_(grid_layer_)
    , factor_mapper_(factor_space_.backend())
    , communicator_(CommunicationChooser<GridLayerImp>::create(grid_layer_))
    , communicator_prepared_(false)
  {
  }

  DunePdelabDgProductSpaceWrapper(const ThisType& other)
    : grid_layer_(other.grid_layer_)
    , factor_space_(other.factor_space_)
    , factor_mapper_(other.factor_mapper_)
    , communicator_(CommunicationChooser<GridLayerImp>::create(grid_layer_))
    , communicator_prepared_(false)
  {
    // make sure our new communicator is prepared if other's was
    if (other.communicator_prepared_)
      const auto& comm DUNE_UNUSED = this->communicator();
  }

  DunePdelabDgProductSpaceWrapper(ThisType&& source) = default;

  ThisType& operator=(const ThisType& other) = delete;

  ThisType& operator=(ThisType&& source) = delete;

  const GridLayerType& grid_layer() const
  {
    return grid_layer_;
  }

  GridLayerType& grid_layer()
  {
    return grid_layer_;
  }

  const BackendType& backend() const
  {
    return factor_space_.backend();
  }

  const MapperType& mapper() const
  {
    return factor_mapper_;
  }

  BaseFunctionSetType base_function_set(const EntityType& entity) const
  {
    return BaseFunctionSetType(backend(), entity);
  }

  CommunicatorType& communicator() const
  {
    DUNE_UNUSED std::lock_guard<std::mutex> gg(communicator_mutex_);
    if (!communicator_prepared_)
      communicator_prepared_ = CommunicationChooser<GridLayerType>::prepare(*this, *communicator_);
    return *communicator_;
  } // ... communicator(...)

  template <size_t ii>
  const FactorSpaceType& factor() const
  {
    return factor_space_;
  }

private:
  GridLayerType grid_layer_;
  const FactorSpaceType factor_space_;
  const MapperType factor_mapper_;
  mutable std::unique_ptr<CommunicatorType> communicator_;
  mutable bool communicator_prepared_;
  mutable std::mutex communicator_mutex_;
}; // class DefaultProduct< ..., 1 >

#else // HAVE_DUNE_PDELAB

template <class GridLayerImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1>
class DunePdelabDgSpaceWrapper
{
  static_assert(Dune::AlwaysFalse<GridLayerImp>::value, "You are missing dune-pdelab!");
};

#endif // HAVE_DUNE_PDELAB

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_PLAYGROUND_SPACES_DG_DUNE_PDELAB_WRAPPER_HH
<|endoftext|>


<commit_before>// __BEGIN_LICENSE__
//  Copyright (c) 2009-2013, United States Government as represented by the
//  Administrator of the National Aeronautics and Space Administration. All
//  rights reserved.
//
//  The NGT platform is 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.
// __END_LICENSE__

/// \file StereoSessionFactory.cc
///

// This include must exist for linking purposes
#include <asp/Sessions/StereoSessionFactory.h>
#include <asp/Sessions/StereoSessionMapProj.h>
#include <asp/Sessions/StereoSessionIsis.h>
#include <asp/Sessions/StereoSessionNadirPinhole.h>
#include <asp/Sessions/StereoSessionPinhole.h>
#include <asp/Sessions/StereoSessionRPC.h>
#include <asp/Sessions/StereoSessionASTER.h>

#include <vw/FileIO/DiskImageResourceRaw.h>
#include <vw/Camera/CameraUtilities.h>
#include <asp/Camera/SPOT_XML.h>
#include <asp/Camera/ASTER_XML.h>
#include <vw/Camera/OpticalBarModel.h>

namespace asp{

StereoSession* StereoSessionFactory::create(std::string        & session_type, // in-out variable
                                              vw::cartography::GdalWriteOptions const& options,
                                              std::string const& left_image_file,
                                              std::string const& right_image_file,
                                              std::string const& left_camera_file,
                                              std::string const& right_camera_file,
                                              std::string const& out_prefix,
                                              std::string const& input_dem,
                                              const bool allow_map_promote) {

    // Known user session types are:
    // DG, RPC, ISIS, Pinhole, NadirPinhole, OpticalBar
    //
    // Hidden sessions are:
    // DGMapRPC, Blank (Guessing)

    // Try to guess the session if not provided
    std::string actual_session_type = session_type;
    boost::to_lower(actual_session_type);
    if (actual_session_type.empty()) {
      if (asp::has_pinhole_extension(left_camera_file ) || // TODO: Fix this dangerous code!
          asp::has_pinhole_extension(right_camera_file)   ) {
        // There can be several types of .tsai files
        std::string error_pinhole, error_opticalbar;
        try {
          boost::shared_ptr<vw::camera::CameraModel> P =
            vw::camera::load_pinhole_camera_model(left_camera_file);
          actual_session_type = "pinhole";
        }catch (std::exception & e) {
          error_pinhole = e.what();
          try {
            vw::camera::OpticalBarModel P;
            P.read(left_camera_file);
            actual_session_type = "opticalbar";
          }catch (std::exception & e) {
            error_opticalbar = e.what();
            vw_throw(vw::NoImplErr() << "Could not read the camera model " <<
                     left_camera_file << " as pinhole. "
                     << "The error was: " << error_pinhole << "\n"
                     << "Could not read it as opticalbar model either, the error was: "
                     << error_opticalbar);
          }
        }
      }
      if (boost::iends_with(boost::to_lower_copy(left_camera_file ), ".json") ||
          boost::iends_with(boost::to_lower_copy(right_camera_file), ".json") ) {
        actual_session_type = "csm";
      }else if (boost::iends_with(boost::to_lower_copy(left_image_file  ), ".cub") ||
		boost::iends_with(boost::to_lower_copy(right_image_file ), ".cub") ||
		boost::iends_with(boost::to_lower_copy(left_camera_file ), ".cub") ||
		boost::iends_with(boost::to_lower_copy(right_camera_file), ".cub") ) {
        actual_session_type = "isis";
      }else if (boost::iends_with(boost::to_lower_copy(left_camera_file ), ".xml") ||
		boost::iends_with(boost::to_lower_copy(right_camera_file), ".xml") ) {
        actual_session_type = "dg";
      } else if (boost::iends_with(boost::to_lower_copy(left_camera_file ), ".dim") ||
		 boost::iends_with(boost::to_lower_copy(right_camera_file), ".dim") ) {
        actual_session_type = "spot5";
      }
    }

    try {
      if (actual_session_type.empty()) {
        // RPC can be in the main file or it can be in the camera file.
        // DG sessions are always RPC sessions because they contain that
        //   as an extra camera model. Thus this RPC check must happen last.
        StereoSessionRPC session;
        boost::shared_ptr<vw::camera::CameraModel>
          left_model  = session.camera_model(left_image_file,  left_camera_file ),
          right_model = session.camera_model(right_image_file, right_camera_file);
        actual_session_type = "rpc";
      }
    } catch (vw::NotFoundErr const& e) {
      vw_out() << "Error: " << e.what() << "\n";
      // If it throws, it wasn't RPC
    } catch (std::exception const& e) {
      vw_out() << "Error: " << e.what() << std::endl;
      vw_out() << "Using the rpc session failed. Cannot guess other "
	       << "sessions based on filename extension.\n" << e.what() << std::endl;
    }

    if (allow_map_promote) {
      if (!input_dem.empty() && actual_session_type == "dg") {
        // User says DG but also gives a DEM.
        actual_session_type = "dgmaprpc";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: dgmaprpc" << std::endl;
      }
      if (!input_dem.empty() && actual_session_type == "rpc") {
        // User says RPC but also gives a DEM.
        actual_session_type = "rpcmaprpc";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: rpcmaprpc" << std::endl;
      }
      if (!input_dem.empty() && actual_session_type == "pinhole") {
        // User says PINHOLE but also gives a DEM.
        actual_session_type = "pinholemappinhole";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: pinholemappinhole" << std::endl;
      }
      if (!input_dem.empty() && actual_session_type == "opticalbar") {
        // User says OPTICAL BAR but also gives a DEM.
        actual_session_type = "opticalbarmapopticalbar";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: opticalbarmapopticalbar" << std::endl;
      }
      if (!input_dem.empty() && actual_session_type == "csm") {
        // User says CSM but also gives a DEM.
        actual_session_type = "csmmapcsm";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: csmmapcsm" << std::endl;
      }
      if (!input_dem.empty() && actual_session_type == "isis") {
        // User says ISIS but also gives a DEM.
        actual_session_type = "isismapisis";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: isismapisis" << std::endl;
      }
      if (!input_dem.empty() && actual_session_type == "spot5") {
        // User says SPOT5 but also gives a DEM.
        actual_session_type = "spot5maprpc";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: spot5maprpc" << std::endl;
      }
      if (!input_dem.empty() && actual_session_type == "aster") {
        // User says ASTER but also gives a DEM.
        actual_session_type = "astermaprpc";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: astermaprpc" << std::endl;
      }
      if (!input_dem.empty() && actual_session_type == "perusat") {
        // User says PeruSat but also gives a DEM.
        actual_session_type = "perusatmaprpc";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: perusatmaprpc" << std::endl;
      }

      // Quetly switch from nadirpinhole to pinhole for mapprojected images
      if (!input_dem.empty() && actual_session_type == "nadirpinhole") {
        // User says nadirpinhole but also gives a DEM.
        actual_session_type = "pinholemappinhole";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: pinhole" << std::endl;
      }

    } // End map promotion section

    // We should know the session type by now.
    VW_ASSERT(!actual_session_type.empty(),
              vw::ArgumentErr() << "Could not determine stereo session type. "
              << "Please set it explicitly using the -t switch.\n"
              << "Options include: [nadirpinhole pinhole isis dg rpc spot5 perusat aster opticalbar csm pinholemappinhole isismapisis dgmaprpc rpcmaprpc spot5maprpc perusatrpc astermaprpc opticalbarmapopticalbar csmmapcsm].\n");
    vw_out() << "Using session: " << actual_session_type << ".\n";

    // Compare the current session name to all recognized types
    // - Only one of these will ever get triggered
    StereoSession* session_new = 0;
    if (actual_session_type == "dg")
      session_new = StereoSessionDG::construct();
    else if (actual_session_type == "dgmaprpc")
        session_new = StereoSessionDGMapRPC::construct();
    else if (actual_session_type == "nadirpinhole")
      session_new = StereoSessionNadirPinhole::construct();
    else if (actual_session_type == "pinhole")
      session_new = StereoSessionPinhole::construct();
    else if (actual_session_type == "rpc")
      session_new = StereoSessionRPC::construct();
    else if (actual_session_type == "rpcmaprpc")
      session_new = StereoSessionRPCMapRPC::construct();
    else if (actual_session_type == "pinholemappinhole")
      session_new = StereoSessionPinholeMapPinhole::construct();
    else if (actual_session_type == "opticalbarmapopticalbar")
      session_new = StereoSessionBarMapBar::construct();
    else if (actual_session_type == "spot5maprpc")
        session_new = StereoSessionSpot5MapRPC::construct();
    else if (actual_session_type == "perusatmaprpc")
        session_new = StereoSessionPeruSatMapRPC::construct();
    else if (actual_session_type == "astermaprpc")
        session_new = StereoSessionASTERMapRPC::construct();
#if defined(ASP_HAVE_PKG_ISISIO) && ASP_HAVE_PKG_ISISIO == 1
    else if (actual_session_type == "isis")
      session_new = StereoSessionIsis::construct();
    else if (actual_session_type == "isismapisis")
      session_new = StereoSessionIsisMapIsis::construct();
#endif
    else if (actual_session_type == "spot5")
      session_new = StereoSessionSpot::construct();
    else if (actual_session_type == "perusat")
      session_new = StereoSessionPeruSat::construct();
    else if (actual_session_type == "aster")
      session_new = StereoSessionASTER::construct();
    else if (actual_session_type == "opticalbar")
      session_new = StereoSessionOpticalBar::construct();
    else if (actual_session_type == "csm")
      session_new = StereoSessionCsm::construct();
    else if (actual_session_type == "csmmapcsm")
      session_new = StereoSessionCsmMapCsm::construct();
    if (session_new == 0)
      vw_throw(vw::NoImplErr() << "Unsupported stereo session type: " << actual_session_type);

    session_new->initialize( options,         // Initialize the new object
                             left_image_file,  right_image_file,
                             left_camera_file, right_camera_file,
                             out_prefix, input_dem );
    session_type = session_new->name();
    return session_new;
} // End function create()

} // end namespace asp
<commit_msg>Autoguess DG, RPC, and PeruSat sessions by peeking inside the .xml<commit_after>// __BEGIN_LICENSE__
//  Copyright (c) 2009-2013, United States Government as represented by the
//  Administrator of the National Aeronautics and Space Administration. All
//  rights reserved.
//
//  The NGT platform is 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.
// __END_LICENSE__

/// \file StereoSessionFactory.cc
///

// This include must exist for linking purposes
#include <asp/Sessions/StereoSessionFactory.h>
#include <asp/Sessions/StereoSessionMapProj.h>
#include <asp/Sessions/StereoSessionIsis.h>
#include <asp/Sessions/StereoSessionNadirPinhole.h>
#include <asp/Sessions/StereoSessionPinhole.h>
#include <asp/Sessions/StereoSessionRPC.h>
#include <asp/Sessions/StereoSessionASTER.h>

#include <vw/FileIO/DiskImageResourceRaw.h>
#include <vw/Camera/CameraUtilities.h>
#include <asp/Camera/SPOT_XML.h>
#include <asp/Camera/ASTER_XML.h>
#include <vw/Camera/OpticalBarModel.h>

namespace asp{

StereoSession* StereoSessionFactory::create(std::string        & session_type, // in-out variable
                                            vw::cartography::GdalWriteOptions const& options,
                                            std::string const& left_image_file,
                                            std::string const& right_image_file,
                                            std::string const& left_camera_file,
                                            std::string const& right_camera_file,
                                            std::string const& out_prefix,
                                            std::string const& input_dem,
                                            const bool allow_map_promote) {

    // Known user session types are:
    // DG, RPC, ISIS, Pinhole, NadirPinhole, OpticalBar
    //
    // Hidden sessions are:
    // DGMapRPC, Blank (Guessing)

    // Try to guess the session if not provided
    std::string actual_session_type = session_type;
    boost::to_lower(actual_session_type);
    if (actual_session_type.empty()) {
      if (asp::has_pinhole_extension(left_camera_file ) || // TODO: Fix this dangerous code!
          asp::has_pinhole_extension(right_camera_file)   ) {
        // There can be several types of .tsai files
        std::string error_pinhole, error_opticalbar;
        try {
          boost::shared_ptr<vw::camera::CameraModel> P =
            vw::camera::load_pinhole_camera_model(left_camera_file);
          actual_session_type = "pinhole";
        }catch (std::exception & e) {
          error_pinhole = e.what();
          try {
            vw::camera::OpticalBarModel P;
            P.read(left_camera_file);
            actual_session_type = "opticalbar";
          }catch (std::exception & e) {
            error_opticalbar = e.what();
            vw_throw(vw::NoImplErr() << "Could not read the camera model " <<
                     left_camera_file << " as pinhole. "
                     << "The error was: " << error_pinhole << "\n"
                     << "Could not read it as opticalbar model either, the error was: "
                     << error_opticalbar);
          }
        }
      } else if (boost::iends_with(boost::to_lower_copy(left_camera_file ), ".json") ||
          boost::iends_with(boost::to_lower_copy(right_camera_file), ".json") ) {
        actual_session_type = "csm";
      }else if (boost::iends_with(boost::to_lower_copy(left_image_file  ), ".cub") ||
		boost::iends_with(boost::to_lower_copy(right_image_file ), ".cub") ||
		boost::iends_with(boost::to_lower_copy(left_camera_file ), ".cub") ||
		boost::iends_with(boost::to_lower_copy(right_camera_file), ".cub") ) {
        actual_session_type = "isis";
      } else if (boost::iends_with(boost::to_lower_copy(left_camera_file ), ".dim") ||
                 boost::iends_with(boost::to_lower_copy(right_camera_file), ".dim") ) {
        actual_session_type = "spot5";
      }else if (boost::iends_with(boost::to_lower_copy(left_camera_file ), ".xml") ||
		boost::iends_with(boost::to_lower_copy(right_camera_file), ".xml") ) {

        // Here we have several options
        if (actual_session_type.empty()) {
          // Try DG exact linescan model
          try {
            StereoSessionDG session;
            boost::shared_ptr<vw::camera::CameraModel>
              left_model  = session.camera_model(left_image_file,  left_camera_file ),
              right_model = session.camera_model(right_image_file, right_camera_file);
            actual_session_type = "dg";
          } catch (...) {}
        }

        if (actual_session_type.empty()) {
          // Try PeruSat exact linescan model
          try {
            StereoSessionPeruSat session;
            boost::shared_ptr<vw::camera::CameraModel>
              left_model  = session.camera_model(left_image_file,  left_camera_file ),
              right_model = session.camera_model(right_image_file, right_camera_file);
            actual_session_type = "perusat";
          } catch (...) {}
        }

        if (actual_session_type.empty()) {
          // Try RPC
          try {
            StereoSessionRPC session;
            boost::shared_ptr<vw::camera::CameraModel>
              left_model  = session.camera_model(left_image_file,  left_camera_file ),
              right_model = session.camera_model(right_image_file, right_camera_file);
            actual_session_type = "rpc";
          } catch (...) {
            vw_out() << "Tried the DG, PeruSat and RPC sessions. Please specify the session "
                     << "explicitly using the -t option.\n";
          }
        }
      } // end considering the xml extension case
    }

    if (allow_map_promote) {
      if (!input_dem.empty() && actual_session_type == "dg") {
        // User says DG but also gives a DEM.
        actual_session_type = "dgmaprpc";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: dgmaprpc.\n";
      }
      if (!input_dem.empty() && actual_session_type == "rpc") {
        // User says RPC but also gives a DEM.
        actual_session_type = "rpcmaprpc";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: rpcmaprpc.\n";
      }
      if (!input_dem.empty() && actual_session_type == "pinhole") {
        // User says PINHOLE but also gives a DEM.
        actual_session_type = "pinholemappinhole";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: pinholemappinhole.\n";
      }
      if (!input_dem.empty() && actual_session_type == "opticalbar") {
        // User says OPTICAL BAR but also gives a DEM.
        actual_session_type = "opticalbarmapopticalbar";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: opticalbarmapopticalbar.\n";
      }
      if (!input_dem.empty() && actual_session_type == "csm") {
        // User says CSM but also gives a DEM.
        actual_session_type = "csmmapcsm";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: csmmapcsm.\n";
      }
      if (!input_dem.empty() && actual_session_type == "isis") {
        // User says ISIS but also gives a DEM.
        actual_session_type = "isismapisis";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: isismapisis.\n";
      }
      if (!input_dem.empty() && actual_session_type == "spot5") {
        // User says SPOT5 but also gives a DEM.
        actual_session_type = "spot5maprpc";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: spot5maprpc.\n";
      }
      if (!input_dem.empty() && actual_session_type == "aster") {
        // User says ASTER but also gives a DEM.
        actual_session_type = "astermaprpc";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: astermaprpc.\n";
      }
      if (!input_dem.empty() && actual_session_type == "perusat") {
        // User says PeruSat but also gives a DEM.
        actual_session_type = "perusatmaprpc";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: perusatmaprpc.\n";
      }

      // Quetly switch from nadirpinhole to pinhole for mapprojected images
      if (!input_dem.empty() && actual_session_type == "nadirpinhole") {
        // User says nadirpinhole but also gives a DEM.
        actual_session_type = "pinholemappinhole";
        VW_OUT(vw::DebugMessage,"asp") << "Changing session type to: pinhole.\n";
      }

    } // End map promotion section

    // We should know the session type by now.
    VW_ASSERT(!actual_session_type.empty(),
              vw::ArgumentErr() << "Could not determine stereo session type. "
              << "Please set it explicitly using the -t switch.\n"
              << "Options include: [nadirpinhole pinhole isis dg rpc spot5 perusat aster opticalbar csm pinholemappinhole isismapisis dgmaprpc rpcmaprpc spot5maprpc perusatrpc astermaprpc opticalbarmapopticalbar csmmapcsm].\n");
    vw_out() << "Using session: " << actual_session_type << ".\n";

    // Compare the current session name to all recognized types
    // - Only one of these will ever get triggered
    StereoSession* session = NULL;
    if (actual_session_type == "dg")
      session = StereoSessionDG::construct();
    else if (actual_session_type == "dgmaprpc")
        session = StereoSessionDGMapRPC::construct();
    else if (actual_session_type == "nadirpinhole")
      session = StereoSessionNadirPinhole::construct();
    else if (actual_session_type == "pinhole")
      session = StereoSessionPinhole::construct();
    else if (actual_session_type == "rpc")
      session = StereoSessionRPC::construct();
    else if (actual_session_type == "rpcmaprpc")
      session = StereoSessionRPCMapRPC::construct();
    else if (actual_session_type == "pinholemappinhole")
      session = StereoSessionPinholeMapPinhole::construct();
    else if (actual_session_type == "opticalbarmapopticalbar")
      session = StereoSessionBarMapBar::construct();
    else if (actual_session_type == "spot5maprpc")
        session = StereoSessionSpot5MapRPC::construct();
    else if (actual_session_type == "perusatmaprpc")
        session = StereoSessionPeruSatMapRPC::construct();
    else if (actual_session_type == "astermaprpc")
        session = StereoSessionASTERMapRPC::construct();
#if defined(ASP_HAVE_PKG_ISISIO) && ASP_HAVE_PKG_ISISIO == 1
    else if (actual_session_type == "isis")
      session = StereoSessionIsis::construct();
    else if (actual_session_type == "isismapisis")
      session = StereoSessionIsisMapIsis::construct();
#endif
    else if (actual_session_type == "spot5")
      session = StereoSessionSpot::construct();
    else if (actual_session_type == "perusat")
      session = StereoSessionPeruSat::construct();
    else if (actual_session_type == "aster")
      session = StereoSessionASTER::construct();
    else if (actual_session_type == "opticalbar")
      session = StereoSessionOpticalBar::construct();
    else if (actual_session_type == "csm")
      session = StereoSessionCsm::construct();
    else if (actual_session_type == "csmmapcsm")
      session = StereoSessionCsmMapCsm::construct();
    if (session == 0)
      vw_throw(vw::NoImplErr() << "Unsupported stereo session type: " << actual_session_type);

    session->initialize(options,         // Initialize the new object
                        left_image_file,  right_image_file,
                        left_camera_file, right_camera_file,
                        out_prefix, input_dem);
    session_type = session->name(); // update the session name
    return session;
} // End function create()

} // end namespace asp
<|endoftext|>