<commit_before>#include "client_netcom.hpp"
#include "server_netcom.hpp"

namespace client {
    netcom::netcom() : self_id_(invalid_actor_id), is_connected_(false), terminate_thread_(false),
        listener_thread_(std::bind(&netcom::loop_, this)), sc_factory_(*this) {}

    netcom::~netcom() {
        terminate();
    }

    actor_id_t netcom::self_id() const {
        return self_id_;
    }

    bool netcom::is_connected() const {
        return is_connected_;
    }

    void netcom::run(const std::string& addr, std::uint16_t port) {
        if (is_connected_) {
            terminate();
        }
        terminate_thread_ = false;
        address_ = addr;
        port_ = port;
        listener_thread_.launch();
    }

    void netcom::terminate_() {
        terminate_thread_ = true;
        listener_thread_.wait();

        netcom_base::terminate_();
        self_id_ = invalid_actor_id;
    }

    void netcom::loop_() {
        sf::TcpSocket socket;

        // Try to connect
        std::size_t wait_count = 5;
        while (wait_count != 0) {
            switch (socket.connect(sf::IpAddress(address_), port_, sf::seconds(1))) {
            case sf::Socket::Done : {
                send_message(self_actor_id, message::server::connection_established{});

                out_packet_t op(server_actor_id);
                if (socket.receive(op.impl) == sf::Socket::Done) {
                    out_packet_t top = op;
                    netcom_impl::packet_type t;
                    op >> t;
                    if (t != netcom_impl::packet_type::message) {
                        send_message(self_actor_id, make_packet<message::server::connection_denied>(
                            message::server::connection_denied::reason::unexpected_packet
                        ));
                        return;
                    }

                    packet_id_t id;
                    op >> id;
                    switch (id) {
                    case message::server::connection_granted::packet_id__ :
                        op >> self_id_;
                        input_.push(std::move(top.to_input()));
                        break;
                    case message::server::connection_denied::packet_id__ :
                        input_.push(std::move(top.to_input()));
                        return;
                    default :
                        send_message(self_actor_id, make_packet<message::server::connection_denied>(
                            message::server::connection_denied::reason::unexpected_packet
                        ));
                        return;
                    }
                } else {
                    send_message(self_actor_id, make_packet<message::server::connection_failed>(
                        message::server::connection_failed::reason::cannot_authenticate
                    ));
                    return;
                }

                wait_count = 0;
                break;
            }
            case sf::Socket::NotReady : break;
            case sf::Socket::Error : break;
            case sf::Socket::Disconnected :
                send_message(self_actor_id, make_packet<message::server::connection_failed>(
                    message::server::connection_failed::reason::disconnected
                ));
                return;
            }

            if (wait_count == 0) break;

            --wait_count;

            if (wait_count == 0) {
                send_message(self_actor_id, make_packet<message::server::connection_failed>(
                    message::server::connection_failed::reason::timed_out
                ));
                return;
            }
        }

        is_connected_ = true;

        // Enter main loop
        while (!terminate_thread_) {
            // Receive incoming packets
            in_packet_t ip(server_actor_id);
            socket.setBlocking(false);
            switch (socket.receive(ip.impl)) {
            case sf::Socket::Done :
                input_.push(std::move(ip));
                break;
            case sf::Socket::NotReady : break;
            case sf::Socket::Disconnected :
            case sf::Socket::Error :
                send_message(self_actor_id, make_packet<message::server::connection_failed>(
                    message::server::connection_failed::reason::disconnected
                ));
                terminate_thread_ = true;
                break;
            }

            if (terminate_thread_) break;

            // Send outgoing packets
            socket.setBlocking(true);
            out_packet_t op;
            while (output_.pop(op)) {
                switch (socket.send(op.impl)) {
                case sf::Socket::Done : break;
                case sf::Socket::NotReady :
                case sf::Socket::Disconnected :
                case sf::Socket::Error :
                    send_message(self_actor_id, make_packet<message::server::connection_failed>(
                        message::server::connection_failed::reason::disconnected
                    ));
                    terminate_thread_ = true;
                    break;
                }
            }

            sf::sleep(sf::milliseconds(5));
        }

        input_.clear();
        output_.clear();
        is_connected_ = false;
    }
}
<commit_msg>Removed useless copy of packet in client_netcom.<commit_after>#include "client_netcom.hpp"
#include "server_netcom.hpp"

namespace client {
    netcom::netcom() : self_id_(invalid_actor_id), is_connected_(false), terminate_thread_(false),
        listener_thread_(std::bind(&netcom::loop_, this)), sc_factory_(*this) {}

    netcom::~netcom() {
        terminate();
    }

    actor_id_t netcom::self_id() const {
        return self_id_;
    }

    bool netcom::is_connected() const {
        return is_connected_;
    }

    void netcom::run(const std::string& addr, std::uint16_t port) {
        if (is_connected_) {
            terminate();
        }
        terminate_thread_ = false;
        address_ = addr;
        port_ = port;
        listener_thread_.launch();
    }

    void netcom::terminate_() {
        terminate_thread_ = true;
        listener_thread_.wait();

        netcom_base::terminate_();
        self_id_ = invalid_actor_id;
    }

    void netcom::loop_() {
        sf::TcpSocket socket;

        // Try to connect
        std::size_t wait_count = 5;
        while (wait_count != 0) {
            switch (socket.connect(sf::IpAddress(address_), port_, sf::seconds(1))) {
            case sf::Socket::Done : {
                send_message(self_actor_id, message::server::connection_established{});

                out_packet_t op(server_actor_id);
                if (socket.receive(op.impl) == sf::Socket::Done) {
                    auto opv = op.view();
                    netcom_impl::packet_type t;
                    opv >> t;
                    if (t != netcom_impl::packet_type::message) {
                        send_message(self_actor_id, make_packet<message::server::connection_denied>(
                            message::server::connection_denied::reason::unexpected_packet
                        ));
                        return;
                    }

                    packet_id_t id;
                    opv >> id;
                    switch (id) {
                    case message::server::connection_granted::packet_id__ :
                        opv >> self_id_;
                        input_.push(std::move(op.to_input()));
                        break;
                    case message::server::connection_denied::packet_id__ :
                        input_.push(std::move(op.to_input()));
                        return;
                    default :
                        send_message(self_actor_id, make_packet<message::server::connection_denied>(
                            message::server::connection_denied::reason::unexpected_packet
                        ));
                        return;
                    }
                } else {
                    send_message(self_actor_id, make_packet<message::server::connection_failed>(
                        message::server::connection_failed::reason::cannot_authenticate
                    ));
                    return;
                }

                wait_count = 0;
                break;
            }
            case sf::Socket::NotReady : break;
            case sf::Socket::Error : break;
            case sf::Socket::Disconnected :
                send_message(self_actor_id, make_packet<message::server::connection_failed>(
                    message::server::connection_failed::reason::disconnected
                ));
                return;
            }

            if (wait_count == 0) break;

            --wait_count;

            if (wait_count == 0) {
                send_message(self_actor_id, make_packet<message::server::connection_failed>(
                    message::server::connection_failed::reason::timed_out
                ));
                return;
            }
        }

        is_connected_ = true;

        // Enter main loop
        while (!terminate_thread_) {
            // Receive incoming packets
            in_packet_t ip(server_actor_id);
            socket.setBlocking(false);
            switch (socket.receive(ip.impl)) {
            case sf::Socket::Done :
                input_.push(std::move(ip));
                break;
            case sf::Socket::NotReady : break;
            case sf::Socket::Disconnected :
            case sf::Socket::Error :
                send_message(self_actor_id, make_packet<message::server::connection_failed>(
                    message::server::connection_failed::reason::disconnected
                ));
                terminate_thread_ = true;
                break;
            }

            if (terminate_thread_) break;

            // Send outgoing packets
            socket.setBlocking(true);
            out_packet_t op;
            while (output_.pop(op)) {
                switch (socket.send(op.impl)) {
                case sf::Socket::Done : break;
                case sf::Socket::NotReady :
                case sf::Socket::Disconnected :
                case sf::Socket::Error :
                    send_message(self_actor_id, make_packet<message::server::connection_failed>(
                        message::server::connection_failed::reason::disconnected
                    ));
                    terminate_thread_ = true;
                    break;
                }
            }

            sf::sleep(sf::milliseconds(5));
        }

        input_.clear();
        output_.clear();
        is_connected_ = false;
    }
}
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2013 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/// \author James Hughes
/// \date   April 2013

#ifndef IAUNS_ARC_LOOK_AT_H
#define IAUNS_ARC_LOOK_AT_H

#include <stdint.h>
#include <memory>

#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_inverse.hpp>
#include <glm/gtc/matrix_transform.hpp>

#include <glm-aabb/AABB.hpp>

// Forward declaration of ArcBall in its CPM namespace.
namespace CPM_ARC_BALL_NS {
  class ArcBall;
}

namespace CPM_ARC_LOOK_AT_NS {

/// Basic camera class that uses cpm-arc-ball to control view orientation.
/// Supports a number of utility functions such as ensuring a given
/// AABB is in the view of the frustum (zooming only).
/// All coordinates, unless otherwise specified, are in 2D screen space
/// coordinates.
class ArcLookAt
{
public:
  ArcLookAt();
  virtual ~ArcLookAt();

  /// Sets the reference point for upcoming operations.
  /// Should always be called before any of the 'do' functions below.
  void doReferenceDown(const glm::vec2& ssPos);

  /// Pans the camera based on the reference position, current orientation, and
  /// the current screen / space position.
  /// Note that this pans the lookat point by the same amount as the camera.
  void doPan(const glm::vec2& ssPos);

  /// Rotates about the look at position.
  void doRotation(const glm::vec2& ssPos);

  /// Dollys the camera towards(negative) / away(positive) from the look at
  /// point.
  void doZoom(glm::float_t camZoom);

  /// Uses a custom function to determine camera zoom. Downwards and to the
  /// right increases size, upwards or to the left decreases size
  void doZoom(const glm::vec2& ssPos);

  /// Implements autoview on a bounding box. Implemented just like SCIRun 4's
  /// autoview in Dataflow/Modules/Render/ViewWindow.cc.
  /// This function will change the lookat point to the center of the bounding
  /// box.
  /// \p fov is expected to be in radians.
  void autoview(const CPM_GLM_AABB_NS::AABB& aabb, float fov);

  /// Retrieves the camera's distance away from the look at point.
  glm::float_t getCamDistance() const   {return mCamDistance;}

  /// Retrieves the current lookat point.
  glm::vec3 getLookAt() const   {return mCamLookAt;}

  /// Retrieves the world transformation for the camera (looking down
  /// negative z).
  glm::mat4 getWorldViewTransform() const;

private:
  std::unique_ptr<CPM_ARC_BALL_NS::ArcBall>  mArcBall;

  glm::vec3                 mCamLookAt;     ///< Current lookat position.
  glm::float_t              mCamDistance;   ///< Distance from look-at.

  // The following are reference variables set when doReferenceDown is called.
  glm::vec2                 mReferenceScreenPos;
  glm::vec3                 mReferenceLookAt;
  glm::mat4                 mReferenceTransform;
  glm::float_t              mReferenceCamDistance;
};

} // namespace CPM_ARC_LOOK_AT_NS

#endif
<commit_msg>Update camera documentation.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2013 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/// \author James Hughes
/// \date   April 2013

#ifndef IAUNS_ARC_LOOK_AT_H
#define IAUNS_ARC_LOOK_AT_H

#include <stdint.h>
#include <memory>

#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_inverse.hpp>
#include <glm/gtc/matrix_transform.hpp>

#include <glm-aabb/AABB.hpp>

// Forward declaration of ArcBall in its CPM namespace.
namespace CPM_ARC_BALL_NS {
  class ArcBall;
}

namespace CPM_ARC_LOOK_AT_NS {

/// Basic camera class that uses cpm-arc-ball to control view orientation.
/// Supports a number of utility functions such as ensuring a given
/// AABB is in the view of the frustum (zooming only).
/// All coordinates, unless otherwise specified, are in 2D screen space
/// coordinates.
class ArcLookAt
{
public:
  ArcLookAt();
  virtual ~ArcLookAt();

  /// Sets the reference point for upcoming operations.
  /// Should be be called before any of the 'do' function below, and acts
  /// as the 'mouse down' in the mouse input process. The 'do' functions below
  /// behave like 'mouse move'.
  void doReferenceDown(const glm::vec2& ssPos);

  /// Pans the camera based on the reference position, current orientation, and
  /// the current screen / space position.
  /// Note that this pans the lookat point by the same amount as the camera.
  void doPan(const glm::vec2& ssPos);

  /// Rotates about the look at position.
  void doRotation(const glm::vec2& ssPos);

  /// Dollys the camera towards(negative) / away(positive) from the look at
  /// point.
  void doZoom(glm::float_t camZoom);

  /// Uses a custom function to determine camera zoom. Downwards and to the
  /// right increases size, upwards or to the left decreases size
  void doZoom(const glm::vec2& ssPos);

  /// Implements autoview on a bounding box. Implemented just like SCIRun 4's
  /// autoview in Dataflow/Modules/Render/ViewWindow.cc.
  /// This function will change the lookat point to the center of the bounding
  /// box.
  /// \p fov is expected to be in radians.
  void autoview(const CPM_GLM_AABB_NS::AABB& aabb, float fov);

  /// Retrieves the camera's distance away from the look at point.
  glm::float_t getCamDistance() const   {return mCamDistance;}

  /// Retrieves the current lookat point.
  glm::vec3 getLookAt() const   {return mCamLookAt;}

  /// Retrieves the world transformation for the camera (looking down
  /// negative z).
  glm::mat4 getWorldViewTransform() const;

private:
  std::unique_ptr<CPM_ARC_BALL_NS::ArcBall>  mArcBall;

  glm::vec3                 mCamLookAt;     ///< Current lookat position.
  glm::float_t              mCamDistance;   ///< Distance from look-at.

  // The following are reference variables set when doReferenceDown is called.
  glm::vec2                 mReferenceScreenPos;
  glm::vec3                 mReferenceLookAt;
  glm::mat4                 mReferenceTransform;
  glm::float_t              mReferenceCamDistance;
};

} // namespace CPM_ARC_LOOK_AT_NS

#endif
<|endoftext|>


<commit_before>/**
 * @file llhudrender.cpp
 * @brief LLHUDRender class implementation
 *
 * $LicenseInfo:firstyear=2002&license=viewergpl$
 *
 * Copyright (c) 2002-2009, Linden Research, Inc.
 *
 * Second Life Viewer Source Code
 * The source code in this file ("Source Code") is provided by Linden Lab
 * to you under the terms of the GNU General Public License, version 2.0
 * ("GPL"), unless you have obtained a separate licensing agreement
 * ("Other License"), formally executed by you and Linden Lab.  Terms of
 * the GPL can be found in doc/GPL-license.txt in this distribution, or
 * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
 *
 * There are special exceptions to the terms and conditions of the GPL as
 * it is applied to this Source Code. View the full text of the exception
 * in the file doc/FLOSS-exception.txt in this software distribution, or
 * online at
 * http://secondlifegrid.net/programs/open_source/licensing/flossexception
 *
 * By copying, modifying or distributing this software, you acknowledge
 * that you have read and understood your obligations described above,
 * and agree to abide by those obligations.
 *
 * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
 * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
 * COMPLETENESS OR PERFORMANCE.
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "llhudrender.h"

#include "llrender.h"
#include "llgl.h"
#include "llviewercamera.h"
#include "v3math.h"
#include "llquaternion.h"
#include "llfontgl.h"
#include "llglheaders.h"
#include "llviewerwindow.h"
#include "llui.h"

void hud_render_utf8text(const std::string &str, const LLVector3 &pos_agent,
					 const LLFontGL &font,
					 const U8 style,
					 const LLFontGL::ShadowType shadow,
					 const F32 x_offset, const F32 y_offset,
					 const LLColor4& color,
					 const BOOL orthographic)
{
	LLWString wstr(utf8str_to_wstring(str));
	hud_render_text(wstr, pos_agent, font, style, shadow, x_offset, y_offset, color, orthographic);
}

void hud_render_text(const LLWString &wstr, const LLVector3 &pos_agent,
					const LLFontGL &font,
					const U8 style,
					const LLFontGL::ShadowType shadow,
					const F32 x_offset, const F32 y_offset,
					const LLColor4& color,
					const BOOL orthographic)
{
	LLViewerCamera* camera = LLViewerCamera::getInstance();
	// Do cheap plane culling
	LLVector3 dir_vec = pos_agent - camera->getOrigin();
	dir_vec /= dir_vec.magVec();

	if (wstr.empty() || (!orthographic && dir_vec * camera->getAtAxis() <= 0.f))
	{
		return;
	}

	LLVector3 right_axis;
	LLVector3 up_axis;
	if (orthographic)
	{
		right_axis.setVec(0.f, -1.f / gViewerWindow->getWorldViewWidthRaw(), 0.f);
		up_axis.setVec(0.f, 0.f, 1.f / gViewerWindow->getWorldViewHeightRaw());
	}
	else
	{
		camera->getPixelVectors(pos_agent, up_axis, right_axis);
	}
	LLCoordFrame render_frame = *camera;
	LLQuaternion rot;
	if (!orthographic)
	{
		rot = render_frame.getQuaternion();
		rot = rot * LLQuaternion(-F_PI_BY_TWO, camera->getYAxis());
		rot = rot * LLQuaternion(F_PI_BY_TWO, camera->getXAxis());
	}
	else
	{
		rot = LLQuaternion(-F_PI_BY_TWO, LLVector3(0.f, 0.f, 1.f));
		rot = rot * LLQuaternion(-F_PI_BY_TWO, LLVector3(0.f, 1.f, 0.f));
	}
	F32 angle;
	LLVector3 axis;
	rot.getAngleAxis(&angle, axis);

	LLVector3 render_pos = pos_agent + (floorf(x_offset) * right_axis) + (floorf(y_offset) * up_axis);

	//get the render_pos in screen space

	F64 winX, winY, winZ;
	LLRect world_view_rect = gViewerWindow->getWorldViewRectRaw();
	S32	viewport[4];
	viewport[0] = world_view_rect.mLeft;
	viewport[1] = world_view_rect.mBottom;
	viewport[2] = world_view_rect.getWidth();
	viewport[3] = world_view_rect.getHeight();
	gluProject(render_pos.mV[0], render_pos.mV[1], render_pos.mV[2],
				gGLModelView, gGLProjection, (GLint*) viewport,
				&winX, &winY, &winZ);

	//fonts all render orthographically, set up projection``
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glMatrixMode(GL_MODELVIEW);
	gGL.pushMatrix();
	LLUI::pushMatrix();

	gl_state_for_2d(world_view_rect.getWidth(), world_view_rect.getHeight());
	gViewerWindow->setup3DViewport();

	winX -= world_view_rect.mLeft;
	winY -= world_view_rect.mBottom;
	LLUI::loadIdentity();
	glLoadIdentity();
	LLUI::translate((F32) winX*1.0f/LLFontGL::sScaleX, (F32) winY*1.0f/(LLFontGL::sScaleY), -(((F32) winZ*2.f)-1.f));
	F32 right_x;

	font.render(wstr, 0, 0, 0, color, LLFontGL::LEFT, LLFontGL::BASELINE, style, shadow, wstr.length(), 1000, &right_x);

	LLUI::popMatrix();
	gGL.popMatrix();

	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
}
<commit_msg>EXT-1998 	 [BSI] Hover text on HUD attachments is offset toward the right Reviewed by Richard CC#193<commit_after>/**
 * @file llhudrender.cpp
 * @brief LLHUDRender class implementation
 *
 * $LicenseInfo:firstyear=2002&license=viewergpl$
 *
 * Copyright (c) 2002-2009, Linden Research, Inc.
 *
 * Second Life Viewer Source Code
 * The source code in this file ("Source Code") is provided by Linden Lab
 * to you under the terms of the GNU General Public License, version 2.0
 * ("GPL"), unless you have obtained a separate licensing agreement
 * ("Other License"), formally executed by you and Linden Lab.  Terms of
 * the GPL can be found in doc/GPL-license.txt in this distribution, or
 * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
 *
 * There are special exceptions to the terms and conditions of the GPL as
 * it is applied to this Source Code. View the full text of the exception
 * in the file doc/FLOSS-exception.txt in this software distribution, or
 * online at
 * http://secondlifegrid.net/programs/open_source/licensing/flossexception
 *
 * By copying, modifying or distributing this software, you acknowledge
 * that you have read and understood your obligations described above,
 * and agree to abide by those obligations.
 *
 * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
 * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
 * COMPLETENESS OR PERFORMANCE.
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "llhudrender.h"

#include "llrender.h"
#include "llgl.h"
#include "llviewercamera.h"
#include "v3math.h"
#include "llquaternion.h"
#include "llfontgl.h"
#include "llglheaders.h"
#include "llviewerwindow.h"
#include "llui.h"

void hud_render_utf8text(const std::string &str, const LLVector3 &pos_agent,
					 const LLFontGL &font,
					 const U8 style,
					 const LLFontGL::ShadowType shadow,
					 const F32 x_offset, const F32 y_offset,
					 const LLColor4& color,
					 const BOOL orthographic)
{
	LLWString wstr(utf8str_to_wstring(str));
	hud_render_text(wstr, pos_agent, font, style, shadow, x_offset, y_offset, color, orthographic);
}

void hud_render_text(const LLWString &wstr, const LLVector3 &pos_agent,
					const LLFontGL &font,
					const U8 style,
					const LLFontGL::ShadowType shadow,
					const F32 x_offset, const F32 y_offset,
					const LLColor4& color,
					const BOOL orthographic)
{
	LLViewerCamera* camera = LLViewerCamera::getInstance();
	// Do cheap plane culling
	LLVector3 dir_vec = pos_agent - camera->getOrigin();
	dir_vec /= dir_vec.magVec();

	if (wstr.empty() || (!orthographic && dir_vec * camera->getAtAxis() <= 0.f))
	{
		return;
	}

	LLVector3 right_axis;
	LLVector3 up_axis;
	if (orthographic)
	{
		right_axis.setVec(0.f, -1.f / gViewerWindow->getWorldViewHeightRaw(), 0.f);
		up_axis.setVec(0.f, 0.f, 1.f / gViewerWindow->getWorldViewHeightRaw());
	}
	else
	{
		camera->getPixelVectors(pos_agent, up_axis, right_axis);
	}
	LLCoordFrame render_frame = *camera;
	LLQuaternion rot;
	if (!orthographic)
	{
		rot = render_frame.getQuaternion();
		rot = rot * LLQuaternion(-F_PI_BY_TWO, camera->getYAxis());
		rot = rot * LLQuaternion(F_PI_BY_TWO, camera->getXAxis());
	}
	else
	{
		rot = LLQuaternion(-F_PI_BY_TWO, LLVector3(0.f, 0.f, 1.f));
		rot = rot * LLQuaternion(-F_PI_BY_TWO, LLVector3(0.f, 1.f, 0.f));
	}
	F32 angle;
	LLVector3 axis;
	rot.getAngleAxis(&angle, axis);

	LLVector3 render_pos = pos_agent + (floorf(x_offset) * right_axis) + (floorf(y_offset) * up_axis);

	//get the render_pos in screen space

	F64 winX, winY, winZ;
	LLRect world_view_rect = gViewerWindow->getWorldViewRectRaw();
	S32	viewport[4];
	viewport[0] = world_view_rect.mLeft;
	viewport[1] = world_view_rect.mBottom;
	viewport[2] = world_view_rect.getWidth();
	viewport[3] = world_view_rect.getHeight();
	gluProject(render_pos.mV[0], render_pos.mV[1], render_pos.mV[2],
				gGLModelView, gGLProjection, (GLint*) viewport,
				&winX, &winY, &winZ);

	//fonts all render orthographically, set up projection``
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glMatrixMode(GL_MODELVIEW);
	gGL.pushMatrix();
	LLUI::pushMatrix();

	gl_state_for_2d(world_view_rect.getWidth(), world_view_rect.getHeight());
	gViewerWindow->setup3DViewport();

	winX -= world_view_rect.mLeft;
	winY -= world_view_rect.mBottom;
	LLUI::loadIdentity();
	glLoadIdentity();
	LLUI::translate((F32) winX*1.0f/LLFontGL::sScaleX, (F32) winY*1.0f/(LLFontGL::sScaleY), -(((F32) winZ*2.f)-1.f));
	F32 right_x;

	font.render(wstr, 0, 0, 0, color, LLFontGL::LEFT, LLFontGL::BASELINE, style, shadow, wstr.length(), 1000, &right_x);

	LLUI::popMatrix();
	gGL.popMatrix();

	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
}
<|endoftext|>


<commit_before>#include "stdafx.h"

static InputElement elements[] = {
	CInputElement("POSITION", SF_R32G32B32_FLOAT, 0),
	CInputElement("COLOR", SF_R32G32B32_FLOAT, 12),
};

struct Vertex {
	Vec3 pos;
	Vec3 color;
};

struct PickingUBO {
	Mat matVP;
};

class Picking {
	VBOID vbo2d, vbo3d;
	UBOID ubo;
	ShaderMan::SMID shader;
public:
	Picking();
	~Picking();
	void Update();
	void Draw2D();
	void Draw3D();
};

#define CLASSNAME "Picking"
#define GET_PICKING \
	Picking* p = (Picking*)luaL_checkudata(L, 1, CLASSNAME);	\
	if (!p) {	\
		return 0;	\
	}

class PickingBinder {
public:
	PickingBinder() {
		GetLuaBindFuncContainer().push_back([](lua_State* L) {
			static luaL_Reg methods[] = {
				{ "Update", [](lua_State* L) { GET_PICKING p->Update(); return 0; } },
				{ "Draw2D", [](lua_State* L) { GET_PICKING p->Draw2D(); return 0; } },
				{ "Draw3D", [](lua_State* L) { GET_PICKING p->Draw3D(); return 0; } },
				{ nullptr, nullptr },
			};
			aflBindClass(L, CLASSNAME, methods, [](lua_State* L) { void* u = lua_newuserdata(L, sizeof(Picking)); new (u) Picking(); return 1; });
		});
	}
} static binder;

Picking::Picking()
{
	ubo = afCreateUBO(sizeof(Mat));
	vbo2d = afCreateDynamicVertexBuffer(sizeof(Vertex) * 3);
	vbo3d = afCreateDynamicVertexBuffer(sizeof(Vertex) * 3);
	shader = shaderMan.Create("solid", elements, dimof(elements), BM_NONE, DSM_DEPTH_ENABLE, CM_DISABLE);
	Update();
}

Picking::~Picking()
{
	afSafeDeleteBuffer(ubo);
	afSafeDeleteBuffer(vbo2d);
	afSafeDeleteBuffer(vbo3d);
}

void ScreenPosToRay(const Vec2& scrPos, Vec3& nearPos, Vec3& farPos)
{
	Mat v, p;
	matrixMan.Get(MatrixMan::VIEW, v);
	matrixMan.Get(MatrixMan::PROJ, p);
	Mat vp = makeViewportMatrix(systemMisc.GetScreenSize());
	Mat mInv = inv(v * p * vp);
	Vec4 nearPos4 = transform(Vec4(scrPos.x, scrPos.y, NDC_SPACE_NEAR, 1), mInv);
	Vec4 farPos4 = transform(Vec4(scrPos.x, scrPos.y, NDC_SPACE_FAR, 1), mInv);
	nearPos = Vec3(nearPos4.x, nearPos4.y, nearPos4.z) / nearPos4.w;
	farPos = Vec3(farPos4.x, farPos4.y, farPos4.z) / farPos4.w;
}

bool RayVsTriangle(const Vec3& ray1, const Vec3& ray2, const Vec3 triangle[])
{
	Vec3 rayDir = ray2 - ray1;
	float inner[3];
	for (int i = 0; i < 3; i++) {
		const Vec3& a = triangle[i];
		const Vec3& b = triangle[(i + 1) % 3];
		inner[i] = dot(cross(ray1 - a, a - b), rayDir);
	}
	return (inner[0] < 0 && inner[1] < 0 && inner[2] < 0) || (inner[0] > 0 && inner[1] > 0 && inner[2] > 0);
}

void Picking::Update()
{
	Vertex v[3];
	float radian = (float)(std::fmod(GetTime(), 3) * M_PI * 2 / 3);
	float radius = 0.5f;
	float aspect = (float)systemMisc.GetScreenSize().x / systemMisc.GetScreenSize().y;
	for (int i = 0; i < 3; i++) {
		static Vec3 center(-0.7f, 0.7f, 0.f);
		radian += (float)M_PI * 2 / 3;
		v[i].pos = Vec3(std::sin(radian) / aspect, std::cos(radian), 0) * radius + center;
	}

	bool hit = true;

	Vec2 scrPos = systemMisc.GetScreenSize();
	Vec2 curPos = systemMisc.GetMousePos();

	Vec2 curPosInNDC = curPos / scrPos * Vec2(2, -2) + Vec2(-1, 1);

	// test
	Mat vp = makeViewportMatrix(scrPos);
	Vec3 transformed = transform(Vec3(curPos.x, curPos.y, 1), inv(vp));
	assert(std::abs(transformed.x - curPosInNDC.x) < 0.001f);
	assert(std::abs(transformed.y - curPosInNDC.y) < 0.001f);

	for (int i = 0; i < 3; i++) {
		Vec3 dir = v[(i + 1) % 3].pos - v[i].pos;
		Vec3 cursorDir = Vec3(curPosInNDC.x, curPosInNDC.y, 0) - v[i].pos;
		if (cross(dir, cursorDir).z > 0) {
			hit = false;
		}
	}

	for (int i = 0; i < 3; i++) {
		v[i].color = hit ? Vec3(i == 0, i == 1, i == 2) : Vec3(0.5, 0.5, 0.5);
	}

	afWriteBuffer(vbo2d, v, sizeof(v));

	radian = (float)(std::fmod(GetTime(), 10) * M_PI * 2 / 10);
	radius = 50.f;
	Vec3 triangle[3];
	for (int i = 0; i < 3; i++) {
		radian += (float)M_PI * 2 / 3;
		triangle[i] = v[i].pos = Vec3(std::sin(radian) * radius, std::cos(radian) * radius, 50.f);
		v[i].color = Vec3(0.5, 0.5, 0.5);
	}

	Vec3 n, f;
	ScreenPosToRay(systemMisc.GetMousePos(), n, f);
	hit = RayVsTriangle(n, f, triangle);
	for (int i = 0; i < 3; i++) {
		v[i].color = hit ? Vec3(i == 0, i == 1, i == 2) : Vec3(0.5, 0.5, 0.5);
	}

	afWriteBuffer(vbo3d, v, sizeof(v));
}

void Picking::Draw3D()
{
	Vec3 n, f;
	ScreenPosToRay(systemMisc.GetMousePos(), n, f);
	fontMan.DrawString(systemMisc.GetMousePos(), 15, SPrintf("near={%f,%f,%f} far={%f,%f,%f}", n.x, n.y, n.z, f.x, f.y, f.z));

	shaderMan.Apply(shader);
	VBOID vbos[] = {vbo3d};
	int strides[] = {sizeof(Vertex)};
	afSetVertexAttributes(elements, dimof(elements), 1, vbos, strides);

	Mat mView, mProj;
	matrixMan.Get(MatrixMan::VIEW, mView);
	matrixMan.Get(MatrixMan::PROJ, mProj);
	Mat mVP = mView * mProj;
	afWriteBuffer(ubo, &mVP, sizeof(Mat));
	afBindBufferToBindingPoint(ubo, 0);

	afDrawTriangleStrip(3);
}

void Picking::Draw2D()
{
	shaderMan.Apply(shader);
	VBOID vbos[] = {vbo2d};
	int strides[] = {sizeof(Vertex)};
	afSetVertexAttributes(elements, dimof(elements), 1, vbos, strides);

	PickingUBO buf;
	afWriteBuffer(ubo, &buf, sizeof(buf));
	afBindBufferToBindingPoint(ubo, 0);

	afDrawTriangleStrip(3);

	// test
	ivec2 scrSize = systemMisc.GetScreenSize();
	float f = 1000;
	float n = 1;
	float aspect = (float)scrSize.x / scrSize.y;
	Mat proj = perspectiveLH(45.0f * (float)M_PI / 180.0f, aspect, n, f);

	Vec3 v1 = { 0, 0, 1 };
	Vec3 v2 = { 0, 0, 1000 };
	Vec3 v1trans = transform(v1, proj);
	Vec3 v2trans = transform(v2, proj);
	Vec4 v1m = transform(Vec4(v1.x, v1.y, v1.z, 1), proj);
	Vec4 v2m = transform(Vec4(v2.x, v2.y, v2.z, 1), proj);
}
<commit_msg>ray-grid intersection<commit_after>#include "stdafx.h"

static InputElement elements[] = {
	CInputElement("POSITION", SF_R32G32B32_FLOAT, 0),
	CInputElement("COLOR", SF_R32G32B32_FLOAT, 12),
};

struct Vertex {
	Vec3 pos;
	Vec3 color;
};

struct PickingUBO {
	Mat matVP;
};

class Picking {
	VBOID vbo2d, vbo3d;
	UBOID ubo;
	ShaderMan::SMID shader;
public:
	Picking();
	~Picking();
	void Update();
	void Draw2D();
	void Draw3D();
};

#define CLASSNAME "Picking"
#define GET_PICKING \
	Picking* p = (Picking*)luaL_checkudata(L, 1, CLASSNAME);	\
	if (!p) {	\
		return 0;	\
	}

class PickingBinder {
public:
	PickingBinder() {
		GetLuaBindFuncContainer().push_back([](lua_State* L) {
			static luaL_Reg methods[] = {
				{ "Update", [](lua_State* L) { GET_PICKING p->Update(); return 0; } },
				{ "Draw2D", [](lua_State* L) { GET_PICKING p->Draw2D(); return 0; } },
				{ "Draw3D", [](lua_State* L) { GET_PICKING p->Draw3D(); return 0; } },
				{ nullptr, nullptr },
			};
			aflBindClass(L, CLASSNAME, methods, [](lua_State* L) { void* u = lua_newuserdata(L, sizeof(Picking)); new (u) Picking(); return 1; });
		});
	}
} static binder;

Picking::Picking()
{
	ubo = afCreateUBO(sizeof(Mat));
	vbo2d = afCreateDynamicVertexBuffer(sizeof(Vertex) * 3);
	vbo3d = afCreateDynamicVertexBuffer(sizeof(Vertex) * 3);
	shader = shaderMan.Create("solid", elements, dimof(elements), BM_NONE, DSM_DEPTH_ENABLE, CM_DISABLE);
	Update();
}

Picking::~Picking()
{
	afSafeDeleteBuffer(ubo);
	afSafeDeleteBuffer(vbo2d);
	afSafeDeleteBuffer(vbo3d);
}

void ScreenPosToRay(const Vec2& scrPos, Vec3& nearPos, Vec3& farPos)
{
	Mat v, p;
	matrixMan.Get(MatrixMan::VIEW, v);
	matrixMan.Get(MatrixMan::PROJ, p);
	Mat vp = makeViewportMatrix(systemMisc.GetScreenSize());
	Mat mInv = inv(v * p * vp);
	Vec4 nearPos4 = transform(Vec4(scrPos.x, scrPos.y, NDC_SPACE_NEAR, 1), mInv);
	Vec4 farPos4 = transform(Vec4(scrPos.x, scrPos.y, NDC_SPACE_FAR, 1), mInv);
	nearPos = Vec3(nearPos4.x, nearPos4.y, nearPos4.z) / nearPos4.w;
	farPos = Vec3(farPos4.x, farPos4.y, farPos4.z) / farPos4.w;
}

bool RayVsTriangle(const Vec3& ray1, const Vec3& ray2, const Vec3 triangle[])
{
	Vec3 rayDir = ray2 - ray1;
	float inner[3];
	for (int i = 0; i < 3; i++) {
		const Vec3& a = triangle[i];
		const Vec3& b = triangle[(i + 1) % 3];
		inner[i] = dot(cross(ray1 - a, a - b), rayDir);
	}
	return (inner[0] < 0 && inner[1] < 0 && inner[2] < 0) || (inner[0] > 0 && inner[1] > 0 && inner[2] > 0);
}

void Picking::Update()
{
	Vertex v[3];
	float radian = (float)(std::fmod(GetTime(), 3) * M_PI * 2 / 3);
	float radius = 0.5f;
	float aspect = (float)systemMisc.GetScreenSize().x / systemMisc.GetScreenSize().y;
	for (int i = 0; i < 3; i++) {
		static Vec3 center(-0.7f, 0.7f, 0.f);
		radian += (float)M_PI * 2 / 3;
		v[i].pos = Vec3(std::sin(radian) / aspect, std::cos(radian), 0) * radius + center;
	}

	bool hit = true;

	Vec2 scrPos = systemMisc.GetScreenSize();
	Vec2 curPos = systemMisc.GetMousePos();

	Vec2 curPosInNDC = curPos / scrPos * Vec2(2, -2) + Vec2(-1, 1);

	// test
	Mat vp = makeViewportMatrix(scrPos);
	Vec3 transformed = transform(Vec3(curPos.x, curPos.y, 1), inv(vp));
	assert(std::abs(transformed.x - curPosInNDC.x) < 0.001f);
	assert(std::abs(transformed.y - curPosInNDC.y) < 0.001f);

	for (int i = 0; i < 3; i++) {
		Vec3 dir = v[(i + 1) % 3].pos - v[i].pos;
		Vec3 cursorDir = Vec3(curPosInNDC.x, curPosInNDC.y, 0) - v[i].pos;
		if (cross(dir, cursorDir).z > 0) {
			hit = false;
		}
	}

	for (int i = 0; i < 3; i++) {
		v[i].color = hit ? Vec3(i == 0, i == 1, i == 2) : Vec3(0.5, 0.5, 0.5);
	}

	afWriteBuffer(vbo2d, v, sizeof(v));

	radian = (float)(std::fmod(GetTime(), 10) * M_PI * 2 / 10);
	radius = 50.f;
	Vec3 triangle[3];
	for (int i = 0; i < 3; i++) {
		radian += (float)M_PI * 2 / 3;
		triangle[i] = v[i].pos = Vec3(std::sin(radian) * radius, std::cos(radian) * radius, 50.f);
		v[i].color = Vec3(0.5, 0.5, 0.5);
	}

	Vec3 n, f;
	ScreenPosToRay(systemMisc.GetMousePos(), n, f);
	hit = RayVsTriangle(n, f, triangle);
	for (int i = 0; i < 3; i++) {
		v[i].color = hit ? Vec3(i == 0, i == 1, i == 2) : Vec3(0.5, 0.5, 0.5);
	}

	afWriteBuffer(vbo3d, v, sizeof(v));
}

void Picking::Draw3D()
{
	shaderMan.Apply(shader);
	VBOID vbos[] = {vbo3d};
	int strides[] = {sizeof(Vertex)};
	afSetVertexAttributes(elements, dimof(elements), 1, vbos, strides);

	Mat mView, mProj;
	matrixMan.Get(MatrixMan::VIEW, mView);
	matrixMan.Get(MatrixMan::PROJ, mProj);
	Mat mVP = mView * mProj;
	afWriteBuffer(ubo, &mVP, sizeof(Mat));
	afBindBufferToBindingPoint(ubo, 0);

	afDrawTriangleStrip(3);
}

void Picking::Draw2D()
{
	shaderMan.Apply(shader);
	VBOID vbos[] = {vbo2d};
	int strides[] = {sizeof(Vertex)};
	afSetVertexAttributes(elements, dimof(elements), 1, vbos, strides);

	PickingUBO buf;
	afWriteBuffer(ubo, &buf, sizeof(buf));
	afBindBufferToBindingPoint(ubo, 0);

	afDrawTriangleStrip(3);

	Vec2 strPos = systemMisc.GetMousePos();
	auto drawStr = [&](const char* s) {
		fontMan.DrawString(strPos, 15, s);
		strPos.y += 16;
	};

	// make a ray from cursor pos
	Vec3 n, f;
	ScreenPosToRay(systemMisc.GetMousePos(), n, f);
	drawStr(SPrintf("near={%f,%f,%f}", n.x, n.y, n.z));
	drawStr(SPrintf("far={%f,%f,%f}", f.x, f.y, f.z));

	// ray-grid intersection
	Vec3 planeCenter = {0, 0, 0};
	Vec3 planeNormal = {0, 1, 0};
	float nDotPlane = dot(n, planeNormal);
	float fDotPlane = dot(f, planeNormal);
	if (nDotPlane * fDotPlane < 0) {
		nDotPlane = abs(nDotPlane);
		fDotPlane = abs(fDotPlane);
		Vec3 hitPos = n + (f - n) * nDotPlane / (nDotPlane + fDotPlane);
		drawStr(SPrintf("hit={%f,%f,%f}", hitPos.x, hitPos.y, hitPos.z));
	}
}
<|endoftext|>


<commit_before>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implmentation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

// (c) COPYRIGHT URI/MIT 1998-2000
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
//	jhrg,jimg	James Gallagher <jgallagher@gso.uri.edu>

/** Asciival is a simple DODS client similar to geturl or writeval that reads
    a DODS data object (either by dereferencing a URL, reading from a file or
    reading from stdin) and writes comma separated ASCII representation of the
    data values in that object.

    @author: jhrg */

//#include "config_dap.h"
#include "config_asciival.h"

static char rcsid[] not_used = {"$Id$"};

#include <stdio.h>
#include <assert.h>
#include <string>

#include <GetOpt.h>

#include "BaseType.h"
#include "Connect.h"
#include "name_map.h"
#include "cgi_util.h"
#include "debug.h"

#include "AsciiByte.h"
#include "AsciiInt32.h"
#include "AsciiUInt32.h"
#include "AsciiFloat64.h"
#include "AsciiStr.h"
#include "AsciiUrl.h"
#include "AsciiArray.h"
#include "AsciiStructure.h"
#include "AsciiSequence.h"
#include "AsciiGrid.h"

name_map names;
bool translate = false;

#ifdef DODS_VERSION
const char *VERSION = DODS_VERSION;
#else
const char *VERSION = "unknown";
#endif /* DODS_VERSION */

static void
usage(string name)
{
    cerr << "Usage: " << name
	 << " [mngvVt] -- [<url> [-r <var>:<newvar> ...] ...]" << endl
	 << "       m: Output a MIME header." << endl
	 << "       n: Turn on name canonicalization." << endl
	 << "       v: Verbose output." << endl
	 << "       V: Print the version number and exit" << endl
	 << "       r: Per-URL name mappings; var becomes newvar." << endl
	 << endl
	 << "<url> may be a true URL, which asciival will dereference," << endl
	 << "it may be a local file or it may be standard input." << endl
	 << "In the later case use `-' for <url>."
	 << endl;
}

static void
process_per_url_options(int &i, int argc, char *argv[], bool verbose = false)
{
    names.delete_all();	// Clear the global name map for this URL.

    // Test for per-url option. Set variables accordingly.
    while (argv[i+1] && argv[i+1][0] == '-')
	switch (argv[++i][1]) {
	  case 'r':
	    ++i;	// Move past option to argument.
	    if (verbose)
		cerr << "  Renaming: " << argv[i] << endl;
	    // Note that NAMES is a global variable so that all the
	    // writeval() mfuncs can access it without having to pass
	    // it into each function call.
	    names.add(argv[i]);
	    break;

	  default:
	    cerr << "Unknown option `" << argv[i][1]
		 << "' paired with URL has been ignored." << endl;
	    break;
	}

}

static void
process_data(DDS *dds)
{
    cout << "Dataset: " << dds->get_dataset_name() << endl;

    for (Pix q = dds->first_var(); q; dds->next_var(q)) {
	dynamic_cast<AsciiOutput *>(dds->var(q))->print_ascii(cout);
	cout << endl;
    }
}

/** Write out the given error object. If the Error object #e# is empty, don't
    write anything out (since that will confuse loaddods).

    @author jhrg */

static void
output_error_object(const Error &e)
{
    if (e.OK())
	cout << "Error: " << e.get_error_message() << endl;
}

// Read a DODS data object. The object maybe specified by a URL (which will
// be dereferenceed using Connect, it maybe read from a file or it maybe read
// from stdin. Use `-' in the command line to indicate the next input should
// be read from standard input.

int
main(int argc, char * argv[])
{
    GetOpt getopt (argc, argv, "ngmvVh?");
    int option_char;
    bool verbose = false;
#if 0
    bool trace = false;
#endif
    bool translate = false;
    bool gui = false;
    bool mime_header = false;
    string expr = "";
#if 0
    char *tcode = NULL;
    int topts = 0;
#endif
    putenv("_POSIX_OPTION_ORDER=1"); // Suppress GetOpt's argv[] permutation.

    while ((option_char = getopt()) != EOF)
	switch (option_char) {
	  case 'n': translate = true; break;
	  case 'g': gui = true; break;
	  case 'm': mime_header = true; break;
	  case 'v': verbose = true; break;
	  case 'V': {cerr << "asciival: " << VERSION << endl; exit(0);}
	  case 'h':
	  case '?':
	  default:
	    usage((string)argv[0]); exit(1); break;
	}

    Connect *url = 0;

    for (int i = getopt.optind; i < argc; ++i) {
	try {
	    if (url)
		delete url;

	    if (strcmp(argv[i], "-") == 0){
		url = new Connect("stdin", trace, false);
		DBG(cerr << "Instantiated Connect object using stdin." \
		    << endl);

	    }
	    else{
		url = new Connect(argv[i], trace);
		DBG(cerr << endl << "Instantiated Connect object using " \
		    << argv[i] << endl << endl);
	    }

	    // asciival is used almost always as part of the DODS server. It
	    // should not be caching values returned from/by the DAS, DDS, or
	    // DataDDS handlers of the server. Doing so makes little hiccups
	    // in the caching very hard for users to correct. 1/16/2002 jhrg
	    url->set_cache_enabled(false);

	    DBG2(cerr << "argv[" << i << "] (of " << argc << "): "
		 << argv[i] << endl);

	    if (verbose) {
		string source_name;

		DBG(cerr << "URL->is_local(): " << url->is_local() << endl);
		DBG(cerr << "argv[" << i << "]: \"" << argv[i] << "\""
		    << endl);

		if (url->is_local() && (strcmp(argv[i], "-") == 0))
		    source_name = "standard input";
		else if (url->is_local())
		    source_name = argv[i];
		else
		    source_name = url->URL(false);

		cerr << endl << "Reading: " << source_name << endl;
	    }

	    process_per_url_options(i, argc, argv, verbose);

	    DataDDS dds;

	    if (url->is_local() && (strcmp(argv[i], "-") == 0))
		url->read_data(dds, stdin);
	    else if (url->is_local())
		url->read_data(dds, fopen(argv[i], "r"));
	    else
		url->request_data(dds, expr);

	    if (mime_header)
		set_mime_text(cout, dods_data);
	    process_data(&dds);
	}
	catch (Error &e) {
	    DBG(cerr << "Caught an Error object." << endl);
	    output_error_object(e);
	}
    }

    cout.flush();
    cerr.flush();

    return 0;
}

// $Log: ascii_val.cc,v $
// Revision 1.2  2004/01/26 18:58:48  jimg
// Build fixes
//
// Revision 1.1  2003/03/13 23:37:32  jimg
// Added.
//
// Revision 1.16  2003/03/06 18:52:10  jimg
// Replaced call to Connect::disable_cache() with a call to
// Connect::set_cache_enable(false). The disable_cache() method no longer exists.
//
// Revision 1.15  2003/01/27 19:38:23  jimg
// Updated the copyright information.
// Merged with release-3-2-6.
//
// Revision 1.13.4.6  2002/12/23 23:23:03  jimg
// Removed unused XDR * pointer from the process_data() function. This changes
// was made to accommodate a change in Connect.
//
// Revision 1.13.4.5  2002/07/05 23:58:23  jimg
// I switched to the local config header (config_asciival.h) from the DAP's
// header. I removed a lot of code that was specific to libwww's trace system. I
// changed they way the code uses Connect so that the new methods are used in
// place of the old ones.
//
// Revision 1.13.4.4  2002/06/21 00:31:41  jimg
// I changed many files throughout the source so that the 'make World' build
// works with the new versions of Connect and libdap++ that use libcurl.
// Most of these changes are either to Makefiles, configure scripts or to
// the headers included by various C++ files. In a few places the oddities
// of libwww forced us to hack up code and I've undone those and some of the
// clients had code that supported libwww's generous tracing capabilities
// (that's one part of libwww I'll miss); I had to remove support for that.
// Once this code compiles and more work is done on Connect, I'll return to
// each of these changes and polish them.
//
// Revision 1.13.4.3  2002/01/17 00:45:06  jimg
// I added a call to Connect::disable_cache(). This will suppress use of the
// cache which is important since this `client' is used as part of the DODS
// server and it seems to cause problems whenthe server caches DataDDS
// objects (among other things). I think servers should not cache, in general.
//
// Revision 1.14  2001/09/28 23:46:06  jimg
// merged with 3.2.3.
//
// Revision 1.13.4.2  2001/09/27 03:10:36  jimg
// Minor fix to a DBG call.
//
// Revision 1.13.4.1  2001/09/18 23:29:26  jimg
// Massive changes to use the new AsciiOutput class. Output more or less
// conforms to the DAP Spec. draft.
//
// Revision 1.13  2000/10/02 20:09:52  jimg
// Moved Log entries to the end of the files
//
// Revision 1.12  1999/07/28 23:00:54  jimg
// Separated from the writeval directory, moved to tools
//
// Revision 1.11  1999/07/24 00:10:28  jimg
// Merged the release-3-0-2 branch
//
// Revision 1.10  1999/05/25 18:47:11  jimg
// Merged Nathan's fixes for the -t option and some debugging instrumentation.
//
// Revision 1.9  1999/05/18 20:59:32  jimg
// Removed name_from_url(...) since int is never used.
//
// Revision 1.8  1999/04/30 17:06:56  jimg
// Merged with no-gnu and release-2-24
//
// Revision 1.7  1999/03/24 06:23:43  brent
// convert String.h to std lib <string>, convert to packages regex -- B^2
//
// Revision 1.6  1998/09/16 23:30:26  jimg
// Change process_data() so that it calls print_all_vals() for Structure.
//
// Revision 1.5  1998/08/01 01:31:36  jimg
// Fixed a bug in process_data() where deserialize() was not called before the
// call to print_all_vals().
//
// Revision 1.4  1998/07/30 19:05:54  jimg
// Fixed the call to usage; passing a char * invoked cgi-util.cc:usage which
// was not what we wanted. Also added help about the -m option.
//
// Revision 1.3  1998/03/19 23:26:03  jimg
// Added code to write out error messages read from the server.
//
// Revision 1.2  1998/03/16 19:45:09  jimg
// Added mime header output. See -m.
//
// Revision 1.1  1998/03/16 18:30:19  jimg
// Added
<commit_msg>Removed the old ascii_val.cc since this was not used and confused the eclipse debugger.<commit_after><|endoftext|>


<commit_before>/*****************************************************************************
 *****************************************************************************
 *
 * Simple client application using the UnoUrlResolver service.
 *
 *****************************************************************************
 *****************************************************************************/
#include <stdio.h>

#include <cppuhelper/bootstrap.hxx>

#include <osl/file.hxx>
#include <osl/process.h>

#include <com/sun/star/bridge/XUnoUrlResolver.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>

#include <string.h>

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::bridge;
using namespace com::sun::star::frame;
using namespace com::sun::star::registry;

//============================================================================
int SAL_CALL main( int argc, char **argv )
{
    OUString sConnectionString(RTL_CONSTASCII_USTRINGPARAM("uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager"));
     if (argc < 2)
    {
        printf("using: DocumentLoader <file_url> [<uno_connection_url>]\n\n"
               "example: DocumentLoader  \"file:///e:/temp/test.sxw\" \"uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager\"\n");
        exit(1);
    }
     if (argc == 3)
    {
        sConnectionString = OUString::createFromAscii(argv[2]);
    }

    // Creates a simple registry service instance.
    Reference< XSimpleRegistry > xSimpleRegistry(
        ::cppu::createSimpleRegistry() );

    // Connects the registry to a persistent data source represented by an URL.
    xSimpleRegistry->open( OUString( RTL_CONSTASCII_USTRINGPARAM(
        "DocumentLoader.rdb") ), sal_True, sal_False );

    /* Bootstraps an initial component context with service manager upon a given
       registry. This includes insertion of initial services:
       - (registry) service manager, shared lib loader,
       - simple registry, nested registry,
       - implementation registration
       - registry typedescription provider, typedescription manager (also
         installs it into cppu core)
    */
    Reference< XComponentContext > xComponentContext(
        ::cppu::bootstrap_InitialComponentContext( xSimpleRegistry ) );

    /* Bootstraps an initial component context with service manager upon default
       types and services registry. This includes insertion of initial services:
       - (registry) service manager, shared lib loader,
       - simple registry, nested registry,
       - implementation registration
       - registry typedescription provider, typedescription manager (also
         installs it into cppu core)

       This function tries to find its parameters via these bootstrap variables:
       - UNO_TYPES        -- a space separated list of file urls of type rdbs
       - UNO_SERVICES     -- a space separated list of file urls of service rdbs
       - UNO_WRITERDB     -- a file url of a write rdb (e.g. user.rdb)

       For further info, please look at:
       http://udk.openoffice.org/common/man/concept/uno_default_bootstrapping.html
    */
    /*
    Reference< XComponentContext > xComponentContext(
        ::cppu::defaultBootstrap_InitialComponentContext() );
    OSL_ASSERT( xcomponentcontext.is() );
    */

    /* Gets the service manager instance to be used (or null). This method has
       been added for convenience, because the service manager is a often used
       object.
    */
    Reference< XMultiComponentFactory > xMultiComponentFactoryClient(
        xComponentContext->getServiceManager() );

    /* Creates an instance of a component which supports the services specified
       by the factory.
    */
    Reference< XInterface > xInterface =
        xMultiComponentFactoryClient->createInstanceWithContext(
            OUString::createFromAscii( "com.sun.star.bridge.UnoUrlResolver" ),
            xComponentContext );

    Reference< XUnoUrlResolver > resolver( xInterface, UNO_QUERY );

    // Resolves the component context from the office, on the uno URL given by argv[1].
    xInterface = Reference< XInterface >(
        resolver->resolve( sConnectionString ), UNO_QUERY );

    // gets the server component context as property of the office component factory
    Reference< XPropertySet > xPropSet( xInterface, UNO_QUERY );
    xPropSet->getPropertyValue( OUString::createFromAscii("DefaultContext") ) >>= xComponentContext;

    // gets the service manager from the office
    Reference< XMultiComponentFactory > xMultiComponentFactoryServer(
        xComponentContext->getServiceManager() );

    /* Creates an instance of a component which supports the services specified
       by the factory. Important: using the office component context.
    */
    Reference < XComponentLoader > xComponentLoader(
        xMultiComponentFactoryServer->createInstanceWithContext(
            OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.Desktop" ) ),
            xComponentContext ), UNO_QUERY );

    /* Loads a component specified by an URL into the specified new or existing
       frame.
    */
    OUString sDocUrl, sWorkingDir;
    osl_getProcessWorkingDir(&sWorkingDir.pData);
    osl::FileBase::getAbsoluteFileURL( sWorkingDir, OUString::createFromAscii(argv[1]), sDocUrl);

    Reference< XComponent > xComponent = xComponentLoader->loadComponentFromURL(
        sDocUrl, OUString( RTL_CONSTASCII_USTRINGPARAM("_blank") ), 0,
        Sequence < ::com::sun::star::beans::PropertyValue >() );

    // dispose the local service manager
    Reference< XComponent >::query( xMultiComponentFactoryClient )->dispose();

    return 0;
}
<commit_msg>INTEGRATION: CWS sdk01 (1.3.20.1.6); FILE MERGED 2003/03/13 11:39:21 jsc 1.3.20.1.6.1: #107908# catch exception<commit_after>/*****************************************************************************
 *****************************************************************************
 *
 * Simple client application using the UnoUrlResolver service.
 *
 *****************************************************************************
 *****************************************************************************/
#include <stdio.h>

#include <cppuhelper/bootstrap.hxx>

#include <osl/file.hxx>
#include <osl/process.h>

#include <com/sun/star/bridge/XUnoUrlResolver.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>

#include <string.h>

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::bridge;
using namespace com::sun::star::frame;
using namespace com::sun::star::registry;

//============================================================================
int SAL_CALL main( int argc, char **argv )
{
    OUString sConnectionString(RTL_CONSTASCII_USTRINGPARAM("uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager"));
     if (argc < 2)
    {
        printf("using: DocumentLoader <file_url> [<uno_connection_url>]\n\n"
               "example: DocumentLoader  \"file:///e:/temp/test.sxw\" \"uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager\"\n");
        exit(1);
    }
     if (argc == 3)
    {
        sConnectionString = OUString::createFromAscii(argv[2]);
    }

    // Creates a simple registry service instance.
    Reference< XSimpleRegistry > xSimpleRegistry(
        ::cppu::createSimpleRegistry() );

    // Connects the registry to a persistent data source represented by an URL.
    xSimpleRegistry->open( OUString( RTL_CONSTASCII_USTRINGPARAM(
        "DocumentLoader.rdb") ), sal_True, sal_False );

    /* Bootstraps an initial component context with service manager upon a given
       registry. This includes insertion of initial services:
       - (registry) service manager, shared lib loader,
       - simple registry, nested registry,
       - implementation registration
       - registry typedescription provider, typedescription manager (also
         installs it into cppu core)
    */
    Reference< XComponentContext > xComponentContext(
        ::cppu::bootstrap_InitialComponentContext( xSimpleRegistry ) );

    /* Bootstraps an initial component context with service manager upon default
       types and services registry. This includes insertion of initial services:
       - (registry) service manager, shared lib loader,
       - simple registry, nested registry,
       - implementation registration
       - registry typedescription provider, typedescription manager (also
         installs it into cppu core)

       This function tries to find its parameters via these bootstrap variables:
       - UNO_TYPES        -- a space separated list of file urls of type rdbs
       - UNO_SERVICES     -- a space separated list of file urls of service rdbs
       - UNO_WRITERDB     -- a file url of a write rdb (e.g. user.rdb)

       For further info, please look at:
       http://udk.openoffice.org/common/man/concept/uno_default_bootstrapping.html
    */
    /*
    Reference< XComponentContext > xComponentContext(
        ::cppu::defaultBootstrap_InitialComponentContext() );
    OSL_ASSERT( xcomponentcontext.is() );
    */

    /* Gets the service manager instance to be used (or null). This method has
       been added for convenience, because the service manager is a often used
       object.
    */
    Reference< XMultiComponentFactory > xMultiComponentFactoryClient(
        xComponentContext->getServiceManager() );

    /* Creates an instance of a component which supports the services specified
       by the factory.
    */
    Reference< XInterface > xInterface =
        xMultiComponentFactoryClient->createInstanceWithContext(
            OUString::createFromAscii( "com.sun.star.bridge.UnoUrlResolver" ),
            xComponentContext );

    Reference< XUnoUrlResolver > resolver( xInterface, UNO_QUERY );

    // Resolves the component context from the office, on the uno URL given by argv[1].
    try
    {
        xInterface = Reference< XInterface >(
            resolver->resolve( sConnectionString ), UNO_QUERY );
    }
    catch ( Exception& e )
    {
        printf("Error: cannot establish a connection using '%s':\n       %s\n",
               OUStringToOString(sConnectionString, RTL_TEXTENCODING_ASCII_US).getStr(),
               OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US).getStr());
        exit(1);
    }

    // gets the server component context as property of the office component factory
    Reference< XPropertySet > xPropSet( xInterface, UNO_QUERY );
    xPropSet->getPropertyValue( OUString::createFromAscii("DefaultContext") ) >>= xComponentContext;

    // gets the service manager from the office
    Reference< XMultiComponentFactory > xMultiComponentFactoryServer(
        xComponentContext->getServiceManager() );

    /* Creates an instance of a component which supports the services specified
       by the factory. Important: using the office component context.
    */
    Reference < XComponentLoader > xComponentLoader(
        xMultiComponentFactoryServer->createInstanceWithContext(
            OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.Desktop" ) ),
            xComponentContext ), UNO_QUERY );

    /* Loads a component specified by an URL into the specified new or existing
       frame.
    */
    OUString sDocUrl, sWorkingDir;
    osl_getProcessWorkingDir(&sWorkingDir.pData);
    osl::FileBase::getAbsoluteFileURL( sWorkingDir, OUString::createFromAscii(argv[1]), sDocUrl);

    Reference< XComponent > xComponent = xComponentLoader->loadComponentFromURL(
        sDocUrl, OUString( RTL_CONSTASCII_USTRINGPARAM("_blank") ), 0,
        Sequence < ::com::sun::star::beans::PropertyValue >() );

    // dispose the local service manager
    Reference< XComponent >::query( xMultiComponentFactoryClient )->dispose();

    return 0;
}
<|endoftext|>


<commit_before>// Module:  Log4CPLUS
// File:    fileappender.cxx
// Created: 6/2001
// Author:  Tad E. Smith
//
//
// Copyright (C) The Apache Software Foundation. All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.APL file.
//

#include <log4cplus/fileappender.h>
#include <log4cplus/layout.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/stringhelper.h>
#include <log4cplus/spi/loggingevent.h>
#include <algorithm>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;
using namespace log4cplus::helpers;

#define MINIMUM_ROLLING_LOG_SIZE 200*1024L

log4cplus::FileAppender::FileAppender(const std::string& filename,
                                      std::ios::openmode mode)
{
    init(filename, mode);
}

log4cplus::FileAppender::FileAppender(log4cplus::helpers::Properties properties,
                                      std::ios::openmode mode)
: Appender(properties)
{
     string filename = properties.getProperty("File");
     if(filename.length() == 0) {
         getErrorHandler()->error("Invalid filename");
         return;
     }

     init(filename, mode);
}

void
log4cplus::FileAppender::init(const std::string& filename,
                              std::ios::openmode mode)
{
    this->filename = filename;
    out.open(filename.c_str(), mode);

    if(!out.good()) {
        getErrorHandler()->error("Unable to open file: " + filename);
        return;
    }
    getLogLog().debug("Just opened file: " + filename);

    int columns = 80;
    std::string tmp;
    tmp.resize(columns);
    std::fill_n(tmp.begin(), columns, '#');

    out << tmp << std::endl
        << "#" << std::endl
        << "# Created Appender on: "
        << getFormattedTime(time(NULL), "%m-%d-%y %H:%M:%S") << std::endl
        << "#" << std::endl
        << tmp << std::endl;
}

log4cplus::FileAppender::~FileAppender()
{
    destructorImpl();
}

void
log4cplus::FileAppender::close()
{
    LOG4CPLUS_BEGIN_SYNCHRONIZE_ON_MUTEX( access_mutex )
        out.close();
    LOG4CPLUS_END_SYNCHRONIZE_ON_MUTEX
}

// This method does not need to be locked since it is called by
// doAppend() which performs the locking
void
log4cplus::FileAppender::append(const spi::InternalLoggingEvent& event)
{
    if(!out.is_open()) {
        getErrorHandler()->error("file is not open: " + filename);
        return;
    }

    layout->formatAndAppend(out, event);
}

log4cplus::RollingFileAppender::RollingFileAppender(const std::string& filename,
                                                    long maxFileSize,
                                                    int maxBackupIndex)
: FileAppender(filename, std::ios::app)
{
    init(maxFileSize, maxBackupIndex);
}

log4cplus::RollingFileAppender::RollingFileAppender(log4cplus::helpers::Properties properties)
: FileAppender(properties, std::ios::app)
{
    int maxFileSize = 10*1024*1024;
    int maxBackupIndex = 1;
    if(properties.exists("MaxFileSize")) {
        string tmp = toupper( properties.getProperty("MaxFileSize") );
        maxFileSize = atoi(tmp.c_str());
        if(tmp.find("MB") == (tmp.length() - 2)) {
            maxFileSize *= (1024 * 1024); // convert to megabytes
        }
        if(tmp.find("KB") == (tmp.length() - 2)) {
            maxFileSize *= 1024; // convert to kilobytes
        }
    }

    if(properties.exists("MaxBackupIndex")) {
        string tmp = properties.getProperty("MaxBackupIndex");
        maxBackupIndex = atoi(tmp.c_str());
    }

    init(maxFileSize, maxBackupIndex);
}

log4cplus::RollingFileAppender::~RollingFileAppender()
{
    destructorImpl();
}

void
log4cplus::RollingFileAppender::init(long maxFileSize, int maxBackupIndex)
{
    this->maxFileSize = max(maxFileSize, MINIMUM_ROLLING_LOG_SIZE);
    this->maxBackupIndex = max(maxBackupIndex, 1);
}

// This method does not need to be locked since it is called by
// doAppend() which performs the locking
void
log4cplus::RollingFileAppender::append(const spi::InternalLoggingEvent& event)
{
    if(!out.is_open()) {
        getErrorHandler()->error("file is not open: " + filename);
        return;
    }

    layout->formatAndAppend(out, event);

    if(out.tellp() > maxFileSize) {
        rollover();
    }
}

void
log4cplus::RollingFileAppender::rollover()
{
    // If maxBackups <= 0, then there is no file renaming to be done.
    if(maxBackupIndex > 0) {
        // Delete the oldest file
        std::ostringstream buffer;
        buffer << filename << '.' << maxBackupIndex;
        remove(buffer.str().c_str());

        // Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2}
        for(int i=maxBackupIndex - 1; i >= 1; i--) {
            std::ostringstream source;
            std::ostringstream target;

            source << filename << '.' << i;
            target << filename << '.' << (i+1);
            if(rename(source.str().c_str(), target.str().c_str()) == 0) {
                getLogLog().debug("Renamed file " + source.str() + " to " + target.str());
            }
        }

        // Close the current file
        out.close();
        out.clear(); // reset flags since the C++ standard specified that all the
                     // flags should remain unchanged on a close

        // Rename fileName to fileName.1
        std::string target = filename + ".1";
        getLogLog().debug("Renaming file " + filename + " to " + target);
        rename(filename.c_str(), target.c_str());

        // Open a new file
        out.open(filename.c_str(), std::ios::out | std::ios::trunc);
    }
    else {
        getLogLog().debug(filename + " has no backups specified");
        // Close the current file
        out.close();
        out.clear(); // reset flags since the C++ standard specified that all the
                     // flags should remain unchanged on a close

        // Open it up again in truncation mode
        out.open(filename.c_str(), std::ios::out | std::ios::trunc);
    }
}

<commit_msg>Standardized the formatting.<commit_after>// Module:  Log4CPLUS
// File:    fileappender.cxx
// Created: 6/2001
// Author:  Tad E. Smith
//
//
// Copyright (C) Tad E. Smith  All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.APL file.
//
// $Log: not supported by cvs2svn $

#include <log4cplus/fileappender.h>
#include <log4cplus/layout.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/stringhelper.h>
#include <log4cplus/spi/loggingevent.h>
#include <algorithm>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;
using namespace log4cplus::helpers;

#define MINIMUM_ROLLING_LOG_SIZE 200*1024L

///////////////////////////////////////////////////////////////////////////////
// log4cplus::FileAppender ctors and dtor
///////////////////////////////////////////////////////////////////////////////

log4cplus::FileAppender::FileAppender(const std::string& filename,
                                      std::ios::openmode mode)
{
    init(filename, mode);
}

log4cplus::FileAppender::FileAppender(log4cplus::helpers::Properties properties,
                                      std::ios::openmode mode)
: Appender(properties)
{
     string filename = properties.getProperty("File");
     if(filename.length() == 0) {
         getErrorHandler()->error("Invalid filename");
         return;
     }

     init(filename, mode);
}

void
log4cplus::FileAppender::init(const std::string& filename,
                              std::ios::openmode mode)
{
    this->filename = filename;
    out.open(filename.c_str(), mode);

    if(!out.good()) {
        getErrorHandler()->error("Unable to open file: " + filename);
        return;
    }
    getLogLog().debug("Just opened file: " + filename);

    int columns = 80;
    std::string tmp;
    tmp.resize(columns);
    std::fill_n(tmp.begin(), columns, '#');

    out << tmp << std::endl
        << "#" << std::endl
        << "# Created Appender on: "
        << getFormattedTime(time(NULL), "%m-%d-%y %H:%M:%S") << std::endl
        << "#" << std::endl
        << tmp << std::endl;
}

log4cplus::FileAppender::~FileAppender()
{
    destructorImpl();
}

///////////////////////////////////////////////////////////////////////////////
// log4cplus::FileAppender public methods
///////////////////////////////////////////////////////////////////////////////

void
log4cplus::FileAppender::close()
{
    LOG4CPLUS_BEGIN_SYNCHRONIZE_ON_MUTEX( access_mutex )
        out.close();
    LOG4CPLUS_END_SYNCHRONIZE_ON_MUTEX
}

///////////////////////////////////////////////////////////////////////////////
// log4cplus::FileAppender protected methods
///////////////////////////////////////////////////////////////////////////////

// This method does not need to be locked since it is called by
// doAppend() which performs the locking
void
log4cplus::FileAppender::append(const spi::InternalLoggingEvent& event)
{
    if(!out.is_open()) {
        getErrorHandler()->error("file is not open: " + filename);
        return;
    }

    layout->formatAndAppend(out, event);
}

///////////////////////////////////////////////////////////////////////////////
// log4cplus::RollingFileAppender ctors and dtor
///////////////////////////////////////////////////////////////////////////////

log4cplus::RollingFileAppender::RollingFileAppender(const std::string& filename,
                                                    long maxFileSize,
                                                    int maxBackupIndex)
: FileAppender(filename, std::ios::app)
{
    init(maxFileSize, maxBackupIndex);
}

log4cplus::RollingFileAppender::RollingFileAppender(log4cplus::helpers::Properties properties)
: FileAppender(properties, std::ios::app)
{
    int maxFileSize = 10*1024*1024;
    int maxBackupIndex = 1;
    if(properties.exists("MaxFileSize")) {
        string tmp = toupper( properties.getProperty("MaxFileSize") );
        maxFileSize = atoi(tmp.c_str());
        if(tmp.find("MB") == (tmp.length() - 2)) {
            maxFileSize *= (1024 * 1024); // convert to megabytes
        }
        if(tmp.find("KB") == (tmp.length() - 2)) {
            maxFileSize *= 1024; // convert to kilobytes
        }
    }

    if(properties.exists("MaxBackupIndex")) {
        string tmp = properties.getProperty("MaxBackupIndex");
        maxBackupIndex = atoi(tmp.c_str());
    }

    init(maxFileSize, maxBackupIndex);
}

void
log4cplus::RollingFileAppender::init(long maxFileSize, int maxBackupIndex)
{
    this->maxFileSize = max(maxFileSize, MINIMUM_ROLLING_LOG_SIZE);
    this->maxBackupIndex = max(maxBackupIndex, 1);
}

log4cplus::RollingFileAppender::~RollingFileAppender()
{
    destructorImpl();
}

///////////////////////////////////////////////////////////////////////////////
// log4cplus::RollingFileAppender protected methods
///////////////////////////////////////////////////////////////////////////////

// This method does not need to be locked since it is called by
// doAppend() which performs the locking
void
log4cplus::RollingFileAppender::append(const spi::InternalLoggingEvent& event)
{
    if(!out.is_open()) {
        getErrorHandler()->error("file is not open: " + filename);
        return;
    }

    layout->formatAndAppend(out, event);

    if(out.tellp() > maxFileSize) {
        rollover();
    }
}

void
log4cplus::RollingFileAppender::rollover()
{
    // If maxBackups <= 0, then there is no file renaming to be done.
    if(maxBackupIndex > 0) {
        // Delete the oldest file
        std::ostringstream buffer;
        buffer << filename << '.' << maxBackupIndex;
        remove(buffer.str().c_str());

        // Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2}
        for(int i=maxBackupIndex - 1; i >= 1; i--) {
            std::ostringstream source;
            std::ostringstream target;

            source << filename << '.' << i;
            target << filename << '.' << (i+1);
            if(rename(source.str().c_str(), target.str().c_str()) == 0) {
                getLogLog().debug("Renamed file " + source.str() + " to " + target.str());
            }
        }

        // Close the current file
        out.close();
        out.clear(); // reset flags since the C++ standard specified that all the
                     // flags should remain unchanged on a close

        // Rename fileName to fileName.1
        std::string target = filename + ".1";
        getLogLog().debug("Renaming file " + filename + " to " + target);
        rename(filename.c_str(), target.c_str());

        // Open a new file
        out.open(filename.c_str(), std::ios::out | std::ios::trunc);
    }
    else {
        getLogLog().debug(filename + " has no backups specified");
        // Close the current file
        out.close();
        out.clear(); // reset flags since the C++ standard specified that all the
                     // flags should remain unchanged on a close

        // Open it up again in truncation mode
        out.open(filename.c_str(), std::ios::out | std::ios::trunc);
    }
}

<|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: typegroupconverter.hxx,v $
 *
 * $Revision: 1.2 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef OOX_DRAWINGML_CHART_TYPEGROUPCONVERTER_HXX
#define OOX_DRAWINGML_CHART_TYPEGROUPCONVERTER_HXX

#include "oox/drawingml/chart/converterbase.hxx"

namespace com { namespace sun { namespace star {
    namespace chart2 { class XChartType; }
    namespace chart2 { class XCoordinateSystem; }
    namespace chart2 { class XDataSeries; }
    namespace chart2 { class XDiagram; }
    namespace chart2 { namespace data { class XLabeledDataSequence; } }
} } }

namespace oox {
namespace drawingml {
namespace chart {

// ============================================================================

/** Enumerates different chart types. */
enum TypeId
{
    TYPEID_BAR,                     /// Vertical bar chart.
    TYPEID_HORBAR,                  /// Horizontal bar chart.
    TYPEID_LINE,                    /// Line chart.
    TYPEID_AREA,                    /// Area chart.
    TYPEID_STOCK,                   /// Stock chart.
    TYPEID_RADARLINE,               /// Linear radar chart.
    TYPEID_RADARAREA,               /// Filled radar chart.
    TYPEID_PIE,                     /// Pie chart.
    TYPEID_DOUGHNUT,                /// Doughnut (ring) chart.
    TYPEID_OFPIE,                   /// Pie-to-pie or pie-to-bar chart.
    TYPEID_SCATTER,                 /// Scatter (XY) chart.
    TYPEID_BUBBLE,                  /// Bubble chart.
    TYPEID_SURFACE,                 /// Surface chart.
    TYPEID_UNKNOWN                  /// Default for unknown chart types.
};

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

/** Enumerates different categories of similar chart types. */
enum TypeCategory
{
    TYPECATEGORY_BAR,               /// Bar charts (horizontal or vertical).
    TYPECATEGORY_LINE,              /// Line charts (line, area, stock charts).
    TYPECATEGORY_RADAR,             /// Radar charts (linear or filled).
    TYPECATEGORY_PIE,               /// Pie and donut charts.
    TYPECATEGORY_SCATTER,           /// Scatter and bubble charts.
    TYPECATEGORY_SURFACE            /// Surface charts.
};

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

/** Enumerates modes for varying point colors in a series. */
enum VarPointMode
{
    VARPOINTMODE_NONE,              /// No varied colors supported.
    VARPOINTMODE_SINGLE,            /// Only supported, if type group contains only one series.
    VARPOINTMODE_MULTI              /// Supported for multiple series in a chart type group.
};

// ============================================================================

/** Contains info for a chart type related to the OpenOffice.org chart module. */
struct TypeGroupInfo
{
    TypeId              meTypeId;               /// Unique chart type identifier.
    TypeCategory        meTypeCategory;         /// Category this chart type belongs to.
    const sal_Char*     mpcServiceName;         /// Service name of the type.
    VarPointMode        meVarPointMode;         /// Mode for varying point colors.
    bool                mbCombinable2d;         /// True = types can be combined in one axes set.
    bool                mbSupports3d;           /// True = 3D type allowed, false = only 2D type.
    bool                mbWalls3d;              /// True = 3D type includes wall and floor format.
    bool                mbPolarCoordSystem;     /// True = polar, false = cartesian.
    bool                mbSeriesIsFrame2d;      /// True = 2D type series with area formatting.
    bool                mbSeriesIsFrame3d;      /// True = 3D type series with area formatting.
    bool                mbSingleSeriesVis;      /// True = only first series visible (e.g. pie charts).
    bool                mbCategoryAxis;         /// True = X axis contains categories.
    bool                mbSwappedAxesSet;       /// True = X axis and Y axis are swapped.
    bool                mbSupportsStacking;     /// True = data points can be stacked on each other.
    bool                mbReverseSeries;        /// True = insert unstacked series in reverse order.
    bool                mbTicksBetweenCateg;    /// True = X axis ticks between categories.
};

// ============================================================================

struct TypeGroupModel;
struct View3DModel;

class TypeGroupConverter : public ConverterBase< TypeGroupModel >
{
public:
    explicit            TypeGroupConverter( const ConverterRoot& rParent, TypeGroupModel& rModel );
    virtual             ~TypeGroupConverter();

    /** Returns the type info struct that describes this chart type group. */
    inline const TypeGroupInfo& getTypeInfo() const { return maTypeInfo; }

    /** Returns true, if the series in this chart type group are stacked on each other (no percentage). */
    bool                isStacked() const;
    /** Returns true, if the series in this chart type group are stacked on each other as percentage. */
    bool                isPercent() const;
    /** Returns true, if the chart is three-dimensional. */
    bool                is3dChart() const;
    /** Returns true, if chart type supports wall and floor format in 3D mode. */
    bool                isWall3dChart() const;
    /** Returns true, if the series in this chart type group are ordered on the Z axis. */
    bool                isDeep3dChart() const;

    /** Returns true, if this chart type supports area formatting for its series. */
    bool                isSeriesFrameFormat() const;
    /** Returns true, if this chart type has to reverse its series order. */
    bool                isReverseSeries() const;
    /** Returns series title, if the chart type group contains only one single series. */
    ::rtl::OUString     getSingleSeriesTitle() const;

    /** Creates a coordinate system according to the contained chart type. */
    ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XCoordinateSystem >
                        createCoordinateSystem();
    /** Creates a labeled data sequence object for axis categories. */
    ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XLabeledDataSequence >
                        createCategorySequence();

    /** Converts the OOXML type group model into a chart2 coordinate system. */
    void                convertModelToDocument(
                            const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram >& rxDiagram,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XCoordinateSystem >& rxCoordSystem,
                            sal_Int32 nAxesSetIdx );

private:
    /** Inserts the passed series into the chart type. Adds additional properties to the series. */
    void                insertDataSeries(
                            const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& rxChartType,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& rxSeries,
                            sal_Int32 nAxesSetIdx );

private:
    TypeGroupInfo       maTypeInfo;         /// Extended type info for contained chart type model.
    bool                mb3dChart;          /// True = type is a 3D chart type.
};

// ============================================================================

} // namespace chart
} // namespace drawingml
} // namespace oox

#endif

<commit_msg>INTEGRATION: CWS xmlfilter05 (1.1.4); FILE MERGED 2008/05/21 11:40:23 dr 1.1.4.10: #i10000# new header 2008/04/23 15:59:53 dr 1.1.4.9: chart auto formatting, first steps... 2008/04/22 10:46:22 dr 1.1.4.8: conversion helpers 2008/04/21 14:47:57 dr 1.1.4.7: chart data point settings 2008/04/18 12:34:22 dr 1.1.4.6: import stock charts, improved default attribute handling 2008/04/16 13:10:08 dr 1.1.4.5: new optional token handling, fix default rotation in 3d charts 2008/04/16 09:36:45 dr 1.1.4.4: #i88265# import chart 3d view settings 2008/04/02 12:41:48 hbrinkm 1.1.4.3: merged changes from xmlfilter04 to xmlfilter05 2008/04/01 15:37:29 hbrinkm 1.1.4.2: 'Merged xmlfilter04' 2008/02/29 15:27:13 hbrinkm 1.1.4.1: file typegroupconverter.hxx was added on branch cws_dev300_xmlfilter05 on 2008-04-01 15:37:28 +0000<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: typegroupconverter.hxx,v $
 *
 * $Revision: 1.3 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef OOX_DRAWINGML_CHART_TYPEGROUPCONVERTER_HXX
#define OOX_DRAWINGML_CHART_TYPEGROUPCONVERTER_HXX

#include "oox/drawingml/chart/converterbase.hxx"

namespace com { namespace sun { namespace star {
    namespace chart2 { class XChartType; }
    namespace chart2 { class XCoordinateSystem; }
    namespace chart2 { class XDataSeries; }
    namespace chart2 { class XDiagram; }
    namespace chart2 { namespace data { class XLabeledDataSequence; } }
} } }

namespace oox {
namespace drawingml {
namespace chart {

// ============================================================================

/** Enumerates different chart types. */
enum TypeId
{
    TYPEID_BAR,                     /// Vertical bar chart.
    TYPEID_HORBAR,                  /// Horizontal bar chart.
    TYPEID_LINE,                    /// Line chart.
    TYPEID_AREA,                    /// Area chart.
    TYPEID_STOCK,                   /// Stock chart.
    TYPEID_RADARLINE,               /// Linear radar chart.
    TYPEID_RADARAREA,               /// Filled radar chart.
    TYPEID_PIE,                     /// Pie chart.
    TYPEID_DOUGHNUT,                /// Doughnut (ring) chart.
    TYPEID_OFPIE,                   /// Pie-to-pie or pie-to-bar chart.
    TYPEID_SCATTER,                 /// Scatter (XY) chart.
    TYPEID_BUBBLE,                  /// Bubble chart.
    TYPEID_SURFACE,                 /// Surface chart.
    TYPEID_UNKNOWN                  /// Default for unknown chart types.
};

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

/** Enumerates different categories of similar chart types. */
enum TypeCategory
{
    TYPECATEGORY_BAR,               /// Bar charts (horizontal or vertical).
    TYPECATEGORY_LINE,              /// Line charts (line, area, stock charts).
    TYPECATEGORY_RADAR,             /// Radar charts (linear or filled).
    TYPECATEGORY_PIE,               /// Pie and donut charts.
    TYPECATEGORY_SCATTER,           /// Scatter and bubble charts.
    TYPECATEGORY_SURFACE            /// Surface charts.
};

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

/** Enumerates modes for varying point colors in a series. */
enum VarPointMode
{
    VARPOINTMODE_NONE,              /// No varied colors supported.
    VARPOINTMODE_SINGLE,            /// Only supported, if type group contains only one series.
    VARPOINTMODE_MULTI              /// Supported for multiple series in a chart type group.
};

// ============================================================================

/** Contains info for a chart type related to the OpenOffice.org chart module. */
struct TypeGroupInfo
{
    TypeId              meTypeId;               /// Unique chart type identifier.
    TypeCategory        meTypeCategory;         /// Category this chart type belongs to.
    const sal_Char*     mpcServiceName;         /// Service name of the type.
    VarPointMode        meVarPointMode;         /// Mode for varying point colors.
    bool                mbCombinable2d;         /// True = types can be combined in one axes set.
    bool                mbSupports3d;           /// True = 3D type allowed, false = only 2D type.
    bool                mbPolarCoordSystem;     /// True = polar, false = cartesian.
    bool                mbSeriesIsFrame2d;      /// True = 2D type series with area formatting.
    bool                mbSeriesIsFrame3d;      /// True = 3D type series with area formatting.
    bool                mbSingleSeriesVis;      /// True = only first series visible (e.g. pie charts).
    bool                mbCategoryAxis;         /// True = X axis contains categories.
    bool                mbSwappedAxesSet;       /// True = X axis and Y axis are swapped.
    bool                mbSupportsStacking;     /// True = data points can be stacked on each other.
    bool                mbReverseSeries;        /// True = insert unstacked series in reverse order.
    bool                mbTicksBetweenCateg;    /// True = X axis ticks between categories.
};

// ============================================================================

struct UpDownBarsModel;

class UpDownBarsConverter : public ConverterBase< UpDownBarsModel >
{
public:
    explicit            UpDownBarsConverter( const ConverterRoot& rParent, UpDownBarsModel& rModel );
    virtual             ~UpDownBarsConverter();

    /** Converts the OOXML up/down bars. */
    void                convertFromModel(
                            const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& rxChartType );
};

// ============================================================================

struct TypeGroupModel;
struct View3DModel;

class TypeGroupConverter : public ConverterBase< TypeGroupModel >
{
public:
    explicit            TypeGroupConverter( const ConverterRoot& rParent, TypeGroupModel& rModel );
    virtual             ~TypeGroupConverter();

    /** Returns the type info struct that describes this chart type group. */
    inline const TypeGroupInfo& getTypeInfo() const { return maTypeInfo; }

    /** Returns true, if the series in this chart type group are stacked on each other (no percentage). */
    bool                isStacked() const;
    /** Returns true, if the series in this chart type group are stacked on each other as percentage. */
    bool                isPercent() const;
    /** Returns true, if the chart is three-dimensional. */
    bool                is3dChart() const;
    /** Returns true, if chart type supports wall and floor format in 3D mode. */
    bool                isWall3dChart() const;
    /** Returns true, if the series in this chart type group are ordered on the Z axis. */
    bool                isDeep3dChart() const;

    /** Returns true, if this chart type supports area formatting for its series. */
    bool                isSeriesFrameFormat() const;
    /** Returns true, if this chart type has to reverse its series order. */
    bool                isReverseSeries() const;
    /** Returns series title, if the chart type group contains only one single series. */
    ::rtl::OUString     getSingleSeriesTitle() const;

    /** Creates a coordinate system according to the contained chart type. */
    ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XCoordinateSystem >
                        createCoordinateSystem();
    /** Creates a labeled data sequence object for axis categories. */
    ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XLabeledDataSequence >
                        createCategorySequence();

    /** Converts the OOXML type group model into a chart2 coordinate system. */
    void                convertFromModel(
                            const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram >& rxDiagram,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XCoordinateSystem >& rxCoordSystem,
                            sal_Int32 nAxesSetIdx );

    /** Sets the passed OOXML marker style at the passed property set. */
    void                convertMarker( PropertySet& rPropSet, sal_Int32 nOoxSymbol, sal_Int32 nOoxSize ) const;
    /** Sets the passed OOXML line smoothing at the passed property set. */
    void                convertLineSmooth( PropertySet& rPropSet, bool bOoxSmooth ) const;
    /** Sets the passed OOXML bar 3D geometry at the passed property set. */
    void                convertBarGeometry( PropertySet& rPropSet, sal_Int32 nOoxShape ) const;
    /** Sets the passed OOXML pie rotation at the passed property set. */
    void                convertPieRotation( PropertySet& rPropSet, sal_Int32 nOoxAngle ) const;
    /** Sets the passed OOXML pie explosion at the passed property set. */
    void                convertPieExplosion( PropertySet& rPropSet, sal_Int32 nOoxExplosion ) const;

private:
    /** Inserts the passed series into the chart type. Adds additional properties to the series. */
    void                insertDataSeries(
                            const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& rxChartType,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& rxSeries,
                            sal_Int32 nAxesSetIdx );

private:
    TypeGroupInfo       maTypeInfo;         /// Extended type info for contained chart type model.
    bool                mb3dChart;          /// True = type is a 3D chart type.
};

// ============================================================================

} // namespace chart
} // namespace drawingml
} // namespace oox

#endif

<|endoftext|>