<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
/** @file Implement greedy projection triangulation
 */
#include "elm/layers/triangulation.h"

#ifdef __WITH_PCL   // the layer is otherwise implemented as unsupported

#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/features/normal_3d.h>
#include <opencv2/core/eigen.hpp> // for eigen2cv(), must be preceeded definitio of Eigen either PCL or #include <Eigen/Dense>

#include "elm/core/defs.h"
#include "elm/core/exception.h"
#include "elm/core/featuredata.h"
#include "elm/core/graph/adjacency.h"
#include "elm/core/inputname.h"
#include "elm/core/layerconfig.h"
#include "elm/core/signal.h"
#include "elm/ts/layerattr_.h"

using namespace std;
using namespace cv;
using namespace pcl;
using namespace elm;

// initialize paramter keys
const string Triangulation::PARAM_SEARCH_RADIUS        = "radius";
const string Triangulation::PARAM_MU                   = "mu";
const string Triangulation::PARAM_MAX_NN               = "max_nn";
const string Triangulation::PARAM_MAX_SURFACE_ANGLE    = "max_surface_angle";
const string Triangulation::PARAM_MIN_ANGLE            = "min_angle";
const string Triangulation::PARAM_MAX_ANGLE            = "max_angle";
const string Triangulation::PARAM_IS_NORMAL_CONSISTENT = "normal_consistency";

// initialize default float paramter values
const float Triangulation::DEFAULT_SEARCH_RADIUS            = 0.025f;
const float Triangulation::DEFAULT_MU                       = 2.5f;
const float Triangulation::DEFAULT_MAX_SURFACE_ANGLE        = ELM_PI2 / 2.f;
const float Triangulation::DEFAULT_MIN_ANGLE                = CV_PI / 18.f;
const float Triangulation::DEFAULT_MAX_ANGLE                = 2 * CV_PI / 3.f;
const int   Triangulation::DEFAULT_MAX_NN                   = 100;  ///< maximum neighrest neighbors
const bool  Triangulation::DEFAULT_IS_NORMAL_CONSISTENCY    = false;

// initialize I/O names
const string Triangulation::KEY_INPUT_POINT_CLOUD   = "cloud";
const string Triangulation::KEY_OUTPUT_VERTICES     = "vertices";
const string Triangulation::KEY_OUTPUT_OPT_ADJACENCY = "adjacency";

/** @todo why does define guard lead to undefined reference error?
 */
//#ifdef __WITH_GTEST
#include <boost/assign/list_of.hpp>
template <>
elm::MapIONames LayerAttr_<Triangulation>::io_pairs = boost::assign::map_list_of
        ELM_ADD_INPUT_PAIR(Triangulation::KEY_INPUT_POINT_CLOUD)
        ELM_ADD_OUTPUT_PAIR(Triangulation::KEY_OUTPUT_VERTICES)
        ;
//#endif

Triangulation::Triangulation()
    : base_Layer()
{
}

void Triangulation::Clear()
{
    gp3 = pcl::GreedyProjectionTriangulation<pcl::PointNormal>();
}

void Triangulation::Reconfigure(const LayerConfig &cfg)
{
    PTree p = cfg.Params();

    float search_radius     = p.get<float>(PARAM_SEARCH_RADIUS, DEFAULT_SEARCH_RADIUS);

    float mu                = p.get<float>( PARAM_MU,     DEFAULT_MU);
    int max_nn              = p.get<int>(   PARAM_MAX_NN, DEFAULT_MAX_NN);
    float max_surface_angle = p.get<float>( PARAM_MAX_SURFACE_ANGLE, DEFAULT_MAX_SURFACE_ANGLE);
    float min_angle         = p.get<float>( PARAM_MIN_ANGLE, DEFAULT_MIN_ANGLE);
    float max_angle         = p.get<float>( PARAM_MAX_ANGLE, DEFAULT_MAX_ANGLE);
    bool is_normal_consistency = p.get<bool>(PARAM_IS_NORMAL_CONSISTENT, DEFAULT_IS_NORMAL_CONSISTENCY);

    // Set the maximum distance between connected points (maximum edge length)
    gp3.setSearchRadius(search_radius);

    // Set typical values for the parameters
    gp3.setMu(mu);
    gp3.setMaximumNearestNeighbors(max_nn);
    gp3.setMaximumSurfaceAngle(max_surface_angle);
    gp3.setMinimumAngle(min_angle);
    gp3.setMaximumAngle(max_angle);
    gp3.setNormalConsistency(is_normal_consistency);
}

void Triangulation::InputNames(const LayerInputNames &io)
{
    name_src_cloud_ = io.Input(KEY_INPUT_POINT_CLOUD);
}

void Triangulation::OutputNames(const LayerOutputNames &io)
{
    name_vertices_  = io.Output(KEY_OUTPUT_VERTICES);
    name_opt_adj_   = io.OutputOpt(KEY_OUTPUT_OPT_ADJACENCY);
}

void Triangulation::Activate(const Signal &signal)
{
    CloudXYZPtr cld_in = signal.MostRecent(name_src_cloud_).get<CloudXYZPtr>();
    if(cld_in->empty()) {

        ELM_THROW_BAD_DIMS("Cannot Activate Triangulation layer with empty input point cloud.");
    }

    // Normal estimation*
    NormalEstimation<PointXYZ, Normal> norml_est;
    PointCloud<Normal>::Ptr normals(new PointCloud<Normal>);
    search::KdTree<PointXYZ>::Ptr tree(new search::KdTree<PointXYZ>);

    tree->setInputCloud(cld_in);
    norml_est.setInputCloud(cld_in);
    norml_est.setSearchMethod(tree);
    norml_est.setKSearch(20);
    norml_est.compute(*normals);
    //* normals should now contain the point normals + surface curvatures

    // Concatenate the XYZ and normal fields*
    PointCloud<PointNormal>::Ptr cloud_with_normals(new PointCloud<PointNormal>);
    concatenateFields(*cld_in, *normals, *cloud_with_normals);
    //* cloud_with_normals = cloud + normals

    // Create search tree*
    search::KdTree<PointNormal>::Ptr tree2(new search::KdTree<PointNormal>);
    tree2->setInputCloud(cloud_with_normals);

    // Get result
    gp3.setInputCloud(cloud_with_normals);
    gp3.setSearchMethod(tree2);

    // PolygonMesh triangles;
    // gp3.reconstruct(triangles);

    std::vector<Vertices > vertices;
    gp3.reconstruct(vertices);

    vertices_ = VecVertices2Mat(vertices, false);

    if(name_opt_adj_) {

        TriangulatedCloudToAdjacency(cld_in, vertices, adj_);
    }
}

void Triangulation::Response(Signal &signal)
{
    // Additional vertex information
//    vector<int> parts = gp3.getPartIDs();
//    vector<int> states = gp3.getPointStates();

    signal.Append(name_vertices_, vertices_);

    if(name_opt_adj_) {

        signal.Append(name_opt_adj_.get(), adj_);
    }
}

#endif // __WITH_PCL
<commit_msg>remove unused includes and reuce code clutter<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
/** @file Implement greedy projection triangulation
 */
#include "elm/layers/triangulation.h"

#ifdef __WITH_PCL   // the layer is otherwise implemented as unsupported

#include <pcl/point_types.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/features/normal_3d.h>
//#include <opencv2/core/eigen.hpp>   // for eigen2cv(), must be preceeded definitio of Eigen either PCL or #include <Eigen/Dense>

#include "elm/core/defs.h"          // ELM_PI2
#include "elm/core/exception.h"
#include "elm/core/featuredata.h"
#include "elm/core/graph/adjacency.h"
#include "elm/core/inputname.h"
#include "elm/core/layerconfig.h"
#include "elm/core/signal.h"
#include "elm/ts/layerattr_.h"

using namespace std;
using namespace cv;
using namespace pcl;
using namespace elm;

// initialize paramter keys
const string Triangulation::PARAM_SEARCH_RADIUS        = "radius";
const string Triangulation::PARAM_MU                   = "mu";
const string Triangulation::PARAM_MAX_NN               = "max_nn";
const string Triangulation::PARAM_MAX_SURFACE_ANGLE    = "max_surface_angle";
const string Triangulation::PARAM_MIN_ANGLE            = "min_angle";
const string Triangulation::PARAM_MAX_ANGLE            = "max_angle";
const string Triangulation::PARAM_IS_NORMAL_CONSISTENT = "normal_consistency";

// initialize default float paramter values
const float Triangulation::DEFAULT_SEARCH_RADIUS            = 0.025f;
const float Triangulation::DEFAULT_MU                       = 2.5f;
const float Triangulation::DEFAULT_MAX_SURFACE_ANGLE        = ELM_PI2 / 2.f;
const float Triangulation::DEFAULT_MIN_ANGLE                = CV_PI / 18.f;
const float Triangulation::DEFAULT_MAX_ANGLE                = 2 * CV_PI / 3.f;
const int   Triangulation::DEFAULT_MAX_NN                   = 100;  ///< maximum neighrest neighbors
const bool  Triangulation::DEFAULT_IS_NORMAL_CONSISTENCY    = false;

// initialize I/O names
const string Triangulation::KEY_INPUT_POINT_CLOUD   = "cloud";
const string Triangulation::KEY_OUTPUT_VERTICES     = "vertices";
const string Triangulation::KEY_OUTPUT_OPT_ADJACENCY = "adjacency";

#include <boost/assign/list_of.hpp>
template <>
elm::MapIONames LayerAttr_<Triangulation>::io_pairs = boost::assign::map_list_of
        ELM_ADD_INPUT_PAIR(Triangulation::KEY_INPUT_POINT_CLOUD)
        ELM_ADD_OUTPUT_PAIR(Triangulation::KEY_OUTPUT_VERTICES)
        ;

Triangulation::Triangulation()
    : base_Layer()
{
}

void Triangulation::Clear()
{
    gp3 = pcl::GreedyProjectionTriangulation<pcl::PointNormal>();
}

void Triangulation::Reconfigure(const LayerConfig &cfg)
{
    PTree p = cfg.Params();

    float search_radius     = p.get<float>(PARAM_SEARCH_RADIUS, DEFAULT_SEARCH_RADIUS);

    float mu                = p.get<float>( PARAM_MU,     DEFAULT_MU);
    int max_nn              = p.get<int>(   PARAM_MAX_NN, DEFAULT_MAX_NN);
    float max_surface_angle = p.get<float>( PARAM_MAX_SURFACE_ANGLE, DEFAULT_MAX_SURFACE_ANGLE);
    float min_angle         = p.get<float>( PARAM_MIN_ANGLE, DEFAULT_MIN_ANGLE);
    float max_angle         = p.get<float>( PARAM_MAX_ANGLE, DEFAULT_MAX_ANGLE);
    bool is_normal_consistency = p.get<bool>(PARAM_IS_NORMAL_CONSISTENT, DEFAULT_IS_NORMAL_CONSISTENCY);

    // Set the maximum distance between connected points (maximum edge length)
    gp3.setSearchRadius(search_radius);

    // Set typical values for the parameters
    gp3.setMu(mu);
    gp3.setMaximumNearestNeighbors(max_nn);
    gp3.setMaximumSurfaceAngle(max_surface_angle);
    gp3.setMinimumAngle(min_angle);
    gp3.setMaximumAngle(max_angle);
    gp3.setNormalConsistency(is_normal_consistency);
}

void Triangulation::InputNames(const LayerInputNames &io)
{
    name_src_cloud_ = io.Input(KEY_INPUT_POINT_CLOUD);
}

void Triangulation::OutputNames(const LayerOutputNames &io)
{
    name_vertices_  = io.Output(KEY_OUTPUT_VERTICES);
    name_opt_adj_   = io.OutputOpt(KEY_OUTPUT_OPT_ADJACENCY);
}

void Triangulation::Activate(const Signal &signal)
{
    CloudXYZPtr cld_in = signal.MostRecent(name_src_cloud_).get<CloudXYZPtr>();
    if(cld_in->empty()) {

        ELM_THROW_BAD_DIMS("Cannot Activate Triangulation layer with empty input point cloud.");
    }

    // Normal estimation
    NormalEstimation<PointXYZ, Normal> norml_est;
    PointCloud<Normal>::Ptr normals(new PointCloud<Normal>);
    search::KdTree<PointXYZ>::Ptr tree(new search::KdTree<PointXYZ>);

    tree->setInputCloud(cld_in);
    norml_est.setInputCloud(cld_in);
    norml_est.setSearchMethod(tree);
    norml_est.setKSearch(20);
    norml_est.compute(*normals);
    // normals should now contain the point normals + surface curvatures

    // Concatenate the XYZ and normal fields*
    PointCloud<PointNormal>::Ptr cloud_with_normals(new PointCloud<PointNormal>);
    concatenateFields(*cld_in, *normals, *cloud_with_normals);

    // Create search tree*
    search::KdTree<PointNormal>::Ptr tree2(new search::KdTree<PointNormal>);
    tree2->setInputCloud(cloud_with_normals);

    // Get result
    gp3.setInputCloud(cloud_with_normals);
    gp3.setSearchMethod(tree2);

    std::vector<Vertices > vertices;
    gp3.reconstruct(vertices);

    vertices_ = VecVertices2Mat(vertices, false);

    if(name_opt_adj_) {

        TriangulatedCloudToAdjacency(cld_in, vertices, adj_);
    }
}

void Triangulation::Response(Signal &signal)
{
    // Additional vertex information
//    vector<int> parts = gp3.getPartIDs();
//    vector<int> states = gp3.getPointStates();

    signal.Append(name_vertices_, vertices_);

    if(name_opt_adj_) {

        signal.Append(name_opt_adj_.get(), adj_);
    }
}

#endif // __WITH_PCL
<|endoftext|>


<commit_before>// System Dependencies
#include <windows.h>
#include <exdisp.h>

// External Dependencies
#include "../../core/include/spinlock.h"
#include "../../core/include/system.h"

// Module Dependencies
#include "componentadapterproperties.h"
#include "../include/componentadapter.h"
#include "../include/webview.h"

namespace native
{
	namespace ui
	{
		class Win32WebViewAdapter : public WebViewAdapter, public IOleClientSite, public IOleInPlaceSite
		{
		public:
			// Constructor
			Win32WebViewAdapter(WebView* view, HWND hwnd);
			~Win32WebViewAdapter();

			// Helper Functions
			void setSize(const Size& size);
			virtual void navigate(const String& url) override;
			virtual void goBack() override;
			virtual void goForward() override;

			// IUnknown Functions
			virtual HRESULT QueryInterface(REFIID riid, void** ppvObject) override;
			virtual ULONG AddRef()  override { return 1; }	// Unneeded
			virtual ULONG Release() override { return 1; }	// Unneeded

			// IOleClientSite Functions
			virtual HRESULT SaveObject() override { return E_NOTIMPL; }
			virtual HRESULT GetMoniker(DWORD dwAssign, DWORD dwWhichMoniker, IMoniker** ppmk) override { return E_NOTIMPL; }
			virtual HRESULT GetContainer(IOleContainer** ppContainer) override { return E_NOINTERFACE; }
			virtual HRESULT ShowObject() override { return S_OK; }
			virtual HRESULT OnShowWindow(BOOL fShow) override { return E_NOTIMPL; }
			virtual HRESULT RequestNewObjectLayout() override { return E_NOTIMPL; }

			// IOleWindow Functions
			virtual HRESULT GetWindow(HWND* phwnd) override;
			virtual HRESULT ContextSensitiveHelp(BOOL fEnterMode) override { return E_NOTIMPL; }

			// IOleInPlaceSite Functions
			virtual HRESULT CanInPlaceActivate() override { return S_OK; }
			virtual HRESULT OnInPlaceActivate()  override { return S_OK; }
			virtual HRESULT OnUIActivate() override { return S_OK; }
			virtual HRESULT GetWindowContext(IOleInPlaceFrame** ppFrame, IOleInPlaceUIWindow** ppDoc, LPRECT lprcPosRect, LPRECT lprcClipRect, LPOLEINPLACEFRAMEINFO lpFrameInfo) override;
			virtual HRESULT Scroll(SIZE scrollExtant) override { return E_NOTIMPL; }
			virtual HRESULT OnUIDeactivate(BOOL fUndoable) override { return S_OK; }
			virtual HRESULT OnInPlaceDeactivate() override { return S_OK; }
			virtual HRESULT DiscardUndoState() override { return E_NOTIMPL; }
			virtual HRESULT DeactivateAndUndo() override { return E_NOTIMPL; }
			virtual HRESULT OnPosRectChange(LPCRECT lprcPosRect) override;

			// Instance Variables
			IStorage*   storage;
			IOleObject* webObject;
			HWND        hwnd;
		};

		/*
			WebView Functions
		 */

		WebView::WebView() : Component(new WebViewAdapter(this))
		{
			setAlignment(Align::Fill);
		}

		void WebView::navigate(const String& url)
		{
			((WebViewAdapter*) getAdapter())->navigate(url);
		}

		void WebView::goBack()
		{
			((WebViewAdapter*) getAdapter())->goBack();
		}

		void WebView::goForward()
		{
			((WebViewAdapter*) getAdapter())->goForward();
		}

		void WebView::onSize(const Size& size)
		{
			((Win32WebViewAdapter*) getAdapter())->setSize(size);
		}

		/*
			WebViewAdapter Functions
		*/

		WebViewAdapter::WebViewAdapter(WebView* view) : ComponentAdapter({ view, nullptr, WS_CHILD | WS_VISIBLE, 0 })
		{
		}

		WebViewAdapter::~WebViewAdapter()
		{
		}

		void WebViewAdapter::navigate(const String& url)
		{
			// Always overridden.
			throw NotSupportedException();
		}

		void WebViewAdapter::goBack()
		{
			// Always overridden.
			throw NotSupportedException();
		}

		void WebViewAdapter::goForward()
		{
			// Always overridden.
			throw NotSupportedException();
		}

		/*
			BrowserData Functions
		*/

		Win32WebViewAdapter::Win32WebViewAdapter(WebView* view, HWND hwnd) : WebViewAdapter(view), hwnd(hwnd)
		{
			static bool isOleInitialized = false;
			static SpinLock lock;

			lock.lock();

			if (!isOleInitialized)
			{
				// Initialise the ActiveX environment.
				isOleInitialized = true;
				::OleInitialize(NULL);
				System::onExit([]() { ::OleUninitialize(); });

				// Get the current process name.
				// TODO: Make this a function elsewhere.
				WCHAR buffer[MAX_PATH + 1];
				::GetModuleFileName(NULL, buffer, sizeof(buffer));
				String fileName = buffer;
				fileName = fileName.substring(fileName.lastIndexOf(L"\\") + 1, fileName.getLength());

				// Ensure we're using a decent browser version.
				HKEY browserEmulationKey;
				DWORD ieVersion = 11000;	// IE11 pretty please.
				::RegOpenKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", 0, KEY_WRITE, &browserEmulationKey);
				::RegSetValueEx(browserEmulationKey, fileName.toArray(), 0, REG_DWORD, (BYTE*) &ieVersion, sizeof(ieVersion));
				::RegCloseKey(browserEmulationKey);
			}

			lock.release();

			// Create the ActiveX container.
			if (FAILED(::StgCreateStorageEx(NULL, STGM_READWRITE | STGM_SHARE_EXCLUSIVE | STGM_DIRECT | STGM_CREATE | STGM_DELETEONRELEASE, STGFMT_STORAGE, 0, NULL, NULL, IID_IStorage, (void**)&storage)))
				throw UserInterfaceException("Failed to create ActiveX browser component.");

			if (FAILED(::OleCreate(CLSID_WebBrowser, IID_IOleObject, OLERENDER_DRAW, NULL, this, storage, (LPVOID*) &webObject)))
				throw UserInterfaceException("Failed to create ActiveX browser component.");

			// Embed the ActiveX container in our Component.
			RECT rect = { 0 };
			::OleSetContainedObject(webObject, TRUE);
			webObject->DoVerb(OLEIVERB_INPLACEACTIVATE, NULL, this, -1, hwnd, &rect);
		}

		Win32WebViewAdapter::~Win32WebViewAdapter()
		{
			if (storage)   storage->Release();
			if (webObject) webObject->Release();
		}

		void Win32WebViewAdapter::setSize(const Size& size)
		{
			IWebBrowser2* browser = nullptr;

			webObject->QueryInterface(IID_IWebBrowser2, (void**) &browser);

			browser->put_Width(size.width);
			browser->put_Height(size.height);

			browser->Release();
		}

		void Win32WebViewAdapter::navigate(const String& url)
		{
			IWebBrowser2* browser = nullptr;
			webObject->QueryInterface(IID_IWebBrowser2, (void**) &browser);

			VARIANT vurl, vempty;

			vempty.vt = VT_EMPTY;
			vurl.vt   = VT_BSTR;
			vurl.bstrVal = ::SysAllocString(url.toArray());

			browser->Navigate2(&vurl, &vempty, &vempty, &vempty, &vempty);

			browser->Release();
			::SysFreeString(vurl.bstrVal);
		}

		void Win32WebViewAdapter::goBack()
		{
			IWebBrowser2* browser = nullptr;
			webObject->QueryInterface(IID_IWebBrowser2, (void**) &browser);

			browser->GoBack();

			browser->Release();
		}

		void Win32WebViewAdapter::goForward()
		{
			IWebBrowser2* browser = nullptr;
			webObject->QueryInterface(IID_IWebBrowser2, (void**) &browser);

			browser->GoForward();

			browser->Release();
		}

		HRESULT Win32WebViewAdapter::QueryInterface(REFIID riid, void** ppvObject)
		{
			if (riid == IID_IUnknown || riid == IID_IOleClientSite)
			{
				*ppvObject = (IOleClientSite*) this;
			}
			else if (riid == IID_IOleInPlaceSite)
			{
				*ppvObject = (IOleInPlaceSite*) this;
			}
			else
			{
				*ppvObject = NULL;
				return E_NOINTERFACE;
			}

			AddRef();
			return S_OK;
		}

		HRESULT Win32WebViewAdapter::GetWindow(HWND* phwnd)
		{
			*phwnd = hwnd;
			return S_OK;
		}

		HRESULT Win32WebViewAdapter::GetWindowContext(IOleInPlaceFrame** ppFrame, IOleInPlaceUIWindow** ppDoc, LPRECT lprcPosRect, LPRECT lprcClipRect, LPOLEINPLACEFRAMEINFO lpFrameInfo)
		{
			*ppFrame = NULL;
			*ppDoc = NULL;
			*lprcPosRect = { 0 };
			*lprcClipRect = *lprcPosRect;

			lpFrameInfo->fMDIApp = FALSE;
			lpFrameInfo->hwndFrame = hwnd;
			lpFrameInfo->cAccelEntries = 0;

			return S_OK;
		}

		HRESULT Win32WebViewAdapter::OnPosRectChange(LPCRECT lprcPosRect)
		{
			IOleInPlaceObject* place = nullptr;

			webObject->QueryInterface(IID_IOleInPlaceObject, (void**) &place);

			place->SetObjectRects(lprcPosRect, lprcPosRect);

			place->Release();

			return S_OK;
		}
	}
}

<commit_msg>Oops. Compile fix.<commit_after>// System Dependencies
#include <windows.h>
#include <exdisp.h>

// External Dependencies
#include "../../core/include/spinlock.h"
#include "../../core/include/system.h"

// Module Dependencies
#include "componentadapterproperties.h"
#include "../include/componentadapter.h"
#include "../include/webview.h"

namespace native
{
	namespace ui
	{
		class Win32WebViewAdapter : public WebViewAdapter, public IOleClientSite, public IOleInPlaceSite
		{
		public:
			// Constructor
			Win32WebViewAdapter(WebView* view);
			~Win32WebViewAdapter();

			// Helper Functions
			void setSize(const Size& size);
			virtual void navigate(const String& url) override;
			virtual void goBack() override;
			virtual void goForward() override;

			// IUnknown Functions
			virtual HRESULT QueryInterface(REFIID riid, void** ppvObject) override;
			virtual ULONG AddRef()  override { return 1; }	// Unneeded
			virtual ULONG Release() override { return 1; }	// Unneeded

			// IOleClientSite Functions
			virtual HRESULT SaveObject() override { return E_NOTIMPL; }
			virtual HRESULT GetMoniker(DWORD dwAssign, DWORD dwWhichMoniker, IMoniker** ppmk) override { return E_NOTIMPL; }
			virtual HRESULT GetContainer(IOleContainer** ppContainer) override { return E_NOINTERFACE; }
			virtual HRESULT ShowObject() override { return S_OK; }
			virtual HRESULT OnShowWindow(BOOL fShow) override { return E_NOTIMPL; }
			virtual HRESULT RequestNewObjectLayout() override { return E_NOTIMPL; }

			// IOleWindow Functions
			virtual HRESULT GetWindow(HWND* phwnd) override;
			virtual HRESULT ContextSensitiveHelp(BOOL fEnterMode) override { return E_NOTIMPL; }

			// IOleInPlaceSite Functions
			virtual HRESULT CanInPlaceActivate() override { return S_OK; }
			virtual HRESULT OnInPlaceActivate()  override { return S_OK; }
			virtual HRESULT OnUIActivate() override { return S_OK; }
			virtual HRESULT GetWindowContext(IOleInPlaceFrame** ppFrame, IOleInPlaceUIWindow** ppDoc, LPRECT lprcPosRect, LPRECT lprcClipRect, LPOLEINPLACEFRAMEINFO lpFrameInfo) override;
			virtual HRESULT Scroll(SIZE scrollExtant) override { return E_NOTIMPL; }
			virtual HRESULT OnUIDeactivate(BOOL fUndoable) override { return S_OK; }
			virtual HRESULT OnInPlaceDeactivate() override { return S_OK; }
			virtual HRESULT DiscardUndoState() override { return E_NOTIMPL; }
			virtual HRESULT DeactivateAndUndo() override { return E_NOTIMPL; }
			virtual HRESULT OnPosRectChange(LPCRECT lprcPosRect) override;

			// Instance Variables
			IStorage*   storage;
			IOleObject* webObject;
			HWND        hwnd;
		};

		/*
			WebView Functions
		 */

		WebView::WebView() : Component(new Win32WebViewAdapter(this))
		{
			setAlignment(Align::Fill);
		}

		void WebView::navigate(const String& url)
		{
			((WebViewAdapter*) getAdapter())->navigate(url);
		}

		void WebView::goBack()
		{
			((WebViewAdapter*) getAdapter())->goBack();
		}

		void WebView::goForward()
		{
			((WebViewAdapter*) getAdapter())->goForward();
		}

		void WebView::onSize(const Size& size)
		{
			((Win32WebViewAdapter*) getAdapter())->setSize(size);
		}

		/*
			WebViewAdapter Functions
		*/

		WebViewAdapter::WebViewAdapter(WebView* view) : ComponentAdapter({ view, nullptr, WS_CHILD | WS_VISIBLE, 0 })
		{
		}

		WebViewAdapter::~WebViewAdapter()
		{
		}

		void WebViewAdapter::navigate(const String& url)
		{
			// Always overridden.
			throw NotSupportedException();
		}

		void WebViewAdapter::goBack()
		{
			// Always overridden.
			throw NotSupportedException();
		}

		void WebViewAdapter::goForward()
		{
			// Always overridden.
			throw NotSupportedException();
		}

		/*
			BrowserData Functions
		*/

		Win32WebViewAdapter::Win32WebViewAdapter(WebView* view) : WebViewAdapter(view), hwnd(HWND(getHandle()))
		{
			static bool isOleInitialized = false;
			static SpinLock lock;

			lock.lock();

			if (!isOleInitialized)
			{
				// Initialise the ActiveX environment.
				isOleInitialized = true;
				::OleInitialize(NULL);
				System::onExit([]() { ::OleUninitialize(); });

				// Get the current process name.
				// TODO: Make this a function elsewhere.
				WCHAR buffer[MAX_PATH + 1];
				::GetModuleFileName(NULL, buffer, sizeof(buffer));
				String fileName = buffer;
				fileName = fileName.substring(fileName.lastIndexOf(L"\\") + 1, fileName.getLength());

				// Ensure we're using a decent browser version.
				HKEY browserEmulationKey;
				DWORD ieVersion = 11000;	// IE11 pretty please.
				::RegOpenKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", 0, KEY_WRITE, &browserEmulationKey);
				::RegSetValueEx(browserEmulationKey, fileName.toArray(), 0, REG_DWORD, (BYTE*) &ieVersion, sizeof(ieVersion));
				::RegCloseKey(browserEmulationKey);
			}

			lock.release();

			// Create the ActiveX container.
			if (FAILED(::StgCreateStorageEx(NULL, STGM_READWRITE | STGM_SHARE_EXCLUSIVE | STGM_DIRECT | STGM_CREATE | STGM_DELETEONRELEASE, STGFMT_STORAGE, 0, NULL, NULL, IID_IStorage, (void**)&storage)))
				throw UserInterfaceException("Failed to create ActiveX browser component.");

			if (FAILED(::OleCreate(CLSID_WebBrowser, IID_IOleObject, OLERENDER_DRAW, NULL, this, storage, (LPVOID*) &webObject)))
				throw UserInterfaceException("Failed to create ActiveX browser component.");

			// Embed the ActiveX container in our Component.
			RECT rect = { 0 };
			::OleSetContainedObject(webObject, TRUE);
			webObject->DoVerb(OLEIVERB_INPLACEACTIVATE, NULL, this, -1, hwnd, &rect);
		}

		Win32WebViewAdapter::~Win32WebViewAdapter()
		{
			if (storage)   storage->Release();
			if (webObject) webObject->Release();
		}

		void Win32WebViewAdapter::setSize(const Size& size)
		{
			IWebBrowser2* browser = nullptr;

			webObject->QueryInterface(IID_IWebBrowser2, (void**) &browser);

			browser->put_Width(size.width);
			browser->put_Height(size.height);

			browser->Release();
		}

		void Win32WebViewAdapter::navigate(const String& url)
		{
			IWebBrowser2* browser = nullptr;
			webObject->QueryInterface(IID_IWebBrowser2, (void**) &browser);

			VARIANT vurl, vempty;

			vempty.vt = VT_EMPTY;
			vurl.vt   = VT_BSTR;
			vurl.bstrVal = ::SysAllocString(url.toArray());

			browser->Navigate2(&vurl, &vempty, &vempty, &vempty, &vempty);

			browser->Release();
			::SysFreeString(vurl.bstrVal);
		}

		void Win32WebViewAdapter::goBack()
		{
			IWebBrowser2* browser = nullptr;
			webObject->QueryInterface(IID_IWebBrowser2, (void**) &browser);

			browser->GoBack();

			browser->Release();
		}

		void Win32WebViewAdapter::goForward()
		{
			IWebBrowser2* browser = nullptr;
			webObject->QueryInterface(IID_IWebBrowser2, (void**) &browser);

			browser->GoForward();

			browser->Release();
		}

		HRESULT Win32WebViewAdapter::QueryInterface(REFIID riid, void** ppvObject)
		{
			if (riid == IID_IUnknown || riid == IID_IOleClientSite)
			{
				*ppvObject = (IOleClientSite*) this;
			}
			else if (riid == IID_IOleInPlaceSite)
			{
				*ppvObject = (IOleInPlaceSite*) this;
			}
			else
			{
				*ppvObject = NULL;
				return E_NOINTERFACE;
			}

			AddRef();
			return S_OK;
		}

		HRESULT Win32WebViewAdapter::GetWindow(HWND* phwnd)
		{
			*phwnd = hwnd;
			return S_OK;
		}

		HRESULT Win32WebViewAdapter::GetWindowContext(IOleInPlaceFrame** ppFrame, IOleInPlaceUIWindow** ppDoc, LPRECT lprcPosRect, LPRECT lprcClipRect, LPOLEINPLACEFRAMEINFO lpFrameInfo)
		{
			*ppFrame = NULL;
			*ppDoc = NULL;
			*lprcPosRect = { 0 };
			*lprcClipRect = *lprcPosRect;

			lpFrameInfo->fMDIApp = FALSE;
			lpFrameInfo->hwndFrame = hwnd;
			lpFrameInfo->cAccelEntries = 0;

			return S_OK;
		}

		HRESULT Win32WebViewAdapter::OnPosRectChange(LPCRECT lprcPosRect)
		{
			IOleInPlaceObject* place = nullptr;

			webObject->QueryInterface(IID_IOleInPlaceObject, (void**) &place);

			place->SetObjectRects(lprcPosRect, lprcPosRect);

			place->Release();

			return S_OK;
		}
	}
}

<|endoftext|>


<commit_before>#include "../unicode/utfconv.h"

#include <cstring>

#include "cppunit-header.h"

const char * string_utf8
  = u8"a\u5916\u56FD\u8A9E\u306E\u5B66\u7FD2\u3068\u6559\u6388"
      "\U0010FF00  \U00011111 \U0010FFFF";

const char16_t * string_utf16
  = u"a\u5916\u56FD\u8A9E\u306E\u5B66\u7FD2\u3068\u6559\u6388"
     "\U0010FF00  \U00011111 \U0010FFFF";

const char32_t * string_utf32
  = U"a\u5916\u56FD\u8A9E\u306E\u5B66\u7FD2\u3068\u6559\u6388"
     "\U0010FF00  \U00011111 \U0010FFFF";

class Test_Unicode : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(Test_Unicode);
	CPPUNIT_TEST(testStuff<char>);
	CPPUNIT_TEST(testStuff<wchar_t>);
	CPPUNIT_TEST(testStuff<char32_t>);
	CPPUNIT_TEST_SUITE_END();

	typedef std::codecvt_base::result result;

	template <class CHAR_T = char32_t, unsigned int limit = 0x10FFFF>
	void testStuff()
	{
#if 0
		static_assert(std::numeric_limits<CHAR_T>::max() >= limit,
		              "Upper limit for char values must be less "
		              "than charater type max");
#endif
		CHAR_T wc[4];
		char nc[8];

		const CHAR_T * last_in = nullptr;
		char * last_out = nullptr;
		codecvt_utf8<CHAR_T, limit> cnv;

		for (wc[0] = 0;
		     static_cast<unsigned int>(wc[0]) < (limit + 1); ++wc[0])
		{
			if (config::verbose && ((wc[0] & 0xFFFF) == 0))
				printf("Processing plane 0x%08x\n", wc[0]);

			std::mbstate_t mbs = std::mbstate_t();
			memset(nc, 0, 8);
			result r = cnv.out(mbs, wc, wc + 1, last_in, nc, nc + 8, last_out);

			CPPUNIT_ASSERT(  r == std::codecvt_base::ok
			              || (r == std::codecvt_base::noconv
			                 && std::is_same<CHAR_T, char>::value));
			CPPUNIT_ASSERT(mbs.__count == 0);

			const char * last_in2 = nullptr;
			CHAR_T * last_out2 = nullptr;
			memset(&mbs, 0, sizeof(mbs));

			r = cnv.in(mbs, nc, last_out, last_in2, wc + 1, wc + 2, last_out2);

			CPPUNIT_ASSERT(  r == std::codecvt_base::ok
			              || (r == std::codecvt_base::noconv
			                 && std::is_same<CHAR_T, char>::value));

			if (r != std::codecvt_base::noconv)
				CPPUNIT_ASSERT(wc[0] == wc[1]);

			CPPUNIT_ASSERT(mbs.__count == 0);

			if (wc[0] == std::numeric_limits<CHAR_T>::max())
				break;
		}
	}
};
CPPUNIT_TEST_SUITE_REGISTRATION(Test_Unicode);
<commit_msg>Adding tests for trivial functions<commit_after>#include "../unicode/utfconv.h"

#include <cstring>

#include "cppunit-header.h"

const char * string_utf8
  = u8"a\u5916\u56FD\u8A9E\u306E\u5B66\u7FD2\u3068\u6559\u6388"
      "\U0010FF00  \U00011111 \U0010FFFF";

const char16_t * string_utf16
  = u"a\u5916\u56FD\u8A9E\u306E\u5B66\u7FD2\u3068\u6559\u6388"
     "\U0010FF00  \U00011111 \U0010FFFF";

const char32_t * string_utf32
  = U"a\u5916\u56FD\u8A9E\u306E\u5B66\u7FD2\u3068\u6559\u6388"
     "\U0010FF00  \U00011111 \U0010FFFF";

class Test_Unicode : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(Test_Unicode);
	CPPUNIT_TEST(trivialTests<char>);
	CPPUNIT_TEST(trivialTests<wchar_t>);
	CPPUNIT_TEST(trivialTests<char32_t>);

	CPPUNIT_TEST(testStuff<char>);
	CPPUNIT_TEST(testStuff<wchar_t>);
	CPPUNIT_TEST(testStuff<char32_t>);
	CPPUNIT_TEST_SUITE_END();

	typedef std::codecvt_base::result result;

	template <class CHAR_T = char32_t, unsigned int limit = 0x10FFFF>
	void trivialTests()
	{
		codecvt_utf8<CHAR_T, limit> cnv;
		if (std::is_same<CHAR_T, char>::value)
			CPPUNIT_ASSERT(cnv.encoding() == 1);
		else
			CPPUNIT_ASSERT(cnv.encoding() == 0);
	}

	template <class CHAR_T = char32_t, unsigned int limit = 0x10FFFF>
	void testStuff()
	{
		CHAR_T wc[4];
		char nc[8];

		const CHAR_T * last_in = nullptr;
		char * last_out = nullptr;
		codecvt_utf8<CHAR_T, limit> cnv;

		for (wc[0] = 0;
		     static_cast<unsigned int>(wc[0]) < (limit + 1); ++wc[0])
		{
			if (config::verbose && ((wc[0] & 0xFFFF) == 0))
				printf("Processing plane 0x%08x\n", wc[0]);

			std::mbstate_t mbs;

			memset(&mbs, 0, sizeof(mbs));
			memset(nc, 0, 8);
			result r = cnv.out(mbs, wc, wc + 1, last_in, nc, nc + 8, last_out);

			CPPUNIT_ASSERT(  r == std::codecvt_base::ok
			              || (r == std::codecvt_base::noconv
			                 && std::is_same<CHAR_T, char>::value));
			CPPUNIT_ASSERT(mbs.__count == 0);

			const char * last_in2 = nullptr;
			CHAR_T * last_out2 = nullptr;
			memset(&mbs, 0, sizeof(mbs));
			int len = cnv.length(mbs, nc, last_out, 20);

			memset(&mbs, 0, sizeof(mbs));

			r = cnv.in(mbs, nc, last_out, last_in2, wc + 1, wc + 2, last_out2);

			CPPUNIT_ASSERT(len == (last_in2 - nc));

			CPPUNIT_ASSERT(  r == std::codecvt_base::ok
			              || (r == std::codecvt_base::noconv
			                 && std::is_same<CHAR_T, char>::value));

			if (r != std::codecvt_base::noconv)
				CPPUNIT_ASSERT(wc[0] == wc[1]);

			CPPUNIT_ASSERT(mbs.__count == 0);

			if (wc[0] == std::numeric_limits<CHAR_T>::max())
				break;
		}
	}
};
CPPUNIT_TEST_SUITE_REGISTRATION(Test_Unicode);
<|endoftext|>


<commit_before>/*
 * Functions for working with relative URIs.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef BENG_URI_RELATIVE_HXX
#define BENG_URI_RELATIVE_HXX

struct StringView;

/**
 * Check if an (absolute) URI is relative to an a base URI (also
 * absolute), and return the relative part.  Returns NULL if both URIs
 * do not match.
 */
StringView
uri_relative(StringView base, StringView uri);

#endif
<commit_msg>uri/relative: add "pure" attribute<commit_after>/*
 * Functions for working with relative URIs.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef BENG_URI_RELATIVE_HXX
#define BENG_URI_RELATIVE_HXX

#include <inline/compiler.h>

struct StringView;

/**
 * Check if an (absolute) URI is relative to an a base URI (also
 * absolute), and return the relative part.  Returns NULL if both URIs
 * do not match.
 */
gcc_pure
StringView
uri_relative(StringView base, StringView uri);

#endif
<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

=========================================================================*/
#ifdef _MSC_VER
#pragma warning ( disable : 4786 )
#endif

#include "otbImageIOFactory.h"
#include "itkMutexLock.h"
#include "itkMutexLockHolder.h"

#include "otbONERAImageIOFactory.h"
#include "otbMSTARImageIOFactory.h"
#include "otbGDALImageIOFactory.h"
#include "otbLUMImageIOFactory.h"
#include "otbBSQImageIOFactory.h"
#ifndef OTB_JPEG2000_DISABLED
#include "otbJPEG2000ImageIOFactory.h"
#endif
#ifdef OTB_USE_CURL
#include "otbTileMapImageIOFactory.h"
#endif

namespace otb
{

  itk::ImageIOBase::Pointer
      ImageIOFactory::CreateImageIO(const char* path, FileModeType mode)
      {

        RegisterBuiltInFactories();
        return (Superclass::CreateImageIO(path,mode) );

      }

      void
          ImageIOFactory::RegisterBuiltInFactories()
      {
        static bool firstTime = true;

        static itk::SimpleMutexLock mutex;
        {
                // This helper class makes sure the Mutex is unlocked
                // in the event an exception is thrown.
          itk::MutexLockHolder<itk::SimpleMutexLock> mutexHolder( mutex );
          if( firstTime )
          {
	    // BSQ format for OTB
            itk::ObjectFactoryBase::RegisterFactory( BSQImageIOFactory::New() );

	    // LUM format for OTB
            itk::ObjectFactoryBase::RegisterFactory( LUMImageIOFactory::New() );

#ifndef OTB_JPEG2000_DISABLED
	    // JPEG2000 : New format for OTB
            itk::ObjectFactoryBase::RegisterFactory( JPEG2000ImageIOFactory::New() );
#endif OTB_JPEG2000_DISABLED

	    // GDAL : New format for OTB
            itk::ObjectFactoryBase::RegisterFactory( GDALImageIOFactory::New() );

	    // ONERA format for OTB
            itk::ObjectFactoryBase::RegisterFactory( ONERAImageIOFactory::New() );

	    // MSTAR Format for OTB
            itk::ObjectFactoryBase::RegisterFactory( MSTARImageIOFactory::New() );

#ifdef OTB_USE_CURL
	    // TileMap : New format for OTB
            itk::ObjectFactoryBase::RegisterFactory( TileMapImageIOFactory::New() );
#endif
            firstTime = false;
          }
        }

      }

} // end namespace otb
<commit_msg>Correction warning brescou<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

=========================================================================*/
#ifdef _MSC_VER
#pragma warning ( disable : 4786 )
#endif

#include "otbImageIOFactory.h"
#include "itkMutexLock.h"
#include "itkMutexLockHolder.h"

#include "otbONERAImageIOFactory.h"
#include "otbMSTARImageIOFactory.h"
#include "otbGDALImageIOFactory.h"
#include "otbLUMImageIOFactory.h"
#include "otbBSQImageIOFactory.h"
#ifndef OTB_JPEG2000_DISABLED
#include "otbJPEG2000ImageIOFactory.h"
#endif
#ifdef OTB_USE_CURL
#include "otbTileMapImageIOFactory.h"
#endif

namespace otb
{

  itk::ImageIOBase::Pointer
      ImageIOFactory::CreateImageIO(const char* path, FileModeType mode)
      {

        RegisterBuiltInFactories();
        return (Superclass::CreateImageIO(path,mode) );

      }

      void
          ImageIOFactory::RegisterBuiltInFactories()
      {
        static bool firstTime = true;

        static itk::SimpleMutexLock mutex;
        {
                // This helper class makes sure the Mutex is unlocked
                // in the event an exception is thrown.
          itk::MutexLockHolder<itk::SimpleMutexLock> mutexHolder( mutex );
          if( firstTime )
          {
	    // BSQ format for OTB
            itk::ObjectFactoryBase::RegisterFactory( BSQImageIOFactory::New() );

	    // LUM format for OTB
            itk::ObjectFactoryBase::RegisterFactory( LUMImageIOFactory::New() );

#ifndef OTB_JPEG2000_DISABLED
	    // JPEG2000 : New format for OTB
            itk::ObjectFactoryBase::RegisterFactory( JPEG2000ImageIOFactory::New() );
#endif

	    // GDAL : New format for OTB
            itk::ObjectFactoryBase::RegisterFactory( GDALImageIOFactory::New() );

	    // ONERA format for OTB
            itk::ObjectFactoryBase::RegisterFactory( ONERAImageIOFactory::New() );

	    // MSTAR Format for OTB
            itk::ObjectFactoryBase::RegisterFactory( MSTARImageIOFactory::New() );

#ifdef OTB_USE_CURL
	    // TileMap : New format for OTB
            itk::ObjectFactoryBase::RegisterFactory( TileMapImageIOFactory::New() );
#endif
            firstTime = false;
          }
        }

      }

} // end namespace otb
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// rpc_client_test.cpp
//
// Identification: test/networking/rpc_client_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "common/harness.h"

#include "networking/tcp_address.h"
#include "networking/rpc_type.h"
#include "networking/rpc_client.h"
#include "networking/rpc_server.h"
#include "networking/tcp_connection.h"
#include "networking/peloton_service.h"
#include "networking/abstract_service.pb.h"

#include <functional>

namespace peloton {
namespace test {

class RpcClientTests : public PelotonTest {};

/*
TEST_F(RpcClientTests, BasicTest) {
  networking::RpcServer rpc_server(PELOTON_SERVER_PORT);
  networking::PelotonService service;
  rpc_server.RegisterService(&service);

  // Heartbeat is 13 for index
  const google::protobuf::MethodDescriptor* method_des =
      service.descriptor()->method(13);

  std::string methodname = std::string(method_des->full_name());

  ///////////Generate data//////////////
  std::hash<std::string> string_hash_fn;

  // we use unit64_t because we should specify the exact length
  uint64_t opcode = string_hash_fn(methodname);

  networking::HeartbeatRequest request;

  request.set_sender_site(12);
  request.set_last_transaction_id(34);

  // set the type
  uint16_t type = networking::MSG_TYPE_REQ;

  // prepare the sending buf
  uint32_t msg_len = request.ByteSize() + sizeof(type) + sizeof(opcode);

  // total length of the message: header length (4bytes) + message length
  // (8bytes + ...)
  PL_ASSERT(HEADERLEN == sizeof(msg_len));
  char buf[sizeof(msg_len) + msg_len];

  // copy the header into the buf
  PL_MEMCPY(buf, &msg_len, sizeof(msg_len));

  // copy the type into the buf
  PL_MEMCPY(buf + sizeof(msg_len), &type, sizeof(type));

  // copy the hashcode into the buf, following the header
  PL_ASSERT(OPCODELEN == sizeof(opcode));
  PL_MEMCPY(buf + sizeof(msg_len) + sizeof(type), &opcode, sizeof(opcode));

  // call protobuf to serialize the request message into sending buf
  request.SerializeToArray(
      buf + sizeof(msg_len) + sizeof(type) + sizeof(opcode),
      request.ByteSize());

  std::string methodname2 = rpc_server.FindMethod(opcode)->method_->full_name();
  bool comp = (methodname == methodname2);
  EXPECT_EQ(comp, true);
}
*/
}
}
<commit_msg>Fixed rpc client test<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// rpc_client_test.cpp
//
// Identification: test/networking/rpc_client_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "common/harness.h"

#include "networking/tcp_address.h"
#include "networking/rpc_type.h"
#include "networking/rpc_client.h"
#include "networking/rpc_server.h"
#include "networking/tcp_connection.h"
#include "networking/peloton_service.h"
#include "peloton/proto/abstract_service.pb.h"

#include <functional>

namespace peloton {
namespace test {

class RpcClientTests : public PelotonTest {};

/*
TEST_F(RpcClientTests, BasicTest) {
  networking::RpcServer rpc_server(PELOTON_SERVER_PORT);
  networking::PelotonService service;
  rpc_server.RegisterService(&service);

  // Heartbeat is 13 for index
  const google::protobuf::MethodDescriptor* method_des =
      service.descriptor()->method(13);

  std::string methodname = std::string(method_des->full_name());

  ///////////Generate data//////////////
  std::hash<std::string> string_hash_fn;

  // we use unit64_t because we should specify the exact length
  uint64_t opcode = string_hash_fn(methodname);

  networking::HeartbeatRequest request;

  request.set_sender_site(12);
  request.set_last_transaction_id(34);

  // set the type
  uint16_t type = networking::MSG_TYPE_REQ;

  // prepare the sending buf
  uint32_t msg_len = request.ByteSize() + sizeof(type) + sizeof(opcode);

  // total length of the message: header length (4bytes) + message length
  // (8bytes + ...)
  PL_ASSERT(HEADERLEN == sizeof(msg_len));
  char buf[sizeof(msg_len) + msg_len];

  // copy the header into the buf
  PL_MEMCPY(buf, &msg_len, sizeof(msg_len));

  // copy the type into the buf
  PL_MEMCPY(buf + sizeof(msg_len), &type, sizeof(type));

  // copy the hashcode into the buf, following the header
  PL_ASSERT(OPCODELEN == sizeof(opcode));
  PL_MEMCPY(buf + sizeof(msg_len) + sizeof(type), &opcode, sizeof(opcode));

  // call protobuf to serialize the request message into sending buf
  request.SerializeToArray(
      buf + sizeof(msg_len) + sizeof(type) + sizeof(opcode),
      request.ByteSize());

  std::string methodname2 = rpc_server.FindMethod(opcode)->method_->full_name();
  bool comp = (methodname == methodname2);
  EXPECT_EQ(comp, true);
}
*/
}
}
<|endoftext|>


<commit_before>#include "LLVM_Headers.h"
#include "LLVM_Output.h"
#include "CodeGen_LLVM.h"
#include "CodeGen_C.h"

#include <iostream>
#include <fstream>

using namespace std;

namespace Halide {

llvm::raw_fd_ostream *new_raw_fd_ostream(const std::string &filename) {
    std::string error_string;
    #if LLVM_VERSION < 35
    llvm::raw_fd_ostream *raw_out = new llvm::raw_fd_ostream(filename.c_str(), error_string);
    #elif LLVM_VERSION == 35
    llvm::raw_fd_ostream *raw_out = new llvm::raw_fd_ostream(filename.c_str(), error_string, llvm::sys::fs::F_None);
    #else // llvm 3.6
    std::error_code err;
    llvm::raw_fd_ostream *raw_out = new llvm::raw_fd_ostream(filename.c_str(), err, llvm::sys::fs::F_None);
    if (err) error_string = err.message();
    #endif
    internal_assert(error_string.empty())
        << "Error opening output " << filename << ": " << error_string << "\n";

    return raw_out;
}

namespace Internal {

bool get_md_bool(LLVMMDNodeArgumentType value, bool &result) {
    #if LLVM_VERSION < 36 || defined(WITH_NATIVE_CLIENT)
    llvm::ConstantInt *c = llvm::cast<llvm::ConstantInt>(value);
    #else
    llvm::ConstantAsMetadata *cam = llvm::cast<llvm::ConstantAsMetadata>(value);
    llvm::ConstantInt *c = llvm::cast<llvm::ConstantInt>(cam->getValue());
    #endif
    if (c) {
        result = !c->isZero();
        return true;
    }
    return false;
}

bool get_md_string(LLVMMDNodeArgumentType value, std::string &result) {
    #if LLVM_VERSION < 36 || defined(WITH_NATIVE_CLIENT)
    if (llvm::dyn_cast<llvm::ConstantAggregateZero>(value)) {
        result = "";
        return true;
    }
    llvm::ConstantDataArray *c = llvm::cast<llvm::ConstantDataArray>(value);
    if (c) {
        result = c->getAsCString();
        return true;
    }
    #else
    llvm::MDString *c = llvm::dyn_cast<llvm::MDString>(value);
    if (c) {
        result = c->getString();
        return true;
    }
    #endif
    return false;
}

}

void get_target_options(const llvm::Module *module, llvm::TargetOptions &options, std::string &mcpu, std::string &mattrs) {
    bool use_soft_float_abi = false;
    Internal::get_md_bool(module->getModuleFlag("halide_use_soft_float_abi"), use_soft_float_abi);
    Internal::get_md_string(module->getModuleFlag("halide_mcpu"), mcpu);
    Internal::get_md_string(module->getModuleFlag("halide_mattrs"), mattrs);

    options = llvm::TargetOptions();
    options.LessPreciseFPMADOption = true;
    options.NoFramePointerElim = false;
    options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
    options.UnsafeFPMath = true;
    options.NoInfsFPMath = true;
    options.NoNaNsFPMath = true;
    options.HonorSignDependentRoundingFPMathOption = false;
    options.UseSoftFloat = false;
    options.NoZerosInBSS = false;
    options.GuaranteedTailCallOpt = false;
    options.DisableTailCalls = false;
    options.StackAlignmentOverride = 0;
    options.TrapFuncName = "";
    options.PositionIndependentExecutable = true;
    options.FunctionSections = true;
    #ifdef WITH_NATIVE_CLIENT
    options.UseInitArray = true;
    #else
    options.UseInitArray = false;
    #endif
    options.FloatABIType =
        use_soft_float_abi ? llvm::FloatABI::Soft : llvm::FloatABI::Hard;
}

void clone_target_options(const llvm::Module *from, llvm::Module *to) {
    to->setTargetTriple(from->getTargetTriple());

    llvm::LLVMContext &context = to->getContext();

    bool use_soft_float_abi = false;
    if (Internal::get_md_bool(from->getModuleFlag("halide_use_soft_float_abi"), use_soft_float_abi))
        to->addModuleFlag(llvm::Module::Warning, "halide_use_soft_float_abi", use_soft_float_abi ? 1 : 0);

    std::string mcpu;
    if (Internal::get_md_string(from->getModuleFlag("halide_mcpu"), mcpu)) {
        #if LLVM_VERSION < 36
        to->addModuleFlag(llvm::Module::Warning, "halide_mcpu", llvm::ConstantDataArray::getString(context, mcpu));
        #else
        to->addModuleFlag(llvm::Module::Warning, "halide_mcpu", llvm::MDString::get(context, mcpu));
        #endif
    }

    std::string mattrs;
    if (Internal::get_md_string(from->getModuleFlag("halide_mattrs"), mattrs)) {
        #if LLVM_VERSION < 36 || defined(WITH_NATIVE_CLIENT)
        to->addModuleFlag(llvm::Module::Warning, "halide_mattrs", llvm::ConstantDataArray::getString(context, mattrs));
        #else
        to->addModuleFlag(llvm::Module::Warning, "halide_mattrs", llvm::MDString::get(context, mattrs));
        #endif
    }
}

llvm::TargetMachine *get_target_machine(const llvm::Module *module) {
    string error_string;

    const llvm::Target *target = llvm::TargetRegistry::lookupTarget(module->getTargetTriple(), error_string);
    if (!target) {
        cout << error_string << endl;
        llvm::TargetRegistry::printRegisteredTargetsForVersion();
    }
    internal_assert(target) << "Could not create target\n";

    llvm::TargetOptions options;
    std::string mcpu = "";
    std::string mattrs = "";
    get_target_options(module, options, mcpu, mattrs);

    return target->createTargetMachine(module->getTargetTriple(),
                                       mcpu, mattrs,
                                       options,
                                       llvm::Reloc::PIC_,
                                       llvm::CodeModel::Default,
                                       llvm::CodeGenOpt::Aggressive);
}

void emit_file(llvm::Module *module, const std::string &filename, llvm::TargetMachine::CodeGenFileType file_type) {
    Internal::debug(1) << "Compiling to native code...\n";
    Internal::debug(2) << "Target triple: " << module->getTargetTriple() << "\n";

    // Get the target specific parser.
    llvm::TargetMachine *target_machine = get_target_machine(module);
    internal_assert(target_machine) << "Could not allocate target machine!\n";

    // Build up all of the passes that we want to do to the module.
    #if LLVM_VERSION < 37
    llvm::PassManager pass_manager;
    #else
    llvm::legacy::PassManager pass_manager;
    #endif

    #if LLVM_VERSION < 37
    // Add an appropriate TargetLibraryInfo pass for the module's triple.
    pass_manager.add(new llvm::TargetLibraryInfo(llvm::Triple(module->getTargetTriple())));
    #else
    pass_manager.add(new llvm::TargetLibraryInfoWrapperPass(llvm::Triple(module->getTargetTriple())));
    #endif

    #if LLVM_VERSION < 33
    pass_manager.add(new llvm::TargetTransformInfo(target_machine->getScalarTargetTransformInfo(),
                                                   target_machine->getVectorTargetTransformInfo()));
    #elif LLVM_VERSION < 37
    target_machine->addAnalysisPasses(pass_manager);
    #endif

    #if LLVM_VERSION < 35
    llvm::DataLayout *layout = new llvm::DataLayout(module);
    Internal::debug(2) << "Data layout: " << layout->getStringRepresentation();
    pass_manager.add(layout);
    #endif

    // Make sure things marked as always-inline get inlined
    pass_manager.add(llvm::createAlwaysInlinerPass());

    // Override default to generate verbose assembly.
    #if LLVM_VERSION < 37
    target_machine->setAsmVerbosityDefault(true);
    #else
    target_machine->Options.MCOptions.AsmVerbose = true;
    #endif

    llvm::raw_fd_ostream *raw_out = new_raw_fd_ostream(filename);
    llvm::formatted_raw_ostream *out = new llvm::formatted_raw_ostream(*raw_out);

    // Ask the target to add backend passes as necessary.
    target_machine->addPassesToEmitFile(pass_manager, *out, file_type);

    pass_manager.run(*module);

    delete out;
    delete raw_out;

    delete target_machine;
}

llvm::Module *compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context) {
    return codegen_llvm(module, context);
}

void compile_llvm_module_to_object(llvm::Module *module, const std::string &filename) {
    emit_file(module, filename, llvm::TargetMachine::CGFT_ObjectFile);
}

void compile_llvm_module_to_assembly(llvm::Module *module, const std::string &filename) {
    emit_file(module, filename, llvm::TargetMachine::CGFT_AssemblyFile);
}

void compile_llvm_module_to_native(llvm::Module *module,
                                   const std::string &object_filename,
                                   const std::string &assembly_filename) {
    emit_file(module, object_filename, llvm::TargetMachine::CGFT_ObjectFile);
    emit_file(module, assembly_filename, llvm::TargetMachine::CGFT_AssemblyFile);
}

void compile_llvm_module_to_llvm_bitcode(llvm::Module *module, const std::string &filename) {
    llvm::raw_fd_ostream *file = new_raw_fd_ostream(filename);
    WriteBitcodeToFile(module, *file);
    delete file;
}

void compile_llvm_module_to_llvm_assembly(llvm::Module *module, const std::string &filename) {
    llvm::raw_fd_ostream *file = new_raw_fd_ostream(filename);
    module->print(*file, NULL);
    delete file;
}

}  // namespace Halide
<commit_msg>Fixes for NaCl.<commit_after>#include "LLVM_Headers.h"
#include "LLVM_Output.h"
#include "CodeGen_LLVM.h"
#include "CodeGen_C.h"

#include <iostream>
#include <fstream>

using namespace std;

namespace Halide {

llvm::raw_fd_ostream *new_raw_fd_ostream(const std::string &filename) {
    std::string error_string;
    #if LLVM_VERSION < 35
    llvm::raw_fd_ostream *raw_out = new llvm::raw_fd_ostream(filename.c_str(), error_string);
    #elif LLVM_VERSION == 35
    llvm::raw_fd_ostream *raw_out = new llvm::raw_fd_ostream(filename.c_str(), error_string, llvm::sys::fs::F_None);
    #else // llvm 3.6
    std::error_code err;
    llvm::raw_fd_ostream *raw_out = new llvm::raw_fd_ostream(filename.c_str(), err, llvm::sys::fs::F_None);
    if (err) error_string = err.message();
    #endif
    internal_assert(error_string.empty())
        << "Error opening output " << filename << ": " << error_string << "\n";

    return raw_out;
}

namespace Internal {

bool get_md_bool(LLVMMDNodeArgumentType value, bool &result) {
    #if LLVM_VERSION < 36 || defined(WITH_NATIVE_CLIENT)
    llvm::ConstantInt *c = llvm::cast<llvm::ConstantInt>(value);
    #else
    llvm::ConstantAsMetadata *cam = llvm::cast<llvm::ConstantAsMetadata>(value);
    llvm::ConstantInt *c = llvm::cast<llvm::ConstantInt>(cam->getValue());
    #endif
    if (c) {
        result = !c->isZero();
        return true;
    }
    return false;
}

bool get_md_string(LLVMMDNodeArgumentType value, std::string &result) {
    #if LLVM_VERSION < 36
    if (llvm::dyn_cast<llvm::ConstantAggregateZero>(value)) {
        result = "";
        return true;
    }
    llvm::ConstantDataArray *c = llvm::cast<llvm::ConstantDataArray>(value);
    if (c) {
        result = c->getAsCString();
        return true;
    }
    #else
    llvm::MDString *c = llvm::dyn_cast<llvm::MDString>(value);
    if (c) {
        result = c->getString();
        return true;
    }
    #endif
    return false;
}

}

void get_target_options(const llvm::Module *module, llvm::TargetOptions &options, std::string &mcpu, std::string &mattrs) {
    bool use_soft_float_abi = false;
    Internal::get_md_bool(module->getModuleFlag("halide_use_soft_float_abi"), use_soft_float_abi);
    Internal::get_md_string(module->getModuleFlag("halide_mcpu"), mcpu);
    Internal::get_md_string(module->getModuleFlag("halide_mattrs"), mattrs);

    options = llvm::TargetOptions();
    options.LessPreciseFPMADOption = true;
    options.NoFramePointerElim = false;
    options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
    options.UnsafeFPMath = true;
    options.NoInfsFPMath = true;
    options.NoNaNsFPMath = true;
    options.HonorSignDependentRoundingFPMathOption = false;
    options.UseSoftFloat = false;
    options.NoZerosInBSS = false;
    options.GuaranteedTailCallOpt = false;
    options.DisableTailCalls = false;
    options.StackAlignmentOverride = 0;
    options.TrapFuncName = "";
    options.PositionIndependentExecutable = true;
    options.FunctionSections = true;
    #ifdef WITH_NATIVE_CLIENT
    options.UseInitArray = true;
    #else
    options.UseInitArray = false;
    #endif
    options.FloatABIType =
        use_soft_float_abi ? llvm::FloatABI::Soft : llvm::FloatABI::Hard;
}

void clone_target_options(const llvm::Module *from, llvm::Module *to) {
    to->setTargetTriple(from->getTargetTriple());

    llvm::LLVMContext &context = to->getContext();

    bool use_soft_float_abi = false;
    if (Internal::get_md_bool(from->getModuleFlag("halide_use_soft_float_abi"), use_soft_float_abi))
        to->addModuleFlag(llvm::Module::Warning, "halide_use_soft_float_abi", use_soft_float_abi ? 1 : 0);

    std::string mcpu;
    if (Internal::get_md_string(from->getModuleFlag("halide_mcpu"), mcpu)) {
        #if LLVM_VERSION < 36
        to->addModuleFlag(llvm::Module::Warning, "halide_mcpu", llvm::ConstantDataArray::getString(context, mcpu));
        #else
        to->addModuleFlag(llvm::Module::Warning, "halide_mcpu", llvm::MDString::get(context, mcpu));
        #endif
    }

    std::string mattrs;
    if (Internal::get_md_string(from->getModuleFlag("halide_mattrs"), mattrs)) {
        #if LLVM_VERSION < 36
        to->addModuleFlag(llvm::Module::Warning, "halide_mattrs", llvm::ConstantDataArray::getString(context, mattrs));
        #else
        to->addModuleFlag(llvm::Module::Warning, "halide_mattrs", llvm::MDString::get(context, mattrs));
        #endif
    }
}

llvm::TargetMachine *get_target_machine(const llvm::Module *module) {
    string error_string;

    const llvm::Target *target = llvm::TargetRegistry::lookupTarget(module->getTargetTriple(), error_string);
    if (!target) {
        cout << error_string << endl;
        llvm::TargetRegistry::printRegisteredTargetsForVersion();
    }
    internal_assert(target) << "Could not create target\n";

    llvm::TargetOptions options;
    std::string mcpu = "";
    std::string mattrs = "";
    get_target_options(module, options, mcpu, mattrs);

    return target->createTargetMachine(module->getTargetTriple(),
                                       mcpu, mattrs,
                                       options,
                                       llvm::Reloc::PIC_,
                                       llvm::CodeModel::Default,
                                       llvm::CodeGenOpt::Aggressive);
}

void emit_file(llvm::Module *module, const std::string &filename, llvm::TargetMachine::CodeGenFileType file_type) {
    Internal::debug(1) << "Compiling to native code...\n";
    Internal::debug(2) << "Target triple: " << module->getTargetTriple() << "\n";

    // Get the target specific parser.
    llvm::TargetMachine *target_machine = get_target_machine(module);
    internal_assert(target_machine) << "Could not allocate target machine!\n";

    // Build up all of the passes that we want to do to the module.
    #if LLVM_VERSION < 37
    llvm::PassManager pass_manager;
    #else
    llvm::legacy::PassManager pass_manager;
    #endif

    #if LLVM_VERSION < 37
    // Add an appropriate TargetLibraryInfo pass for the module's triple.
    pass_manager.add(new llvm::TargetLibraryInfo(llvm::Triple(module->getTargetTriple())));
    #else
    pass_manager.add(new llvm::TargetLibraryInfoWrapperPass(llvm::Triple(module->getTargetTriple())));
    #endif

    #if LLVM_VERSION < 33
    pass_manager.add(new llvm::TargetTransformInfo(target_machine->getScalarTargetTransformInfo(),
                                                   target_machine->getVectorTargetTransformInfo()));
    #elif LLVM_VERSION < 37
    target_machine->addAnalysisPasses(pass_manager);
    #endif

    #if LLVM_VERSION < 35
    llvm::DataLayout *layout = new llvm::DataLayout(module);
    Internal::debug(2) << "Data layout: " << layout->getStringRepresentation();
    pass_manager.add(layout);
    #endif

    // Make sure things marked as always-inline get inlined
    pass_manager.add(llvm::createAlwaysInlinerPass());

    // Override default to generate verbose assembly.
    #if LLVM_VERSION < 37
    target_machine->setAsmVerbosityDefault(true);
    #else
    target_machine->Options.MCOptions.AsmVerbose = true;
    #endif

    llvm::raw_fd_ostream *raw_out = new_raw_fd_ostream(filename);
    llvm::formatted_raw_ostream *out = new llvm::formatted_raw_ostream(*raw_out);

    // Ask the target to add backend passes as necessary.
    target_machine->addPassesToEmitFile(pass_manager, *out, file_type);

    pass_manager.run(*module);

    delete out;
    delete raw_out;

    delete target_machine;
}

llvm::Module *compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context) {
    return codegen_llvm(module, context);
}

void compile_llvm_module_to_object(llvm::Module *module, const std::string &filename) {
    emit_file(module, filename, llvm::TargetMachine::CGFT_ObjectFile);
}

void compile_llvm_module_to_assembly(llvm::Module *module, const std::string &filename) {
    emit_file(module, filename, llvm::TargetMachine::CGFT_AssemblyFile);
}

void compile_llvm_module_to_native(llvm::Module *module,
                                   const std::string &object_filename,
                                   const std::string &assembly_filename) {
    emit_file(module, object_filename, llvm::TargetMachine::CGFT_ObjectFile);
    emit_file(module, assembly_filename, llvm::TargetMachine::CGFT_AssemblyFile);
}

void compile_llvm_module_to_llvm_bitcode(llvm::Module *module, const std::string &filename) {
    llvm::raw_fd_ostream *file = new_raw_fd_ostream(filename);
    WriteBitcodeToFile(module, *file);
    delete file;
}

void compile_llvm_module_to_llvm_assembly(llvm::Module *module, const std::string &filename) {
    llvm::raw_fd_ostream *file = new_raw_fd_ostream(filename);
    module->print(*file, NULL);
    delete file;
}

}  // namespace Halide
<|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file LexProgress.cxx
 **  Lexer for Progress 4GL.
 ** Based on LexCPP.cxx of Neil Hodgson <neilh@scintilla.org>
  **/
// Copyright 2006-2007 by Yuval Papish <Yuval@YuvCom.com>
// The License.txt file describes the conditions under which this software may be distributed.

/** TODO:
WebSpeed support in html lexer
Support "end triggers" expression of the triggers phrase
change lmPS to lmProgress
Support more than 6 comments levels
**/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

static inline bool IsAWordChar(int ch) {
	return (ch < 0x80) && (isalnum(ch) || ch == '_');
}

static inline bool IsAWordStart(int ch) {
	return (ch < 0x80) && (isalpha(ch) || ch == '_');
}

enum SentenceStart { SetSentenceStart = 0xf, ResetSentenceStart = 0x10}; // true -> bit5 = 0

static void Colourise4glDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
                            Accessor &styler) {

    WordList &keywords1 = *keywordlists[0];   // regular keywords
    WordList &keywords2 = *keywordlists[1];   // block opening keywords, only when SentenceStart
    WordList &keywords3 = *keywordlists[2];   // block opening keywords
    //WordList &keywords4 = *keywordlists[3]; // preprocessor keywords. Not implemented

	int visibleChars = 0;
	int sentenceStartState; // true -> bit5 = 0

	StyleContext sc(startPos, length, initStyle, styler);

	for (; sc.More(); sc.Forward()) {

		if (sc.atLineStart) {
			// Reset states to begining of colourise so no surprises
			// if different sets of lines lexed.
			visibleChars = 0;
		}

		// Handle line continuation generically.
		if (sc.ch == '~') {
			if (sc.chNext > ' ') {
				// skip special char after ~
				sc.Forward();
				continue;
			}
			else {
				// Skip whitespace between ~ and EOL
				while (sc.More() && (sc.chNext == ' ' || sc.chNext == '\t') ) {
					sc.Forward();
				}
				if (sc.chNext == '\n' || sc.chNext == '\r') {
					sc.Forward();
					if (sc.ch == '\r' && sc.chNext == '\n') {
						sc.Forward();
					}
					sc.Forward();
					continue;
				}
			}
		}
		// Determine if a new state should be terminated.
		sentenceStartState = sc.state & 0x10;
		switch (sc.state & 0xf) {
			case SCE_4GL_OPERATOR:
				sc.SetState(SCE_4GL_DEFAULT | sentenceStartState);
				break;
			case SCE_4GL_NUMBER:
				if (!(IsADigit(sc.ch))) {
					sc.SetState(SCE_4GL_DEFAULT | sentenceStartState);
				}
				break;
			case SCE_4GL_IDENTIFIER:
				if (!IsAWordChar(sc.ch) && sc.ch != '-') {
					char s[1000];
					sc.GetCurrentLowered(s, sizeof(s));
					if ((sentenceStartState == 0) && keywords2.InList(s) || keywords3.InList(s)) {
						sc.ChangeState(SCE_4GL_BLOCK | ResetSentenceStart);
					}
					else if (keywords1.InList(s)) {
						if ((s[0] == 'e' && s[1] =='n' && s[2] == 'd' && !isalnum(s[3]) && s[3] != '-') ||
							(s[0] == 'f' && s[1] =='o' && s[2] == 'r' && s[3] == 'w' && s[4] =='a' && s[5] == 'r' && s[6] == 'd'&& !isalnum(s[7]))) {
							sc.ChangeState(SCE_4GL_END | ResetSentenceStart);
						}
						else if	((s[0] == 'e' && s[1] =='l' && s[2] == 's' && s[3] == 'e') ||
								 (s[0] == 't' && s[1] =='h' && s[2] == 'e' && s[3] == 'n')) {
							sc.ChangeState(SCE_4GL_WORD & SetSentenceStart);
						}
						else {
							sc.ChangeState(SCE_4GL_WORD | ResetSentenceStart);
						}
					}
					sc.SetState(SCE_4GL_DEFAULT | (sc.state & 0x10));
				}
				break;
			case SCE_4GL_PREPROCESSOR:
				if (sc.atLineStart) {
					sc.SetState(SCE_4GL_DEFAULT & SetSentenceStart);
				} else if (sc.ch == '*' && sc.chNext == '/') {
					sc.ForwardSetState(SCE_4GL_DEFAULT | sentenceStartState);
				}
				break;
			case SCE_4GL_STRING:
				if (sc.ch == '\"') {
					sc.ForwardSetState(SCE_4GL_DEFAULT | sentenceStartState);
				}
				break;
			case SCE_4GL_CHARACTER:
				if (sc.ch == '\'') {
					sc.ForwardSetState(SCE_4GL_DEFAULT | sentenceStartState);
				}
				break;
			default:
				if ((sc.state & 0xf) >= SCE_4GL_COMMENT1) {
					if (sc.ch == '*' && sc.chNext == '/') {
						sc.Forward();
						if ((sc.state & 0xf) == SCE_4GL_COMMENT1) {
							sc.ForwardSetState(SCE_4GL_DEFAULT | sentenceStartState);
						}
						else
							sc.SetState((sc.state & 0x1f) - 1);
					} else if (sc.ch == '/' && sc.chNext == '*') {
						sc.Forward();
						sc.SetState((sc.state & 0x1f) + 1);
					}
				}
		}

		// Determine if a new state should be entered.
		sentenceStartState = sc.state & 0x10;
		if ((sc.state & 0xf) == SCE_4GL_DEFAULT) {
			if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
				sc.SetState(SCE_4GL_NUMBER | ResetSentenceStart);
			} else if (IsAWordStart(sc.ch) || sc.ch == '@') {
				sc.SetState(SCE_4GL_IDENTIFIER | sentenceStartState);
			} else if (sc.ch == '/' && sc.chNext == '*') {
				sc.SetState(SCE_4GL_COMMENT1 | sentenceStartState);
				sc.Forward();
			} else if (sc.ch == '\"') {
				sc.SetState(SCE_4GL_STRING | ResetSentenceStart);
			} else if (sc.ch == '\'') {
				sc.SetState(SCE_4GL_CHARACTER | ResetSentenceStart);
			} else if (sc.ch == '&' && visibleChars == 0 && ((sc.state & 0x10) == 0)) {
				sc.SetState(SCE_4GL_PREPROCESSOR | ResetSentenceStart);
				// Skip whitespace between & and preprocessor word
				do {
					sc.Forward();
				} while ((sc.ch == ' ' || sc.ch == '\t') && sc.More());
			// Handle syntactical line termination
			} else if ((sc.ch == '.' || sc.ch == ':' || sc.ch == '}') && (sc.chNext == ' ' || sc.chNext == '\t' || sc.chNext == '\n' || sc.chNext == '\r')) {
				sc.SetState(sc.state & SetSentenceStart);
			} else if (isoperator(static_cast<char>(sc.ch))) {
		/* 	This code allows highlight of handles. Alas, it would cause the frase "last-event:function"
			to be recognized as a BlockBegin

				if (sc.ch == ':')
					sc.SetState(SCE_4GL_OPERATOR & SetSentenceStart);
				else */
					sc.SetState(SCE_4GL_OPERATOR | ResetSentenceStart);
			}
		}

		if (!IsASpace(sc.ch)) {
			visibleChars++;
		}
	}
	sc.Complete();
}

static bool IsStreamCommentStyle(int style) {
	return (style & 0xf) >= SCE_4GL_COMMENT1 ;
}

// Store both the current line's fold level and the next lines in the
// level store to make it easy to pick up with each increment
// and to make it possible to fiddle the current level for "} else {".
static void FoldNoBox4glDoc(unsigned int startPos, int length, int initStyle,
                            Accessor &styler) {
	bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
	bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
	bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0;
	unsigned int endPos = startPos + length;
	int visibleChars = 0;
	int lineCurrent = styler.GetLine(startPos);
	int levelCurrent = SC_FOLDLEVELBASE;
	if (lineCurrent > 0)
		levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
	int levelMinCurrent = levelCurrent;
	int levelNext = levelCurrent;
	char chNext = static_cast<char>(tolower(styler[startPos]));
	int styleNext = styler.StyleAt(startPos);
	int style = initStyle;
	for (unsigned int i = startPos; i < endPos; i++) {
		char ch = chNext;
		chNext = static_cast<char>(tolower(styler.SafeGetCharAt(i + 1)));
		int stylePrev = style;
		style = styleNext;
		styleNext = styler.StyleAt(i + 1);
		bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
		if (foldComment && IsStreamCommentStyle(style)) {
			if (!IsStreamCommentStyle(stylePrev)) {
				levelNext++;
			} else if (!IsStreamCommentStyle(styleNext)) { // && !atEOL) {
				// Comments don't end at end of line and the next character may be unstyled.
				levelNext--;
			}
		}
		else if ((style & 0xf) == SCE_4GL_BLOCK && !isalnum(chNext)) {
			levelNext++;
		}
		else if ((style & 0xf) == SCE_4GL_END  && (ch == 'e' || ch == 'f')) {
			levelNext--;
		}
		if (atEOL) {
			int levelUse = levelCurrent;
			if (foldAtElse) {
				levelUse = levelMinCurrent;
			}
			int lev = levelUse | levelNext << 16;
			if (visibleChars == 0 && foldCompact)
				lev |= SC_FOLDLEVELWHITEFLAG;
			if (levelUse < levelNext)
				lev |= SC_FOLDLEVELHEADERFLAG;
			if (lev != styler.LevelAt(lineCurrent)) {
				styler.SetLevel(lineCurrent, lev);
			}
			lineCurrent++;
			levelCurrent = levelNext;
			levelMinCurrent = levelCurrent;
			visibleChars = 0;
		}
		if (!isspacechar(ch))
			visibleChars++;
	}
}

static void Fold4glDoc(unsigned int startPos, int length, int initStyle, WordList *[],
                       Accessor &styler) {
	FoldNoBox4glDoc(startPos, length, initStyle, styler);
}

static const char * const FglWordLists[] = {
            "Primary keywords and identifiers",
            "Secondary keywords and identifiers",
            "Documentation comment keywords",
            "Unused",
            "Global classes and typedefs",
            0,
        };

LexerModule lmProgress(SCLEX_PROGRESS, Colourise4glDoc, "progress", Fold4glDoc, FglWordLists);
<commit_msg>Refixed warning.<commit_after>// Scintilla source code edit control
/** @file LexProgress.cxx
 **  Lexer for Progress 4GL.
 ** Based on LexCPP.cxx of Neil Hodgson <neilh@scintilla.org>
  **/
// Copyright 2006-2007 by Yuval Papish <Yuval@YuvCom.com>
// The License.txt file describes the conditions under which this software may be distributed.

/** TODO:
WebSpeed support in html lexer
Support "end triggers" expression of the triggers phrase
change lmPS to lmProgress
Support more than 6 comments levels
**/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

static inline bool IsAWordChar(int ch) {
	return (ch < 0x80) && (isalnum(ch) || ch == '_');
}

static inline bool IsAWordStart(int ch) {
	return (ch < 0x80) && (isalpha(ch) || ch == '_');
}

enum SentenceStart { SetSentenceStart = 0xf, ResetSentenceStart = 0x10}; // true -> bit5 = 0

static void Colourise4glDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
                            Accessor &styler) {

    WordList &keywords1 = *keywordlists[0];   // regular keywords
    WordList &keywords2 = *keywordlists[1];   // block opening keywords, only when SentenceStart
    WordList &keywords3 = *keywordlists[2];   // block opening keywords
    //WordList &keywords4 = *keywordlists[3]; // preprocessor keywords. Not implemented

	int visibleChars = 0;
	int sentenceStartState; // true -> bit5 = 0

	StyleContext sc(startPos, length, initStyle, styler);

	for (; sc.More(); sc.Forward()) {

		if (sc.atLineStart) {
			// Reset states to begining of colourise so no surprises
			// if different sets of lines lexed.
			visibleChars = 0;
		}

		// Handle line continuation generically.
		if (sc.ch == '~') {
			if (sc.chNext > ' ') {
				// skip special char after ~
				sc.Forward();
				continue;
			}
			else {
				// Skip whitespace between ~ and EOL
				while (sc.More() && (sc.chNext == ' ' || sc.chNext == '\t') ) {
					sc.Forward();
				}
				if (sc.chNext == '\n' || sc.chNext == '\r') {
					sc.Forward();
					if (sc.ch == '\r' && sc.chNext == '\n') {
						sc.Forward();
					}
					sc.Forward();
					continue;
				}
			}
		}
		// Determine if a new state should be terminated.
		sentenceStartState = sc.state & 0x10;
		switch (sc.state & 0xf) {
			case SCE_4GL_OPERATOR:
				sc.SetState(SCE_4GL_DEFAULT | sentenceStartState);
				break;
			case SCE_4GL_NUMBER:
				if (!(IsADigit(sc.ch))) {
					sc.SetState(SCE_4GL_DEFAULT | sentenceStartState);
				}
				break;
			case SCE_4GL_IDENTIFIER:
				if (!IsAWordChar(sc.ch) && sc.ch != '-') {
					char s[1000];
					sc.GetCurrentLowered(s, sizeof(s));
					if (((sentenceStartState == 0) && keywords2.InList(s)) || keywords3.InList(s)) {
						sc.ChangeState(SCE_4GL_BLOCK | ResetSentenceStart);
					}
					else if (keywords1.InList(s)) {
						if ((s[0] == 'e' && s[1] =='n' && s[2] == 'd' && !isalnum(s[3]) && s[3] != '-') ||
							(s[0] == 'f' && s[1] =='o' && s[2] == 'r' && s[3] == 'w' && s[4] =='a' && s[5] == 'r' && s[6] == 'd'&& !isalnum(s[7]))) {
							sc.ChangeState(SCE_4GL_END | ResetSentenceStart);
						}
						else if	((s[0] == 'e' && s[1] =='l' && s[2] == 's' && s[3] == 'e') ||
								 (s[0] == 't' && s[1] =='h' && s[2] == 'e' && s[3] == 'n')) {
							sc.ChangeState(SCE_4GL_WORD & SetSentenceStart);
						}
						else {
							sc.ChangeState(SCE_4GL_WORD | ResetSentenceStart);
						}
					}
					sc.SetState(SCE_4GL_DEFAULT | (sc.state & 0x10));
				}
				break;
			case SCE_4GL_PREPROCESSOR:
				if (sc.atLineStart) {
					sc.SetState(SCE_4GL_DEFAULT & SetSentenceStart);
				} else if (sc.ch == '*' && sc.chNext == '/') {
					sc.ForwardSetState(SCE_4GL_DEFAULT | sentenceStartState);
				}
				break;
			case SCE_4GL_STRING:
				if (sc.ch == '\"') {
					sc.ForwardSetState(SCE_4GL_DEFAULT | sentenceStartState);
				}
				break;
			case SCE_4GL_CHARACTER:
				if (sc.ch == '\'') {
					sc.ForwardSetState(SCE_4GL_DEFAULT | sentenceStartState);
				}
				break;
			default:
				if ((sc.state & 0xf) >= SCE_4GL_COMMENT1) {
					if (sc.ch == '*' && sc.chNext == '/') {
						sc.Forward();
						if ((sc.state & 0xf) == SCE_4GL_COMMENT1) {
							sc.ForwardSetState(SCE_4GL_DEFAULT | sentenceStartState);
						}
						else
							sc.SetState((sc.state & 0x1f) - 1);
					} else if (sc.ch == '/' && sc.chNext == '*') {
						sc.Forward();
						sc.SetState((sc.state & 0x1f) + 1);
					}
				}
		}

		// Determine if a new state should be entered.
		sentenceStartState = sc.state & 0x10;
		if ((sc.state & 0xf) == SCE_4GL_DEFAULT) {
			if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
				sc.SetState(SCE_4GL_NUMBER | ResetSentenceStart);
			} else if (IsAWordStart(sc.ch) || sc.ch == '@') {
				sc.SetState(SCE_4GL_IDENTIFIER | sentenceStartState);
			} else if (sc.ch == '/' && sc.chNext == '*') {
				sc.SetState(SCE_4GL_COMMENT1 | sentenceStartState);
				sc.Forward();
			} else if (sc.ch == '\"') {
				sc.SetState(SCE_4GL_STRING | ResetSentenceStart);
			} else if (sc.ch == '\'') {
				sc.SetState(SCE_4GL_CHARACTER | ResetSentenceStart);
			} else if (sc.ch == '&' && visibleChars == 0 && ((sc.state & 0x10) == 0)) {
				sc.SetState(SCE_4GL_PREPROCESSOR | ResetSentenceStart);
				// Skip whitespace between & and preprocessor word
				do {
					sc.Forward();
				} while ((sc.ch == ' ' || sc.ch == '\t') && sc.More());
			// Handle syntactical line termination
			} else if ((sc.ch == '.' || sc.ch == ':' || sc.ch == '}') && (sc.chNext == ' ' || sc.chNext == '\t' || sc.chNext == '\n' || sc.chNext == '\r')) {
				sc.SetState(sc.state & SetSentenceStart);
			} else if (isoperator(static_cast<char>(sc.ch))) {
		/* 	This code allows highlight of handles. Alas, it would cause the frase "last-event:function"
			to be recognized as a BlockBegin

				if (sc.ch == ':')
					sc.SetState(SCE_4GL_OPERATOR & SetSentenceStart);
				else */
					sc.SetState(SCE_4GL_OPERATOR | ResetSentenceStart);
			}
		}

		if (!IsASpace(sc.ch)) {
			visibleChars++;
		}
	}
	sc.Complete();
}

static bool IsStreamCommentStyle(int style) {
	return (style & 0xf) >= SCE_4GL_COMMENT1 ;
}

// Store both the current line's fold level and the next lines in the
// level store to make it easy to pick up with each increment
// and to make it possible to fiddle the current level for "} else {".
static void FoldNoBox4glDoc(unsigned int startPos, int length, int initStyle,
                            Accessor &styler) {
	bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
	bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
	bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0;
	unsigned int endPos = startPos + length;
	int visibleChars = 0;
	int lineCurrent = styler.GetLine(startPos);
	int levelCurrent = SC_FOLDLEVELBASE;
	if (lineCurrent > 0)
		levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
	int levelMinCurrent = levelCurrent;
	int levelNext = levelCurrent;
	char chNext = static_cast<char>(tolower(styler[startPos]));
	int styleNext = styler.StyleAt(startPos);
	int style = initStyle;
	for (unsigned int i = startPos; i < endPos; i++) {
		char ch = chNext;
		chNext = static_cast<char>(tolower(styler.SafeGetCharAt(i + 1)));
		int stylePrev = style;
		style = styleNext;
		styleNext = styler.StyleAt(i + 1);
		bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
		if (foldComment && IsStreamCommentStyle(style)) {
			if (!IsStreamCommentStyle(stylePrev)) {
				levelNext++;
			} else if (!IsStreamCommentStyle(styleNext)) { // && !atEOL) {
				// Comments don't end at end of line and the next character may be unstyled.
				levelNext--;
			}
		}
		else if ((style & 0xf) == SCE_4GL_BLOCK && !isalnum(chNext)) {
			levelNext++;
		}
		else if ((style & 0xf) == SCE_4GL_END  && (ch == 'e' || ch == 'f')) {
			levelNext--;
		}
		if (atEOL) {
			int levelUse = levelCurrent;
			if (foldAtElse) {
				levelUse = levelMinCurrent;
			}
			int lev = levelUse | levelNext << 16;
			if (visibleChars == 0 && foldCompact)
				lev |= SC_FOLDLEVELWHITEFLAG;
			if (levelUse < levelNext)
				lev |= SC_FOLDLEVELHEADERFLAG;
			if (lev != styler.LevelAt(lineCurrent)) {
				styler.SetLevel(lineCurrent, lev);
			}
			lineCurrent++;
			levelCurrent = levelNext;
			levelMinCurrent = levelCurrent;
			visibleChars = 0;
		}
		if (!isspacechar(ch))
			visibleChars++;
	}
}

static void Fold4glDoc(unsigned int startPos, int length, int initStyle, WordList *[],
                       Accessor &styler) {
	FoldNoBox4glDoc(startPos, length, initStyle, styler);
}

static const char * const FglWordLists[] = {
            "Primary keywords and identifiers",
            "Secondary keywords and identifiers",
            "Documentation comment keywords",
            "Unused",
            "Global classes and typedefs",
            0,
        };

LexerModule lmProgress(SCLEX_PROGRESS, Colourise4glDoc, "progress", Fold4glDoc, FglWordLists);
<|endoftext|>