<commit_before>/*
 * File:   AppleCoreaudioBackend.hpp
 * Author: ivan
 *
 * Created on February 3, 2016, 9:36 PM
 */

#pragma once

#include "../Exc.hpp"
#include "../AudioFormat.hpp"
#include "../Listener.hpp"

//#include <CoreAudio/CoreAudio.h>
#include <AudioUnit/AudioUnit.h>

namespace audout{

class AppleCoreaudioBackend{

	struct AudioComponent{
		AudioComponentInstance instance;

		AudioComponent(){
			//open the default audio device
			AudioComponentDescription desc;
			desc.componentType = kAudioUnitType_Output;
			desc.componentSubType = kAudioUnitSubType_DefaultOutput;
			desc.componentFlags = 0;
			desc.componentFlagsMask = 0;
			desc.componentManufacturer = kAudioUnitManufacturer_Apple;

			auto component = AudioComponentFindNext(nullptr, &desc);
			if(!component){
				throw audout::Exc("Failed to find default audio device");
			}

			if(AudioComponentInstanceNew(component, &this->instance)){
				throw audout::Exc("Failed to open default audio device");
			}
		}

		~AudioComponent()noexcept{
			AudioComponentInstanceDispose(this->instance);
		}
	} audioComponent;

	static OSStatus outputCallback(
			void *inRefCon,
			AudioUnitRenderActionFlags *ioActionFlags,
			const AudioTimeStamp *inTimeStamp,
			UInt32 inBusNumber,
			UInt32 inNumberFrames,
			AudioBufferList *ioData
		)
	{
		auto listener = reinterpret_cast<Listener*>(inRefCon);

		for(unsigned i = 0; i != ioData->mNumberBuffers; ++i){
			auto& buf = ioData->mBuffers[i];
//			TRACE(<< "num channels = " << buf.mNumberChannels << std::endl)
			ASSERT(buf.mDataByteSize % sizeof(std::int16_t) == 0)
			listener->fillPlayBuf(utki::wrapBuf(
					reinterpret_cast<std::int16_t*>(buf.mData),
					buf.mDataByteSize / sizeof(std::int16_t)
				));
		}

		return 0;
	}

public:
	AppleCoreaudioBackend(
			audout::AudioFormat outputFormat,
			std::uint32_t bufferSizeFrames,
			audout::Listener* listener
		)
	{
		if(AudioUnitInitialize(this->audioComponent.instance)){
			throw audout::Exc("Failed to initialize audio unit instance");
		}

		AudioStreamBasicDescription formatDesc;
		formatDesc.mSampleRate = outputFormat.frequency();
		formatDesc.mFormatID = kAudioFormatLinearPCM;
		formatDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger;
		formatDesc.mFramesPerPacket = 1;
		formatDesc.mChannelsPerFrame = outputFormat.numChannels();
		formatDesc.mBitsPerChannel = 16;
		formatDesc.mBytesPerFrame = formatDesc.mChannelsPerFrame * 2;
		formatDesc.mBytesPerPacket = formatDesc.mBytesPerFrame;

		if(AudioUnitSetProperty(
				this->audioComponent.instance,
				kAudioUnitProperty_StreamFormat,
				kAudioUnitScope_Input,
				0,
				&formatDesc,
				sizeof(formatDesc)
			))
		{
			throw audout::Exc("Failed to set audio unit input property");
		}

		AURenderCallbackStruct callback;
		memset(&callback, 0, sizeof(callback));
		callback.inputProc = &outputCallback;
		callback.inputProcRefCon = listener;

		if(AudioUnitSetProperty(
				this->audioComponent.instance,
				kAudioUnitProperty_SetRenderCallback,
				kAudioUnitScope_Input,
				0,
				&callback,
				sizeof(callback)
			))
		{
			throw audout::Exc("Unable to attach an IOProc to the selected audio unit");
		}

		this->setPaused(false);
	}

	~AppleCoreaudioBackend()noexcept{
		this->setPaused(true);
	}

	void setPaused(bool paused){
		if(paused){
			AudioOutputUnitStop(this->audioComponent.instance);
		}else{
			if(AudioOutputUnitStart(this->audioComponent.instance)){
				throw audout::Exc("Unable to start audio unit");
			}
		}
	}
};

}
<commit_msg>stuff<commit_after>/*
 * File:   AppleCoreaudioBackend.hpp
 * Author: ivan
 *
 * Created on February 3, 2016, 9:36 PM
 */

#pragma once

#include "../Exc.hpp"
#include "../AudioFormat.hpp"
#include "../Listener.hpp"

#include <AudioUnit/AudioUnit.h>

namespace audout{

class AppleCoreaudioBackend{

	struct AudioComponent{
		AudioComponentInstance instance;

		AudioComponent(){
			//open the default audio device
			AudioComponentDescription desc;
			desc.componentType = kAudioUnitType_Output;
			desc.componentSubType = kAudioUnitSubType_DefaultOutput;
			desc.componentFlags = 0;
			desc.componentFlagsMask = 0;
			desc.componentManufacturer = kAudioUnitManufacturer_Apple;

			auto component = AudioComponentFindNext(nullptr, &desc);
			if(!component){
				throw audout::Exc("Failed to find default audio device");
			}

			if(AudioComponentInstanceNew(component, &this->instance)){
				throw audout::Exc("Failed to open default audio device");
			}
		}

		~AudioComponent()noexcept{
			AudioComponentInstanceDispose(this->instance);
		}
	} audioComponent;

	static OSStatus outputCallback(
			void *inRefCon,
			AudioUnitRenderActionFlags *ioActionFlags,
			const AudioTimeStamp *inTimeStamp,
			UInt32 inBusNumber,
			UInt32 inNumberFrames,
			AudioBufferList *ioData
		)
	{
		auto listener = reinterpret_cast<Listener*>(inRefCon);

		for(unsigned i = 0; i != ioData->mNumberBuffers; ++i){
			auto& buf = ioData->mBuffers[i];
//			TRACE(<< "num channels = " << buf.mNumberChannels << std::endl)
			ASSERT(buf.mDataByteSize % sizeof(std::int16_t) == 0)
			listener->fillPlayBuf(utki::wrapBuf(
					reinterpret_cast<std::int16_t*>(buf.mData),
					buf.mDataByteSize / sizeof(std::int16_t)
				));
		}

		return 0;
	}

public:
	AppleCoreaudioBackend(
			audout::AudioFormat outputFormat,
			std::uint32_t bufferSizeFrames,
			audout::Listener* listener
		)
	{
		if(AudioUnitInitialize(this->audioComponent.instance)){
			throw audout::Exc("Failed to initialize audio unit instance");
		}

		AudioStreamBasicDescription formatDesc;
		formatDesc.mSampleRate = outputFormat.frequency();
		formatDesc.mFormatID = kAudioFormatLinearPCM;
		formatDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger;
		formatDesc.mFramesPerPacket = 1;
		formatDesc.mChannelsPerFrame = outputFormat.numChannels();
		formatDesc.mBitsPerChannel = 16;
		formatDesc.mBytesPerFrame = formatDesc.mChannelsPerFrame * 2;
		formatDesc.mBytesPerPacket = formatDesc.mBytesPerFrame;

		if(AudioUnitSetProperty(
				this->audioComponent.instance,
				kAudioUnitProperty_StreamFormat,
				kAudioUnitScope_Input,
				0,
				&formatDesc,
				sizeof(formatDesc)
			))
		{
			throw audout::Exc("Failed to set audio unit input property");
		}

		AURenderCallbackStruct callback;
		memset(&callback, 0, sizeof(callback));
		callback.inputProc = &outputCallback;
		callback.inputProcRefCon = listener;

		if(AudioUnitSetProperty(
				this->audioComponent.instance,
				kAudioUnitProperty_SetRenderCallback,
				kAudioUnitScope_Input,
				0,
				&callback,
				sizeof(callback)
			))
		{
			throw audout::Exc("Unable to attach an IOProc to the selected audio unit");
		}

		this->setPaused(false);
	}

	~AppleCoreaudioBackend()noexcept{
		this->setPaused(true);
	}

	void setPaused(bool paused){
		if(paused){
			AudioOutputUnitStop(this->audioComponent.instance);
		}else{
			if(AudioOutputUnitStart(this->audioComponent.instance)){
				throw audout::Exc("Unable to start audio unit");
			}
		}
	}
};

}
<|endoftext|>


<commit_before>/*
*
* Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: Ken Zangelin
*/
#include "unittest.h"

#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "rest/ConnectionInfo.h"

extern int servicePathCheck(ConnectionInfo* ciP, const char* path);
extern int servicePathSplit(ConnectionInfo* ciP);

/* ****************************************************************************
*
* rest.servicePathCheck -
*/
TEST(rest, servicePathCheck)
{
  ConnectionInfo  ci;
  int             r;

  // 0. OK - as no Service Path has been received ...
  ci.servicePath = "";
  r = servicePathCheck(&ci, ci.servicePath.c_str());
  EXPECT_EQ(0, r);

  // Mark that a Service Path has been received
  ci.httpHeaders.servicePathReceived = true;

  // 1. OK
  ci.servicePath = "/h1/_h2/h3/_h4/h5/_h6/h7/_h8/h9/_h10h10h10";
  r = servicePathCheck(&ci, ci.servicePath.c_str());
  EXPECT_EQ(0, r);

  // Not starting with '/'
  ci.servicePath = "x";
  r = servicePathCheck(&ci, ci.servicePath.c_str());
  EXPECT_EQ(1, r);

  // 2. More than 10 components in Service Path
  ci.servicePath = "/h1/h2/h3/h4/h5/h6/h7/h8/h9/h10/h11";
  r = servicePathCheck(&ci, ci.servicePath.c_str());
  EXPECT_EQ(2, r);

  // More than 10 chars in path component of Service Path
  ci.servicePath = "/h0123456789";
  r = servicePathCheck(&ci, ci.servicePath.c_str());
  EXPECT_EQ(3, r);

  // Bad character ('-') in Service Path
  ci.servicePath = "/h-0";
  r = servicePathCheck(&ci, ci.servicePath.c_str());
  EXPECT_EQ(4, r);
}

/* ****************************************************************************
*
* rest.servicePathSplit -
*/
TEST(rest, servicePathSplit)
{
  ConnectionInfo  ci1;
  ConnectionInfo  ci2;
  ConnectionInfo  ci3;
  ConnectionInfo  ci4;
  ConnectionInfo  ci5;
  int             r;

  // 1. OK - as no Service Path has been received ...
  LM_M(("---- 1 -----"));
  ci1.servicePath = "";
  r = servicePathSplit(&ci1);
  EXPECT_EQ(0, r);
  LM_M(("---- 1 -----"));

  // 2. OK - one service path
  ci2.httpHeaders.servicePathReceived = true;
  LM_M(("---- 2 -----"));
  ci2.servicePath = "/h1/_h2/h3/_h4/h5/_h6/h7/_h8/h9/_h10h10h10";
  r = servicePathSplit(&ci2);
  EXPECT_EQ(0, r);
  LM_M(("---- 2 -----"));

  // 3. OK - two service paths
  LM_M(("---- 3 -----"));
  ci3.httpHeaders.servicePathReceived = true;
  ci3.servicePath = "/h1/_h2/h3/_h4/h5/_h6/h7/_h8/h9/_h10h10h10, /1/2/3";
  r = servicePathSplit(&ci3);
  EXPECT_EQ(0, r);
  EXPECT_STREQ("", ci3.answer.c_str());
  LM_M(("---- 3 -----"));

  // 4. OK - nine service paths
  LM_M(("---- 4 -----"));
  ci4.httpHeaders.servicePathReceived = true;
  ci4.servicePath = "/home/kz/01, /home/kz/02, /home/kz/03, /home/kz/04, /home/kz/05, /home/kz/06, /home/kz/07, /home/kz/08, /home/kz/09";
  r = servicePathSplit(&ci4);
  EXPECT_EQ(0, r);
  EXPECT_STREQ("", ci4.answer.c_str());
  LM_M(("---- 4 -----"));

  // 5. NOT OK - eleven service paths
  LM_M(("---- 5 -----"));
  ci5.httpHeaders.servicePathReceived = true;
  ci5.servicePath = "/home/kz/01, /home/kz/02, /home/kz/03, /home/kz/04, /home/kz/05, /home/kz/06, /home/kz/07, /home/kz/08, /home/kz/09, /home/kz/10, /home/kz/11";
  r = servicePathSplit(&ci5);
  EXPECT_EQ(5, r);
  EXPECT_EQ(177, ci5.answer.size());
  LM_M(("---- 5 -----"));
}
<commit_msg>FIX broken unit test after PR #423<commit_after>/*
*
* Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: Ken Zangelin
*/
#include "unittest.h"

#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "rest/ConnectionInfo.h"

extern int servicePathCheck(ConnectionInfo* ciP, const char* path);
extern int servicePathSplit(ConnectionInfo* ciP);

/* ****************************************************************************
*
* rest.servicePathCheck -
*/
TEST(rest, servicePathCheck)
{
  ConnectionInfo  ci;
  int             r;

  // 0. OK - as no Service Path has been received ...
  ci.servicePath = "";
  r = servicePathCheck(&ci, ci.servicePath.c_str());
  EXPECT_EQ(0, r);

  // Mark that a Service Path has been received
  ci.httpHeaders.servicePathReceived = true;

  // 1. OK
  ci.servicePath = "/h1/_h2/h3/_h4/h5/_h6/h7/_h8/h9/_h10h10h10";
  r = servicePathCheck(&ci, ci.servicePath.c_str());
  EXPECT_EQ(0, r);

  // Not starting with '/'
  ci.servicePath = "x";
  r = servicePathCheck(&ci, ci.servicePath.c_str());
  EXPECT_EQ(1, r);

  // 2. More than 10 components in Service Path
  ci.servicePath = "/h1/h2/h3/h4/h5/h6/h7/h8/h9/h10/h11";
  r = servicePathCheck(&ci, ci.servicePath.c_str());
  EXPECT_EQ(2, r);

  // More than 10 chars in path component of Service Path
  ci.servicePath = "/h0123456789";
  r = servicePathCheck(&ci, ci.servicePath.c_str());
  EXPECT_EQ(3, r);

  // Bad character ('-') in Service Path
  ci.servicePath = "/h-0";
  r = servicePathCheck(&ci, ci.servicePath.c_str());
  EXPECT_EQ(4, r);
}

/* ****************************************************************************
*
* rest.servicePathSplit -
*/
TEST(rest, servicePathSplit)
{
  ConnectionInfo  ci1;
  ConnectionInfo  ci2;
  ConnectionInfo  ci3;
  ConnectionInfo  ci4;
  ConnectionInfo  ci5;
  int             r;

  // 1. OK - as no Service Path has been received ...
  LM_M(("---- 1 -----"));
  ci1.servicePath = "";
  r = servicePathSplit(&ci1);
  EXPECT_EQ(0, r);
  LM_M(("---- 1 -----"));

  // 2. OK - one service path
  ci2.httpHeaders.servicePathReceived = true;
  LM_M(("---- 2 -----"));
  ci2.servicePath = "/h1/_h2/h3/_h4/h5/_h6/h7/_h8/h9/_h10h10h10";
  r = servicePathSplit(&ci2);
  EXPECT_EQ(0, r);
  LM_M(("---- 2 -----"));

  // 3. OK - two service paths
  LM_M(("---- 3 -----"));
  ci3.httpHeaders.servicePathReceived = true;
  ci3.servicePath = "/h1/_h2/h3/_h4/h5/_h6/h7/_h8/h9/_h10h10h10, /1/2/3";
  r = servicePathSplit(&ci3);
  EXPECT_EQ(0, r);
  EXPECT_STREQ("", ci3.answer.c_str());
  LM_M(("---- 3 -----"));

  // 4. OK - nine service paths
  LM_M(("---- 4 -----"));
  ci4.httpHeaders.servicePathReceived = true;
  ci4.servicePath = "/home/kz/01, /home/kz/02, /home/kz/03, /home/kz/04, /home/kz/05, /home/kz/06, /home/kz/07, /home/kz/08, /home/kz/09";
  r = servicePathSplit(&ci4);
  EXPECT_EQ(0, r);
  EXPECT_STREQ("", ci4.answer.c_str());
  LM_M(("---- 4 -----"));

  // 5. NOT OK - eleven service paths
  LM_M(("---- 5 -----"));
  ci5.httpHeaders.servicePathReceived = true;
  ci5.servicePath = "/home/kz/01, /home/kz/02, /home/kz/03, /home/kz/04, /home/kz/05, /home/kz/06, /home/kz/07, /home/kz/08, /home/kz/09, /home/kz/10, /home/kz/11";
  r = servicePathSplit(&ci5);
  EXPECT_EQ(-1, r);
  EXPECT_EQ(177, ci5.answer.size());
  LM_M(("---- 5 -----"));
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/hwpf/fapi2/include/target_types.H $                */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2012,2022                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 * @file target_types.H
 * @brief definitions for fapi2 target types
 */

#ifndef __FAPI2_TARGET_TYPES__
#define __FAPI2_TARGET_TYPES__
#include <stdint.h>

/// FAPI namespace
namespace fapi2
{
///
/// @enum fapi::TargetType
/// @brief Types, kinds, of targets
/// @note TYPE_NONE is used to represent empty/NULL targets in lists
/// or tables. TYPE_ALL is used to pass targets to methods which
/// can act generally on any type of target
///

/// Target Kind
enum TargetType : uint64_t
{
    TARGET_TYPE_NONE            = 0x0000000000000000, ///< No type
    TARGET_TYPE_SYSTEM          = 0x0000000000000001, ///< System type
    TARGET_TYPE_DIMM            = 0x0000000000000002, ///< DIMM type
    TARGET_TYPE_PROC_CHIP       = 0x0000000000000004, ///< Processor type
    TARGET_TYPE_MEMBUF_CHIP     = 0x0000000000000008, ///< Membuf type
    TARGET_TYPE_EX              = 0x0000000000000010, ///< EX - 2x Core, L2, L3 - can be deconfigured
    TARGET_TYPE_MBA             = 0x0000000000000020, ///< MBA type
    TARGET_TYPE_MCS             = 0x0000000000000040, ///< MCS type
    TARGET_TYPE_XBUS            = 0x0000000000000080, ///< XBUS type
    TARGET_TYPE_ABUS            = 0x0000000000000100, ///< ABUS type
    TARGET_TYPE_L4              = 0x0000000000000200, ///< L4 type
    TARGET_TYPE_CORE            = 0x0000000000000400, ///< Core
    TARGET_TYPE_EQ              = 0x0000000000000800, ///< EQ - 4x core, 2x L2, 2x L3 - can be deconfigured
    TARGET_TYPE_MCA             = 0x0000000000001000, ///< MCA type
    TARGET_TYPE_MCBIST          = 0x0000000000002000, ///< MCBIST type
    TARGET_TYPE_MI              = 0x0000000000004000, ///< MI Memory Interface (Cumulus)
    TARGET_TYPE_CAPP            = 0x0000000000008000, ///< CAPP target
    TARGET_TYPE_DMI             = 0x0000000000010000, ///< DMI type
    TARGET_TYPE_OBUS            = 0x0000000000020000, ///< OBUS type
    TARGET_TYPE_OBUS_BRICK      = 0x0000000000040000, ///< OBUS BRICK type
    TARGET_TYPE_SBE             = 0x0000000000080000, ///< SBE type
    TARGET_TYPE_PPE             = 0x0000000000100000, ///< PPE type
    TARGET_TYPE_PERV            = 0x0000000000200000, ///< Pervasive type
    TARGET_TYPE_PEC             = 0x0000000000400000, ///< PEC type
    TARGET_TYPE_PHB             = 0x0000000000800000, ///< PHB type
    TARGET_TYPE_MC              = 0x0000000001000000, ///< MC type
    TARGET_TYPE_OMI             = 0x0000000002000000, ///< OMI type
    TARGET_TYPE_OMIC            = 0x0000000004000000, ///< OMIC type
    TARGET_TYPE_MCC             = 0x0000000008000000, ///< MCC type
    TARGET_TYPE_OCMB_CHIP       = 0x0000000010000000, ///< OCMB type
    TARGET_TYPE_MEM_PORT        = 0x0000000020000000, ///< MEM_PORT type
    TARGET_TYPE_NMMU            = 0x0000000040000000, ///< NEST MMU type
    TARGET_TYPE_RESERVED        = 0x0000000080000000, ///< Reserved for Cronus (Z)
    TARGET_TYPE_PAU             = 0x0000000100000000, ///< PAU type
    TARGET_TYPE_IOHS            = 0x0000000200000000, ///< IOHS type
    TARGET_TYPE_FC              = 0x0000000400000000, ///< Fused Core type
    TARGET_TYPE_PMIC            = 0x0000000800000000, ///< PMIC type
    TARGET_TYPE_PAUC            = 0x0000001000000000, ///< PAUC type
    TARGET_TYPE_GENERICI2CSLAVE = 0x0000002000000000, ///< GENERICI2CSLAVE type
    TARGET_TYPE_GENERICI2CRESPONDER = 0x0000002000000000, ///< GENERICI2RESPONDER type
    TARGET_TYPE_IOLINK          = 0x0000004000000000, ///< IOLINK type
    TARGET_TYPE_MDS_CTLR        = 0x0000008000000000, ///< MDS Media Controller type
    TARGET_TYPE_MULTICAST       = 0x8000000000000000, ///< MULTICAST type
    TARGET_TYPE_ALL             = 0x7FFFFFFFFFFFFFFF, ///< Any/All types
    TARGET_TYPE_ALL_MC          = 0xFFFFFFFFFFFFFFFF, ///< Any/All types + Multicast

    // Compound target types
    TARGET_TYPE_CHIPS         = TARGET_TYPE_PROC_CHIP |
                                TARGET_TYPE_MEMBUF_CHIP |
                                TARGET_TYPE_OCMB_CHIP,

    TARGET_TYPE_CHIPLETS      = TARGET_TYPE_EX            |
                                TARGET_TYPE_MBA           |
                                TARGET_TYPE_MCS           |
                                TARGET_TYPE_XBUS          |
                                TARGET_TYPE_ABUS          |
                                TARGET_TYPE_L4            |
                                TARGET_TYPE_CORE          |
                                TARGET_TYPE_EQ            |
                                TARGET_TYPE_MCA           |
                                TARGET_TYPE_MCBIST        |
                                TARGET_TYPE_MI            |
                                TARGET_TYPE_DMI           |
                                TARGET_TYPE_OBUS          |
                                TARGET_TYPE_OBUS_BRICK    |
                                TARGET_TYPE_SBE           |
                                TARGET_TYPE_PPE           |
                                TARGET_TYPE_PERV          |
                                TARGET_TYPE_PEC           |
                                TARGET_TYPE_PHB           |
                                TARGET_TYPE_MC            |
                                TARGET_TYPE_OMI           |
                                TARGET_TYPE_OMIC          |
                                TARGET_TYPE_MCC           |
                                TARGET_TYPE_MEM_PORT      |
                                TARGET_TYPE_NMMU          |
                                TARGET_TYPE_PAU           |
                                TARGET_TYPE_IOHS          |
                                TARGET_TYPE_FC            |
                                TARGET_TYPE_PAUC          |
                                TARGET_TYPE_IOLINK,

    TARGET_TYPE_MULTICASTABLE = TARGET_TYPE_CORE   |
                                TARGET_TYPE_EQ     |
                                TARGET_TYPE_IOHS   |
                                TARGET_TYPE_MC     |
                                TARGET_TYPE_PAUC   |
                                TARGET_TYPE_PEC    |
                                TARGET_TYPE_PERV,

    TARGET_TYPE_MULTICAST_CHIP = TARGET_TYPE_PROC_CHIP  |
                                 TARGET_TYPE_OCMB_CHIP,

    TARGET_TYPE_ANY_POZ_CHIP  = TARGET_TYPE_PROC_CHIP |
                                TARGET_TYPE_OCMB_CHIP,

    // Mappings to target types found in the error xml files
    TARGET_TYPE_EX_CHIPLET    = TARGET_TYPE_EX,
    TARGET_TYPE_MBA_CHIPLET   = TARGET_TYPE_MBA,
    TARGET_TYPE_MCS_CHIPLET   = TARGET_TYPE_MCS,
    TARGET_TYPE_XBUS_ENDPOINT = TARGET_TYPE_XBUS,
    TARGET_TYPE_ABUS_ENDPOINT = TARGET_TYPE_ABUS,
};

// The fsp x86 compiler is too old to support the full C++11 standard and
// they have not been able to upgrade to a later compiler yet due to a
// requirement to run tools on LCB machines which are still running RHEL6
// which doesn't have the necessary runtime support for executables compiled
// with the newer compiler versions.
//
// Don't compile this forward declaration unless c++11 or greater is being
// used.
//
#if(__GNUC__ && (__cplusplus >= 201103L))
///
/// Target filter 64-bit
/// Declare the enumeration size so that target.H will compile without chip specific filter.
/// When users want to use an enumeration value then they can include the chip specific
/// target_filters.H, which would have the enumerator list of values.
///
enum TargetFilter : uint64_t;
#endif

// attributeOverride tool requires x86.nfp compile
#ifndef CONTEXT_x86_nfp
/// @cond
    constexpr TargetType operator|(TargetType x, TargetType y)
{
    return static_cast<TargetType>(static_cast<uint64_t>(x) |
                                   static_cast<uint64_t>(y));
}

constexpr TargetType operator&(TargetType x, TargetType y)
{
    return static_cast<TargetType>(static_cast<uint64_t>(x) &
                                   static_cast<uint64_t>(y));
}

constexpr TargetType operator~(TargetType x)
{
    return static_cast<TargetType>(~static_cast<uint64_t>(x));
}
#endif

template<uint64_t V>
class bitCount
{
    public:
        // Don't use enums, too hard to compare
        static const uint8_t count = bitCount < (V >> 1) >::count + (V & 1);
};

template<>
class bitCount<0>
{
    public:
        static const uint8_t count = 0;
};
/// @endcond

}

#endif
<commit_msg>Add new ocmb device target types<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/hwpf/fapi2/include/target_types.H $                */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2012,2022                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 * @file target_types.H
 * @brief definitions for fapi2 target types
 */

#ifndef __FAPI2_TARGET_TYPES__
#define __FAPI2_TARGET_TYPES__
#include <stdint.h>

/// FAPI namespace
namespace fapi2
{
///
/// @enum fapi::TargetType
/// @brief Types, kinds, of targets
/// @note TYPE_NONE is used to represent empty/NULL targets in lists
/// or tables. TYPE_ALL is used to pass targets to methods which
/// can act generally on any type of target
///

/// Target Kind
enum TargetType : uint64_t
{
    TARGET_TYPE_NONE            = 0x0000000000000000, ///< No type
    TARGET_TYPE_SYSTEM          = 0x0000000000000001, ///< System type
    TARGET_TYPE_DIMM            = 0x0000000000000002, ///< DIMM type
    TARGET_TYPE_PROC_CHIP       = 0x0000000000000004, ///< Processor type
    TARGET_TYPE_MEMBUF_CHIP     = 0x0000000000000008, ///< Membuf type
    TARGET_TYPE_EX              = 0x0000000000000010, ///< EX - 2x Core, L2, L3 - can be deconfigured
    TARGET_TYPE_MBA             = 0x0000000000000020, ///< MBA type
    TARGET_TYPE_MCS             = 0x0000000000000040, ///< MCS type
    TARGET_TYPE_XBUS            = 0x0000000000000080, ///< XBUS type
    TARGET_TYPE_ABUS            = 0x0000000000000100, ///< ABUS type
    TARGET_TYPE_L4              = 0x0000000000000200, ///< L4 type
    TARGET_TYPE_CORE            = 0x0000000000000400, ///< Core
    TARGET_TYPE_EQ              = 0x0000000000000800, ///< EQ - 4x core, 2x L2, 2x L3 - can be deconfigured
    TARGET_TYPE_MCA             = 0x0000000000001000, ///< MCA type
    TARGET_TYPE_MCBIST          = 0x0000000000002000, ///< MCBIST type
    TARGET_TYPE_MI              = 0x0000000000004000, ///< MI Memory Interface (Cumulus)
    TARGET_TYPE_CAPP            = 0x0000000000008000, ///< CAPP target
    TARGET_TYPE_DMI             = 0x0000000000010000, ///< DMI type
    TARGET_TYPE_OBUS            = 0x0000000000020000, ///< OBUS type
    TARGET_TYPE_OBUS_BRICK      = 0x0000000000040000, ///< OBUS BRICK type
    TARGET_TYPE_SBE             = 0x0000000000080000, ///< SBE type
    TARGET_TYPE_PPE             = 0x0000000000100000, ///< PPE type
    TARGET_TYPE_PERV            = 0x0000000000200000, ///< Pervasive type
    TARGET_TYPE_PEC             = 0x0000000000400000, ///< PEC type
    TARGET_TYPE_PHB             = 0x0000000000800000, ///< PHB type
    TARGET_TYPE_MC              = 0x0000000001000000, ///< MC type
    TARGET_TYPE_OMI             = 0x0000000002000000, ///< OMI type
    TARGET_TYPE_OMIC            = 0x0000000004000000, ///< OMIC type
    TARGET_TYPE_MCC             = 0x0000000008000000, ///< MCC type
    TARGET_TYPE_OCMB_CHIP       = 0x0000000010000000, ///< OCMB type
    TARGET_TYPE_MEM_PORT        = 0x0000000020000000, ///< MEM_PORT type
    TARGET_TYPE_NMMU            = 0x0000000040000000, ///< NEST MMU type
    TARGET_TYPE_RESERVED        = 0x0000000080000000, ///< Reserved for Cronus (Z)
    TARGET_TYPE_PAU             = 0x0000000100000000, ///< PAU type
    TARGET_TYPE_IOHS            = 0x0000000200000000, ///< IOHS type
    TARGET_TYPE_FC              = 0x0000000400000000, ///< Fused Core type
    TARGET_TYPE_PMIC            = 0x0000000800000000, ///< PMIC type
    TARGET_TYPE_PAUC            = 0x0000001000000000, ///< PAUC type
    TARGET_TYPE_GENERICI2CSLAVE = 0x0000002000000000, ///< GENERICI2CSLAVE type
    TARGET_TYPE_GENERICI2CRESPONDER = 0x0000002000000000, ///< GENERICI2RESPONDER type
    TARGET_TYPE_IOLINK          = 0x0000004000000000, ///< IOLINK type
    TARGET_TYPE_MDS_CTLR        = 0x0000008000000000, ///< MDS Media Controller type
//RESERVED BIT FIELDS - DO NOT USE
    /*
        TARGET_TYPE_RESERVED        = 0x0000010000000000, ///< Reserved - DO NOT USE
        TARGET_TYPE_RESERVED        = 0x0000020000000000, ///< Reserved - DO NOT USE
        TARGET_TYPE_RESERVED        = 0x0000040000000000, ///< Reserved - DO NOT USE
        TARGET_TYPE_RESERVED        = 0x0000080000000000, ///< Reserved - DO NOT USE
        TARGET_TYPE_RESERVED        = 0x0000100000000000, ///< Reserved - DO NOT USE
        TARGET_TYPE_RESERVED        = 0x0000200000000000, ///< Reserved - DO NOT USE
        TARGET_TYPE_RESERVED        = 0x0000400000000000, ///< Reserved - DO NOT USE
        TARGET_TYPE_RESERVED        = 0x0000800000000000, ///< Reserved - DO NOT USE
        TARGET_TYPE_RESERVED        = 0x0001000000000000, ///< Reserved - DO NOT USE
        TARGET_TYPE_RESERVED        = 0x0002000000000000, ///< Reserved - DO NOT USE
        TARGET_TYPE_RESERVED        = 0x0004000000000000, ///< Reserved - DO NOT USE
        TARGET_TYPE_RESERVED        = 0x0008000000000000, ///< Reserved - DO NOT USE
        TARGET_TYPE_RESERVED        = 0x0010000000000000, ///< Reserved - DO NOT USE
        TARGET_TYPE_RESERVED        = 0x0020000000000000, ///< Reserved - DO NOT USE
    */
    TARGET_TYPE_POWER_IC        = 0x0040000000000000, ///< POWER_IC type
    TARGET_TYPE_TEMP_SENSOR     = 0x0080000000000000, ///< TEMP_SENSOR type
    TARGET_TYPE_MULTICAST       = 0x8000000000000000, ///< MULTICAST type
    TARGET_TYPE_ALL             = 0x7FFFFFFFFFFFFFFF, ///< Any/All types
    TARGET_TYPE_ALL_MC          = 0xFFFFFFFFFFFFFFFF, ///< Any/All types + Multicast

    // Compound target types
    TARGET_TYPE_CHIPS         = TARGET_TYPE_PROC_CHIP |
                                TARGET_TYPE_MEMBUF_CHIP |
                                TARGET_TYPE_OCMB_CHIP,

    TARGET_TYPE_CHIPLETS      = TARGET_TYPE_EX            |
                                TARGET_TYPE_MBA           |
                                TARGET_TYPE_MCS           |
                                TARGET_TYPE_XBUS          |
                                TARGET_TYPE_ABUS          |
                                TARGET_TYPE_L4            |
                                TARGET_TYPE_CORE          |
                                TARGET_TYPE_EQ            |
                                TARGET_TYPE_MCA           |
                                TARGET_TYPE_MCBIST        |
                                TARGET_TYPE_MI            |
                                TARGET_TYPE_DMI           |
                                TARGET_TYPE_OBUS          |
                                TARGET_TYPE_OBUS_BRICK    |
                                TARGET_TYPE_SBE           |
                                TARGET_TYPE_PPE           |
                                TARGET_TYPE_PERV          |
                                TARGET_TYPE_PEC           |
                                TARGET_TYPE_PHB           |
                                TARGET_TYPE_MC            |
                                TARGET_TYPE_OMI           |
                                TARGET_TYPE_OMIC          |
                                TARGET_TYPE_MCC           |
                                TARGET_TYPE_MEM_PORT      |
                                TARGET_TYPE_NMMU          |
                                TARGET_TYPE_PAU           |
                                TARGET_TYPE_IOHS          |
                                TARGET_TYPE_FC            |
                                TARGET_TYPE_PAUC          |
                                TARGET_TYPE_IOLINK,

    TARGET_TYPE_MULTICASTABLE = TARGET_TYPE_CORE   |
                                TARGET_TYPE_EQ     |
                                TARGET_TYPE_IOHS   |
                                TARGET_TYPE_MC     |
                                TARGET_TYPE_PAUC   |
                                TARGET_TYPE_PEC    |
                                TARGET_TYPE_PERV,

    TARGET_TYPE_MULTICAST_CHIP = TARGET_TYPE_PROC_CHIP  |
                                 TARGET_TYPE_OCMB_CHIP,

    TARGET_TYPE_ANY_POZ_CHIP  = TARGET_TYPE_PROC_CHIP |
                                TARGET_TYPE_OCMB_CHIP,

    // Mappings to target types found in the error xml files
    TARGET_TYPE_EX_CHIPLET    = TARGET_TYPE_EX,
    TARGET_TYPE_MBA_CHIPLET   = TARGET_TYPE_MBA,
    TARGET_TYPE_MCS_CHIPLET   = TARGET_TYPE_MCS,
    TARGET_TYPE_XBUS_ENDPOINT = TARGET_TYPE_XBUS,
    TARGET_TYPE_ABUS_ENDPOINT = TARGET_TYPE_ABUS,
};

// The fsp x86 compiler is too old to support the full C++11 standard and
// they have not been able to upgrade to a later compiler yet due to a
// requirement to run tools on LCB machines which are still running RHEL6
// which doesn't have the necessary runtime support for executables compiled
// with the newer compiler versions.
//
// Don't compile this forward declaration unless c++11 or greater is being
// used.
//
#if(__GNUC__ && (__cplusplus >= 201103L))
///
/// Target filter 64-bit
/// Declare the enumeration size so that target.H will compile without chip specific filter.
/// When users want to use an enumeration value then they can include the chip specific
/// target_filters.H, which would have the enumerator list of values.
///
enum TargetFilter : uint64_t;
#endif

// attributeOverride tool requires x86.nfp compile
#ifndef CONTEXT_x86_nfp
/// @cond
    constexpr TargetType operator|(TargetType x, TargetType y)
{
    return static_cast<TargetType>(static_cast<uint64_t>(x) |
                                   static_cast<uint64_t>(y));
}

constexpr TargetType operator&(TargetType x, TargetType y)
{
    return static_cast<TargetType>(static_cast<uint64_t>(x) &
                                   static_cast<uint64_t>(y));
}

constexpr TargetType operator~(TargetType x)
{
    return static_cast<TargetType>(~static_cast<uint64_t>(x));
}
#endif

template<uint64_t V>
class bitCount
{
    public:
        // Don't use enums, too hard to compare
        static const uint8_t count = bitCount < (V >> 1) >::count + (V & 1);
};

template<>
class bitCount<0>
{
    public:
        static const uint8_t count = 0;
};
/// @endcond

}

#endif
<|endoftext|>


<commit_before>/*------------------------------------------------------------------------------
	Interface routines for HSP Script Editor
------------------------------------------------------------------------------*/

#include <windows.h>
#include <commctrl.h>
#include "hsed_config.h"
#include "interface.h"
#include "tabmanager.h"
#include "footy2.h"

//
// ^̒`
typedef BOOL (CALLBACK *DLLFUNC)(int, int, int, int);

//
// O[oϐ
static const char *szInterfaceName = HSED_INTERFACE_NAME;

//
// Oϐ
extern HWND hWndMain;
extern HWND hwndTab;
extern HWND hwndClient;
extern HWND hwndToolBar;
extern HWND hwndStatusBar;
extern DLLFUNC hsc_ver;
extern int activeID;
extern int activeFootyID;

//
// ֐̐錾
static LRESULT InterfaceProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
static inline LRESULT GetHspcmpVer(HANDLE hPipe);
static inline LRESULT GetModify(int nFootyID);
static inline LRESULT GetFilePath(int nTabID, HANDLE hPipe);
static inline LRESULT GetFootyID(int nTabID);
static inline LRESULT SetText(int nFootyID, HANDLE hPipe);
static inline LRESULT SetSelText(int nFootyID, HANDLE hPipe);
static inline LRESULT GetText(int nFootyID, HANDLE hPipe);

//
// C^[tFCX̏
bool InitInterface(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize        = sizeof(WNDCLASSEX);
	wcex.lpszClassName = szInterfaceName;
	wcex.hInstance     = hInstance;
	wcex.lpfnWndProc   = (WNDPROC)InterfaceProc;
	wcex.hCursor       = NULL;
	wcex.hIcon         = NULL;
 	wcex.lpszMenuName  = NULL;
	wcex.hbrBackground = NULL;
	wcex.style         = 0;
	wcex.cbClsExtra    = 0;
	wcex.cbWndExtra    = 0;
	wcex.hIconSm       = NULL;

	if(RegisterClassEx(&wcex) == NULL)
		return false;

	if(CreateWindow(szInterfaceName, szInterfaceName, 0, 0, 0, 0, 0, NULL, NULL, hInstance, NULL) == NULL)
		return false;

	return true;
}

//
// C^[tFCX̃vV[W
static LRESULT InterfaceProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	int footy_defid;
	int nRet;
	footy_defid = (int)wParam;
	if ( footy_defid < 0 ) footy_defid = activeFootyID;

	switch(uMsg){
		case HSED_GETVER:
			switch(wParam){
				case HGV_PUBLICVER:
					return HSED_PUBLIC_VER;

				case HGV_PRIVATEVER:
					return HSED_PRIVATE_VER;

				case HGV_HSPCMPVER:
					return GetHspcmpVer((HANDLE)lParam);

				case HGV_FOOTYVER:
					return GetFooty2Ver();

				case HGV_FOOTYBETAVER:
					return GetFooty2BetaVer();

				default:
					return -1;
			}

		case HSED_GETWND:
			switch(wParam){
				case HGW_MAIN:
					return (LRESULT)hWndMain;

				case HGW_CLIENT:
					return (LRESULT)hwndClient;

				case HGW_TAB:
					return (LRESULT)hwndTab;

				case HGW_FOOTY:
					return (LRESULT)Footy2GetWnd((int)lParam, 0);

				case HGW_TOOLBAR:
					return (LRESULT)hwndToolBar;

				case HGW_STATUSBAR:
					return (LRESULT)hwndStatusBar;

				default:
					return NULL;
			}

		case HSED_GETPATH:
			return GetFilePath((int)wParam, (HANDLE)lParam);

		case HSED_GETTABCOUNT:
			return TabCtrl_GetItemCount(hwndTab);

		case HSED_GETTABID:
			return GetTabID((int)wParam);

		case HSED_GETFOOTYID:
			return GetFootyID((int)wParam);

		case HSED_GETACTTABID:
			return activeID;

		case HSED_GETACTFOOTYID:
			return activeFootyID;

		case HSED_CANCOPY:
			nRet = Footy2GetSel((int)wParam, NULL, NULL, NULL, NULL);
			return (nRet == FOOTY2ERR_NOTSELECTED) ? -1 : (nRet == FOOTY2ERR_NONE);

		case HSED_CANPASTE:
			return IsClipboardFormatAvailable(CF_TEXT) != 0;

		case HSED_CANUNDO:
			nRet = 0;
			Footy2GetMetrics((int)wParam, SM_UNDOREM, &nRet);
//			return (nRet == F_RET_OUTID) ? -1 : (nRet > 0);
			return nRet;	// 2008-02-17 Shark++ ֋@\

		case HSED_CANREDO:
			nRet = 0;
			Footy2GetMetrics((int)wParam, SM_REDOREM, &nRet);
//			return (nRet == F_RET_OUTID) ? -1 : (nRet > 0);
			return nRet;	// 2008-02-17 Shark++ ֋@\

		case HSED_GETMODIFY:
			return GetModify((int)wParam);

		case HSED_COPY:
			return Footy2Copy(footy_defid);

		case HSED_CUT:
			return Footy2Cut(footy_defid);

		case HSED_PASTE:
			return Footy2Paste(footy_defid);

		case HSED_UNDO:
			return Footy2Undo(footy_defid);

		case HSED_REDO:
			return Footy2Redo(footy_defid);

		case HSED_INDENT:
//			return FootyIndent(footy_defid);
			return -1;	// 2008-02-17 Shark++ ֋@\

		case HSED_UNINDENT:
//			return FootyUnIndent(footy_defid);
			return -1;	// 2008-02-17 Shark++ ֋@\

		case HSED_SELECTALL:
			return Footy2SelectAll(footy_defid);

		case HSED_SETTEXT:
			return SetText((int)wParam, (HANDLE)lParam);

		case HSED_GETTEXT:
			return GetText((int)wParam, (HANDLE)lParam);

		case HSED_GETTEXTLENGTH:
			return Footy2GetTextLength(footy_defid, LM_CRLF);

		case HSED_GETLINES:
			return Footy2GetLines(footy_defid);

		case HSED_SETSELTEXT:
			return SetSelText((int)wParam, (HANDLE)lParam);
/*
		case HSED_GETSELTEXT:
			return ;

		case HSED_GETLINETEXT:
			return ;
*/
		case HSED_GETLINELENGTH:
			return Footy2GetLineLength(footy_defid, (int)lParam);

		case HSED_GETLINECODE:
			return Footy2GetLineCode(footy_defid);	// 2008-02-17 Shark++ SDKKvH
/*
		case HSED_SETSELA:
			return ;

		case HSED_GETSELA:
			return ;

		case HSED_SETSELB:
			return ;

		case HSED_GETSELB:
			return ;
*/
		case HSED_GETCARETLINE:
			Footy2GetCaretPosition(footy_defid, (size_t*)&nRet, NULL);
			return nRet + 1;

		case HSED_GETCARETPOS:
			Footy2GetCaretPosition(footy_defid, NULL, (size_t*)&nRet);
			return nRet + 1;

		case HSED_SETCARETLINE:
			return Footy2SetCaretPosition(footy_defid, (int)lParam, 0);	// 2008-02-17 Shark++ SDKKvHSDKŎgpĂȂH

		case HSED_SETCARETPOS:
//			return FootySetCaretPos(footy_defid, (int)lParam);
			return 0;	// 2008-02-17 Shark++ ֋@\

		case HSED_GETCARETTHROUGH:
//			return FootyGetCaretThrough(footy_defid);
			return 0;	// 2008-02-17 Shark++ ֋@\

		case HSED_SETCARETTHROUGH:
//			return FootySetCaretThrough(footy_defid, (int)lParam);
			return 0;	// 2008-02-17 Shark++ ֋@\

		case HSED_GETCARETVPOS:
//			return FootyGetCaretVPos(footy_defid);
			return 0;	// 2008-02-17 Shark++ ֋@\

		case HSED_SETMARK:
		//	return FootySetMark(footy_defid);
			Footy2GetLineIcon(footy_defid, (size_t)lParam, &nRet);
			return Footy2SetLineIcon(footy_defid, (size_t)lParam, (nRet & ~LINEICON_BLUE) | (wParam ? LINEICON_BLUE : 0) );	// 2008-02-23 Shark++ SDKKv

		case HSED_GETMARK:
//			return FootyGetMark(footy_defid, (int)lParam);
			Footy2GetLineIcon(footy_defid, (size_t)lParam, &nRet);
			return (nRet & LINEICON_BLUE) ? 1 : 0;	// 2008-02-23 Shark++ vmF
/*
		case HSED_SETHIGHLIGHT:
			return ;
*/

	}
	return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

//
// hspcmp.dll ̃o[W擾
static inline LRESULT GetHspcmpVer(HANDLE hPipe)
{
	char szRefstr[4096];
	DWORD dwNumberOfBytesWritten;
	BOOL bRet;

	hsc_ver(0, 0, 0, (int)szRefstr);
	bRet = WriteFile(hPipe, szRefstr, lstrlen(szRefstr) + 1, &dwNumberOfBytesWritten, NULL);
	return bRet ? dwNumberOfBytesWritten : -1;
}

//
// t@C̕ύXtO擾
static inline LRESULT GetModify(int nFootyID)
{
	int nTabID;
	TABINFO *lpTabInfo;

	nTabID = GetTabID(nFootyID);
	if(nTabID < 0) return -1;

	lpTabInfo = GetTabInfo(nTabID);
	if(lpTabInfo == NULL) return -1;

	return lpTabInfo->NeedSave != FALSE;
}

//
// t@C̃pX擾
static inline LRESULT GetFilePath(int nTabID, HANDLE hPipe)
{
	TABINFO *lpTabInfo = GetTabInfo(nTabID);
	DWORD dwNumberOfBytesWritten;
	BOOL bRet;
	if(lpTabInfo == NULL) return -1;
	bRet = WriteFile(hPipe, lpTabInfo->FileName, lstrlen(lpTabInfo->FileName), &dwNumberOfBytesWritten, NULL);
	return bRet ? 0 : -1;
}

//
// Footy ID擾
static inline LRESULT GetFootyID(int nTabID)
{
//	int nFootyID;
	TABINFO *lpTabInfo;

	lpTabInfo = GetTabInfo(nTabID);
	if(lpTabInfo == NULL) return -1;

	return lpTabInfo->FootyID;
}

static inline int ReadPipe(HANDLE hPipe, char **pbuffer)
{
	DWORD dwSize, dwNumberOfBytesRead;
	char *lpBuffer;

	if(!PeekNamedPipe(hPipe, NULL, 0, NULL, &dwSize, NULL)) {
		return 1;
	}
	lpBuffer = (char *)malloc(dwSize + 1);
	*pbuffer = lpBuffer;
	if(lpBuffer == NULL) return 1;
	if(dwSize > 0) {
		ReadFile(hPipe, lpBuffer, dwSize, &dwNumberOfBytesRead, NULL);
	}
	lpBuffer[dwSize] = '\0';
	return 0;
}

//
// Footyɕ
static inline LRESULT SetText(int nFootyID, HANDLE hPipe)
{
	int nRet;
	char *lpBuffer;

	if(ReadPipe(hPipe, &lpBuffer)){
		return -3;
	}
//	nRet = Footy2SetText(nFootyID, lpBuffer); // 2008-02-21 Shark++ Ƌ̐ݒ肪j
	Footy2SelectAll(nFootyID, false);
	nRet = Footy2SetSelText(nFootyID, lpBuffer);
	free(lpBuffer);

	switch(nRet){
		case FOOTY2ERR_NONE:   return 0;
		case FOOTY2ERR_MEMORY: return -1;
		case FOOTY2ERR_NOID:   return -2;
		default:               return -4;
	}
}

//
// Footyɕ}
static inline LRESULT SetSelText(int nFootyID, HANDLE hPipe)
{
	int nRet;
	char *lpBuffer;

	if(ReadPipe(hPipe, &lpBuffer)){
		return -3;
	}
	nRet = Footy2SetSelText(nFootyID, lpBuffer);
	free(lpBuffer);

	switch(nRet){
		case FOOTY2ERR_NONE:   return 0;
		case FOOTY2ERR_MEMORY: return -1;
		case FOOTY2ERR_NOID:   return -2;
		default:               return -4;
	}
}

//
// Footy當ǂݍ
static inline LRESULT GetText(int nFootyID, HANDLE hPipe)
{
	int nRet;
	DWORD dwSize, dwNumberOfBytesWritten;
	char *lpBuffer;

	dwSize = Footy2GetTextLength(nFootyID, LM_CRLF);
	lpBuffer = (char *)malloc(dwSize + 1);
	if(lpBuffer == NULL) return -1;
	nRet = Footy2GetText(nFootyID, lpBuffer, LM_CRLF, dwSize);
	if(nRet == FOOTY2ERR_NONE){
		if(!WriteFile(hPipe, lpBuffer, dwSize, &dwNumberOfBytesWritten, NULL)){
			free(lpBuffer);
			return -3;
		}
	} else {
		free(lpBuffer);
	}

	switch(nRet){
		case FOOTY2ERR_NONE:   return 0;
		case FOOTY2ERR_MEMORY: return -1;
		case FOOTY2ERR_NOID:   return -2;
		default:               return -4;
	}
}<commit_msg><commit_after>/*------------------------------------------------------------------------------
	Interface routines for HSP Script Editor
------------------------------------------------------------------------------*/

#include <windows.h>
#include <commctrl.h>
#include "hsed_config.h"
#include "interface.h"
#include "tabmanager.h"
#include "footy2.h"

//
// ^̒`
typedef BOOL (CALLBACK *DLLFUNC)(int, int, int, int);

//
// O[oϐ
static const char *szInterfaceName = HSED_INTERFACE_NAME;

//
// Oϐ
extern HWND hWndMain;
extern HWND hwndTab;
extern HWND hwndClient;
extern HWND hwndToolBar;
extern HWND hwndStatusBar;
extern DLLFUNC hsc_ver;
extern int activeID;
extern int activeFootyID;

//
// ֐̐錾
static LRESULT InterfaceProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
static inline LRESULT GetHspcmpVer(HANDLE hPipe);
static inline LRESULT GetModify(int nFootyID);
static inline LRESULT GetFilePath(int nTabID, HANDLE hPipe);
static inline LRESULT GetFootyID(int nTabID);
static inline LRESULT SetText(int nFootyID, HANDLE hPipe);
static inline LRESULT SetSelText(int nFootyID, HANDLE hPipe);
static inline LRESULT GetText(int nFootyID, HANDLE hPipe);

//
// C^[tFCX̏
bool InitInterface(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize        = sizeof(WNDCLASSEX);
	wcex.lpszClassName = szInterfaceName;
	wcex.hInstance     = hInstance;
	wcex.lpfnWndProc   = (WNDPROC)InterfaceProc;
	wcex.hCursor       = NULL;
	wcex.hIcon         = NULL;
 	wcex.lpszMenuName  = NULL;
	wcex.hbrBackground = NULL;
	wcex.style         = 0;
	wcex.cbClsExtra    = 0;
	wcex.cbWndExtra    = 0;
	wcex.hIconSm       = NULL;

	if(RegisterClassEx(&wcex) == NULL)
		return false;

	if(CreateWindow(szInterfaceName, szInterfaceName, 0, 0, 0, 0, 0, NULL, NULL, hInstance, NULL) == NULL)
		return false;

	return true;
}

//
// C^[tFCX̃vV[W
static LRESULT InterfaceProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	int footy_defid;
	int nRet;
	footy_defid = (int)wParam;
	if ( footy_defid < 0 ) footy_defid = activeFootyID;

	switch(uMsg){
		case HSED_GETVER:
			switch(wParam){
				case HGV_PUBLICVER:
					return HSED_PUBLIC_VER;

				case HGV_PRIVATEVER:
					return HSED_PRIVATE_VER;

				case HGV_HSPCMPVER:
					return GetHspcmpVer((HANDLE)lParam);

				case HGV_FOOTYVER:
					return GetFooty2Ver();

				case HGV_FOOTYBETAVER:
					return GetFooty2BetaVer();

				default:
					return -1;
			}

		case HSED_GETWND:
			switch(wParam){
				case HGW_MAIN:
					return (LRESULT)hWndMain;

				case HGW_CLIENT:
					return (LRESULT)hwndClient;

				case HGW_TAB:
					return (LRESULT)hwndTab;

				case HGW_FOOTY:
					return (LRESULT)Footy2GetWnd((int)lParam, 0);

				case HGW_TOOLBAR:
					return (LRESULT)hwndToolBar;

				case HGW_STATUSBAR:
					return (LRESULT)hwndStatusBar;

				default:
					return NULL;
			}

		case HSED_GETPATH:
			return GetFilePath((int)wParam, (HANDLE)lParam);

		case HSED_GETTABCOUNT:
			return TabCtrl_GetItemCount(hwndTab);

		case HSED_GETTABID:
			return GetTabID((int)wParam);

		case HSED_GETFOOTYID:
			return GetFootyID((int)wParam);

		case HSED_GETACTTABID:
			return activeID;

		case HSED_GETACTFOOTYID:
			return activeFootyID;

		case HSED_CANCOPY:
			nRet = Footy2GetSel((int)wParam, NULL, NULL, NULL, NULL);
			return (nRet == FOOTY2ERR_NOTSELECTED) ? -1 : (nRet == FOOTY2ERR_NONE);

		case HSED_CANPASTE:
			return IsClipboardFormatAvailable(CF_TEXT) != 0;

		case HSED_CANUNDO:
			nRet = 0;
			Footy2GetMetrics((int)wParam, SM_UNDOREM, &nRet);
//			return (nRet == F_RET_OUTID) ? -1 : (nRet > 0);
			return nRet;	// 2008-02-17 Shark++ ֋@\

		case HSED_CANREDO:
			nRet = 0;
			Footy2GetMetrics((int)wParam, SM_REDOREM, &nRet);
//			return (nRet == F_RET_OUTID) ? -1 : (nRet > 0);
			return nRet;	// 2008-02-17 Shark++ ֋@\

		case HSED_GETMODIFY:
			return GetModify((int)wParam);

		case HSED_COPY:
			return Footy2Copy(footy_defid);

		case HSED_CUT:
			return Footy2Cut(footy_defid);

		case HSED_PASTE:
			return Footy2Paste(footy_defid);

		case HSED_UNDO:
			return Footy2Undo(footy_defid);

		case HSED_REDO:
			return Footy2Redo(footy_defid);

		case HSED_INDENT:
//			return FootyIndent(footy_defid);
			return -1;	// 2008-02-17 Shark++ ֋@\

		case HSED_UNINDENT:
//			return FootyUnIndent(footy_defid);
			return -1;	// 2008-02-17 Shark++ ֋@\

		case HSED_SELECTALL:
			return Footy2SelectAll(footy_defid);

		case HSED_SETTEXT:
			return SetText((int)wParam, (HANDLE)lParam);

		case HSED_GETTEXT:
			return GetText((int)wParam, (HANDLE)lParam);

		case HSED_GETTEXTLENGTH:
			return Footy2GetTextLength(footy_defid, LM_CRLF);

		case HSED_GETLINES:
			return Footy2GetLines(footy_defid);

		case HSED_SETSELTEXT:
			return SetSelText((int)wParam, (HANDLE)lParam);
/*
		case HSED_GETSELTEXT:
			return ;

		case HSED_GETLINETEXT:
			return ;
*/
		case HSED_GETLINELENGTH:
			return Footy2GetLineLength(footy_defid, (int)lParam);

		case HSED_GETLINECODE:
			return Footy2GetLineCode(footy_defid);	// 2008-02-17 Shark++ SDKKvH
/*
		case HSED_SETSELA:
			return ;

		case HSED_GETSELA:
			return ;

		case HSED_SETSELB:
			return ;

		case HSED_GETSELB:
			return ;
*/
		case HSED_GETCARETLINE:
			Footy2GetCaretPosition(footy_defid, (size_t*)&nRet, NULL);
			return nRet + 1;

		case HSED_GETCARETPOS:
			Footy2GetCaretPosition(footy_defid, NULL, (size_t*)&nRet);
			return nRet + 1;

		case HSED_SETCARETLINE:
			return Footy2SetCaretPosition(footy_defid, (int)lParam, 0);	// 2008-02-17 Shark++ SDKKvHSDKŎgpĂȂH

		case HSED_SETCARETPOS:
//			return FootySetCaretPos(footy_defid, (int)lParam);
			return 0;	// 2008-02-17 Shark++ ֋@\

		case HSED_GETCARETTHROUGH:
//			return FootyGetCaretThrough(footy_defid);
			return 0;	// 2008-02-17 Shark++ ֋@\

		case HSED_SETCARETTHROUGH:
//			return FootySetCaretThrough(footy_defid, (int)lParam);
			return 0;	// 2008-02-17 Shark++ ֋@\

		case HSED_GETCARETVPOS:
//			return FootyGetCaretVPos(footy_defid);
			return 0;	// 2008-02-17 Shark++ ֋@\

		case HSED_SETMARK:
		//	return FootySetMark(footy_defid);
			Footy2GetLineIcon(footy_defid, (size_t)lParam, &nRet);
			return Footy2SetLineIcon(footy_defid, (size_t)lParam, (nRet & ~LINEICON_BLUE) | (wParam ? LINEICON_BLUE : 0) );	// 2008-02-23 Shark++ SDKKv

		case HSED_GETMARK:
//			return FootyGetMark(footy_defid, (int)lParam);
			Footy2GetLineIcon(footy_defid, (size_t)lParam, &nRet);
			return (nRet & LINEICON_BLUE) ? 1 : 0;	// 2008-02-23 Shark++ vmF
/*
		case HSED_SETHIGHLIGHT:
			return ;
*/

	}
	return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

//
// hspcmp.dll ̃o[W擾
static inline LRESULT GetHspcmpVer(HANDLE hPipe)
{
	char szRefstr[4096];
	DWORD dwNumberOfBytesWritten;
	BOOL bRet;

	hsc_ver(0, 0, 0, (int)szRefstr);
	bRet = WriteFile(hPipe, szRefstr, lstrlen(szRefstr) + 1, &dwNumberOfBytesWritten, NULL);
	return bRet ? dwNumberOfBytesWritten : -1;
}

//
// t@C̕ύXtO擾
static inline LRESULT GetModify(int nFootyID)
{
	int nTabID;
	TABINFO *lpTabInfo;

	nTabID = GetTabID(nFootyID);
	if(nTabID < 0) return -1;

	lpTabInfo = GetTabInfo(nTabID);
	if(lpTabInfo == NULL) return -1;

	return lpTabInfo->NeedSave != FALSE;
}

//
// t@C̃pX擾
static inline LRESULT GetFilePath(int nTabID, HANDLE hPipe)
{
	TABINFO *lpTabInfo = GetTabInfo(nTabID);
	DWORD dwNumberOfBytesWritten;
	BOOL bRet;
	if(lpTabInfo == NULL) return -1;
	bRet = WriteFile(hPipe, lpTabInfo->FileName, lstrlen(lpTabInfo->FileName), &dwNumberOfBytesWritten, NULL);
	return bRet ? 0 : -1;
}

//
// Footy ID擾
static inline LRESULT GetFootyID(int nTabID)
{
//	int nFootyID;
	TABINFO *lpTabInfo;

	lpTabInfo = GetTabInfo(nTabID);
	if(lpTabInfo == NULL) return -1;

	return lpTabInfo->FootyID;
}

static inline int ReadPipe(HANDLE hPipe, char **pbuffer)
{
	DWORD dwSize, dwNumberOfBytesRead;
	char *lpBuffer;

	if(!PeekNamedPipe(hPipe, NULL, 0, NULL, &dwSize, NULL)) {
		return 1;
	}
	lpBuffer = (char *)malloc(dwSize + 1);
	*pbuffer = lpBuffer;
	if(lpBuffer == NULL) return 1;
	if(dwSize > 0) {
		ReadFile(hPipe, lpBuffer, dwSize, &dwNumberOfBytesRead, NULL);
	}
	lpBuffer[dwSize] = '\0';
	return 0;
}

//
// Footyɕ
static inline LRESULT SetText(int nFootyID, HANDLE hPipe)
{
	int nRet;
	char *lpBuffer;

	if(ReadPipe(hPipe, &lpBuffer)){
		return -3;
	}
//	nRet = Footy2SetText(nFootyID, lpBuffer); // 2008-02-21 Shark++ Ƌ̐ݒ肪j
	Footy2SelectAll(nFootyID, false);
	nRet = Footy2SetSelText(nFootyID, lpBuffer);
	free(lpBuffer);

	switch(nRet){
		case FOOTY2ERR_NONE:   return 0;
		case FOOTY2ERR_MEMORY: return -1;
		case FOOTY2ERR_NOID:   return -2;
		default:               return -4;
	}
}

//
// Footyɕ}
static inline LRESULT SetSelText(int nFootyID, HANDLE hPipe)
{
	int nRet;
	char *lpBuffer;

	if(ReadPipe(hPipe, &lpBuffer)){
		return -3;
	}
	nRet = Footy2SetSelText(nFootyID, lpBuffer);
	free(lpBuffer);

	switch(nRet){
		case FOOTY2ERR_NONE:   return 0;
		case FOOTY2ERR_MEMORY: return -1;
		case FOOTY2ERR_NOID:   return -2;
		default:               return -4;
	}
}

//
// Footy當ǂݍ
static inline LRESULT GetText(int nFootyID, HANDLE hPipe)
{
	int nRet;
	DWORD dwSize, dwNumberOfBytesWritten;
	char *lpBuffer;

	dwSize = Footy2GetTextLength(nFootyID, LM_CRLF);
	lpBuffer = (char *)malloc(dwSize + 1);
	if(lpBuffer == NULL) return -1;
	nRet = Footy2GetText(nFootyID, lpBuffer, LM_CRLF, dwSize);
	if (nRet == FOOTY2ERR_NONE && !WriteFile(hPipe, lpBuffer, dwSize, &dwNumberOfBytesWritten, NULL)){
		free(lpBuffer);
		return -3;
	}
	free(lpBuffer);

	switch(nRet){
		case FOOTY2ERR_NONE:   return 0;
		case FOOTY2ERR_MEMORY: return -1;
		case FOOTY2ERR_NOID:   return -2;
		default:               return -4;
	}
}<|endoftext|>


<commit_before>#pragma once

#include "Node.hpp"
#include "../binds.hpp"

namespace wrd
{
	class Chain;
    class Composit : public Node
    {
    public: //    Node:
        //        getMember(); 는 공개하지 않는다:
        //        사용자는 Container채로 받게 되면 밖에서 remove, insert를 할 수 있게 된다.
        virtual const Container& getNodes() const;

    private: //    Node:
        virtual Result& _initNodes();

    private:
        //    _nodes can't be declared with protected accessor:
        //        if we do that, module developers can use _nodes and remove or insert some Node at runtime.
        TStrong<Chain> _nodes; // of Container.
    };
}
<commit_msg>+ [wrd] implement init and release.<commit_after>#pragma once

#include "Node.hpp"
#include "../binds.hpp"

namespace wrd
{
	class Chain;
    class Composit : public Node
    {
    public: //    Node:
        //        getNodes(); 는 공개하지 않는다:
        //        사용자는 Container채로 받게 되면 밖에서 remove, insert를 할 수 있게 된다.
        virtual const Container& getNodes() const;
        //  State:
        virtual Result& init()
        {
            WRD_IS_SUPER(init())
            return _initNodes();
        }
        //  Thing:
        virtual Result& release()
        {
            _nodes.release();
            return Super::release();
        }
    private: //    Node:
        virtual Result& _initNodes();

    private:
        //    _nodes can't be declared with protected accessor:
        //        if we do that, module developers can use _nodes and remove or insert some Node at runtime.
        TStrong<Chain> _nodes; // of Container.
    };
}
<|endoftext|>


<commit_before>/*
    gwcontact.cpp - Kopete GroupWise Protocol

    Copyright (c) 2004      SUSE Linux AG	 	 http://www.suse.com

    Based on Testbed
    Copyright (c) 2003      by Will Stephenson		 <will@stevello.free-online.co.uk>

    Kopete    (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This library 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.      *
    *                                                                       *
    *************************************************************************
*/

#include <kaction.h>
#include <kdebug.h>
#include <klocale.h>

#include "kopeteaccount.h"
#include "kopeteglobal.h"
#include "kopetemessage.h"
#include "kopetemessagemanagerfactory.h"
#include "kopetemetacontact.h"

#include "tasks/deleteitemtask.h"

#include "client.h"
#include "gwaccount.h"
#include "ui/gwcontactproperties.h"
#include "gwerror.h"
#include "gwfakeserver.h"
#include "gwmessagemanager.h"
#include "gwprotocol.h"
#include "userdetailsmanager.h"

#include "gwcontact.h"

using namespace GroupWise;

GroupWiseContact::GroupWiseContact( KopeteAccount* account, const QString &dn,
			KopeteMetaContact *parent,
			const int objectId, const int parentId, const int sequence )
: KopeteContact( account, dn, parent ), m_objectId( objectId ), m_parentId( parentId ),
  m_sequence( sequence ), m_actionBlock( 0 )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << " dn: " << dn << endl;
	setOnlineStatus( ( parent && parent->isTemporary() ) ? protocol()->groupwiseUnknown : protocol()->groupwiseOffline );
}

GroupWiseContact::~GroupWiseContact()
{
	// This is necessary because otherwise the userDetailsManager
	// would not fetch details for this contact if they contact you
	// again from off-contact-list.
	if ( metaContact()->isTemporary() )
		account()->client()->userDetailsManager()->removeContact( contactId() );
}

void GroupWiseContact::updateDetails( const ContactDetails & details )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	if ( !details.cn.isNull() )
		setProperty( protocol()->propCN, details.cn );
	if ( !details.givenName.isNull() )
		setProperty( protocol()->propGivenName, details.givenName );
	if ( !details.surname.isNull() )
		setProperty( protocol()->propLastName, details.surname );
	if ( !details.fullName.isNull() )
		setProperty( protocol()->propFullName, details.fullName );
	//if ( !details.awayMessage.isNull() )
		//setProperty( protocol()->propAwayMessage, details.awayMessage );

	m_serverProperties = details.properties;

	if ( details.status != GroupWise::Invalid )
	{
		KopeteOnlineStatus status = protocol()->gwStatusToKOS( details.status );
		kdDebug( GROUPWISE_DEBUG_GLOBAL ) << "setting initial status to " << status.description() << endl;
		setOnlineStatus( status );
	}
	else
		kdDebug( GROUPWISE_DEBUG_GLOBAL ) << "initial status is, not setting " << details.status << endl;
}

GroupWiseProtocol *GroupWiseContact::protocol()
{
	return static_cast<GroupWiseProtocol *>( KopeteContact::protocol() );
}

GroupWiseAccount *GroupWiseContact::account()
{
	return static_cast<GroupWiseAccount *>( KopeteContact::account() );
}

bool GroupWiseContact::isReachable()
{
	// When we are invisible we can't start a chat with others, but we don't make isReachable return false, because then we
	// don't get any notification when we click on someone in the contact list.  Instead we warn the user when they try to send a message,
	// in GWMessageManager
	// (This is a GroupWise rule, not a problem in Kopete)

	if ( account()->isConnected() && isOnline()/* && account()->myself()->onlineStatus() != protocol()->groupwiseAppearOffline */)
		return true;
	if ( !account()->isConnected()/* || account()->myself()->onlineStatus() == protocol()->groupwiseAppearOffline*/ )
		return false;
}

void GroupWiseContact::serialize( QMap< QString, QString > &serializedData, QMap< QString, QString > & /* addressBookData */ )
{
/*    QString value;
	switch ( m_type )
	{
	case Null:
		value = "null";
	case Echo:
		value = "echo";
	}
	serializedData[ "contactType" ] = value;*/
}

KopeteMessageManager * GroupWiseContact::manager( bool canCreate )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << "called, canCreate: " << canCreate << endl;

	KopeteContactPtrList chatMembers;
	chatMembers.append( this );

	return manager( chatMembers, canCreate );

/*	if ( m_msgManager )
	{
		return m_msgManager;
	}
	else
	{
		QPtrList<KopeteContact> contacts;
		contacts.append(this);
		m_msgManager = KopeteMessageManagerFactory::factory()->create(account()->myself(), contacts, protocol());
		connect(m_msgManager, SIGNAL(messageSent(KopeteMessage&, KopeteMessageManager*)),
				this, SLOT( sendMessage( KopeteMessage& ) ) );
		connect(m_msgManager, SIGNAL(destroyed()), this, SLOT(slotMessageManagerDestroyed()));
		return m_msgManager;
	}*/
}

GroupWiseMessageManager * GroupWiseContact::manager( KopeteContactPtrList chatMembers, bool canCreate )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;

	KopeteMessageManager *_manager = KopeteMessageManagerFactory::factory()->findKopeteMessageManager ( account()->myself(), chatMembers, protocol() );
	GroupWiseMessageManager *mgr = dynamic_cast<GroupWiseMessageManager*>( _manager );

	/*
	 * If we didn't find a message manager for this contact,
	 * instantiate a new one if we are allowed to. (otherwise return 0)
	 */
	if ( !mgr && canCreate )
	{
		mgr = account()->messageManager( account()->myself(), chatMembers, protocol(), QString::null );
		connect( mgr, SIGNAL( destroyed ( QObject * ) ), SLOT( slotMessageManagerDeleted ( QObject * ) ) );
		connect( mgr, SIGNAL( conferenceCreated() ), SLOT( slotConferenceCreated() ) );
		//m_pendingManagers.append( mgr );

	}

	return mgr;
}

GroupWiseMessageManager * GroupWiseContact::manager( const QString & guid, bool canCreate )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << "called for guid: " << guid << ", canCreate: " << canCreate << endl;
	if ( !guid.isNull() )
	{
		GroupWiseMessageManager * mgr = m_msgManagers[ guid ];
		if ( !mgr )
		{
			// we've received the first message from a new conference.
			// create a message manager with the given guid
			kdDebug( GROUPWISE_DEBUG_GLOBAL ) << " - this GroupWiseMessageManager is new to us. " << endl;
			KopeteContactPtrList chatMembers;
			chatMembers.append ( this );
			mgr = account()->messageManager( account()->myself(), chatMembers, protocol(), guid );
			connect( mgr, SIGNAL( destroyed( QObject * ) ), this, SLOT( slotMessageManagerDeleted ( QObject * ) ) );
			m_msgManagers.insert( guid, mgr );
		}
		else
			kdDebug( GROUPWISE_DEBUG_GLOBAL ) << " - found an existing GroupWiseMessageManager for this guid. " << endl;

		return mgr;
	}
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << "GUID is empty, grabbing first available manager." << endl;
	/*
	 * The guid supplied is empty, so just return the first available manager.
	 */
	return dynamic_cast<GroupWiseMessageManager *>( manager( canCreate ) );
}

QPtrList<KAction> *GroupWiseContact::customContextMenuActions()
{
	QPtrList<KAction> *m_actionCollection = new QPtrList<KAction>;

	// Block/unblock Contact
	QString label = /*isBlocked()*/false ? i18n( "Unblock User" ) : i18n( "Block User" );
	if( !m_actionBlock )
	{
		m_actionBlock = new KAction( label, "msn_blocked",0, this, SLOT( slotBlockUser() ),
			this, "actionBlock" );
	}
	else
		m_actionBlock->setText( label );

	m_actionCollection->append( m_actionBlock );

	return m_actionCollection;
}

void GroupWiseContact::slotUserInfo()
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	new GroupWiseContactProperties( this, account(), "gwcontactproperties" );
}

QMap< QString, QString > GroupWiseContact::serverProperties()
{
	return m_serverProperties;
}

void GroupWiseContact::sendMessage( KopeteMessage &message )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	// convert to the what the server wants
	// For this 'protocol', there's nothing to do
	// send it
/*	static_cast<GroupWiseAccount *>( account() )->server()->sendMessage(
			message.to().first()->contactId(),
			message.plainBody() );*/
	// give it back to the manager to display
	manager()->appendMessage( message );
	// tell the manager it was sent successfully
	manager()->messageSucceeded();
}

void GroupWiseContact::dumpManagers()
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << " for: " << contactId() << endl;
	QDictIterator< GroupWiseMessageManager > it( m_msgManagers );
	for ( ; it.current(); ++it )
		kdDebug( GROUPWISE_DEBUG_GLOBAL ) << "guid: " << it.currentKey() << endl;
}

void GroupWiseContact::slotConferenceCreated()
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	const GroupWiseMessageManager * mgr = (GroupWiseMessageManager *)sender();
	m_msgManagers.insert( mgr->guid(), mgr );
	dumpManagers();
}

void GroupWiseContact::slotMessageManagerDeleted( QObject *sender )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << "Message manager deleted, collecting the pieces..." << endl;

	GroupWiseMessageManager *manager = static_cast<GroupWiseMessageManager *>(sender);

	m_msgManagers.remove( manager->guid() );
}

void GroupWiseContact::handleIncomingMessage( const ConferenceEvent & message, bool autoReply )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << "Got a " << ( autoReply ? "auto-reply" : "message" ) << " for conference: " << message.guid << ", message: " << message.message << endl;
	KopeteContactPtrList contactList;
	contactList.append ( account()->myself () );
	GroupWiseMessageManager *mgr = manager( message.guid, true );

	// add an auto-reply indicator if needed
	QString messageMunged = message.message;
	if ( autoReply )
	{
		QString autoReplyPrefix = i18n("Prefix used for automatically generated auto-reply messages when the contact is Away, contains contact's name",
									   "Auto reply from %1: " ).arg( property( Kopete::Global::Properties::self()->nickName() ).value().toString() );
		messageMunged = autoReplyPrefix + message.message;
	}
	KopeteMessage * newMessage = new KopeteMessage ( message.timeStamp, this, contactList, messageMunged,
									KopeteMessage::Inbound,
									autoReply ? KopeteMessage::PlainText : KopeteMessage::RichText );
	Q_ASSERT( mgr );
	mgr->appendMessage( *newMessage );
	delete newMessage;
}

void GroupWiseContact::joinConference( const QString & guid )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	manager( guid, false );
}

void GroupWiseContact::leaveConference( const QString & guid )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << "NOT IMPLEMENTED" << endl;
}

void GroupWiseContact::addCLInstance( const ContactListInstance & instance )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	m_instances.append( instance );
}

void GroupWiseContact::removeCLInstance( const int objectId )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	QValueListIterator< ContactListInstance > it = m_instances.begin();
	const QValueListIterator< ContactListInstance > end = m_instances.end();
	for ( ; it != end; ++it )
	{
		if ( (*it).objectId == objectId )
		{
			kdDebug( GROUPWISE_DEBUG_GLOBAL ) << "removed objectId: " << objectId << endl;
			m_instances.remove( it );
			break;
		}
	}
}

bool GroupWiseContact::hasCLObjectId( const int objectId ) const
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	QValueListConstIterator< ContactListInstance > it = m_instances.begin();
	const QValueListConstIterator< ContactListInstance > end = m_instances.end();
	for ( ; it != end; ++it )
	{
		if ( (*it).objectId == objectId )
		{
			return true;
		}
	}
	return false;
}

CLInstanceList GroupWiseContact::instances() const
{
	return m_instances;
}

void GroupWiseContact::slotDeleteContact()
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	// remove all the instances of this contact from the server's contact list
	QValueListConstIterator< ContactListInstance > it = m_instances.begin();
	const QValueListConstIterator< ContactListInstance > end = m_instances.end();
	for ( ; it != end; ++it )
	{
		DeleteItemTask * dit = new DeleteItemTask( account()->client()->rootTask() );
		dit->item( (*it).parentId, (*it).objectId );
		connect( dit, SIGNAL( gotContactDeleted( const ContactItem & ) ), SLOT( receiveContactDeleted( const ContactItem & ) ) );
		dit->go( true );
	}
}

void GroupWiseContact::receiveContactDeleted( const ContactItem & instance )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	removeCLInstance( instance.id );
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << contactId() << " now has " << m_instances.count() << " instances remaining." << endl;
	if ( m_instances.count() == 0 )
		deleteLater();
}

#include "gwcontact.moc"

// vim: set noet ts=4 sts=4 sw=4:

<commit_msg>fix possible return of random data<commit_after>/*
    gwcontact.cpp - Kopete GroupWise Protocol

    Copyright (c) 2004      SUSE Linux AG	 	 http://www.suse.com

    Based on Testbed
    Copyright (c) 2003      by Will Stephenson		 <will@stevello.free-online.co.uk>

    Kopete    (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This library 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.      *
    *                                                                       *
    *************************************************************************
*/

#include <kaction.h>
#include <kdebug.h>
#include <klocale.h>

#include "kopeteaccount.h"
#include "kopeteglobal.h"
#include "kopetemessage.h"
#include "kopetemessagemanagerfactory.h"
#include "kopetemetacontact.h"

#include "tasks/deleteitemtask.h"

#include "client.h"
#include "gwaccount.h"
#include "ui/gwcontactproperties.h"
#include "gwerror.h"
#include "gwfakeserver.h"
#include "gwmessagemanager.h"
#include "gwprotocol.h"
#include "userdetailsmanager.h"

#include "gwcontact.h"

using namespace GroupWise;

GroupWiseContact::GroupWiseContact( KopeteAccount* account, const QString &dn,
			KopeteMetaContact *parent,
			const int objectId, const int parentId, const int sequence )
: KopeteContact( account, dn, parent ), m_objectId( objectId ), m_parentId( parentId ),
  m_sequence( sequence ), m_actionBlock( 0 )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << " dn: " << dn << endl;
	setOnlineStatus( ( parent && parent->isTemporary() ) ? protocol()->groupwiseUnknown : protocol()->groupwiseOffline );
}

GroupWiseContact::~GroupWiseContact()
{
	// This is necessary because otherwise the userDetailsManager
	// would not fetch details for this contact if they contact you
	// again from off-contact-list.
	if ( metaContact()->isTemporary() )
		account()->client()->userDetailsManager()->removeContact( contactId() );
}

void GroupWiseContact::updateDetails( const ContactDetails & details )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	if ( !details.cn.isNull() )
		setProperty( protocol()->propCN, details.cn );
	if ( !details.givenName.isNull() )
		setProperty( protocol()->propGivenName, details.givenName );
	if ( !details.surname.isNull() )
		setProperty( protocol()->propLastName, details.surname );
	if ( !details.fullName.isNull() )
		setProperty( protocol()->propFullName, details.fullName );
	//if ( !details.awayMessage.isNull() )
		//setProperty( protocol()->propAwayMessage, details.awayMessage );

	m_serverProperties = details.properties;

	if ( details.status != GroupWise::Invalid )
	{
		KopeteOnlineStatus status = protocol()->gwStatusToKOS( details.status );
		kdDebug( GROUPWISE_DEBUG_GLOBAL ) << "setting initial status to " << status.description() << endl;
		setOnlineStatus( status );
	}
	else
		kdDebug( GROUPWISE_DEBUG_GLOBAL ) << "initial status is, not setting " << details.status << endl;
}

GroupWiseProtocol *GroupWiseContact::protocol()
{
	return static_cast<GroupWiseProtocol *>( KopeteContact::protocol() );
}

GroupWiseAccount *GroupWiseContact::account()
{
	return static_cast<GroupWiseAccount *>( KopeteContact::account() );
}

bool GroupWiseContact::isReachable()
{
	// When we are invisible we can't start a chat with others, but we don't make isReachable return false, because then we
	// don't get any notification when we click on someone in the contact list.  Instead we warn the user when they try to send a message,
	// in GWMessageManager
	// (This is a GroupWise rule, not a problem in Kopete)

	if ( account()->isConnected() && isOnline()/* && account()->myself()->onlineStatus() != protocol()->groupwiseAppearOffline */)
		return true;
	if ( !account()->isConnected()/* || account()->myself()->onlineStatus() == protocol()->groupwiseAppearOffline*/ )
		return false;

	// fallback, something went wrong
	return false;
}

void GroupWiseContact::serialize( QMap< QString, QString > &serializedData, QMap< QString, QString > & /* addressBookData */ )
{
/*    QString value;
	switch ( m_type )
	{
	case Null:
		value = "null";
	case Echo:
		value = "echo";
	}
	serializedData[ "contactType" ] = value;*/
}

KopeteMessageManager * GroupWiseContact::manager( bool canCreate )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << "called, canCreate: " << canCreate << endl;

	KopeteContactPtrList chatMembers;
	chatMembers.append( this );

	return manager( chatMembers, canCreate );

/*	if ( m_msgManager )
	{
		return m_msgManager;
	}
	else
	{
		QPtrList<KopeteContact> contacts;
		contacts.append(this);
		m_msgManager = KopeteMessageManagerFactory::factory()->create(account()->myself(), contacts, protocol());
		connect(m_msgManager, SIGNAL(messageSent(KopeteMessage&, KopeteMessageManager*)),
				this, SLOT( sendMessage( KopeteMessage& ) ) );
		connect(m_msgManager, SIGNAL(destroyed()), this, SLOT(slotMessageManagerDestroyed()));
		return m_msgManager;
	}*/
}

GroupWiseMessageManager * GroupWiseContact::manager( KopeteContactPtrList chatMembers, bool canCreate )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;

	KopeteMessageManager *_manager = KopeteMessageManagerFactory::factory()->findKopeteMessageManager ( account()->myself(), chatMembers, protocol() );
	GroupWiseMessageManager *mgr = dynamic_cast<GroupWiseMessageManager*>( _manager );

	/*
	 * If we didn't find a message manager for this contact,
	 * instantiate a new one if we are allowed to. (otherwise return 0)
	 */
	if ( !mgr && canCreate )
	{
		mgr = account()->messageManager( account()->myself(), chatMembers, protocol(), QString::null );
		connect( mgr, SIGNAL( destroyed ( QObject * ) ), SLOT( slotMessageManagerDeleted ( QObject * ) ) );
		connect( mgr, SIGNAL( conferenceCreated() ), SLOT( slotConferenceCreated() ) );
		//m_pendingManagers.append( mgr );

	}

	return mgr;
}

GroupWiseMessageManager * GroupWiseContact::manager( const QString & guid, bool canCreate )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << "called for guid: " << guid << ", canCreate: " << canCreate << endl;
	if ( !guid.isNull() )
	{
		GroupWiseMessageManager * mgr = m_msgManagers[ guid ];
		if ( !mgr )
		{
			// we've received the first message from a new conference.
			// create a message manager with the given guid
			kdDebug( GROUPWISE_DEBUG_GLOBAL ) << " - this GroupWiseMessageManager is new to us. " << endl;
			KopeteContactPtrList chatMembers;
			chatMembers.append ( this );
			mgr = account()->messageManager( account()->myself(), chatMembers, protocol(), guid );
			connect( mgr, SIGNAL( destroyed( QObject * ) ), this, SLOT( slotMessageManagerDeleted ( QObject * ) ) );
			m_msgManagers.insert( guid, mgr );
		}
		else
			kdDebug( GROUPWISE_DEBUG_GLOBAL ) << " - found an existing GroupWiseMessageManager for this guid. " << endl;

		return mgr;
	}
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << "GUID is empty, grabbing first available manager." << endl;
	/*
	 * The guid supplied is empty, so just return the first available manager.
	 */
	return dynamic_cast<GroupWiseMessageManager *>( manager( canCreate ) );
}

QPtrList<KAction> *GroupWiseContact::customContextMenuActions()
{
	QPtrList<KAction> *m_actionCollection = new QPtrList<KAction>;

	// Block/unblock Contact
	QString label = /*isBlocked()*/false ? i18n( "Unblock User" ) : i18n( "Block User" );
	if( !m_actionBlock )
	{
		m_actionBlock = new KAction( label, "msn_blocked",0, this, SLOT( slotBlockUser() ),
			this, "actionBlock" );
	}
	else
		m_actionBlock->setText( label );

	m_actionCollection->append( m_actionBlock );

	return m_actionCollection;
}

void GroupWiseContact::slotUserInfo()
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	new GroupWiseContactProperties( this, account(), "gwcontactproperties" );
}

QMap< QString, QString > GroupWiseContact::serverProperties()
{
	return m_serverProperties;
}

void GroupWiseContact::sendMessage( KopeteMessage &message )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	// convert to the what the server wants
	// For this 'protocol', there's nothing to do
	// send it
/*	static_cast<GroupWiseAccount *>( account() )->server()->sendMessage(
			message.to().first()->contactId(),
			message.plainBody() );*/
	// give it back to the manager to display
	manager()->appendMessage( message );
	// tell the manager it was sent successfully
	manager()->messageSucceeded();
}

void GroupWiseContact::dumpManagers()
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << " for: " << contactId() << endl;
	QDictIterator< GroupWiseMessageManager > it( m_msgManagers );
	for ( ; it.current(); ++it )
		kdDebug( GROUPWISE_DEBUG_GLOBAL ) << "guid: " << it.currentKey() << endl;
}

void GroupWiseContact::slotConferenceCreated()
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	const GroupWiseMessageManager * mgr = (GroupWiseMessageManager *)sender();
	m_msgManagers.insert( mgr->guid(), mgr );
	dumpManagers();
}

void GroupWiseContact::slotMessageManagerDeleted( QObject *sender )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << "Message manager deleted, collecting the pieces..." << endl;

	GroupWiseMessageManager *manager = static_cast<GroupWiseMessageManager *>(sender);

	m_msgManagers.remove( manager->guid() );
}

void GroupWiseContact::handleIncomingMessage( const ConferenceEvent & message, bool autoReply )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << "Got a " << ( autoReply ? "auto-reply" : "message" ) << " for conference: " << message.guid << ", message: " << message.message << endl;
	KopeteContactPtrList contactList;
	contactList.append ( account()->myself () );
	GroupWiseMessageManager *mgr = manager( message.guid, true );

	// add an auto-reply indicator if needed
	QString messageMunged = message.message;
	if ( autoReply )
	{
		QString autoReplyPrefix = i18n("Prefix used for automatically generated auto-reply messages when the contact is Away, contains contact's name",
									   "Auto reply from %1: " ).arg( property( Kopete::Global::Properties::self()->nickName() ).value().toString() );
		messageMunged = autoReplyPrefix + message.message;
	}
	KopeteMessage * newMessage = new KopeteMessage ( message.timeStamp, this, contactList, messageMunged,
									KopeteMessage::Inbound,
									autoReply ? KopeteMessage::PlainText : KopeteMessage::RichText );
	Q_ASSERT( mgr );
	mgr->appendMessage( *newMessage );
	delete newMessage;
}

void GroupWiseContact::joinConference( const QString & guid )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	manager( guid, false );
}

void GroupWiseContact::leaveConference( const QString & guid )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << "NOT IMPLEMENTED" << endl;
}

void GroupWiseContact::addCLInstance( const ContactListInstance & instance )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	m_instances.append( instance );
}

void GroupWiseContact::removeCLInstance( const int objectId )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	QValueListIterator< ContactListInstance > it = m_instances.begin();
	const QValueListIterator< ContactListInstance > end = m_instances.end();
	for ( ; it != end; ++it )
	{
		if ( (*it).objectId == objectId )
		{
			kdDebug( GROUPWISE_DEBUG_GLOBAL ) << "removed objectId: " << objectId << endl;
			m_instances.remove( it );
			break;
		}
	}
}

bool GroupWiseContact::hasCLObjectId( const int objectId ) const
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	QValueListConstIterator< ContactListInstance > it = m_instances.begin();
	const QValueListConstIterator< ContactListInstance > end = m_instances.end();
	for ( ; it != end; ++it )
	{
		if ( (*it).objectId == objectId )
		{
			return true;
		}
	}
	return false;
}

CLInstanceList GroupWiseContact::instances() const
{
	return m_instances;
}

void GroupWiseContact::slotDeleteContact()
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	// remove all the instances of this contact from the server's contact list
	QValueListConstIterator< ContactListInstance > it = m_instances.begin();
	const QValueListConstIterator< ContactListInstance > end = m_instances.end();
	for ( ; it != end; ++it )
	{
		DeleteItemTask * dit = new DeleteItemTask( account()->client()->rootTask() );
		dit->item( (*it).parentId, (*it).objectId );
		connect( dit, SIGNAL( gotContactDeleted( const ContactItem & ) ), SLOT( receiveContactDeleted( const ContactItem & ) ) );
		dit->go( true );
	}
}

void GroupWiseContact::receiveContactDeleted( const ContactItem & instance )
{
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << endl;
	removeCLInstance( instance.id );
	kdDebug( GROUPWISE_DEBUG_GLOBAL ) << k_funcinfo << contactId() << " now has " << m_instances.count() << " instances remaining." << endl;
	if ( m_instances.count() == 0 )
		deleteLater();
}

#include "gwcontact.moc"

// vim: set noet ts=4 sts=4 sw=4:

<|endoftext|>


<commit_before>/*
 *  Copyright 2011 DataStax
 *
 *  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.
 */

#ifndef _PHP_PDO_CASSANDRA_PRIVATE_H_
# define _PHP_PDO_CASSANDRA_PRIVATE_H_

extern "C" {
/* Need to undefine these so that thrift config doesn't complain */
#ifdef HAVE_CONFIG_H
# include "config.h"
# undef PACKAGE_NAME
# undef PACKAGE_STRING
# undef PACKAGE_TARNAME
# undef PACKAGE_VERSION
#endif

#include "ext/standard/info.h"
#include "Zend/zend_exceptions.h"
#include "Zend/zend_interfaces.h"
#include "main/php_ini.h"
#include "pdo/php_pdo.h"
#include "pdo/php_pdo_driver.h"
#include "ext/standard/url.h"
#include "ext/standard/php_string.h"
#include "ext/pcre/php_pcre.h"
}

#define HAVE_ZLIB_CP HAVE_ZLIB
#undef HAVE_ZLIB

#include "gen-cpp/Cassandra.h"
#include <protocol/TBinaryProtocol.h>
#include <transport/TSocketPool.h>
#include <transport/TTransportUtils.h>

#undef HAVE_ZLIB
#define HAVE_ZLIB HAVE_ZLIB_CP

#include <boost/bimap.hpp>

using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace org::apache::cassandra;

enum pdo_cassandra_type {
	PDO_CASSANDRA_TYPE_BYTES,
	PDO_CASSANDRA_TYPE_ASCII,
	PDO_CASSANDRA_TYPE_UTF8,
	PDO_CASSANDRA_TYPE_INTEGER,
	PDO_CASSANDRA_TYPE_LONG,
	PDO_CASSANDRA_TYPE_UUID,
	PDO_CASSANDRA_TYPE_LEXICAL,
	PDO_CASSANDRA_TYPE_TIMEUUID,
	PDO_CASSANDRA_TYPE_UNKNOWN
};

/** {{{
*/
typedef struct {
	const char *file;
	char *errmsg;
	int line;
	unsigned int errcode;
} pdo_cassandra_einfo;
/* }}} */

/* {{{ typedef struct php_cassandra_db_handle
*/
typedef struct {
	zend_object zo;
	zend_bool compression;
	boost::shared_ptr<TSocketPool> socket;
	boost::shared_ptr<TFramedTransport> transport;
	boost::shared_ptr<TProtocol> protocol;
	boost::shared_ptr<CassandraClient> client;
	pdo_cassandra_einfo einfo;
	std::string active_keyspace;
	KsDef description;
	zend_bool has_description;

	zend_bool preserve_keys;
	zend_bool preserve_values;
} pdo_cassandra_db_handle;
/* }}} */

typedef boost::bimap<std::string, int> ColumnMap;
typedef boost::bimap<std::string, pdo_param_type> ColumnTypeMap;

/* {{{ typedef struct pdo_cassandra_stmt
*/
typedef struct {
	pdo_cassandra_db_handle *H;
	zend_bool has_iterator;
	boost::shared_ptr<CqlResult> result;
	std::vector<CqlRow>::iterator it;

	ColumnMap original_column_names;
	ColumnMap column_name_labels;

	std::string active_columnfamily;
} pdo_cassandra_stmt;
/* }}} */

/* {{{ enum pdo_cassandra_constant
*/
enum pdo_cassandra_constant {
	PDO_CASSANDRA_ATTR_MIN = PDO_ATTR_DRIVER_SPECIFIC,
	PDO_CASSANDRA_ATTR_NUM_RETRIES,
	PDO_CASSANDRA_ATTR_RETRY_INTERVAL,
	PDO_CASSANDRA_ATTR_MAX_CONSECUTIVE_FAILURES,
	PDO_CASSANDRA_ATTR_RANDOMIZE,
	PDO_CASSANDRA_ATTR_ALWAYS_TRY_LAST,
	PDO_CASSANDRA_ATTR_LINGER,
	PDO_CASSANDRA_ATTR_NO_DELAY,
	PDO_CASSANDRA_ATTR_CONN_TIMEOUT,
	PDO_CASSANDRA_ATTR_RECV_TIMEOUT,
	PDO_CASSANDRA_ATTR_SEND_TIMEOUT,
	PDO_CASSANDRA_ATTR_COMPRESSION,
	PDO_CASSANDRA_ATTR_THRIFT_DEBUG,
	PDO_CASSANDRA_ATTR_PRESERVE_VALUES,
	PDO_CASSANDRA_ATTR_MAX
};
/* }}} */

enum pdo_cassandra_error {
	PDO_CASSANDRA_GENERAL_ERROR,
	PDO_CASSANDRA_NOT_FOUND,
	PDO_CASSANDRA_INVALID_REQUEST,
	PDO_CASSANDRA_UNAVAILABLE,
	PDO_CASSANDRA_TIMED_OUT,
	PDO_CASSANDRA_AUTHENTICATION_ERROR,
	PDO_CASSANDRA_AUTHORIZATION_ERROR,
	PDO_CASSANDRA_SCHEMA_DISAGREEMENT,
	PDO_CASSANDRA_TRANSPORT_ERROR,
	PDO_CASSANDRA_INVALID_CONNECTION_STRING
};

void pdo_cassandra_error_ex(pdo_dbh_t *dbh TSRMLS_DC, pdo_cassandra_error code, const char *file, int line, zend_bool force_exception, const char *message, ...);
#define pdo_cassandra_error(dbh, code, message, ...) pdo_cassandra_error_ex(dbh TSRMLS_CC, code, __FILE__, __LINE__, 0, message, __VA_ARGS__)
#define pdo_cassandra_error_exception(dbh, code, message, ...) pdo_cassandra_error_ex(dbh TSRMLS_CC, code, __FILE__, __LINE__, 1, message, __VA_ARGS__)

void pdo_cassandra_set_active_keyspace(pdo_cassandra_db_handle *H, const std::string &sql);

#endif /* _PHP_PDO_CASSANDRA_PRIVATE_H_ */
<commit_msg>Remove dead code<commit_after>/*
 *  Copyright 2011 DataStax
 *
 *  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.
 */

#ifndef _PHP_PDO_CASSANDRA_PRIVATE_H_
# define _PHP_PDO_CASSANDRA_PRIVATE_H_

extern "C" {
/* Need to undefine these so that thrift config doesn't complain */
#ifdef HAVE_CONFIG_H
# include "config.h"
# undef PACKAGE_NAME
# undef PACKAGE_STRING
# undef PACKAGE_TARNAME
# undef PACKAGE_VERSION
#endif

#include "ext/standard/info.h"
#include "Zend/zend_exceptions.h"
#include "Zend/zend_interfaces.h"
#include "main/php_ini.h"
#include "pdo/php_pdo.h"
#include "pdo/php_pdo_driver.h"
#include "ext/standard/url.h"
#include "ext/standard/php_string.h"
#include "ext/pcre/php_pcre.h"
}

#define HAVE_ZLIB_CP HAVE_ZLIB
#undef HAVE_ZLIB

#include "gen-cpp/Cassandra.h"
#include <protocol/TBinaryProtocol.h>
#include <transport/TSocketPool.h>
#include <transport/TTransportUtils.h>

#undef HAVE_ZLIB
#define HAVE_ZLIB HAVE_ZLIB_CP

#include <boost/bimap.hpp>

using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace org::apache::cassandra;

enum pdo_cassandra_type {
	PDO_CASSANDRA_TYPE_BYTES,
	PDO_CASSANDRA_TYPE_ASCII,
	PDO_CASSANDRA_TYPE_UTF8,
	PDO_CASSANDRA_TYPE_INTEGER,
	PDO_CASSANDRA_TYPE_LONG,
	PDO_CASSANDRA_TYPE_UUID,
	PDO_CASSANDRA_TYPE_LEXICAL,
	PDO_CASSANDRA_TYPE_TIMEUUID,
	PDO_CASSANDRA_TYPE_UNKNOWN
};

/** {{{
*/
typedef struct {
	const char *file;
	char *errmsg;
	int line;
	unsigned int errcode;
} pdo_cassandra_einfo;
/* }}} */

/* {{{ typedef struct php_cassandra_db_handle
*/
typedef struct {
	zend_object zo;
	zend_bool compression;
	boost::shared_ptr<TSocketPool> socket;
	boost::shared_ptr<TFramedTransport> transport;
	boost::shared_ptr<TProtocol> protocol;
	boost::shared_ptr<CassandraClient> client;
	pdo_cassandra_einfo einfo;
	std::string active_keyspace;
	KsDef description;
	zend_bool has_description;
	zend_bool preserve_values;
} pdo_cassandra_db_handle;
/* }}} */

typedef boost::bimap<std::string, int> ColumnMap;
typedef boost::bimap<std::string, pdo_param_type> ColumnTypeMap;

/* {{{ typedef struct pdo_cassandra_stmt
*/
typedef struct {
	pdo_cassandra_db_handle *H;
	zend_bool has_iterator;
	boost::shared_ptr<CqlResult> result;
	std::vector<CqlRow>::iterator it;

	ColumnMap original_column_names;
	ColumnMap column_name_labels;

	std::string active_columnfamily;
} pdo_cassandra_stmt;
/* }}} */

/* {{{ enum pdo_cassandra_constant
*/
enum pdo_cassandra_constant {
	PDO_CASSANDRA_ATTR_MIN = PDO_ATTR_DRIVER_SPECIFIC,
	PDO_CASSANDRA_ATTR_NUM_RETRIES,
	PDO_CASSANDRA_ATTR_RETRY_INTERVAL,
	PDO_CASSANDRA_ATTR_MAX_CONSECUTIVE_FAILURES,
	PDO_CASSANDRA_ATTR_RANDOMIZE,
	PDO_CASSANDRA_ATTR_ALWAYS_TRY_LAST,
	PDO_CASSANDRA_ATTR_LINGER,
	PDO_CASSANDRA_ATTR_NO_DELAY,
	PDO_CASSANDRA_ATTR_CONN_TIMEOUT,
	PDO_CASSANDRA_ATTR_RECV_TIMEOUT,
	PDO_CASSANDRA_ATTR_SEND_TIMEOUT,
	PDO_CASSANDRA_ATTR_COMPRESSION,
	PDO_CASSANDRA_ATTR_THRIFT_DEBUG,
	PDO_CASSANDRA_ATTR_PRESERVE_VALUES,
	PDO_CASSANDRA_ATTR_MAX
};
/* }}} */

enum pdo_cassandra_error {
	PDO_CASSANDRA_GENERAL_ERROR,
	PDO_CASSANDRA_NOT_FOUND,
	PDO_CASSANDRA_INVALID_REQUEST,
	PDO_CASSANDRA_UNAVAILABLE,
	PDO_CASSANDRA_TIMED_OUT,
	PDO_CASSANDRA_AUTHENTICATION_ERROR,
	PDO_CASSANDRA_AUTHORIZATION_ERROR,
	PDO_CASSANDRA_SCHEMA_DISAGREEMENT,
	PDO_CASSANDRA_TRANSPORT_ERROR,
	PDO_CASSANDRA_INVALID_CONNECTION_STRING
};

void pdo_cassandra_error_ex(pdo_dbh_t *dbh TSRMLS_DC, pdo_cassandra_error code, const char *file, int line, zend_bool force_exception, const char *message, ...);
#define pdo_cassandra_error(dbh, code, message, ...) pdo_cassandra_error_ex(dbh TSRMLS_CC, code, __FILE__, __LINE__, 0, message, __VA_ARGS__)
#define pdo_cassandra_error_exception(dbh, code, message, ...) pdo_cassandra_error_ex(dbh TSRMLS_CC, code, __FILE__, __LINE__, 1, message, __VA_ARGS__)

void pdo_cassandra_set_active_keyspace(pdo_cassandra_db_handle *H, const std::string &sql);

#endif /* _PHP_PDO_CASSANDRA_PRIVATE_H_ */
<|endoftext|>