<commit_before>//----------------------------------------------------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2008 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------------------------------------------------

// the Hessian of the RT element was a tensor of NaN's. This doesn't make much
// sense

#include "../tests.h"
#include <base/logstream.h>
#include <base/function.h>
#include <base/quadrature_lib.h>
#include <lac/vector.h>
#include <grid/grid_generator.h>
#include <grid/tria_boundary_lib.h>
#include <dofs/dof_handler.h>
#include <fe/fe_q.h>
#include <fe/fe_raviart_thomas.h>
#include <fe/fe_nedelec.h>
#include <fe/fe_dgq.h>
#include <fe/fe_system.h>
#include <fe/fe_values.h>
#include <fe/mapping_q1.h>

#include <fstream>

template<int dim>
void test (const Triangulation<dim>& tr,
	   const FiniteElement<dim>& fe)
{
  DoFHandler<dim> dof(tr);
  dof.distribute_dofs(fe);

  const QGauss<dim> quadrature(2);
  FEValues<dim> fe_values (fe, quadrature, update_values | update_hessians);

  fe_values.reinit (dof.begin_active());

  deallog << fe_values.shape_hessian_component (0,0,0) << std::endl;

				   // compare the hessian with
				   // itself. this fails if the
				   // values are NaN's which the
				   // Hessian consists of at the
				   // time this test is written
  Assert (fe_values.shape_hessian_component (0,0,0)
	  ==
	  fe_values.shape_hessian_component (0,0,0),
	  ExcInternalError());
}

template<int dim>
void test_hyper_sphere()
{
  Triangulation<dim> tr;
  GridGenerator::hyper_cube(tr);

  test(tr, FE_RaviartThomas<dim>(1));
}

int main()
{
  std::ofstream logfile ("rt_hessian/output");
  deallog << std::setprecision (2);

  deallog.attach(logfile);
  deallog.depth_console (0);
  deallog.threshold_double(1.e-12);

  test_hyper_sphere<2>();
  test_hyper_sphere<3>();
}
<commit_msg>Simplify update flags.<commit_after>//----------------------------------------------------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2008 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------------------------------------------------

// the Hessian of the RT element was a tensor of NaN's. This doesn't make much
// sense

#include "../tests.h"
#include <base/logstream.h>
#include <base/function.h>
#include <base/quadrature_lib.h>
#include <lac/vector.h>
#include <grid/grid_generator.h>
#include <grid/tria_boundary_lib.h>
#include <dofs/dof_handler.h>
#include <fe/fe_q.h>
#include <fe/fe_raviart_thomas.h>
#include <fe/fe_nedelec.h>
#include <fe/fe_dgq.h>
#include <fe/fe_system.h>
#include <fe/fe_values.h>
#include <fe/mapping_q1.h>

#include <fstream>

template<int dim>
void test (const Triangulation<dim>& tr,
	   const FiniteElement<dim>& fe)
{
  DoFHandler<dim> dof(tr);
  dof.distribute_dofs(fe);

  const QGauss<dim> quadrature(2);
  FEValues<dim> fe_values (fe, quadrature, update_covariant_transformation | update_hessians);

  fe_values.reinit (dof.begin_active());

  deallog << fe_values.shape_hessian_component (0,0,0) << std::endl;

				   // compare the hessian with
				   // itself. this fails if the
				   // values are NaN's which the
				   // Hessian consists of at the
				   // time this test is written
  Assert (fe_values.shape_hessian_component (0,0,0)
	  ==
	  fe_values.shape_hessian_component (0,0,0),
	  ExcInternalError());
}

template<int dim>
void test_hyper_sphere()
{
  Triangulation<dim> tr;
  GridGenerator::hyper_cube(tr);

  test(tr, FE_RaviartThomas<dim>(1));
}

int main()
{
  std::ofstream logfile ("rt_hessian/output");
  deallog << std::setprecision (2);

  deallog.attach(logfile);
  deallog.depth_console (0);
  deallog.threshold_double(1.e-12);

  test_hyper_sphere<2>();
  test_hyper_sphere<3>();
}
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Author: Victor Chudnovsky

#include "base/logging.h"
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/kernel/image/image_frame_interface.h"

namespace pagespeed {

namespace image_compression {

////////// ImageSpec

ImageSpec::ImageSpec() {
    Reset();
}

void ImageSpec::Reset() {
    width = 0;
    height = 0;
    num_frames = 0;
    loop_count = 1;
    memset(bg_color, 0, sizeof(bg_color));
    use_bg_color = true;
}

size_px ImageSpec::TruncateXIndex(const size_px x) {
  if (x > width) {
    return width;
  }
  return x;
}

size_px ImageSpec::TruncateYIndex(const size_px y) {
  if (y > height) {
    return height;
  }
  return y;
}

bool ImageSpec::CanContainFrame(const FrameSpec& frame_spec) const {
  return ((frame_spec.left + frame_spec.width <= width) &&
          (frame_spec.top + frame_spec.height <= height));
}

GoogleString ImageSpec::ToString() const {
  return StringPrintf("Image: %d x %d : %u frames, repeated %u times",
                      width, height, num_frames, loop_count);
}

bool ImageSpec::Equals(const ImageSpec& other) const {
  return ((width == other.width) &&
          (height == other.height) &&
          (num_frames == other.num_frames) &&
          (loop_count == other.loop_count) &&
          (memcmp(bg_color, other.bg_color, sizeof(bg_color)) == 0) &&
          (use_bg_color == other.use_bg_color));
}

////////// FrameSpec

FrameSpec::FrameSpec() {
    Reset();
}

void  FrameSpec::Reset() {
  width = 0;
  height = 0;
  top = 0;
  left = 0;

  pixel_format = UNSUPPORTED;
  duration_ms = 0;
  disposal = DISPOSAL_NONE;
  hint_progressive = false;
}

GoogleString FrameSpec::ToString() const {
  return StringPrintf(
      "Frame: size %u x %u at (%u, %u) "
      "pixel_format: %d, duration_ms: %lu, disposal: %d, progressive: %s",
      width, height, top, left, pixel_format, duration_ms, disposal,
      (hint_progressive ? "yes" : "no"));
}

bool FrameSpec::Equals(const FrameSpec& other) const {
  return ((width == other.width) &&
          (height == other.height) &&
          (top == other.top) &&
          (left == other.left) &&
          (pixel_format == other.pixel_format) &&
          (duration_ms == other.duration_ms) &&
          (disposal == other.disposal) &&
          (hint_progressive == other.hint_progressive));
}

////////// MultipleFrameReader

MultipleFrameReader::MultipleFrameReader(MessageHandler* const handler)
    : message_handler_(handler), quirks_mode_(QUIRKS_NONE) {
  CHECK(handler != NULL);
}

MultipleFrameReader::~MultipleFrameReader() {
}

////////// MultipleFrameWriter

MultipleFrameWriter::MultipleFrameWriter(MessageHandler* const handler)
    : message_handler_(handler) {
  CHECK(handler != NULL);
}

MultipleFrameWriter::~MultipleFrameWriter() {
}

}  // namespace image_compression

}  // namespace pagespeed
<commit_msg>Fix compiler errors on gcc 4.6.3 due to mismatched format strings and integer types.<commit_after>/*
 * Copyright 2014 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Author: Victor Chudnovsky

#include "base/logging.h"
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/kernel/image/image_frame_interface.h"

namespace pagespeed {

namespace image_compression {

////////// ImageSpec

ImageSpec::ImageSpec() {
    Reset();
}

void ImageSpec::Reset() {
    width = 0;
    height = 0;
    num_frames = 0;
    loop_count = 1;
    memset(bg_color, 0, sizeof(bg_color));
    use_bg_color = true;
}

size_px ImageSpec::TruncateXIndex(const size_px x) {
  if (x > width) {
    return width;
  }
  return x;
}

size_px ImageSpec::TruncateYIndex(const size_px y) {
  if (y > height) {
    return height;
  }
  return y;
}

bool ImageSpec::CanContainFrame(const FrameSpec& frame_spec) const {
  return ((frame_spec.left + frame_spec.width <= width) &&
          (frame_spec.top + frame_spec.height <= height));
}

GoogleString ImageSpec::ToString() const {
  return StringPrintf("Image: %d x %d : %u frames, repeated %u times",
                      width, height, num_frames, loop_count);
}

bool ImageSpec::Equals(const ImageSpec& other) const {
  return ((width == other.width) &&
          (height == other.height) &&
          (num_frames == other.num_frames) &&
          (loop_count == other.loop_count) &&
          (memcmp(bg_color, other.bg_color, sizeof(bg_color)) == 0) &&
          (use_bg_color == other.use_bg_color));
}

////////// FrameSpec

FrameSpec::FrameSpec() {
    Reset();
}

void  FrameSpec::Reset() {
  width = 0;
  height = 0;
  top = 0;
  left = 0;

  pixel_format = UNSUPPORTED;
  duration_ms = 0;
  disposal = DISPOSAL_NONE;
  hint_progressive = false;
}

GoogleString FrameSpec::ToString() const {
  return StringPrintf(
      "Frame: size %u x %u at (%u, %u) "
      "pixel_format: %d, duration_ms: %lu, disposal: %d, progressive: %s",
      width, height, top, left, pixel_format,
      static_cast<unsigned long>(duration_ms), disposal,
      (hint_progressive ? "yes" : "no"));
}

bool FrameSpec::Equals(const FrameSpec& other) const {
  return ((width == other.width) &&
          (height == other.height) &&
          (top == other.top) &&
          (left == other.left) &&
          (pixel_format == other.pixel_format) &&
          (duration_ms == other.duration_ms) &&
          (disposal == other.disposal) &&
          (hint_progressive == other.hint_progressive));
}

////////// MultipleFrameReader

MultipleFrameReader::MultipleFrameReader(MessageHandler* const handler)
    : message_handler_(handler), quirks_mode_(QUIRKS_NONE) {
  CHECK(handler != NULL);
}

MultipleFrameReader::~MultipleFrameReader() {
}

////////// MultipleFrameWriter

MultipleFrameWriter::MultipleFrameWriter(MessageHandler* const handler)
    : message_handler_(handler) {
  CHECK(handler != NULL);
}

MultipleFrameWriter::~MultipleFrameWriter() {
}

}  // namespace image_compression

}  // namespace pagespeed
<|endoftext|>


<commit_before>class CfgXM8
{
	extraApps[] = {"ExAd_VG","ExAd_Info","ExAd_CHVD","ExAd_Journal","ExAd_Bike","ExAd_Quad","ExAd_SB"};

	class ExAd_VG
	{
		title = "Virtual Garage";
		controlID = 50000;					//IDC:50000 -> 50015 || These need to be unique and out of range from each other
		logo = "ExadClient\XM8\Apps\VG\Icon_VG.paa";
		onLoad = "ExAdClient\XM8\Apps\VG\onLoad.sqf";
		onOpen = "ExAdClient\XM8\Apps\VG\onOpen.sqf";
		onClose = "ExAdClient\XM8\Apps\VG\onClose.sqf";
	};
	class ExAd_Info
	{
		title = "Server Info";
		controlID = 50100;					//IDC:50100 -> 50102 || These need to be unique and out of range from each other
		logo = "ExadClient\XM8\Apps\Info\Icon_SI.paa";
		onLoad = "ExAdClient\XM8\Apps\Info\onLoad.sqf";
		onOpen = "ExAdClient\XM8\Apps\Info\onOpen.sqf";
		onClose = "ExAdClient\XM8\Apps\Info\onClose.sqf";
	};
	class ExAd_CHVD
	{
		title = "View Distance Settings";
		controlID = 50200;					//IDC:50200 -> 50102 || These need to be unique and out of range from each other
		config = "ExadClient\XM8\Apps\CHVD\config.sqf";
		logo = "ExadClient\XM8\Apps\CHVD\Icon_CHVD.paa";
		onLoad = "ExAdClient\XM8\Apps\CHVD\onLoad.sqf";
		onOpen = "ExAdClient\XM8\Apps\CHVD\onOpen.sqf";
		onClose = "ExAdClient\XM8\Apps\CHVD\onClose.sqf";
	};
	class ExAd_Journal
	{
		title = "Journal";
		controlID = 50300;					//IDC:50300 -> 50305 || These need to be unique and out of range from each other
		config = "ExadClient\XM8\Apps\Journal\config.sqf";
		logo = "ExadClient\XM8\Apps\Journal\Icon_Journal.paa";
		onLoad = "ExAdClient\XM8\Apps\Journal\onLoad.sqf";
		onOpen = "ExAdClient\XM8\Apps\Journal\onOpen.sqf";
		onClose = "ExAdClient\XM8\Apps\Journal\onClose.sqf";
	};
	class ExAd_Bike
	{
		title = "Deploy Bike";
		config = "ExadClient\XM8\Apps\DeployVehicle\config.sqf";
		bambiState = 0;		//Set to 1 to only allow players to deploy as a bambi.
		blockInSafezone = 0;	//Set to 1 to prevent players deploying said vehicle inside of safezones.
		vehicleClass = "Exile_Bike_MountainBike";
		recipe[] = {{"Exile_Item_ExtensionCord",-1}};
		packable = 1;
		autoCleanUp = 1;
		quickFunction = "['ExAd_Bike'] call ExAd_XM8_DV_fnc_spawnVehicle";
	};
	class ExAd_Quad
	{
		title = "Deploy Quad";
		bambiState = 0;
		blockInSafezone = 0;
		vehicleClass = "Exile_Bike_QuadBike_Fia";
		recipe[] = {{"Exile_Item_ExtensionCord",1}};
		packable = 1;
		quickFunction = "['ExAd_Quad'] call ExAd_XM8_DV_fnc_spawnVehicle";
	};
	class ExAd_SB
	{
		title = "Statsbar Settings";
		controlID = 50400;					//IDC:50400 -> 50475 || These need to be unique and out of range from each other
		logo = "ExadClient\XM8\Apps\SB_Settings\Icon_SB.paa";
		onLoad = "ExAdClient\XM8\Apps\SB_Settings\onLoad.sqf";
	};
};

class CfgExileCustomCode
{
	ExileServer_system_territory_database_load = "ExAdClient\VirtualGarage\CustomCode\ExileServer_system_territory_database_load.sqf";
	ExileClient_gui_xm8_slide = "ExAdClient\XM8\CustomCode\ExileClient_gui_xm8_slide.sqf";
	ExileClient_gui_xm8_show = "ExAdClient\XM8\CustomCode\ExileClient_gui_xm8_show.sqf";
};

class CfgInteractionMenus
{
	class Car
	{
		targetType = 2;
		target = "Car";

		class Actions
		{
			class PackDeployedVehicle: ExileAbstractAction
			{
				title = "Pack Vehicle";
				condition = "call ExAd_XM8_DV_fnc_canPack";
				action = "call ExAd_XM8_DV_fnc_pack";
			};
			class ExAdSalvage: ExileAbstractAction
            		{
                	title = "<t color='#ff0000'>ExAd Salvage Aircraft</t>";
                	condition = "(!(alive (ExileClientInteractionObject)))";
                	action = "_this call ExAd_fnc_vehicleSalvage";
			};
		};
	};
	class Bikes
	{
		targetType = 2;
		target = "Bicycle";

		class Actions
		{
			class PackDeployedVehicle: ExileAbstractAction
			{
				title = "Pack Bike";
				condition = "call ExAd_XM8_DV_fnc_canPack";
				action = "call ExAd_XM8_DV_fnc_pack";
			};
		};
	};
	class Flag
	{
		targetType = 2;
		target = "Exile_Construction_Flag_Static";
		class Actions
		{
			class HackVG : ExileAbstractAction
			{
				title = "Hack Virtual Garage";
				condition = "call ExAd_fnc_canHackVG";
				action = "_this spawn ExAd_fnc_startHack";
			};
		};
	};
	class Construction
	{
		targetType = 2;
		target = "Exile_Construction_Abstract_Static";

		class Actions
		{
			class Grind : ExileAbstractAction
			{
				title = "Grind Lock";
				condition = "call ExAd_fnc_canGrindLock";
				action = "_this spawn ExAd_fnc_grindLock";
			};

			class RestoreLock : ExileAbstractAction
			{
				title = "Restore Lock";
				condition = "_object call ExAd_fnc_canRestoreLock";
				action = "_this spawn ExAd_fnc_restoreLock";
			};
		};
	};
	class Safe
	{
		targetType = 2;
		target = "Exile_Container_Safe";

		class Actions
		{
			class HackSafe : ExileAbstractAction
			{
				title = "Hack Safe";
				condition = "call ExAd_fnc_canHackSafe";
				action = "_this spawn ExAd_fnc_startHack";
			};
		};
	};
	class Laptop
	{
		targetType = 2;
		target = "Exile_Construction_Laptop_Static";

		class Actions
		{
			class StopHack: ExileAbstractAction
			{
				title = "Interupt Hack";
				condition = "(ExileClientInteractionObject getVariable ['ExAd_HACKING_IN_PROGRESS', false])";
				action = "_this spawn ExAd_fnc_stopHack";
			};
		};
	};
};
<commit_msg>Update config.cpp<commit_after>class CfgXM8
{
	extraApps[] = {"ExAd_Info","ExAd_CHVD","ExAd_Journal","ExAd_Bike","ExAd_Quad","ExAd_SB"};

	class ExAd_Info
	{
		title = "Server Info";
		controlID = 50100;					//IDC:50100 -> 50102 || These need to be unique and out of range from each other
		logo = "ExadClient\XM8\Apps\Info\Icon_SI.paa";
		onLoad = "ExAdClient\XM8\Apps\Info\onLoad.sqf";
		onOpen = "ExAdClient\XM8\Apps\Info\onOpen.sqf";
		onClose = "ExAdClient\XM8\Apps\Info\onClose.sqf";
	};
	class ExAd_CHVD
	{
		title = "View Distance Settings";
		controlID = 50200;					//IDC:50200 -> 50102 || These need to be unique and out of range from each other
		config = "ExadClient\XM8\Apps\CHVD\config.sqf";
		logo = "ExadClient\XM8\Apps\CHVD\Icon_CHVD.paa";
		onLoad = "ExAdClient\XM8\Apps\CHVD\onLoad.sqf";
		onOpen = "ExAdClient\XM8\Apps\CHVD\onOpen.sqf";
		onClose = "ExAdClient\XM8\Apps\CHVD\onClose.sqf";
	};
	class ExAd_Journal
	{
		title = "Journal";
		controlID = 50300;					//IDC:50300 -> 50305 || These need to be unique and out of range from each other
		config = "ExadClient\XM8\Apps\Journal\config.sqf";
		logo = "ExadClient\XM8\Apps\Journal\Icon_Journal.paa";
		onLoad = "ExAdClient\XM8\Apps\Journal\onLoad.sqf";
		onOpen = "ExAdClient\XM8\Apps\Journal\onOpen.sqf";
		onClose = "ExAdClient\XM8\Apps\Journal\onClose.sqf";
	};
	class ExAd_Bike
	{
		title = "Deploy Bike";
		config = "ExadClient\XM8\Apps\DeployVehicle\config.sqf";
		bambiState = 0;		//Set to 1 to only allow players to deploy as a bambi.
		blockInSafezone = 0;	//Set to 1 to prevent players deploying said vehicle inside of safezones.
		vehicleClass = "Exile_Bike_MountainBike";
		recipe[] = {{"Exile_Item_ExtensionCord",-1}};
		packable = 1;
		autoCleanUp = 1;
		quickFunction = "['ExAd_Bike'] call ExAd_XM8_DV_fnc_spawnVehicle";
	};
	class ExAd_Quad
	{
		title = "Deploy Quad";
		bambiState = 0;
		blockInSafezone = 0;
		vehicleClass = "Exile_Bike_QuadBike_Fia";
		recipe[] = {{"Exile_Item_ExtensionCord",1}};
		packable = 1;
		quickFunction = "['ExAd_Quad'] call ExAd_XM8_DV_fnc_spawnVehicle";
	};
	class ExAd_SB
	{
		title = "Statsbar Settings";
		controlID = 50400;					//IDC:50400 -> 50475 || These need to be unique and out of range from each other
		logo = "ExadClient\XM8\Apps\SB_Settings\Icon_SB.paa";
		onLoad = "ExAdClient\XM8\Apps\SB_Settings\onLoad.sqf";
	};
};

class CfgExileCustomCode
{
	//ExileServer_system_territory_database_load = "ExAdClient\VirtualGarage\CustomCode\ExileServer_system_territory_database_load.sqf";
	//ExileClient_gui_xm8_slide = "ExAdClient\XM8\CustomCode\ExileClient_gui_xm8_slide.sqf";
	//ExileClient_gui_xm8_show = "ExAdClient\XM8\CustomCode\ExileClient_gui_xm8_show.sqf";
};

class CfgInteractionMenus
{
	class Car
	{
		targetType = 2;
		target = "Car";

		class Actions
		{
			class PackDeployedVehicle: ExileAbstractAction
			{
				title = "Pack Vehicle";
				condition = "call ExAd_XM8_DV_fnc_canPack";
				action = "call ExAd_XM8_DV_fnc_pack";
			};
			class ExAdSalvage: ExileAbstractAction
            		{
                	title = "<t color='#ff0000'>ExAd Salvage Aircraft</t>";
                	condition = "(!(alive (ExileClientInteractionObject)))";
                	action = "_this call ExAd_fnc_vehicleSalvage";
			};
		};
	};
	class Bikes
	{
		targetType = 2;
		target = "Bicycle";

		class Actions
		{
			class PackDeployedVehicle: ExileAbstractAction
			{
				title = "Pack Bike";
				condition = "call ExAd_XM8_DV_fnc_canPack";
				action = "call ExAd_XM8_DV_fnc_pack";
			};
		};
	};
	class Construction
	{
		targetType = 2;
		target = "Exile_Construction_Abstract_Static";

		class Actions
		{
			class Grind : ExileAbstractAction
			{
				title = "Grind Lock";
				condition = "call ExAd_fnc_canGrindLock";
				action = "_this spawn ExAd_fnc_grindLock";
			};

			class RestoreLock : ExileAbstractAction
			{
				title = "Restore Lock";
				condition = "_object call ExAd_fnc_canRestoreLock";
				action = "_this spawn ExAd_fnc_restoreLock";
			};
		};
	};
	class Safe
	{
		targetType = 2;
		target = "Exile_Container_Safe";

		class Actions
		{
			class HackSafe : ExileAbstractAction
			{
				title = "Hack Safe";
				condition = "call ExAd_fnc_canHackSafe";
				action = "_this spawn ExAd_fnc_startHack";
			};
		};
	};
	class Laptop
	{
		targetType = 2;
		target = "Exile_Construction_Laptop_Static";

		class Actions
		{
			class StopHack: ExileAbstractAction
			{
				title = "Interupt Hack";
				condition = "(ExileClientInteractionObject getVariable ['ExAd_HACKING_IN_PROGRESS', false])";
				action = "_this spawn ExAd_fnc_stopHack";
			};
		};
	};
};
<|endoftext|>


<commit_before>#include <possumwood_sdk/node_implementation.h>
#include <possumwood_sdk/app.h>

#include <GL/glew.h>
#include <GL/glu.h>

#include <ImathVec.h>

#include "datatypes/vertex_data.inl"

namespace {

Imath::M44d toDouble(const Imath::M44f& matrix) {
	Imath::M44d result;
	for(unsigned a = 0; a < 16; ++a)
		result.getValue()[a] = matrix.getValue()[a];

	return result;
}

dependency_graph::OutAttr<std::shared_ptr<const possumwood::VertexData>> a_vd;

dependency_graph::State compute(dependency_graph::Values& data) {
	dependency_graph::State result;

	// we're drawing quads
	std::unique_ptr<possumwood::VertexData> vd(new possumwood::VertexData(GL_QUADS));

	vd->addVBO<Imath::V3f>("position", 4, possumwood::VertexData::kStatic,
	                       [](possumwood::Buffer<float>& buffer,
	                          const possumwood::Drawable::ViewportState& viewport) {
		                       buffer.element(0) = Imath::V3f(-1, -1, 1);
		                       buffer.element(1) = Imath::V3f(1, -1, 1);
		                       buffer.element(2) = Imath::V3f(1, 1, 1);
		                       buffer.element(3) = Imath::V3f(-1, 1, 1);
		                   });

	vd->addVBO<Imath::V3d>(
	    "iNearPositionVert", 4, possumwood::VertexData::kPerDraw,
	    [](possumwood::Buffer<double>& buffer,
	       const possumwood::Drawable::ViewportState& vp) {
		    GLint viewport[4];
		    viewport[0] = 0;
		    viewport[1] = 0;
		    viewport[2] = vp.width;
		    viewport[3] = vp.height;

		    const Imath::M44d modelview = toDouble(vp.modelview);
		    const Imath::M44d projection = toDouble(vp.projection);

		    // points on the near plane, corresponding to each fragment (useful for
		    // raytracing)
		    double* ptr = buffer.element(0).ptr();
		    gluUnProject(0, 0, 0, modelview.getValue(), projection.getValue(), viewport,
		                 ptr, ptr + 1, ptr + 2);
		    gluUnProject(viewport[2], 0, 0, modelview.getValue(), projection.getValue(),
		                 viewport, ptr + 3, ptr + 4, ptr + 5);
		    gluUnProject(viewport[2], viewport[3], 0, modelview.getValue(),
		                 projection.getValue(), viewport, ptr + 6, ptr + 7, ptr + 8);
		    gluUnProject(0, viewport[3], 0, modelview.getValue(), projection.getValue(),
		                 viewport, ptr + 9, ptr + 10, ptr + 11);
		});

	vd->addVBO<Imath::V3d>(
	    "iFarPositionVert", 4, possumwood::VertexData::kPerDraw,
	    [](possumwood::Buffer<double>& buffer,
	       const possumwood::Drawable::ViewportState& vp) {
		    GLint viewport[4];
		    viewport[0] = 0;
		    viewport[1] = 0;
		    viewport[2] = vp.width;
		    viewport[3] = vp.height;

		    const Imath::M44d modelview = toDouble(vp.modelview);
		    const Imath::M44d projection = toDouble(vp.projection);

		    // points on the near plane, corresponding to each fragment (useful for
		    // raytracing)
		    double* ptr = buffer.element(0).ptr();
		    gluUnProject(0, 0, 1, modelview.getValue(), projection.getValue(), viewport,
		                 ptr, ptr + 1, ptr + 2);
		    gluUnProject(viewport[2], 0, 1, modelview.getValue(), projection.getValue(),
		                 viewport, ptr + 3, ptr + 4, ptr + 5);
		    gluUnProject(viewport[2], viewport[3], 1, modelview.getValue(),
		                 projection.getValue(), viewport, ptr + 6, ptr + 7, ptr + 8);
		    gluUnProject(0, viewport[3], 1, modelview.getValue(), projection.getValue(),
		                 viewport, ptr + 9, ptr + 10, ptr + 11);
		});

	data.set(a_vd, std::shared_ptr<const possumwood::VertexData>(vd.release()));

	return result;
}

void init(possumwood::Metadata& meta) {
	meta.addAttribute(a_vd, "vertex_data");

	meta.setCompute(&compute);
}

possumwood::NodeImplementation s_impl("render/vertex_data/background", init);
}
<commit_msg>Updated Background Vertex Data to use GL_TRIANGLE_FAN (GL_QUADS are not compatible with Core Profile)<commit_after>#include <possumwood_sdk/node_implementation.h>
#include <possumwood_sdk/app.h>

#include <GL/glew.h>
#include <GL/glu.h>

#include <ImathVec.h>

#include "datatypes/vertex_data.inl"

namespace {

Imath::M44d toDouble(const Imath::M44f& matrix) {
	Imath::M44d result;
	for(unsigned a = 0; a < 16; ++a)
		result.getValue()[a] = matrix.getValue()[a];

	return result;
}

dependency_graph::OutAttr<std::shared_ptr<const possumwood::VertexData>> a_vd;

dependency_graph::State compute(dependency_graph::Values& data) {
	dependency_graph::State result;

	// we're drawing quads
	std::unique_ptr<possumwood::VertexData> vd(new possumwood::VertexData(GL_TRIANGLE_FAN));

	vd->addVBO<Imath::V3f>("position", 4, possumwood::VertexData::kStatic,
	                       [](possumwood::Buffer<float>& buffer,
	                          const possumwood::Drawable::ViewportState& viewport) {
		                       buffer.element(0) = Imath::V3f(-1, -1, 1);
		                       buffer.element(1) = Imath::V3f(1, -1, 1);
		                       buffer.element(2) = Imath::V3f(1, 1, 1);
		                       buffer.element(3) = Imath::V3f(-1, 1, 1);
		                   });

	vd->addVBO<Imath::V3d>(
	    "iNearPositionVert", 4, possumwood::VertexData::kPerDraw,
	    [](possumwood::Buffer<double>& buffer,
	       const possumwood::Drawable::ViewportState& vp) {
		    GLint viewport[4];
		    viewport[0] = 0;
		    viewport[1] = 0;
		    viewport[2] = vp.width;
		    viewport[3] = vp.height;

		    const Imath::M44d modelview = toDouble(vp.modelview);
		    const Imath::M44d projection = toDouble(vp.projection);

		    // points on the near plane, corresponding to each fragment (useful for
		    // raytracing)
		    double* ptr = buffer.element(0).ptr();
		    gluUnProject(0, 0, 0, modelview.getValue(), projection.getValue(), viewport,
		                 ptr, ptr + 1, ptr + 2);
		    gluUnProject(viewport[2], 0, 0, modelview.getValue(), projection.getValue(),
		                 viewport, ptr + 3, ptr + 4, ptr + 5);
		    gluUnProject(viewport[2], viewport[3], 0, modelview.getValue(),
		                 projection.getValue(), viewport, ptr + 6, ptr + 7, ptr + 8);
		    gluUnProject(0, viewport[3], 0, modelview.getValue(), projection.getValue(),
		                 viewport, ptr + 9, ptr + 10, ptr + 11);
		});

	vd->addVBO<Imath::V3d>(
	    "iFarPositionVert", 4, possumwood::VertexData::kPerDraw,
	    [](possumwood::Buffer<double>& buffer,
	       const possumwood::Drawable::ViewportState& vp) {
		    GLint viewport[4];
		    viewport[0] = 0;
		    viewport[1] = 0;
		    viewport[2] = vp.width;
		    viewport[3] = vp.height;

		    const Imath::M44d modelview = toDouble(vp.modelview);
		    const Imath::M44d projection = toDouble(vp.projection);

		    // points on the near plane, corresponding to each fragment (useful for
		    // raytracing)
		    double* ptr = buffer.element(0).ptr();
		    gluUnProject(0, 0, 1, modelview.getValue(), projection.getValue(), viewport,
		                 ptr, ptr + 1, ptr + 2);
		    gluUnProject(viewport[2], 0, 1, modelview.getValue(), projection.getValue(),
		                 viewport, ptr + 3, ptr + 4, ptr + 5);
		    gluUnProject(viewport[2], viewport[3], 1, modelview.getValue(),
		                 projection.getValue(), viewport, ptr + 6, ptr + 7, ptr + 8);
		    gluUnProject(0, viewport[3], 1, modelview.getValue(), projection.getValue(),
		                 viewport, ptr + 9, ptr + 10, ptr + 11);
		});

	data.set(a_vd, std::shared_ptr<const possumwood::VertexData>(vd.release()));

	return result;
}

void init(possumwood::Metadata& meta) {
	meta.addAttribute(a_vd, "vertex_data");

	meta.setCompute(&compute);
}

possumwood::NodeImplementation s_impl("render/vertex_data/background", init);
}
<|endoftext|>


<commit_before>/*
 * RemoteSyslogAppender.cpp
 *
 * Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
 * Copyright 2001, Walter Stroebel. All rights reserved.
 *
 * See the COPYING file for the terms of usage and distribution.
 */

#include "log4cpp/Portability.hh"

#ifdef LOG4CPP_HAVE_UNISTD_H
#    include <unistd.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "log4cpp/RemoteSyslogAppender.hh"
#ifdef WIN32
#include <winsock2.h>
#else
#include <netdb.h>
#include <sys/socket.h>
#endif

namespace log4cpp {

    int RemoteSyslogAppender::toSyslogPriority(Priority::Value priority) {
        static int priorities[8] = { LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR,
                                     LOG_WARNING, LOG_NOTICE, LOG_INFO,
                                     LOG_DEBUG };
        int result;

        priority++;
        priority /= 100;

        if (priority < 0) {
            result = LOG_EMERG;
        } else if (priority > 7) {
            result = LOG_DEBUG;
        } else {
            result = priorities[priority];
        }

        return result;
    }

    RemoteSyslogAppender::RemoteSyslogAppender(const std::string& name,
                                   const std::string& syslogName,
				   const std::string& relayer,
                                   int facility,
				   int portNumber) :
        AppenderSkeleton(name),
        _syslogName(syslogName),
	_relayer(relayer),
        _facility(facility),
	_portNumber (portNumber),
	_socket (0),
	_ipAddr (0),
	_cludge (0)
    {
        open();
    }

    RemoteSyslogAppender::~RemoteSyslogAppender() {
        close();
#ifdef WIN32
	if (_cludge) {
	    // we started it, we end it.
	    WSACleanup ();
	}
#endif
    }

    void RemoteSyslogAppender::open() {
	if (!_ipAddr) {
	    struct hostent *pent = gethostbyname (_relayer.c_str ());
	    if (pent == NULL) {
#ifdef WIN32
		if (WSAGetLastError () == WSANOTINITIALISED) {
		    WSADATA wsaData;
		    int err;

		    err = WSAStartup (0x101, &wsaData );
		    if (err) abort ();
		    pent = gethostbyname (_relayer.c_str ());
		    _cludge = 1;
		} else {
		    abort ();
		}
#endif
	    }
	    if (pent == NULL) {
		unsigned long ip = (unsigned long) inet_addr (_relayer.c_str ());
		pent = gethostbyaddr ((const char *) &ip, 4, AF_INET);
	    }
	    if (pent == NULL) {
		abort ();
	    }
	    _ipAddr = *((unsigned long *) pent->h_addr);
	}
	// Get a datagram socket.

	if ((_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
	    abort ();
	} else {
	    sockaddr_in sain;
	    sain.sin_family = AF_INET;
	    sain.sin_port   = htons (_portNumber);
	    sain.sin_addr.s_addr = htonl (_ipAddr);
	    if (connect (_socket, (struct sockaddr *) &sain, sizeof (sain)) < 0) {
		abort ();
	    }
	}
    }

    void RemoteSyslogAppender::close() {
	if (_socket) {
#if WIN32
	    closesocket (_socket);
#else
	    close (_socket);
#endif
	    _socket = 0;
	}
    }

    void RemoteSyslogAppender::_append(const LoggingEvent& event) {
        if (!_layout) {
            // XXX help! help!
            return;
        }

        const char* message = _layout->format(event).c_str();
	int len = strlen (message) + 16;
	char *buf = new char [len];
        int priority = toSyslogPriority(event.priority);
	sprintf (buf, "<%d>", priority);
	memcpy (buf + strlen (buf), message, len - 16);
	sockaddr_in sain;
	sain.sin_family = AF_INET;
	sain.sin_port   = htons (_portNumber);
        sain.sin_addr.s_addr = htonl (_ipAddr);
	int r = sendto (_socket, buf, (int) len, 0, (struct sockaddr *) &sain, sizeof (sain));
	printf ("sendto: %d\n", r);
	delete buf;
    }

    bool RemoteSyslogAppender::reopen() {
        close();
        open();
        return true;
    }

    bool RemoteSyslogAppender::requiresLayout() const {
        return true;
    }

    void RemoteSyslogAppender::setLayout(Layout* layout) {
        _layout = layout;
    }

}
<commit_msg>Debugging<commit_after>/*
 * RemoteSyslogAppender.cpp
 *
 * Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
 * Copyright 2001, Walter Stroebel. All rights reserved.
 *
 * See the COPYING file for the terms of usage and distribution.
 */

#include "log4cpp/Portability.hh"

#ifdef LOG4CPP_HAVE_UNISTD_H
#    include <unistd.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "log4cpp/RemoteSyslogAppender.hh"
#ifdef WIN32
#include <winsock2.h>
#else
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif

namespace log4cpp {

    int RemoteSyslogAppender::toSyslogPriority(Priority::Value priority) {
        static int priorities[8] = { LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR,
                                     LOG_WARNING, LOG_NOTICE, LOG_INFO,
                                     LOG_DEBUG };
        int result;

        priority++;
        priority /= 100;

        if (priority < 0) {
            result = LOG_EMERG;
        } else if (priority > 7) {
            result = LOG_DEBUG;
        } else {
            result = priorities[priority];
        }

        return result;
    }

    RemoteSyslogAppender::RemoteSyslogAppender(const std::string& name,
                                   const std::string& syslogName,
				   const std::string& relayer,
                                   int facility,
				   int portNumber) :
        AppenderSkeleton(name),
        _syslogName(syslogName),
	_relayer(relayer),
        _facility(facility),
	_portNumber (portNumber),
	_socket (0),
	_ipAddr (0),
	_cludge (0)
    {
        open();
    }

    RemoteSyslogAppender::~RemoteSyslogAppender() {
        close();
#ifdef WIN32
	if (_cludge) {
	    // we started it, we end it.
	    WSACleanup ();
	}
#endif
    }

    void RemoteSyslogAppender::open() {
	if (!_ipAddr) {
	    struct hostent *pent = gethostbyname (_relayer.c_str ());
	    if (pent == NULL) {
#ifdef WIN32
		if (WSAGetLastError () == WSANOTINITIALISED) {
		    WSADATA wsaData;
		    int err;

		    err = WSAStartup (0x101, &wsaData );
		    if (err) abort ();
		    pent = gethostbyname (_relayer.c_str ());
		    _cludge = 1;
		} else {
		    abort ();
		}
#endif
	    }
	    if (pent == NULL) {
		unsigned long ip = (unsigned long) inet_addr (_relayer.c_str ());
		pent = gethostbyaddr ((const char *) &ip, 4, AF_INET);
	    }
	    if (pent == NULL) {
		abort ();
	    }
	    _ipAddr = *((unsigned long *) pent->h_addr);
	}
	// Get a datagram socket.

	if ((_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
	    abort ();
	} else {
	    sockaddr_in sain;
	    sain.sin_family = AF_INET;
	    sain.sin_port   = htons (_portNumber);
	    sain.sin_addr.s_addr = htonl (_ipAddr);
	    if (connect (_socket, (struct sockaddr *) &sain, sizeof (sain)) < 0) {
		abort ();
	    }
	}
    }

    void RemoteSyslogAppender::close() {
	if (_socket) {
#if WIN32
	    closesocket (_socket);
#else
	    close (_socket);
#endif
	    _socket = 0;
	}
    }

    void RemoteSyslogAppender::_append(const LoggingEvent& event) {
        if (!_layout) {
            // XXX help! help!
            return;
        }

        const char* message = _layout->format(event).c_str();
	int len = strlen (message) + 16;
	char *buf = new char [len];
        int priority = toSyslogPriority(event.priority);
	sprintf (buf, "<%d>", priority);
	memcpy (buf + strlen (buf), message, len - 16);
	sockaddr_in sain;
	sain.sin_family = AF_INET;
	sain.sin_port   = htons (_portNumber);
        sain.sin_addr.s_addr = htonl (_ipAddr);
	int r = sendto (_socket, buf, (int) len, 0, (struct sockaddr *) &sain, sizeof (sain));
	printf ("sendto: %d\n", r);
	delete buf;
    }

    bool RemoteSyslogAppender::reopen() {
        close();
        open();
        return true;
    }

    bool RemoteSyslogAppender::requiresLayout() const {
        return true;
    }

    void RemoteSyslogAppender::setLayout(Layout* layout) {
        _layout = layout;
    }

}
<|endoftext|>


<commit_before>//===--- swift-reflection-dump.cpp - Reflection testing application -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This is a host-side tool to dump remote reflection sections in swift
// binaries.
//===----------------------------------------------------------------------===//

#include "swift/ABI/MetadataValues.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/Demangling/Demangle.h"
#include "swift/Reflection/ReflectionContext.h"
#include "swift/Reflection/TypeRef.h"
#include "swift/Reflection/TypeRefBuilder.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Object/Archive.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/ELF.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Object/MachOUniversal.h"
#include "llvm/Support/CommandLine.h"

#if defined(_WIN32)
#include <io.h>
#else
#include <unistd.h>
#endif

#include <algorithm>
#include <csignal>
#include <iostream>

using llvm::ArrayRef;
using llvm::dyn_cast;
using llvm::StringRef;
using namespace llvm::object;

using namespace swift;
using namespace swift::reflection;
using namespace swift::remote;
using namespace Demangle;

enum class ActionType { DumpReflectionSections, DumpTypeLowering };

namespace options {
static llvm::cl::opt<ActionType> Action(
    llvm::cl::desc("Mode:"),
    llvm::cl::values(
        clEnumValN(ActionType::DumpReflectionSections,
                   "dump-reflection-sections",
                   "Dump the field reflection section"),
        clEnumValN(
            ActionType::DumpTypeLowering, "dump-type-lowering",
            "Dump the field layout for typeref strings read from stdin")),
    llvm::cl::init(ActionType::DumpReflectionSections));

static llvm::cl::list<std::string>
    BinaryFilename("binary-filename",
                   llvm::cl::desc("Filenames of the binary files"),
                   llvm::cl::OneOrMore);

static llvm::cl::opt<std::string>
    Architecture("arch",
                 llvm::cl::desc("Architecture to inspect in the binary"),
                 llvm::cl::Required);
} // end namespace options

template <typename T> static T unwrap(llvm::Expected<T> value) {
  if (value)
    return std::move(value.get());
  llvm::errs() << "swift-reflection-test error: " << toString(value.takeError())
               << "\n";
  exit(EXIT_FAILURE);
}

static void reportError(std::error_code EC) {
  assert(EC);
  llvm::errs() << "swift-reflection-test error: " << EC.message() << ".\n";
  exit(EXIT_FAILURE);
}

using NativeReflectionContext =
    swift::reflection::ReflectionContext<External<RuntimeTarget<sizeof(uintptr_t)>>>;

using ReadBytesResult = swift::remote::MemoryReader::ReadBytesResult;

static uint64_t getSectionAddress(SectionRef S) {
  // See COFFObjectFile.cpp for the implementation of
  // COFFObjectFile::getSectionAddress. The image base address is added
  // to all the addresses of the sections, thus the behavior is slightly different from
  // the other platforms.
  if (auto C = dyn_cast<COFFObjectFile>(S.getObject()))
    return S.getAddress() - C->getImageBase();
  return S.getAddress();
}

static bool needToRelocate(SectionRef S) {
  if (!getSectionAddress(S))
    return false;

  if (auto EO = dyn_cast<ELFObjectFileBase>(S.getObject())) {
    static const llvm::StringSet<> ELFSectionsList = {
      ".data", ".rodata", "swift5_protocols", "swift5_protocol_conformances",
      "swift5_typeref", "swift5_reflstr", "swift5_assocty", "swift5_replace",
      "swift5_type_metadata", "swift5_fieldmd", "swift5_capture", "swift5_builtin"
    };
    StringRef Name;
    if (auto EC = S.getName(Name))
      reportError(EC);
    return ELFSectionsList.count(Name);
  }

  return true;
}

class Image {
  std::vector<char> Memory;

public:
  explicit Image(const ObjectFile *O) {
    uint64_t VASize = O->getData().size();
    for (SectionRef S : O->sections()) {
      if (auto SectionAddr = getSectionAddress(S))
        VASize = std::max(VASize, SectionAddr + S.getSize());
    }
    Memory.resize(VASize);
    std::memcpy(&Memory[0], O->getData().data(), O->getData().size());

    for (SectionRef S : O->sections()) {
      if (!needToRelocate(S))
        continue;
      StringRef Content;
      if (auto EC = S.getContents(Content))
        reportError(EC);
      std::memcpy(&Memory[getSectionAddress(S)], Content.data(),
                  Content.size());
    }
  }

  RemoteAddress getStartAddress() const {
    return RemoteAddress((uintptr_t)Memory.data());
  }

  bool isAddressValid(RemoteAddress Addr, uint64_t Size) const {
    return (uintptr_t)Memory.data() <= Addr.getAddressData() &&
           Addr.getAddressData() + Size <=
               (uintptr_t)Memory.data() + Memory.size();
  }

  ReadBytesResult readBytes(RemoteAddress Addr, uint64_t Size) {
    if (!isAddressValid(Addr, Size))
      return ReadBytesResult(nullptr, [](const void *) {});
    return ReadBytesResult((const void *)(Addr.getAddressData()),
                           [](const void *) {});
  }
};

class ObjectMemoryReader : public MemoryReader {
  std::vector<Image> Images;

public:
  explicit ObjectMemoryReader(
      const std::vector<const ObjectFile *> &ObjectFiles) {
    for (const ObjectFile *O : ObjectFiles)
      Images.emplace_back(O);
  }

  const std::vector<Image> &getImages() const { return Images; }

  bool queryDataLayout(DataLayoutQueryType type, void *inBuffer,
                       void *outBuffer) override {
    switch (type) {
    case DLQ_GetPointerSize: {
      auto result = static_cast<uint8_t *>(outBuffer);
      *result = sizeof(void *);
      return true;
    }
    case DLQ_GetSizeSize: {
      auto result = static_cast<uint8_t *>(outBuffer);
      *result = sizeof(size_t);
      return true;
    }
    }

    return false;
  }

  RemoteAddress getSymbolAddress(const std::string &name) override {
    return RemoteAddress(nullptr);
  }

  ReadBytesResult readBytes(RemoteAddress Addr, uint64_t Size) override {
    auto I = std::find_if(Images.begin(), Images.end(), [=](const Image &I) {
      return I.isAddressValid(Addr, Size);
    });
    return I == Images.end() ? ReadBytesResult(nullptr, [](const void *) {})
                             : I->readBytes(Addr, Size);
  }

  bool readString(RemoteAddress Addr, std::string &Dest) override {
    ReadBytesResult R = readBytes(Addr, 1);
    if (!R)
      return false;
    StringRef Str((const char *)R.get());
    Dest.append(Str.begin(), Str.end());
    return true;
  }
};

static int doDumpReflectionSections(ArrayRef<std::string> BinaryFilenames,
                                    StringRef Arch, ActionType Action,
                                    std::ostream &OS) {
  // Note: binaryOrError and objectOrError own the memory for our ObjectFile;
  // once they go out of scope, we can no longer do anything.
  std::vector<OwningBinary<Binary>> BinaryOwners;
  std::vector<std::unique_ptr<ObjectFile>> ObjectOwners;
  std::vector<const ObjectFile *> ObjectFiles;

  for (const std::string &BinaryFilename : BinaryFilenames) {
    auto BinaryOwner = unwrap(createBinary(BinaryFilename));
    Binary *BinaryFile = BinaryOwner.getBinary();

    // The object file we are doing lookups in -- either the binary itself, or
    // a particular slice of a universal binary.
    std::unique_ptr<ObjectFile> ObjectOwner;
    const ObjectFile *O = dyn_cast<ObjectFile>(BinaryFile);
    if (!O) {
      auto Universal = cast<MachOUniversalBinary>(BinaryFile);
      ObjectOwner = unwrap(Universal->getObjectForArch(Arch));
      O = ObjectOwner.get();
    }

    // Retain the objects that own section memory
    BinaryOwners.push_back(std::move(BinaryOwner));
    ObjectOwners.push_back(std::move(ObjectOwner));
    ObjectFiles.push_back(O);
  }

  auto Reader = std::make_shared<ObjectMemoryReader>(ObjectFiles);
  NativeReflectionContext Context(Reader);
  for (const Image &I : Reader->getImages())
    Context.addImage(I.getStartAddress());

  switch (Action) {
  case ActionType::DumpReflectionSections:
    // Dump everything
    Context.getBuilder().dumpAllSections(OS);
    break;
  case ActionType::DumpTypeLowering: {
    for (std::string Line; std::getline(std::cin, Line);) {
      if (Line.empty())
        continue;

      if (StringRef(Line).startswith("//"))
        continue;

      Demangle::Demangler Dem;
      auto Demangled = Dem.demangleType(Line);
      auto *TypeRef =
          swift::Demangle::decodeMangledType(Context.getBuilder(), Demangled);
      if (TypeRef == nullptr) {
        OS << "Invalid typeref: " << Line << "\n";
        continue;
      }

      TypeRef->dump(OS);
      auto *TypeInfo =
          Context.getBuilder().getTypeConverter().getTypeInfo(TypeRef);
      if (TypeInfo == nullptr) {
        OS << "Invalid lowering\n";
        continue;
      }
      TypeInfo->dump(OS);
    }
    break;
  }
  }

  return EXIT_SUCCESS;
}

int main(int argc, char *argv[]) {
  PROGRAM_START(argc, argv);
  llvm::cl::ParseCommandLineOptions(argc, argv, "Swift Reflection Dump\n");
  return doDumpReflectionSections(options::BinaryFilename,
                                  options::Architecture, options::Action,
                                  std::cout);
}
<commit_msg>[reflection-dump] Extract NativeRuntime out into its own using directive.<commit_after>//===--- swift-reflection-dump.cpp - Reflection testing application -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This is a host-side tool to dump remote reflection sections in swift
// binaries.
//===----------------------------------------------------------------------===//

#include "swift/ABI/MetadataValues.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/Demangling/Demangle.h"
#include "swift/Reflection/ReflectionContext.h"
#include "swift/Reflection/TypeRef.h"
#include "swift/Reflection/TypeRefBuilder.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Object/Archive.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/ELF.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Object/MachOUniversal.h"
#include "llvm/Support/CommandLine.h"

#if defined(_WIN32)
#include <io.h>
#else
#include <unistd.h>
#endif

#include <algorithm>
#include <csignal>
#include <iostream>

using llvm::ArrayRef;
using llvm::dyn_cast;
using llvm::StringRef;
using namespace llvm::object;

using namespace swift;
using namespace swift::reflection;
using namespace swift::remote;
using namespace Demangle;

enum class ActionType { DumpReflectionSections, DumpTypeLowering };

namespace options {
static llvm::cl::opt<ActionType> Action(
    llvm::cl::desc("Mode:"),
    llvm::cl::values(
        clEnumValN(ActionType::DumpReflectionSections,
                   "dump-reflection-sections",
                   "Dump the field reflection section"),
        clEnumValN(
            ActionType::DumpTypeLowering, "dump-type-lowering",
            "Dump the field layout for typeref strings read from stdin")),
    llvm::cl::init(ActionType::DumpReflectionSections));

static llvm::cl::list<std::string>
    BinaryFilename("binary-filename",
                   llvm::cl::desc("Filenames of the binary files"),
                   llvm::cl::OneOrMore);

static llvm::cl::opt<std::string>
    Architecture("arch",
                 llvm::cl::desc("Architecture to inspect in the binary"),
                 llvm::cl::Required);
} // end namespace options

template <typename T> static T unwrap(llvm::Expected<T> value) {
  if (value)
    return std::move(value.get());
  llvm::errs() << "swift-reflection-test error: " << toString(value.takeError())
               << "\n";
  exit(EXIT_FAILURE);
}

static void reportError(std::error_code EC) {
  assert(EC);
  llvm::errs() << "swift-reflection-test error: " << EC.message() << ".\n";
  exit(EXIT_FAILURE);
}

using NativeRuntime = External<RuntimeTarget<sizeof(uintptr_t)>>;
using NativeReflectionContext =
    swift::reflection::ReflectionContext<NativeRuntime>;

using ReadBytesResult = swift::remote::MemoryReader::ReadBytesResult;

static uint64_t getSectionAddress(SectionRef S) {
  // See COFFObjectFile.cpp for the implementation of
  // COFFObjectFile::getSectionAddress. The image base address is added
  // to all the addresses of the sections, thus the behavior is slightly different from
  // the other platforms.
  if (auto C = dyn_cast<COFFObjectFile>(S.getObject()))
    return S.getAddress() - C->getImageBase();
  return S.getAddress();
}

static bool needToRelocate(SectionRef S) {
  if (!getSectionAddress(S))
    return false;

  if (auto EO = dyn_cast<ELFObjectFileBase>(S.getObject())) {
    static const llvm::StringSet<> ELFSectionsList = {
      ".data", ".rodata", "swift5_protocols", "swift5_protocol_conformances",
      "swift5_typeref", "swift5_reflstr", "swift5_assocty", "swift5_replace",
      "swift5_type_metadata", "swift5_fieldmd", "swift5_capture", "swift5_builtin"
    };
    StringRef Name;
    if (auto EC = S.getName(Name))
      reportError(EC);
    return ELFSectionsList.count(Name);
  }

  return true;
}

class Image {
  std::vector<char> Memory;

public:
  explicit Image(const ObjectFile *O) {
    uint64_t VASize = O->getData().size();
    for (SectionRef S : O->sections()) {
      if (auto SectionAddr = getSectionAddress(S))
        VASize = std::max(VASize, SectionAddr + S.getSize());
    }
    Memory.resize(VASize);
    std::memcpy(&Memory[0], O->getData().data(), O->getData().size());

    for (SectionRef S : O->sections()) {
      if (!needToRelocate(S))
        continue;
      StringRef Content;
      if (auto EC = S.getContents(Content))
        reportError(EC);
      std::memcpy(&Memory[getSectionAddress(S)], Content.data(),
                  Content.size());
    }
  }

  RemoteAddress getStartAddress() const {
    return RemoteAddress((uintptr_t)Memory.data());
  }

  bool isAddressValid(RemoteAddress Addr, uint64_t Size) const {
    return (uintptr_t)Memory.data() <= Addr.getAddressData() &&
           Addr.getAddressData() + Size <=
               (uintptr_t)Memory.data() + Memory.size();
  }

  ReadBytesResult readBytes(RemoteAddress Addr, uint64_t Size) {
    if (!isAddressValid(Addr, Size))
      return ReadBytesResult(nullptr, [](const void *) {});
    return ReadBytesResult((const void *)(Addr.getAddressData()),
                           [](const void *) {});
  }
};

class ObjectMemoryReader : public MemoryReader {
  std::vector<Image> Images;

public:
  explicit ObjectMemoryReader(
      const std::vector<const ObjectFile *> &ObjectFiles) {
    for (const ObjectFile *O : ObjectFiles)
      Images.emplace_back(O);
  }

  const std::vector<Image> &getImages() const { return Images; }

  bool queryDataLayout(DataLayoutQueryType type, void *inBuffer,
                       void *outBuffer) override {
    switch (type) {
    case DLQ_GetPointerSize: {
      auto result = static_cast<uint8_t *>(outBuffer);
      *result = sizeof(void *);
      return true;
    }
    case DLQ_GetSizeSize: {
      auto result = static_cast<uint8_t *>(outBuffer);
      *result = sizeof(size_t);
      return true;
    }
    }

    return false;
  }

  RemoteAddress getSymbolAddress(const std::string &name) override {
    return RemoteAddress(nullptr);
  }

  ReadBytesResult readBytes(RemoteAddress Addr, uint64_t Size) override {
    auto I = std::find_if(Images.begin(), Images.end(), [=](const Image &I) {
      return I.isAddressValid(Addr, Size);
    });
    return I == Images.end() ? ReadBytesResult(nullptr, [](const void *) {})
                             : I->readBytes(Addr, Size);
  }

  bool readString(RemoteAddress Addr, std::string &Dest) override {
    ReadBytesResult R = readBytes(Addr, 1);
    if (!R)
      return false;
    StringRef Str((const char *)R.get());
    Dest.append(Str.begin(), Str.end());
    return true;
  }
};

static int doDumpReflectionSections(ArrayRef<std::string> BinaryFilenames,
                                    StringRef Arch, ActionType Action,
                                    std::ostream &OS) {
  // Note: binaryOrError and objectOrError own the memory for our ObjectFile;
  // once they go out of scope, we can no longer do anything.
  std::vector<OwningBinary<Binary>> BinaryOwners;
  std::vector<std::unique_ptr<ObjectFile>> ObjectOwners;
  std::vector<const ObjectFile *> ObjectFiles;

  for (const std::string &BinaryFilename : BinaryFilenames) {
    auto BinaryOwner = unwrap(createBinary(BinaryFilename));
    Binary *BinaryFile = BinaryOwner.getBinary();

    // The object file we are doing lookups in -- either the binary itself, or
    // a particular slice of a universal binary.
    std::unique_ptr<ObjectFile> ObjectOwner;
    const ObjectFile *O = dyn_cast<ObjectFile>(BinaryFile);
    if (!O) {
      auto Universal = cast<MachOUniversalBinary>(BinaryFile);
      ObjectOwner = unwrap(Universal->getObjectForArch(Arch));
      O = ObjectOwner.get();
    }

    // Retain the objects that own section memory
    BinaryOwners.push_back(std::move(BinaryOwner));
    ObjectOwners.push_back(std::move(ObjectOwner));
    ObjectFiles.push_back(O);
  }

  auto Reader = std::make_shared<ObjectMemoryReader>(ObjectFiles);
  NativeReflectionContext Context(Reader);
  for (const Image &I : Reader->getImages())
    Context.addImage(I.getStartAddress());

  switch (Action) {
  case ActionType::DumpReflectionSections:
    // Dump everything
    Context.getBuilder().dumpAllSections(OS);
    break;
  case ActionType::DumpTypeLowering: {
    for (std::string Line; std::getline(std::cin, Line);) {
      if (Line.empty())
        continue;

      if (StringRef(Line).startswith("//"))
        continue;

      Demangle::Demangler Dem;
      auto Demangled = Dem.demangleType(Line);
      auto *TypeRef =
          swift::Demangle::decodeMangledType(Context.getBuilder(), Demangled);
      if (TypeRef == nullptr) {
        OS << "Invalid typeref: " << Line << "\n";
        continue;
      }

      TypeRef->dump(OS);
      auto *TypeInfo =
          Context.getBuilder().getTypeConverter().getTypeInfo(TypeRef);
      if (TypeInfo == nullptr) {
        OS << "Invalid lowering\n";
        continue;
      }
      TypeInfo->dump(OS);
    }
    break;
  }
  }

  return EXIT_SUCCESS;
}

int main(int argc, char *argv[]) {
  PROGRAM_START(argc, argv);
  llvm::cl::ParseCommandLineOptions(argc, argv, "Swift Reflection Dump\n");
  return doDumpReflectionSections(options::BinaryFilename,
                                  options::Architecture, options::Action,
                                  std::cout);
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 Dariusz Stojaczyk. All Rights Reserved.
 * The following source code is released under an MIT-style license,
 * that can be found in the LICENSE file.
 */

#include "ApplicationContext.h"
#include "Application.h"
#include "window/Window.h"
#include "window/LoadingScreen.h"

ApplicationContext::ApplicationContext(Application &application)
    : m_application(application),
      m_config("global.conf") {

}

void ApplicationContext::switchWindow(std::unique_ptr<Window> &&window) {
    window->context(this);
    m_application.m_newWindow = std::move(window);
}

const Config &ApplicationContext::config() const {
    return m_config;
}

ApplicationContext::~ApplicationContext() = default;
<commit_msg>Added possibility to close the application by switching window to nullptr<commit_after>/*
 * Copyright (c) 2016 Dariusz Stojaczyk. All Rights Reserved.
 * The following source code is released under an MIT-style license,
 * that can be found in the LICENSE file.
 */

#include "ApplicationContext.h"
#include "Application.h"
#include "window/Window.h"
#include "window/LoadingScreen.h"

ApplicationContext::ApplicationContext(Application &application)
    : m_application(application),
      m_config("global.conf") {

}

void ApplicationContext::switchWindow(std::unique_ptr<Window> &&window) {
    if (window) {
        window->context(this);
        m_application.m_newWindow = std::move(window);
    } else {
        m_application.m_running = false;
    }
}

const Config &ApplicationContext::config() const {
    return m_config;
}

ApplicationContext::~ApplicationContext() = default;
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLTextNumRuleInfo.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 15:25:09 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _XMLOFF_XMLTEXTNUMRULEINFO_HXX
#define _XMLOFF_XMLTEXTNUMRULEINFO_HXX

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_
#include <com/sun/star/container/XIndexReplace.hpp>
#endif

namespace com { namespace sun { namespace star {
    namespace text { class XTextContent; }
} } }

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

class XMLTextNumRuleInfo
{
    const ::rtl::OUString sNumberingRules;
    const ::rtl::OUString sNumberingLevel;
    const ::rtl::OUString sNumberingStartValue;
    const ::rtl::OUString sParaIsNumberingRestart;
    const ::rtl::OUString sNumberingType;
    const ::rtl::OUString sIsNumbering;
    const ::rtl::OUString sNumberingIsNumber;
    const ::rtl::OUString sNumberingIsOutline;

    ::com::sun::star::uno::Reference <
        ::com::sun::star::container::XIndexReplace > xNumRules;

    ::rtl::OUString     sName;
    sal_Int16           nStartValue;
    sal_Int16           nLevel;

    sal_Bool            bIsNumbered : 1;
    sal_Bool            bIsOrdered : 1;
    sal_Bool            bIsRestart : 1;
    sal_Bool            bIsNamed : 1;

public:

    XMLTextNumRuleInfo();

    inline XMLTextNumRuleInfo& operator=( const XMLTextNumRuleInfo& rInfo );

    void Set(
        const ::com::sun::star::uno::Reference <
            ::com::sun::star::text::XTextContent > & rTextContnt );
    inline void Reset();

    const ::rtl::OUString& GetName() const { return sName; }
    const ::com::sun::star::uno::Reference <
        ::com::sun::star::container::XIndexReplace >& GetNumRules() const
        { return xNumRules; }
    sal_Int16 GetLevel() const { return nLevel; }

    sal_Bool HasStartValue() const { return nStartValue != -1; }
    sal_uInt32 GetStartValue() const { return nStartValue; }

    sal_Bool IsNumbered() const { return bIsNumbered; }
    sal_Bool IsOrdered() const { return bIsOrdered; }
    sal_Bool IsRestart() const { return bIsRestart; }
    sal_Bool IsNamed() const { return bIsNamed; }

    inline sal_Bool HasSameNumRules( const XMLTextNumRuleInfo& rCmp ) const;
};

inline XMLTextNumRuleInfo& XMLTextNumRuleInfo::operator=(
        const XMLTextNumRuleInfo& rInfo )
{
    sName = rInfo.sName;
    xNumRules = rInfo.xNumRules;
    nStartValue = rInfo.nStartValue;
    nLevel = rInfo.nLevel;
    bIsNumbered = rInfo.bIsNumbered;
    bIsOrdered = rInfo.bIsOrdered;
    bIsRestart = rInfo.bIsRestart;
    bIsNamed = rInfo.bIsNamed;

    return *this;
}

inline void XMLTextNumRuleInfo::Reset()
{
    sName = ::rtl::OUString();
    xNumRules = 0;
    nStartValue = -1;
    nLevel = 0;
    bIsNumbered = bIsOrdered = bIsRestart = bIsNamed = sal_False;
}

inline sal_Bool XMLTextNumRuleInfo::HasSameNumRules(
                        const XMLTextNumRuleInfo& rCmp ) const
{
    return (bIsNamed && rCmp.bIsNamed) ? (rCmp.sName == sName)
                                   : (rCmp.xNumRules == xNumRules);
}

#endif  //  _XMLOFF_XMLTEXTNUMRULEINFO_HXX
<commit_msg>INTEGRATION: CWS swqbf87 (1.5.166); FILE MERGED 2006/09/28 14:13:40 od 1.5.166.1: #i69627# consider <SvXMLExport::writeOutlineStyleAsNormalListStyle()> 	 on export of a paragraph.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLTextNumRuleInfo.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-13 12:16:39 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _XMLOFF_XMLTEXTNUMRULEINFO_HXX
#define _XMLOFF_XMLTEXTNUMRULEINFO_HXX

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_
#include <com/sun/star/container/XIndexReplace.hpp>
#endif

namespace com { namespace sun { namespace star {
    namespace text { class XTextContent; }
} } }

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

class XMLTextNumRuleInfo
{
    const ::rtl::OUString sNumberingRules;
    const ::rtl::OUString sNumberingLevel;
    const ::rtl::OUString sNumberingStartValue;
    const ::rtl::OUString sParaIsNumberingRestart;
    const ::rtl::OUString sNumberingType;
    const ::rtl::OUString sIsNumbering;
    const ::rtl::OUString sNumberingIsNumber;
    const ::rtl::OUString sNumberingIsOutline;

    ::com::sun::star::uno::Reference <
        ::com::sun::star::container::XIndexReplace > xNumRules;

    ::rtl::OUString     sName;
    sal_Int16           nStartValue;
    sal_Int16           nLevel;

    sal_Bool            bIsNumbered : 1;
    sal_Bool            bIsOrdered : 1;
    sal_Bool            bIsRestart : 1;
    sal_Bool            bIsNamed : 1;

    // --> OD 2006-09-27 #i69627#
    sal_Bool mbOutlineStyleAsNormalListStyle : 1;
    // <--

public:

    XMLTextNumRuleInfo();

    inline XMLTextNumRuleInfo& operator=( const XMLTextNumRuleInfo& rInfo );

    // --> OD 2006-09-27 #i69627#
    void Set( const ::com::sun::star::uno::Reference <
                        ::com::sun::star::text::XTextContent > & rTextContnt,
              const sal_Bool bOutlineStyleAsNormalListStyle );
    // <--
    inline void Reset();

    const ::rtl::OUString& GetName() const { return sName; }
    const ::com::sun::star::uno::Reference <
        ::com::sun::star::container::XIndexReplace >& GetNumRules() const
        { return xNumRules; }
    sal_Int16 GetLevel() const { return nLevel; }

    sal_Bool HasStartValue() const { return nStartValue != -1; }
    sal_uInt32 GetStartValue() const { return nStartValue; }

    sal_Bool IsNumbered() const { return bIsNumbered; }
    sal_Bool IsOrdered() const { return bIsOrdered; }
    sal_Bool IsRestart() const { return bIsRestart; }
    sal_Bool IsNamed() const { return bIsNamed; }

    inline sal_Bool HasSameNumRules( const XMLTextNumRuleInfo& rCmp ) const;
};

inline XMLTextNumRuleInfo& XMLTextNumRuleInfo::operator=(
        const XMLTextNumRuleInfo& rInfo )
{
    sName = rInfo.sName;
    xNumRules = rInfo.xNumRules;
    nStartValue = rInfo.nStartValue;
    nLevel = rInfo.nLevel;
    bIsNumbered = rInfo.bIsNumbered;
    bIsOrdered = rInfo.bIsOrdered;
    bIsRestart = rInfo.bIsRestart;
    bIsNamed = rInfo.bIsNamed;
    // --> OD 2006-09-27 #i69627#
    mbOutlineStyleAsNormalListStyle = rInfo.mbOutlineStyleAsNormalListStyle;
    // <--

    return *this;
}

inline void XMLTextNumRuleInfo::Reset()
{
    sName = ::rtl::OUString();
    xNumRules = 0;
    nStartValue = -1;
    nLevel = 0;
    // --> OD 2006-09-27 #i69627#
//    bIsNumbered = bIsOrdered = bIsRestart = bIsNamed = sal_False;
    bIsNumbered = bIsOrdered = bIsRestart = bIsNamed =
    mbOutlineStyleAsNormalListStyle = sal_False;
    // <--
}

inline sal_Bool XMLTextNumRuleInfo::HasSameNumRules(
                        const XMLTextNumRuleInfo& rCmp ) const
{
    return (bIsNamed && rCmp.bIsNamed) ? (rCmp.sName == sName)
                                   : (rCmp.xNumRules == xNumRules);
}

#endif  //  _XMLOFF_XMLTEXTNUMRULEINFO_HXX
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: xmlstreamio.cxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

/*
 * Implementation of the I/O interfaces based on stream and URI binding
 */
#include "xmlstreamio.hxx"
#include <rtl/ustring.hxx>

#include <libxml/uri.h>
#include <xmlsec/io.h>

#define XMLSTREAMIO_INITIALIZED 0x01
#define XMLSTREAMIO_REGISTERED  0x02

/* Global variables */
/*-
 * Enable stream I/O or not.
 */
static char enableXmlStreamIO = 0x00 ;

::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XUriBinding > m_xUriBinding ;

extern "C"
int xmlStreamMatch( const char* uri )
{
    ::com::sun::star::uno::Reference< com::sun::star::io::XInputStream > xInputStream ;

    if( ( enableXmlStreamIO & XMLSTREAMIO_INITIALIZED ) &&
        ( enableXmlStreamIO & XMLSTREAMIO_REGISTERED ) ) {
        if( uri == NULL || !m_xUriBinding.is() )
            return 0 ;

        xInputStream = m_xUriBinding->getUriBinding( ::rtl::OUString::createFromAscii( uri ) ) ;
        if( xInputStream.is() )
            return 1 ;
    }

    return 0 ;
}

extern "C"
void* xmlStreamOpen( const char* uri )
{
    ::com::sun::star::uno::Reference< com::sun::star::io::XInputStream > xInputStream ;
    ::com::sun::star::io::XInputStream* pInputStream ;

    if( ( enableXmlStreamIO & XMLSTREAMIO_INITIALIZED ) &&
        ( enableXmlStreamIO & XMLSTREAMIO_REGISTERED ) ) {
        if( uri == NULL || !m_xUriBinding.is() )
            return NULL ;

        xInputStream = m_xUriBinding->getUriBinding( ::rtl::OUString::createFromAscii( uri ) ) ;
        if( xInputStream.is() ) {
            pInputStream = xInputStream.get() ;
            pInputStream->acquire() ;
            return ( void* )pInputStream ;
        }
    }

    return NULL ;
}

extern "C"
int xmlStreamRead( void* context, char* buffer, int len )
{
    int numbers ;
    ::com::sun::star::uno::Reference< com::sun::star::io::XInputStream > xInputStream ;
    ::com::sun::star::uno::Sequence< sal_Int8 > outSeqs( len ) ;

    numbers = 0 ;
    if( ( enableXmlStreamIO & XMLSTREAMIO_INITIALIZED ) &&
        ( enableXmlStreamIO & XMLSTREAMIO_REGISTERED ) ) {
        if( context != NULL ) {
            xInputStream = ( com::sun::star::io::XInputStream* )context ;
            if( !xInputStream.is() )
                return 0 ;

            numbers = xInputStream->readBytes( outSeqs, len ) ;
            const sal_Int8* readBytes = ( const sal_Int8* )outSeqs.getArray() ;
            for( int i = 0 ; i < numbers ; i ++ )
                *( buffer + i ) = *( readBytes + i ) ;
        }
    }

    return numbers ;
}

extern "C"
int xmlStreamClose( void * context )
{
    ::com::sun::star::io::XInputStream* pInputStream ;

    if( ( enableXmlStreamIO & XMLSTREAMIO_INITIALIZED ) &&
        ( enableXmlStreamIO & XMLSTREAMIO_REGISTERED ) ) {
        if( context != NULL ) {
            pInputStream = ( ::com::sun::star::io::XInputStream* )context ;
            pInputStream->release() ;
        }
    }

    return 0 ;
}

int xmlEnableStreamInputCallbacks()
{
    int cbs = 0 ;

    if( !( enableXmlStreamIO & XMLSTREAMIO_INITIALIZED ) ) {
        //Register the callbacks into libxml2
        //cbs = xmlRegisterInputCallbacks(
        //          xmlStreamMatch,
        //          xmlStreamOpen,
        //          xmlStreamRead,
        //          xmlStreamClose ) ;
        //if( cbs < 0 ) {
        //  return -1 ;
        //}

        //Register the callbacks into xmlSec
        //In order to make the xmlsec io finding the callbacks firstly,
        //I put the callbacks at the very begining.

        //Cleanup the older callbacks.
        //Notes: all none default callbacks will lose.
        xmlSecIOCleanupCallbacks() ;

        //Register my classbacks.
        cbs = xmlSecIORegisterCallbacks(
                    xmlStreamMatch,
                    xmlStreamOpen,
                    xmlStreamRead,
                    xmlStreamClose ) ;
        if( cbs < 0 ) {
            return -1 ;
        }

        //Register the default callbacks.
        //Notes: the error will cause xmlsec working problems.
        cbs = xmlSecIORegisterDefaultCallbacks() ;
        if( cbs < 0 ) {
            return -1 ;
        }

        enableXmlStreamIO |= XMLSTREAMIO_INITIALIZED ;
    }

    return 0 ;
}

int xmlRegisterStreamInputCallbacks(
    ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XUriBinding >& aUriBinding
) {
    if( !( enableXmlStreamIO & XMLSTREAMIO_INITIALIZED ) ) {
        if( xmlEnableStreamInputCallbacks() < 0 )
            return -1 ;
    }

    if( !( enableXmlStreamIO & XMLSTREAMIO_REGISTERED ) ) {
        enableXmlStreamIO |= XMLSTREAMIO_REGISTERED ;
    }

    m_xUriBinding = aUriBinding ;

    return 0 ;
}

int xmlUnregisterStreamInputCallbacks( void )
{
    if( ( enableXmlStreamIO & XMLSTREAMIO_REGISTERED ) ) {
        //Clear the uir-stream binding
        m_xUriBinding.clear() ;

        //disable the registered flag
        enableXmlStreamIO &= ~XMLSTREAMIO_REGISTERED ;
    }

    return 0 ;
}

void xmlDisableStreamInputCallbacks() {
    xmlUnregisterStreamInputCallbacks() ;
    enableXmlStreamIO &= ~XMLSTREAMIO_INITIALIZED ;
}

<commit_msg>INTEGRATION: CWS jl103 (1.5.16); FILE MERGED 2008/06/13 07:28:39 jl 1.5.16.1: #i86233# uri encoding the URI attribute of the reference elements<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: xmlstreamio.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

/*
 * Implementation of the I/O interfaces based on stream and URI binding
 */
#include "xmlstreamio.hxx"
#include <rtl/ustring.hxx>
#include "rtl/uri.hxx"

#include <libxml/uri.h>
#include <xmlsec/io.h>

#define XMLSTREAMIO_INITIALIZED 0x01
#define XMLSTREAMIO_REGISTERED  0x02

/* Global variables */
/*-
 * Enable stream I/O or not.
 */
static char enableXmlStreamIO = 0x00 ;

::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XUriBinding > m_xUriBinding ;

extern "C"
int xmlStreamMatch( const char* uri )
{
    ::com::sun::star::uno::Reference< com::sun::star::io::XInputStream > xInputStream ;

    if( ( enableXmlStreamIO & XMLSTREAMIO_INITIALIZED ) &&
        ( enableXmlStreamIO & XMLSTREAMIO_REGISTERED ) ) {
        if( uri == NULL || !m_xUriBinding.is() )
            return 0 ;
        //XMLSec first unescapes the uri and  calls this function. For example, we pass the Uri
        //ObjectReplacements/Object%201 then XMLSec passes ObjectReplacements/Object 1
        //first. If this failed it would try this
        //again with the original escaped string. However, it does not get this far, because there
        //is another callback registered by libxml which claims to be able to handle this uri.
        ::rtl::OUString sUri =
            ::rtl::Uri::encode( ::rtl::OUString::createFromAscii( uri ),
            rtl_UriCharClassUric, rtl_UriEncodeKeepEscapes, RTL_TEXTENCODING_UTF8);
        xInputStream = m_xUriBinding->getUriBinding( sUri ) ;
        if (!xInputStream.is())
        {
            //Try the the passed in uri directly.
            //For old documents prior OOo 3.0. We did not use URIs then.
            xInputStream = m_xUriBinding->getUriBinding(
                ::rtl::OUString::createFromAscii(uri));
        }
    }
    if (xInputStream.is())
        return 1;
    else
        return 0 ;
}

extern "C"
void* xmlStreamOpen( const char* uri )
{
    ::com::sun::star::uno::Reference< com::sun::star::io::XInputStream > xInputStream ;
    ::com::sun::star::io::XInputStream* pInputStream ;

    if( ( enableXmlStreamIO & XMLSTREAMIO_INITIALIZED ) &&
        ( enableXmlStreamIO & XMLSTREAMIO_REGISTERED ) ) {
        if( uri == NULL || !m_xUriBinding.is() )
            return NULL ;

        //see xmlStreamMatch
        ::rtl::OUString sUri =
            ::rtl::Uri::encode( ::rtl::OUString::createFromAscii( uri ),
            rtl_UriCharClassUric, rtl_UriEncodeKeepEscapes, RTL_TEXTENCODING_UTF8);
        xInputStream = m_xUriBinding->getUriBinding( sUri ) ;
        if (!xInputStream.is())
        {
            //For old documents.
            //try the the passed in uri directly.
            xInputStream = m_xUriBinding->getUriBinding(
                ::rtl::OUString::createFromAscii(uri));
        }

        if( xInputStream.is() ) {
            pInputStream = xInputStream.get() ;
            pInputStream->acquire() ;
            return ( void* )pInputStream ;
        }
    }

    return NULL ;
}

extern "C"
int xmlStreamRead( void* context, char* buffer, int len )
{
    int numbers ;
    ::com::sun::star::uno::Reference< com::sun::star::io::XInputStream > xInputStream ;
    ::com::sun::star::uno::Sequence< sal_Int8 > outSeqs( len ) ;

    numbers = 0 ;
    if( ( enableXmlStreamIO & XMLSTREAMIO_INITIALIZED ) &&
        ( enableXmlStreamIO & XMLSTREAMIO_REGISTERED ) ) {
        if( context != NULL ) {
            xInputStream = ( com::sun::star::io::XInputStream* )context ;
            if( !xInputStream.is() )
                return 0 ;

            numbers = xInputStream->readBytes( outSeqs, len ) ;
            const sal_Int8* readBytes = ( const sal_Int8* )outSeqs.getArray() ;
            for( int i = 0 ; i < numbers ; i ++ )
                *( buffer + i ) = *( readBytes + i ) ;
        }
    }

    return numbers ;
}

extern "C"
int xmlStreamClose( void * context )
{
    ::com::sun::star::io::XInputStream* pInputStream ;

    if( ( enableXmlStreamIO & XMLSTREAMIO_INITIALIZED ) &&
        ( enableXmlStreamIO & XMLSTREAMIO_REGISTERED ) ) {
        if( context != NULL ) {
            pInputStream = ( ::com::sun::star::io::XInputStream* )context ;
            pInputStream->release() ;
        }
    }

    return 0 ;
}

int xmlEnableStreamInputCallbacks()
{
    int cbs = 0 ;

    if( !( enableXmlStreamIO & XMLSTREAMIO_INITIALIZED ) ) {
        //Register the callbacks into libxml2
        //cbs = xmlRegisterInputCallbacks(
        //          xmlStreamMatch,
        //          xmlStreamOpen,
        //          xmlStreamRead,
        //          xmlStreamClose ) ;
        //if( cbs < 0 ) {
        //  return -1 ;
        //}

        //Register the callbacks into xmlSec
        //In order to make the xmlsec io finding the callbacks firstly,
        //I put the callbacks at the very begining.

        //Cleanup the older callbacks.
        //Notes: all none default callbacks will lose.
        xmlSecIOCleanupCallbacks() ;

        //Register my classbacks.
        cbs = xmlSecIORegisterCallbacks(
                    xmlStreamMatch,
                    xmlStreamOpen,
                    xmlStreamRead,
                    xmlStreamClose ) ;
        if( cbs < 0 ) {
            return -1 ;
        }

        //Register the default callbacks.
        //Notes: the error will cause xmlsec working problems.
        cbs = xmlSecIORegisterDefaultCallbacks() ;
        if( cbs < 0 ) {
            return -1 ;
        }

        enableXmlStreamIO |= XMLSTREAMIO_INITIALIZED ;
    }

    return 0 ;
}

int xmlRegisterStreamInputCallbacks(
    ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XUriBinding >& aUriBinding
) {
    if( !( enableXmlStreamIO & XMLSTREAMIO_INITIALIZED ) ) {
        if( xmlEnableStreamInputCallbacks() < 0 )
            return -1 ;
    }

    if( !( enableXmlStreamIO & XMLSTREAMIO_REGISTERED ) ) {
        enableXmlStreamIO |= XMLSTREAMIO_REGISTERED ;
    }

    m_xUriBinding = aUriBinding ;

    return 0 ;
}

int xmlUnregisterStreamInputCallbacks( void )
{
    if( ( enableXmlStreamIO & XMLSTREAMIO_REGISTERED ) ) {
        //Clear the uir-stream binding
        m_xUriBinding.clear() ;

        //disable the registered flag
        enableXmlStreamIO &= ~XMLSTREAMIO_REGISTERED ;
    }

    return 0 ;
}

void xmlDisableStreamInputCallbacks() {
    xmlUnregisterStreamInputCallbacks() ;
    enableXmlStreamIO &= ~XMLSTREAMIO_INITIALIZED ;
}

<|endoftext|>


<commit_before>/*
	kopetemessagemanager.cpp - Manages all chats

	Copyright   : (c) 2002 by Martijn Klingens <klingens@kde.org>
                      (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>
		      (c) 2002 by Daniel Stone <dstone@kde.org>

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

#include "kopetemessagemanager.h"
#include "kopetechatwindow.h"
#include "kopeteevent.h"
#include "kopete.h"

#include "messagelog.h"

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

#include <qstylesheet.h>

KopeteMessageManager::KopeteMessageManager( const KopeteContact *user, KopeteContactList others,
		KopeteProtocol *protocol, QString logFile, int widget, int capabilities,
		QObject *parent, const char *name) : QObject( parent, name)
{

	mContactList = others;
	mUser = user;
	mChatWindow = 0L;
	mUnreadMessageEvent = 0L;
	mProtocol = protocol;
	mWidget = widget;
	mCapabilities = capabilities;

	readModeChanged();
	connect(kopeteapp->appearance(), SIGNAL(queueChanged()), this, SLOT(readModeChanged()));

	if (!logFile.isEmpty())
	{
		QString logFileName = "kopete/" + logFile;
		mLogger = new KopeteMessageLog(logFileName, this);
	}
	else
	{
		mLogger = 0L;
	}
}

KopeteMessageManager::~KopeteMessageManager()
{
	emit dying(this);
}

void KopeteMessageManager::newChatWindow() {
	mChatWindow = new KopeteChatWindow(mCapabilities);
	if (mContactList.first() != 0L)
		mChatWindow->setCaption(mContactList.first()->name()); //TODO: add multi-user support
	for (KopeteContact *it = mContactList.first(); it; it = mContactList.next()) {
		for (QStringList::Iterator it2 = (resources[it]).begin(); it2 != (resources[it]).end(); it2++) {
			mChatWindow->addResource(it, *it2);
		}
	}
	/* When the window is shown, we have to delete this contact event */
	kdDebug() << "[KopeteMessageManager] Connecting message box shown() to event killer" << endl;
	connect (mChatWindow, SIGNAL(shown()), this, SLOT(cancelUnreadMessageEvent()));
	connect (mChatWindow, SIGNAL(sendMessage(const QString &)), this, SLOT(messageSentFromWindow(const QString &)));
	connect (mChatWindow, SIGNAL(closeClicked()), this, SLOT(chatWindowClosing()));
}

void KopeteMessageManager::setReadMode(int mode)
{
	if ((mode == Queued) || (mode == Popup))
	{
		mReadMode = mode;
	}
	else
	{
		kdDebug() << "[KopeteMessageManager] ERROR: unknown reading method, setting to default" << endl;
		mReadMode = Queued;
	}
}

void KopeteMessageManager::readMessages()
{
	if (mWidget == WIDGET_OLDSCHOOL) {
		if (mChatWindow == 0L) {
			kdDebug() << "[KopeteMessageManager] mChatWindow just doesn't exist" << endl;
			newChatWindow();
		}
		if (mChatWindow->isMinimized())
			kdDebug() << "[KopeteMessageManager] mChatWindow is minimized" << endl;
		if (mChatWindow->isHidden())
			kdDebug() << "[KopeteMessageManager] mChatWindow is hidden" << endl;
		mChatWindow->raise();	// make it top window
		for (KopeteMessageList::Iterator it = mMessageQueue.begin(); it != mMessageQueue.end(); it++)
		{
			kdDebug() << "[KopeteMessageManager] Inserting message from " << (*it).from()->name() << endl;
			mChatWindow->messageReceived((*it));
		}
		mChatWindow->show();	// show message window again
	}
	else {
		kdDebug() << "[KopeteMessageManager] Widget is non-oldschool: " << mWidget << endl;
	}

	mMessageQueue.clear();
}

void KopeteMessageManager::slotReadMessages()
{
	readMessages();
}

void KopeteMessageManager::messageSentFromWindow(const QString &message)
{
	QString body = message;
	KopeteMessage tmpmessage(mUser, mContactList, QStyleSheet::escape(body), KopeteMessage::Outbound);
	emit messageSent(tmpmessage);
}

void KopeteMessageManager::chatWindowClosing()
{
	kdDebug() << "[KopeteMessageManager] Chat Window closed, now 0L" << endl;
	mChatWindow = 0L;
}

void KopeteMessageManager::cancelUnreadMessageEvent()
{
	if (mUnreadMessageEvent == 0L)
	{
		kdDebug() << "[KopeteMessageManager] No event to delete" << endl;
	}
	else
	{
		kdDebug() << "[KopeteMessageManager] cancelUnreadMessageEvent Deleting Event" << endl;
		delete mUnreadMessageEvent;
		mUnreadMessageEvent = 0L;
		kdDebug() << "[KopeteMessageManager] cancelUnreadMessageEvent Event Deleted" << endl;
	}
}

void KopeteMessageManager::slotEventDeleted(KopeteEvent *e)
{
	kdDebug() << "[KopeteMessageManager] Event done(), now 0L" << endl;
	if ( e == mUnreadMessageEvent)
		mUnreadMessageEvent = 0L;
}

void KopeteMessageManager::appendMessage( const KopeteMessage &msg )
{
	bool isvisible = false;

	mMessageQueue.append(msg);

	if( mLogger )
	{
		mLogger->append( msg );
	}

	if (mReadMode == Popup)
	{
    	readMessages();
	}
	else if ( mReadMode == Queued )
	{
    	/* First stage, see what to do */
		if ( mChatWindow == 0L )
		{
			isvisible = false;
		}
		else if (  (mChatWindow != 0L) && ( mChatWindow->isHidden() || mChatWindow->isMinimized()) )
        {
			isvisible = false;
		}
		else
		{
			isvisible = true;
		}

		/* Second stage, do it */
		if ( isvisible )
		{
			readMessages();
		}
		else
		{
			/* Create an event if a prevoius one not exist */
			if ( (mUnreadMessageEvent == 0L) && (msg.direction() == KopeteMessage::Inbound) )
			{
		 		mUnreadMessageEvent = new KopeteEvent( i18n("Message from %1").arg(msg.from()->name()), "kopete/pics/newmsg.png", this, SLOT(slotReadMessages()));
				connect(mUnreadMessageEvent, SIGNAL(done(KopeteEvent *)), this, SLOT(slotEventDeleted(KopeteEvent *)));
				kopeteapp->notifyEvent( mUnreadMessageEvent );
			}
		}
	}

}
void KopeteMessageManager::addContact( const KopeteContact *c )
{
	KopeteContact *tmp;

	for ( tmp = mContactList.first(); tmp; tmp = mContactList.next() )
	{
		if ( tmp == c )
		{
			kdDebug() << "[KopeteMessageManager] Contact already exists" <<endl;
			return;
		}
	}

	kdDebug() << "[KopeteMessageManager] Contact Joined session" <<endl;
	mContactList.append(c);
}

void KopeteMessageManager::removeContact( const KopeteContact *c )
{
	mContactList.take( mContactList.find(c) );
}

void KopeteMessageManager::readModeChanged()
{
	if ( kopeteapp->appearance()->useQueue() )
	{
		mReadMode = Queued;
	}
	else
	{
		mReadMode = Popup;
	}
}

void KopeteMessageManager::addResource(const KopeteContact *c, QString resource)
{
	if (mWidget == WIDGET_OLDSCHOOL) {
		kdDebug() << "[KopeteMessageManager] Adding new resource to KCW: " << resource << endl;
		if (mChatWindow != 0L) {
			kdDebug() << "[KopeteMessageManager] mChatWindow != 0L!" << endl;
			mChatWindow->addResource(c, resource);
		}
		(resources[c]).append(resource);
	}
	else {
		kdDebug() << "[KopeteMessageManager] Adding new resource to other widget: " << resource << endl;
		(resources[c]).append(resource);
	}
}

void KopeteMessageManager::removeResource(const KopeteContact *c, QString resource) {
	if (mWidget == WIDGET_OLDSCHOOL) {
		kdDebug() << "[KopeteMessageManager] Removing resource from KCW: " << resource << endl;
		if (mChatWindow != 0L) {
			mChatWindow->removeResource(c, resource);
		}
		(resources[c]).remove(resource);
	}
	else {
		kdDebug() << "[KopeteMessageManager] Removing resource from other widget: " << resource << endl;
	}
}

bool KopeteMessageManager::serverChecked()
{
	return	mChatWindow->cbServer->isChecked();
}

void KopeteMessageManager::checkServer(bool check)
{
	mChatWindow->cbServer->setChecked(check);
}

// vim: set noet ts=4 sts=4 sw=4:
#include "kopetemessagemanager.moc"
<commit_msg>kopetemessagemanager.cpp:  - color support  - null pointer fix<commit_after>/*
	kopetemessagemanager.cpp - Manages all chats

	Copyright   : (c) 2002 by Martijn Klingens <klingens@kde.org>
                      (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>
		      (c) 2002 by Daniel Stone <dstone@kde.org>

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

#include "kopetemessagemanager.h"
#include "kopetechatwindow.h"
#include "kopeteevent.h"
#include "kopete.h"

#include "messagelog.h"

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

#include <qstylesheet.h>

KopeteMessageManager::KopeteMessageManager( const KopeteContact *user, KopeteContactList others,
		KopeteProtocol *protocol, QString logFile, int widget, int capabilities,
		QObject *parent, const char *name) : QObject( parent, name)
{

	mContactList = others;
	mUser = user;
	mChatWindow = 0L;
	mUnreadMessageEvent = 0L;
	mProtocol = protocol;
	mWidget = widget;
	mCapabilities = capabilities;

	readModeChanged();
	connect(kopeteapp->appearance(), SIGNAL(queueChanged()), this, SLOT(readModeChanged()));

	if (!logFile.isEmpty())
	{
		QString logFileName = "kopete/" + logFile;
		mLogger = new KopeteMessageLog(logFileName, this);
	}
	else
	{
		mLogger = 0L;
	}
}

KopeteMessageManager::~KopeteMessageManager()
{
	emit dying(this);
}

void KopeteMessageManager::newChatWindow() {
	mChatWindow = new KopeteChatWindow(mCapabilities);
	if (mContactList.first() != 0L)
		mChatWindow->setCaption(mContactList.first()->name()); //TODO: add multi-user support
	for (KopeteContact *it = mContactList.first(); it; it = mContactList.next()) {
		for (QStringList::Iterator it2 = (resources[it]).begin(); it2 != (resources[it]).end(); it2++) {
			mChatWindow->addResource(it, *it2);
		}
	}
	/* When the window is shown, we have to delete this contact event */
	kdDebug() << "[KopeteMessageManager] Connecting message box shown() to event killer" << endl;
	connect (mChatWindow, SIGNAL(shown()), this, SLOT(cancelUnreadMessageEvent()));
	connect (mChatWindow, SIGNAL(sendMessage(const QString &)), this, SLOT(messageSentFromWindow(const QString &)));
	connect (mChatWindow, SIGNAL(closeClicked()), this, SLOT(chatWindowClosing()));
}

void KopeteMessageManager::setReadMode(int mode)
{
	if ((mode == Queued) || (mode == Popup))
	{
		mReadMode = mode;
	}
	else
	{
		kdDebug() << "[KopeteMessageManager] ERROR: unknown reading method, setting to default" << endl;
		mReadMode = Queued;
	}
}

void KopeteMessageManager::readMessages()
{
	if (mWidget == WIDGET_OLDSCHOOL) {
		if (mChatWindow == 0L) {
			kdDebug() << "[KopeteMessageManager] mChatWindow just doesn't exist" << endl;
			newChatWindow();
		}
		if (mChatWindow->isMinimized())
			kdDebug() << "[KopeteMessageManager] mChatWindow is minimized" << endl;
		if (mChatWindow->isHidden())
			kdDebug() << "[KopeteMessageManager] mChatWindow is hidden" << endl;
		mChatWindow->raise();	// make it top window
		for (KopeteMessageList::Iterator it = mMessageQueue.begin(); it != mMessageQueue.end(); it++)
		{
			kdDebug() << "[KopeteMessageManager] Inserting message from " << (*it).from()->name() << endl;
			mChatWindow->messageReceived((*it));
		}
		mChatWindow->show();	// show message window again
	}
	else {
		kdDebug() << "[KopeteMessageManager] Widget is non-oldschool: " << mWidget << endl;
	}

	mMessageQueue.clear();
}

void KopeteMessageManager::slotReadMessages()
{
	readMessages();
}

void KopeteMessageManager::messageSentFromWindow(const QString &message)
{
	QString body = message;
	KopeteMessage tmpmessage(mUser, mContactList, QStyleSheet::escape(body), KopeteMessage::Outbound);
	if (mChatWindow->fg()->color().isValid()) {
		tmpmessage.setFg(mChatWindow->fg()->color());
	}
	if (mChatWindow->bg()->color().isValid()) {
		tmpmessage.setBg(mChatWindow->bg()->color());
	}
	emit messageSent(tmpmessage);
}

void KopeteMessageManager::chatWindowClosing()
{
	kdDebug() << "[KopeteMessageManager] Chat Window closed, now 0L" << endl;
	mChatWindow = 0L;
}

void KopeteMessageManager::cancelUnreadMessageEvent()
{
	if (mUnreadMessageEvent == 0L)
	{
		kdDebug() << "[KopeteMessageManager] No event to delete" << endl;
	}
	else
	{
		kdDebug() << "[KopeteMessageManager] cancelUnreadMessageEvent Deleting Event" << endl;
		delete mUnreadMessageEvent;
		mUnreadMessageEvent = 0L;
		kdDebug() << "[KopeteMessageManager] cancelUnreadMessageEvent Event Deleted" << endl;
	}
}

void KopeteMessageManager::slotEventDeleted(KopeteEvent *e)
{
	kdDebug() << "[KopeteMessageManager] Event done(), now 0L" << endl;
	if ( e == mUnreadMessageEvent)
		mUnreadMessageEvent = 0L;
}

void KopeteMessageManager::appendMessage( const KopeteMessage &msg )
{
	bool isvisible = false;

	mMessageQueue.append(msg);

	if( mLogger )
	{
		mLogger->append( msg );
	}

	if (mReadMode == Popup)
	{
    	readMessages();
	}
	else if ( mReadMode == Queued )
	{
    	/* First stage, see what to do */
		if ( mChatWindow == 0L )
		{
			isvisible = false;
		}
		else if (  (mChatWindow != 0L) && ( mChatWindow->isHidden() || mChatWindow->isMinimized()) )
        {
			isvisible = false;
		}
		else
		{
			isvisible = true;
		}

		/* Second stage, do it */
		if ( isvisible )
		{
			readMessages();
		}
		else
		{
			/* Create an event if a prevoius one not exist */
			if ( (mUnreadMessageEvent == 0L) && (msg.direction() == KopeteMessage::Inbound) )
			{
		 		mUnreadMessageEvent = new KopeteEvent( i18n("Message from %1").arg(msg.from()->name()), "kopete/pics/newmsg.png", this, SLOT(slotReadMessages()));
				connect(mUnreadMessageEvent, SIGNAL(done(KopeteEvent *)), this, SLOT(slotEventDeleted(KopeteEvent *)));
				kopeteapp->notifyEvent( mUnreadMessageEvent );
			}
		}
	}

}
void KopeteMessageManager::addContact( const KopeteContact *c )
{
	KopeteContact *tmp;

	for ( tmp = mContactList.first(); tmp; tmp = mContactList.next() )
	{
		if ( tmp == c )
		{
			kdDebug() << "[KopeteMessageManager] Contact already exists" <<endl;
			return;
		}
	}

	kdDebug() << "[KopeteMessageManager] Contact Joined session" <<endl;
	mContactList.append(c);
}

void KopeteMessageManager::removeContact( const KopeteContact *c )
{
	mContactList.take( mContactList.find(c) );
}

void KopeteMessageManager::readModeChanged()
{
	if ( kopeteapp->appearance()->useQueue() )
	{
		mReadMode = Queued;
	}
	else
	{
		mReadMode = Popup;
	}
}

void KopeteMessageManager::addResource(const KopeteContact *c, QString resource)
{
	if (mWidget == WIDGET_OLDSCHOOL) {
		kdDebug() << "[KopeteMessageManager] Adding new resource to KCW: " << resource << endl;
		if (mChatWindow != 0L) {
			kdDebug() << "[KopeteMessageManager] mChatWindow != 0L!" << endl;
			mChatWindow->addResource(c, resource);
		}
		(resources[c]).append(resource);
	}
	else {
		kdDebug() << "[KopeteMessageManager] Adding new resource to other widget: " << resource << endl;
		(resources[c]).append(resource);
	}
}

void KopeteMessageManager::removeResource(const KopeteContact *c, QString resource) {
	if (mWidget == WIDGET_OLDSCHOOL) {
		kdDebug() << "[KopeteMessageManager] Removing resource from KCW: " << resource << endl;
		if (mChatWindow != 0L) {
			mChatWindow->removeResource(c, resource);
		}

		QStringList tmpResources = resources[c];
		if (&tmpResources == NULL) {
			kdDebug() << "[KopeteMessageManager] ->rR(): Eeks, no tmpResource!" << endl;
		}
		else {
			tmpResources.remove(resource);
		}
	}
	else {
		kdDebug() << "[KopeteMessageManager] Removing resource from other widget: " << resource << endl;
	}
}

bool KopeteMessageManager::serverChecked()
{
	return	mChatWindow->cbServer->isChecked();
}

void KopeteMessageManager::checkServer(bool check)
{
	mChatWindow->cbServer->setChecked(check);
}

// vim: set noet ts=4 sts=4 sw=4:
#include "kopetemessagemanager.moc"
<|endoftext|>