<commit_before>#include "pch.h"
#include "7zAlloc.h"
#include "7zMyAlloc.h"
#include "7zFile.h"
#include "LzmaEnc.h"
#include "LzmaDec.h"
#include "Types.h"

ZString GetAppDir() {
	char szPathName[MAX_PATH+48] = "";
	GetModuleFileNameA(NULL, szPathName, MAX_PATH);
	char*   p = strrchr(szPathName, '\\');
	p = (!p) ? szPathName : p+1;
	strcpy(p,"");
	return ZString(szPathName);
}

static void *SzAlloc(void *p, size_t size) { p = p; return MidAlloc(size); }
static void SzFree(void *p, void *address) { p = p; MidFree(address); }
static ISzAlloc g_Alloc = { SzAlloc, SzFree };

#define IN_BUF_SIZE (1 << 8)
#define OUT_BUF_SIZE (1 << 8)

static SRes Decode2(CLzmaDec *state, ISeqOutStream *outStream, ISeqInStream *inStream,
	UInt64 unpackSize)
{
	int thereIsSize = (unpackSize != (UInt64)(Int64)-1);
	Byte inBuf[IN_BUF_SIZE];
	Byte outBuf[OUT_BUF_SIZE];
	size_t inPos = 0, inSize = 0, outPos = 0;
	LzmaDec_Init(state);
	for (;;)
	{
		if (inPos == inSize)
		{
			inSize = IN_BUF_SIZE;
			RINOK(inStream->Read(inStream, inBuf, &inSize));
			inPos = 0;
		}
	{
		SRes res;
		SizeT inProcessed = inSize - inPos;
		SizeT outProcessed = OUT_BUF_SIZE - outPos;
		ELzmaFinishMode finishMode = LZMA_FINISH_ANY;
		ELzmaStatus status;
		if (thereIsSize && outProcessed > unpackSize)
		{
			outProcessed = (SizeT)unpackSize;
			finishMode = LZMA_FINISH_END;
		}

		res = LzmaDec_DecodeToBuf(state, outBuf + outPos, &outProcessed,
			inBuf + inPos, &inProcessed, finishMode, &status);
		inPos += inProcessed;
		outPos += outProcessed;
		unpackSize -= outProcessed;

		if (outStream)
			if (outStream->Write(outStream, outBuf, outPos) != outPos)
				return SZ_ERROR_WRITE;

		outPos = 0;

		if (res != SZ_OK || thereIsSize && unpackSize == 0)
			return res;

		if (inProcessed == 0 && outProcessed == 0)
		{
			if (thereIsSize || status != LZMA_STATUS_FINISHED_WITH_MARK)
				return SZ_ERROR_DATA;
			return res;
		}
	}
	}
}

static SRes Decode(ISeqOutStream *outStream, ISeqInStream *inStream)
{
	UInt64 unpackSize;
	int i;
	SRes res = 0;

	CLzmaDec state;

	/* header: 5 bytes of LZMA properties and 8 bytes of uncompressed size */
	unsigned char header[LZMA_PROPS_SIZE + 8];

	/* Read and parse header */

	RINOK(SeqInStream_Read(inStream, header, sizeof(header)));

	unpackSize = 0;
	for (i = 0; i < 8; i++)
		unpackSize += (UInt64)header[LZMA_PROPS_SIZE + i] << (i * 8);

	LzmaDec_Construct(&state);
	RINOK(LzmaDec_Allocate(&state, header, LZMA_PROPS_SIZE, &g_Alloc));
	res = Decode2(&state, outStream, inStream, unpackSize);
	LzmaDec_Free(&state, &g_Alloc);
	return res;
}

static SRes Encode(ISeqOutStream *outStream, ISeqInStream *inStream, UInt64 fileSize, char *rs)
{
	CLzmaEncHandle enc;
	SRes res;
	CLzmaEncProps props;

	rs = rs;

	enc = LzmaEnc_Create(&g_Alloc);
	if (enc == 0)
		return SZ_ERROR_MEM;

	LzmaEncProps_Init(&props);
	res = LzmaEnc_SetProps(enc, &props);

	if (res == SZ_OK)
	{
		Byte header[LZMA_PROPS_SIZE + 8];
		size_t headerSize = LZMA_PROPS_SIZE;
		int i;

		res = LzmaEnc_WriteProperties(enc, header, &headerSize);
		for (i = 0; i < 8; i++)
			header[headerSize++] = (Byte)(fileSize >> (8 * i));
		if (outStream->Write(outStream, header, headerSize) != headerSize)
			res = SZ_ERROR_WRITE;
		else
		{
			if (res == SZ_OK)
				res = LzmaEnc_Encode(enc, outStream, inStream, NULL, &g_Alloc, &g_Alloc);
		}
	}
	LzmaEnc_Destroy(enc, &g_Alloc, &g_Alloc);
	return res;
}

int Extract7z(const char * sz7z, const char * szFile) {
	CFileSeqInStream inStream;
	CFileOutStream outStream;
	int res = -1;
	int res2 = -1;
	UInt64 iLength = 0;
	Bool useOutFile = False;
	FileSeqInStream_CreateVTable(&inStream);
	File_Construct(&inStream.file);
	FileOutStream_CreateVTable(&outStream);
	File_Construct(&outStream.file);

	if (InFile_Open(&inStream.file, sz7z) == 0) {
		if (OutFile_Open(&outStream.file, szFile) == 0) {
			res = Decode(&outStream.s, &inStream.s);
			res2 = File_GetLength(&outStream.file,&iLength);
			File_Close(&outStream.file);
			File_Close(&inStream.file);
		}
	}

	return (res != 0 || res2 != 0 || iLength == 0) ? -1 : (int)iLength;
}

int Create7z(const char * szFile, const char * sz7z) {
	CFileSeqInStream inStream;
	CFileOutStream outStream;
	int res = -1;
	int res2 = -1;
	UInt64 iLength = 0;
	Bool useOutFile = False;
	FileSeqInStream_CreateVTable(&inStream);
	File_Construct(&inStream.file);
	FileOutStream_CreateVTable(&outStream);
	File_Construct(&outStream.file);

	if (InFile_Open(&inStream.file, szFile) == 0) {
		if (OutFile_Open(&outStream.file, sz7z) == 0) {
			UInt64 fileSize;
			File_GetLength(&inStream.file, &fileSize);
			char * rs = NULL;
			res = Encode(&outStream.s, &inStream.s, fileSize, rs);
			res2 = File_GetLength(&outStream.file,&iLength);
			File_Close(&outStream.file);
			File_Close(&inStream.file);
		}
	}

	return (res != 0 || res2 != 0 || iLength == 0) ? -1 : (int)iLength;
}

int Create7z(char * in, int srcLen, char * out) {

	CLzmaEncProps props;
	props.level = 2;
	props.numThreads = 1;
	props.dictSize = 1 << 12;
	props.reduceSize = 4096;
	LzmaEncProps_Init(&props);
	Byte header[LZMA_PROPS_SIZE + 8];
    size_t headerSize = LZMA_PROPS_SIZE;
	size_t destLen = -1;
	Byte * bout = new Byte[srcLen];
	ZeroMemory(bout,srcLen);
	if (SZ_OK == LzmaEncode((Byte*)bout, &destLen, (Byte*)in, srcLen, &props, header, &headerSize, 1, NULL, &g_Alloc, &g_Alloc)) {
		for (int i = 0; i < 8; i++)
		  header[headerSize++] = (Byte)(srcLen >> (8 * i));

		memcpy(out,header,headerSize);
		memcpy(out+headerSize,bout,destLen);
	}
	return destLen + headerSize;
}

FileList FindDumps() {
	FileList tlFiles;
	tlFiles.SetEmpty();

	WIN32_FIND_DATAA finddata;
	ZeroMemory(&finddata,sizeof(WIN32_FIND_DATAA));

	char szPathName[MAX_PATH+48] = "";
	char szName[MAX_PATH+48] = "";
	strcpy(szPathName,(PCC)GetAppDir());
	strcpy(szName,szPathName);
    strcat(szPathName, "*.dmp");

	HANDLE hsearchFiles = 0;
	FILETIME ftTime = {0,0};
	hsearchFiles = FindFirstFileA(szPathName, &finddata);

	if (INVALID_HANDLE_VALUE == hsearchFiles)
		return tlFiles;

	int iKBytes = 0;
	while (INVALID_HANDLE_VALUE != hsearchFiles) {
		if (finddata.cFileName[0] != '.') {
			char*   p = strrchr(szName, '\\');
			p = (!p) ? szName : p+1;
			strcpy(p, "");
			strcat(szName, finddata.cFileName);
			tlFiles.InsertSorted(finddata);
			iKBytes += (finddata.nFileSizeHigh > 0) ? MAXINT : (finddata.nFileSizeLow / 1024);
			if (iKBytes >= MAXINT)
				return tlFiles;
		}
		if (!FindNextFileA(hsearchFiles, &finddata)){
			FindClose(hsearchFiles);
			hsearchFiles = INVALID_HANDLE_VALUE;
		}
	}
	return tlFiles;
}

void DeleteDumps(bool bDelete) {
	FileList tlFiles = FindDumps();
	char szDir[MAX_PATH+52] = "";
	strcpy(szDir,(PCC)GetAppDir());
	if (!tlFiles.IsEmpty()) {
		for (FileList::Iterator iterFile(tlFiles);
			!iterFile.End(); iterFile.Next())
		{
			ZString zFile = ZString(szDir)+ZString(iterFile.Value().cFileName);
			if (!bDelete) {
				MoveFileA((PCC)zFile,zFile+ZString(".old"));
				continue;
			}
			else {
				debugf("**** Deleting %s\n",(PCC)zFile);
				DeleteFileA(zFile);
			}
		}
	}
}

<commit_msg>Replace midalloc and midfree with just malloc and free. hope to get build to pass. thanks imago!!<commit_after>#include "pch.h"
#include "7zAlloc.h"
#include "7zMyAlloc.h"
#include "7zFile.h"
#include "LzmaEnc.h"
#include "LzmaDec.h"
#include "Types.h"

ZString GetAppDir() {
	char szPathName[MAX_PATH+48] = "";
	GetModuleFileNameA(NULL, szPathName, MAX_PATH);
	char*   p = strrchr(szPathName, '\\');
	p = (!p) ? szPathName : p+1;
	strcpy(p,"");
	return ZString(szPathName);
}

static void *SzAlloc(void *p, size_t size) { p = p; return malloc(size); }
static void SzFree(void *p, void *address) { p = p; free(address); }
static ISzAlloc g_Alloc = { SzAlloc, SzFree };

#define IN_BUF_SIZE (1 << 8)
#define OUT_BUF_SIZE (1 << 8)

static SRes Decode2(CLzmaDec *state, ISeqOutStream *outStream, ISeqInStream *inStream,
	UInt64 unpackSize)
{
	int thereIsSize = (unpackSize != (UInt64)(Int64)-1);
	Byte inBuf[IN_BUF_SIZE];
	Byte outBuf[OUT_BUF_SIZE];
	size_t inPos = 0, inSize = 0, outPos = 0;
	LzmaDec_Init(state);
	for (;;)
	{
		if (inPos == inSize)
		{
			inSize = IN_BUF_SIZE;
			RINOK(inStream->Read(inStream, inBuf, &inSize));
			inPos = 0;
		}
	{
		SRes res;
		SizeT inProcessed = inSize - inPos;
		SizeT outProcessed = OUT_BUF_SIZE - outPos;
		ELzmaFinishMode finishMode = LZMA_FINISH_ANY;
		ELzmaStatus status;
		if (thereIsSize && outProcessed > unpackSize)
		{
			outProcessed = (SizeT)unpackSize;
			finishMode = LZMA_FINISH_END;
		}

		res = LzmaDec_DecodeToBuf(state, outBuf + outPos, &outProcessed,
			inBuf + inPos, &inProcessed, finishMode, &status);
		inPos += inProcessed;
		outPos += outProcessed;
		unpackSize -= outProcessed;

		if (outStream)
			if (outStream->Write(outStream, outBuf, outPos) != outPos)
				return SZ_ERROR_WRITE;

		outPos = 0;

		if (res != SZ_OK || thereIsSize && unpackSize == 0)
			return res;

		if (inProcessed == 0 && outProcessed == 0)
		{
			if (thereIsSize || status != LZMA_STATUS_FINISHED_WITH_MARK)
				return SZ_ERROR_DATA;
			return res;
		}
	}
	}
}

static SRes Decode(ISeqOutStream *outStream, ISeqInStream *inStream)
{
	UInt64 unpackSize;
	int i;
	SRes res = 0;

	CLzmaDec state;

	/* header: 5 bytes of LZMA properties and 8 bytes of uncompressed size */
	unsigned char header[LZMA_PROPS_SIZE + 8];

	/* Read and parse header */

	RINOK(SeqInStream_Read(inStream, header, sizeof(header)));

	unpackSize = 0;
	for (i = 0; i < 8; i++)
		unpackSize += (UInt64)header[LZMA_PROPS_SIZE + i] << (i * 8);

	LzmaDec_Construct(&state);
	RINOK(LzmaDec_Allocate(&state, header, LZMA_PROPS_SIZE, &g_Alloc));
	res = Decode2(&state, outStream, inStream, unpackSize);
	LzmaDec_Free(&state, &g_Alloc);
	return res;
}

static SRes Encode(ISeqOutStream *outStream, ISeqInStream *inStream, UInt64 fileSize, char *rs)
{
	CLzmaEncHandle enc;
	SRes res;
	CLzmaEncProps props;

	rs = rs;

	enc = LzmaEnc_Create(&g_Alloc);
	if (enc == 0)
		return SZ_ERROR_MEM;

	LzmaEncProps_Init(&props);
	res = LzmaEnc_SetProps(enc, &props);

	if (res == SZ_OK)
	{
		Byte header[LZMA_PROPS_SIZE + 8];
		size_t headerSize = LZMA_PROPS_SIZE;
		int i;

		res = LzmaEnc_WriteProperties(enc, header, &headerSize);
		for (i = 0; i < 8; i++)
			header[headerSize++] = (Byte)(fileSize >> (8 * i));
		if (outStream->Write(outStream, header, headerSize) != headerSize)
			res = SZ_ERROR_WRITE;
		else
		{
			if (res == SZ_OK)
				res = LzmaEnc_Encode(enc, outStream, inStream, NULL, &g_Alloc, &g_Alloc);
		}
	}
	LzmaEnc_Destroy(enc, &g_Alloc, &g_Alloc);
	return res;
}

int Extract7z(const char * sz7z, const char * szFile) {
	CFileSeqInStream inStream;
	CFileOutStream outStream;
	int res = -1;
	int res2 = -1;
	UInt64 iLength = 0;
	Bool useOutFile = False;
	FileSeqInStream_CreateVTable(&inStream);
	File_Construct(&inStream.file);
	FileOutStream_CreateVTable(&outStream);
	File_Construct(&outStream.file);

	if (InFile_Open(&inStream.file, sz7z) == 0) {
		if (OutFile_Open(&outStream.file, szFile) == 0) {
			res = Decode(&outStream.s, &inStream.s);
			res2 = File_GetLength(&outStream.file,&iLength);
			File_Close(&outStream.file);
			File_Close(&inStream.file);
		}
	}

	return (res != 0 || res2 != 0 || iLength == 0) ? -1 : (int)iLength;
}

int Create7z(const char * szFile, const char * sz7z) {
	CFileSeqInStream inStream;
	CFileOutStream outStream;
	int res = -1;
	int res2 = -1;
	UInt64 iLength = 0;
	Bool useOutFile = False;
	FileSeqInStream_CreateVTable(&inStream);
	File_Construct(&inStream.file);
	FileOutStream_CreateVTable(&outStream);
	File_Construct(&outStream.file);

	if (InFile_Open(&inStream.file, szFile) == 0) {
		if (OutFile_Open(&outStream.file, sz7z) == 0) {
			UInt64 fileSize;
			File_GetLength(&inStream.file, &fileSize);
			char * rs = NULL;
			res = Encode(&outStream.s, &inStream.s, fileSize, rs);
			res2 = File_GetLength(&outStream.file,&iLength);
			File_Close(&outStream.file);
			File_Close(&inStream.file);
		}
	}

	return (res != 0 || res2 != 0 || iLength == 0) ? -1 : (int)iLength;
}

int Create7z(char * in, int srcLen, char * out) {

	CLzmaEncProps props;
	props.level = 2;
	props.numThreads = 1;
	props.dictSize = 1 << 12;
	props.reduceSize = 4096;
	LzmaEncProps_Init(&props);
	Byte header[LZMA_PROPS_SIZE + 8];
    size_t headerSize = LZMA_PROPS_SIZE;
	size_t destLen = -1;
	Byte * bout = new Byte[srcLen];
	ZeroMemory(bout,srcLen);
	if (SZ_OK == LzmaEncode((Byte*)bout, &destLen, (Byte*)in, srcLen, &props, header, &headerSize, 1, NULL, &g_Alloc, &g_Alloc)) {
		for (int i = 0; i < 8; i++)
		  header[headerSize++] = (Byte)(srcLen >> (8 * i));

		memcpy(out,header,headerSize);
		memcpy(out+headerSize,bout,destLen);
	}
	return destLen + headerSize;
}

FileList FindDumps() {
	FileList tlFiles;
	tlFiles.SetEmpty();

	WIN32_FIND_DATAA finddata;
	ZeroMemory(&finddata,sizeof(WIN32_FIND_DATAA));

	char szPathName[MAX_PATH+48] = "";
	char szName[MAX_PATH+48] = "";
	strcpy(szPathName,(PCC)GetAppDir());
	strcpy(szName,szPathName);
    strcat(szPathName, "*.dmp");

	HANDLE hsearchFiles = 0;
	FILETIME ftTime = {0,0};
	hsearchFiles = FindFirstFileA(szPathName, &finddata);

	if (INVALID_HANDLE_VALUE == hsearchFiles)
		return tlFiles;

	int iKBytes = 0;
	while (INVALID_HANDLE_VALUE != hsearchFiles) {
		if (finddata.cFileName[0] != '.') {
			char*   p = strrchr(szName, '\\');
			p = (!p) ? szName : p+1;
			strcpy(p, "");
			strcat(szName, finddata.cFileName);
			tlFiles.InsertSorted(finddata);
			iKBytes += (finddata.nFileSizeHigh > 0) ? MAXINT : (finddata.nFileSizeLow / 1024);
			if (iKBytes >= MAXINT)
				return tlFiles;
		}
		if (!FindNextFileA(hsearchFiles, &finddata)){
			FindClose(hsearchFiles);
			hsearchFiles = INVALID_HANDLE_VALUE;
		}
	}
	return tlFiles;
}

void DeleteDumps(bool bDelete) {
	FileList tlFiles = FindDumps();
	char szDir[MAX_PATH+52] = "";
	strcpy(szDir,(PCC)GetAppDir());
	if (!tlFiles.IsEmpty()) {
		for (FileList::Iterator iterFile(tlFiles);
			!iterFile.End(); iterFile.Next())
		{
			ZString zFile = ZString(szDir)+ZString(iterFile.Value().cFileName);
			if (!bDelete) {
				MoveFileA((PCC)zFile,zFile+ZString(".old"));
				continue;
			}
			else {
				debugf("**** Deleting %s\n",(PCC)zFile);
				DeleteFileA(zFile);
			}
		}
	}
}

<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/views/widget/desktop_native_widget_aura.h"

#include "ui/base/hit_test.h"
#include "ui/views/widget/desktop_root_window_host.h"

namespace views {

////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, public:

DesktopNativeWidgetAura::DesktopNativeWidgetAura(
    internal::NativeWidgetDelegate* delegate)
    : desktop_root_window_host_(DesktopRootWindowHost::Create()),
      window_(NULL),
      ownership_(Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET) {
}

DesktopNativeWidgetAura::~DesktopNativeWidgetAura() {
}

////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, internal::NativeWidgetPrivate implementation:

void DesktopNativeWidgetAura::InitNativeWidget(
    const Widget::InitParams& params) {
}

NonClientFrameView* DesktopNativeWidgetAura::CreateNonClientFrameView() {
  return NULL;
}

bool DesktopNativeWidgetAura::ShouldUseNativeFrame() const {
  return false;
}

void DesktopNativeWidgetAura::FrameTypeChanged() {
}

Widget* DesktopNativeWidgetAura::GetWidget() {
  return native_widget_delegate_->AsWidget();
}

const Widget* DesktopNativeWidgetAura::GetWidget() const {
  return native_widget_delegate_->AsWidget();
}

gfx::NativeView DesktopNativeWidgetAura::GetNativeView() const {
  return window_;
}

gfx::NativeWindow DesktopNativeWidgetAura::GetNativeWindow() const {
  return window_;
}

Widget* DesktopNativeWidgetAura::GetTopLevelWidget() {
  return GetWidget();
}

const ui::Compositor* DesktopNativeWidgetAura::GetCompositor() const {
  return NULL;
}

ui::Compositor* DesktopNativeWidgetAura::GetCompositor() {
  return NULL;
}

void DesktopNativeWidgetAura::CalculateOffsetToAncestorWithLayer(
      gfx::Point* offset,
      ui::Layer** layer_parent) {
}

void DesktopNativeWidgetAura::ViewRemoved(View* view) {
}

void DesktopNativeWidgetAura::SetNativeWindowProperty(const char* name,
                                                      void* value) {
}

void* DesktopNativeWidgetAura::GetNativeWindowProperty(const char* name) const {
  return NULL;
}

TooltipManager* DesktopNativeWidgetAura::GetTooltipManager() const {
  return NULL;
}

bool DesktopNativeWidgetAura::IsScreenReaderActive() const {
  return false;
}

void DesktopNativeWidgetAura::SendNativeAccessibilityEvent(
      View* view,
      ui::AccessibilityTypes::Event event_type) {
}

void DesktopNativeWidgetAura::SetCapture() {
}

void DesktopNativeWidgetAura::ReleaseCapture() {
}

bool DesktopNativeWidgetAura::HasCapture() const {
  return false;
}

InputMethod* DesktopNativeWidgetAura::CreateInputMethod() {
  return NULL;
}

internal::InputMethodDelegate*
    DesktopNativeWidgetAura::GetInputMethodDelegate() {
  return NULL;
}

void DesktopNativeWidgetAura::CenterWindow(const gfx::Size& size) {
}

void DesktopNativeWidgetAura::GetWindowPlacement(
      gfx::Rect* bounds,
      ui::WindowShowState* maximized) const {
}

void DesktopNativeWidgetAura::SetWindowTitle(const string16& title) {
}

void DesktopNativeWidgetAura::SetWindowIcons(const gfx::ImageSkia& window_icon,
                                             const gfx::ImageSkia& app_icon) {
}

void DesktopNativeWidgetAura::SetAccessibleName(const string16& name) {
}

void DesktopNativeWidgetAura::SetAccessibleRole(
    ui::AccessibilityTypes::Role role) {
}

void DesktopNativeWidgetAura::SetAccessibleState(
    ui::AccessibilityTypes::State state) {
}

void DesktopNativeWidgetAura::InitModalType(ui::ModalType modal_type) {
}

gfx::Rect DesktopNativeWidgetAura::GetWindowBoundsInScreen() const {
  return gfx::Rect(100, 100);
}

gfx::Rect DesktopNativeWidgetAura::GetClientAreaBoundsInScreen() const {
  return gfx::Rect(100, 100);
}

gfx::Rect DesktopNativeWidgetAura::GetRestoredBounds() const {
  return gfx::Rect(100, 100);
}

void DesktopNativeWidgetAura::SetBounds(const gfx::Rect& bounds) {
}

void DesktopNativeWidgetAura::SetSize(const gfx::Size& size) {
}

void DesktopNativeWidgetAura::StackAbove(gfx::NativeView native_view) {
}

void DesktopNativeWidgetAura::StackAtTop() {
}

void DesktopNativeWidgetAura::StackBelow(gfx::NativeView native_view) {
}

void DesktopNativeWidgetAura::SetShape(gfx::NativeRegion shape) {
}

void DesktopNativeWidgetAura::Close() {
}

void DesktopNativeWidgetAura::CloseNow() {
}

void DesktopNativeWidgetAura::Show() {
}

void DesktopNativeWidgetAura::Hide() {
}

void DesktopNativeWidgetAura::ShowMaximizedWithBounds(
      const gfx::Rect& restored_bounds) {
}

void DesktopNativeWidgetAura::ShowWithWindowState(ui::WindowShowState state) {
}

bool DesktopNativeWidgetAura::IsVisible() const {
  return false;
}

void DesktopNativeWidgetAura::Activate() {
}

void DesktopNativeWidgetAura::Deactivate() {
}

bool DesktopNativeWidgetAura::IsActive() const {
  return false;
}

void DesktopNativeWidgetAura::SetAlwaysOnTop(bool always_on_top) {
}

void DesktopNativeWidgetAura::Maximize() {
}

void DesktopNativeWidgetAura::Minimize() {
}

bool DesktopNativeWidgetAura::IsMaximized() const {
  return false;
}

bool DesktopNativeWidgetAura::IsMinimized() const {
  return false;
}

void DesktopNativeWidgetAura::Restore() {
}

void DesktopNativeWidgetAura::SetFullscreen(bool fullscreen) {
}

bool DesktopNativeWidgetAura::IsFullscreen() const {
  return false;
}

void DesktopNativeWidgetAura::SetOpacity(unsigned char opacity) {
}

void DesktopNativeWidgetAura::SetUseDragFrame(bool use_drag_frame) {
}

void DesktopNativeWidgetAura::FlashFrame(bool flash_frame) {
}

bool DesktopNativeWidgetAura::IsAccessibleWidget() const {
  return false;
}

void DesktopNativeWidgetAura::RunShellDrag(View* view,
                            const ui::OSExchangeData& data,
                            const gfx::Point& location,
                            int operation) {
}

void DesktopNativeWidgetAura::SchedulePaintInRect(const gfx::Rect& rect) {
}

void DesktopNativeWidgetAura::SetCursor(gfx::NativeCursor cursor) {
}

void DesktopNativeWidgetAura::ClearNativeFocus() {
}

void DesktopNativeWidgetAura::FocusNativeView(gfx::NativeView native_view) {
}

gfx::Rect DesktopNativeWidgetAura::GetWorkAreaBoundsInScreen() const {
  return gfx::Rect(100, 100);
}

void DesktopNativeWidgetAura::SetInactiveRenderingDisabled(bool value) {
}

Widget::MoveLoopResult DesktopNativeWidgetAura::RunMoveLoop(
      const gfx::Point& drag_offset) {
  return Widget::MOVE_LOOP_CANCELED;
}

void DesktopNativeWidgetAura::EndMoveLoop() {
}

void DesktopNativeWidgetAura::SetVisibilityChangedAnimationsEnabled(
    bool value) {
}

////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, aura::WindowDelegate implementation:

gfx::Size DesktopNativeWidgetAura::GetMinimumSize() const {
  return gfx::Size(100, 100);
}

void DesktopNativeWidgetAura::OnBoundsChanged(const gfx::Rect& old_bounds,
                               const gfx::Rect& new_bounds) {
}

void DesktopNativeWidgetAura::OnFocus(aura::Window* old_focused_window) {
}

void DesktopNativeWidgetAura::OnBlur() {
}

bool DesktopNativeWidgetAura::OnKeyEvent(ui::KeyEvent* event) {
  return false;
}

gfx::NativeCursor DesktopNativeWidgetAura::GetCursor(const gfx::Point& point) {
  return NULL;
}

int DesktopNativeWidgetAura::GetNonClientComponent(
    const gfx::Point& point) const {
  return HTCLIENT;
}

bool DesktopNativeWidgetAura::ShouldDescendIntoChildForEventHandling(
      aura::Window* child,
      const gfx::Point& location) {
  return true;
}

bool DesktopNativeWidgetAura::OnMouseEvent(ui::MouseEvent* event) {
  return false;
}

ui::TouchStatus DesktopNativeWidgetAura::OnTouchEvent(ui::TouchEvent* event) {
  return ui::TOUCH_STATUS_UNKNOWN;
}

ui::EventResult DesktopNativeWidgetAura::OnGestureEvent(
    ui::GestureEvent* event) {
  return ui::ER_UNHANDLED;
}

bool DesktopNativeWidgetAura::CanFocus() {
  return true;
}

void DesktopNativeWidgetAura::OnCaptureLost() {
}

void DesktopNativeWidgetAura::OnPaint(gfx::Canvas* canvas) {
}

void DesktopNativeWidgetAura::OnDeviceScaleFactorChanged(
    float device_scale_factor) {
}

void DesktopNativeWidgetAura::OnWindowDestroying() {
}

void DesktopNativeWidgetAura::OnWindowDestroyed() {
}

void DesktopNativeWidgetAura::OnWindowTargetVisibilityChanged(bool visible) {
}

bool DesktopNativeWidgetAura::HasHitTestMask() const {
  return false;
}

void DesktopNativeWidgetAura::GetHitTestMask(gfx::Path* mask) const {
}

}  // namespace views
<commit_msg>aura: Fix build on linux-aura.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/views/widget/desktop_native_widget_aura.h"

#include "ui/base/hit_test.h"
#include "ui/views/widget/desktop_root_window_host.h"

namespace views {

////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, public:

DesktopNativeWidgetAura::DesktopNativeWidgetAura(
    internal::NativeWidgetDelegate* delegate)
    : desktop_root_window_host_(DesktopRootWindowHost::Create()),
      window_(NULL),
      ownership_(Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET) {
}

DesktopNativeWidgetAura::~DesktopNativeWidgetAura() {
}

////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, internal::NativeWidgetPrivate implementation:

void DesktopNativeWidgetAura::InitNativeWidget(
    const Widget::InitParams& params) {
}

NonClientFrameView* DesktopNativeWidgetAura::CreateNonClientFrameView() {
  return NULL;
}

bool DesktopNativeWidgetAura::ShouldUseNativeFrame() const {
  return false;
}

void DesktopNativeWidgetAura::FrameTypeChanged() {
}

Widget* DesktopNativeWidgetAura::GetWidget() {
  return native_widget_delegate_->AsWidget();
}

const Widget* DesktopNativeWidgetAura::GetWidget() const {
  return native_widget_delegate_->AsWidget();
}

gfx::NativeView DesktopNativeWidgetAura::GetNativeView() const {
  return window_;
}

gfx::NativeWindow DesktopNativeWidgetAura::GetNativeWindow() const {
  return window_;
}

Widget* DesktopNativeWidgetAura::GetTopLevelWidget() {
  return GetWidget();
}

const ui::Compositor* DesktopNativeWidgetAura::GetCompositor() const {
  return NULL;
}

ui::Compositor* DesktopNativeWidgetAura::GetCompositor() {
  return NULL;
}

void DesktopNativeWidgetAura::CalculateOffsetToAncestorWithLayer(
      gfx::Point* offset,
      ui::Layer** layer_parent) {
}

void DesktopNativeWidgetAura::ViewRemoved(View* view) {
}

void DesktopNativeWidgetAura::SetNativeWindowProperty(const char* name,
                                                      void* value) {
}

void* DesktopNativeWidgetAura::GetNativeWindowProperty(const char* name) const {
  return NULL;
}

TooltipManager* DesktopNativeWidgetAura::GetTooltipManager() const {
  return NULL;
}

bool DesktopNativeWidgetAura::IsScreenReaderActive() const {
  return false;
}

void DesktopNativeWidgetAura::SendNativeAccessibilityEvent(
      View* view,
      ui::AccessibilityTypes::Event event_type) {
}

void DesktopNativeWidgetAura::SetCapture() {
}

void DesktopNativeWidgetAura::ReleaseCapture() {
}

bool DesktopNativeWidgetAura::HasCapture() const {
  return false;
}

InputMethod* DesktopNativeWidgetAura::CreateInputMethod() {
  return NULL;
}

internal::InputMethodDelegate*
    DesktopNativeWidgetAura::GetInputMethodDelegate() {
  return NULL;
}

void DesktopNativeWidgetAura::CenterWindow(const gfx::Size& size) {
}

void DesktopNativeWidgetAura::GetWindowPlacement(
      gfx::Rect* bounds,
      ui::WindowShowState* maximized) const {
}

void DesktopNativeWidgetAura::SetWindowTitle(const string16& title) {
}

void DesktopNativeWidgetAura::SetWindowIcons(const gfx::ImageSkia& window_icon,
                                             const gfx::ImageSkia& app_icon) {
}

void DesktopNativeWidgetAura::SetAccessibleName(const string16& name) {
}

void DesktopNativeWidgetAura::SetAccessibleRole(
    ui::AccessibilityTypes::Role role) {
}

void DesktopNativeWidgetAura::SetAccessibleState(
    ui::AccessibilityTypes::State state) {
}

void DesktopNativeWidgetAura::InitModalType(ui::ModalType modal_type) {
}

gfx::Rect DesktopNativeWidgetAura::GetWindowBoundsInScreen() const {
  return gfx::Rect(100, 100);
}

gfx::Rect DesktopNativeWidgetAura::GetClientAreaBoundsInScreen() const {
  return gfx::Rect(100, 100);
}

gfx::Rect DesktopNativeWidgetAura::GetRestoredBounds() const {
  return gfx::Rect(100, 100);
}

void DesktopNativeWidgetAura::SetBounds(const gfx::Rect& bounds) {
}

void DesktopNativeWidgetAura::SetSize(const gfx::Size& size) {
}

void DesktopNativeWidgetAura::StackAbove(gfx::NativeView native_view) {
}

void DesktopNativeWidgetAura::StackAtTop() {
}

void DesktopNativeWidgetAura::StackBelow(gfx::NativeView native_view) {
}

void DesktopNativeWidgetAura::SetShape(gfx::NativeRegion shape) {
}

void DesktopNativeWidgetAura::Close() {
}

void DesktopNativeWidgetAura::CloseNow() {
}

void DesktopNativeWidgetAura::Show() {
}

void DesktopNativeWidgetAura::Hide() {
}

void DesktopNativeWidgetAura::ShowMaximizedWithBounds(
      const gfx::Rect& restored_bounds) {
}

void DesktopNativeWidgetAura::ShowWithWindowState(ui::WindowShowState state) {
}

bool DesktopNativeWidgetAura::IsVisible() const {
  return false;
}

void DesktopNativeWidgetAura::Activate() {
}

void DesktopNativeWidgetAura::Deactivate() {
}

bool DesktopNativeWidgetAura::IsActive() const {
  return false;
}

void DesktopNativeWidgetAura::SetAlwaysOnTop(bool always_on_top) {
}

void DesktopNativeWidgetAura::Maximize() {
}

void DesktopNativeWidgetAura::Minimize() {
}

bool DesktopNativeWidgetAura::IsMaximized() const {
  return false;
}

bool DesktopNativeWidgetAura::IsMinimized() const {
  return false;
}

void DesktopNativeWidgetAura::Restore() {
}

void DesktopNativeWidgetAura::SetFullscreen(bool fullscreen) {
}

bool DesktopNativeWidgetAura::IsFullscreen() const {
  return false;
}

void DesktopNativeWidgetAura::SetOpacity(unsigned char opacity) {
}

void DesktopNativeWidgetAura::SetUseDragFrame(bool use_drag_frame) {
}

void DesktopNativeWidgetAura::FlashFrame(bool flash_frame) {
}

bool DesktopNativeWidgetAura::IsAccessibleWidget() const {
  return false;
}

void DesktopNativeWidgetAura::RunShellDrag(View* view,
                            const ui::OSExchangeData& data,
                            const gfx::Point& location,
                            int operation) {
}

void DesktopNativeWidgetAura::SchedulePaintInRect(const gfx::Rect& rect) {
}

void DesktopNativeWidgetAura::SetCursor(gfx::NativeCursor cursor) {
}

void DesktopNativeWidgetAura::ClearNativeFocus() {
}

void DesktopNativeWidgetAura::FocusNativeView(gfx::NativeView native_view) {
}

gfx::Rect DesktopNativeWidgetAura::GetWorkAreaBoundsInScreen() const {
  return gfx::Rect(100, 100);
}

void DesktopNativeWidgetAura::SetInactiveRenderingDisabled(bool value) {
}

Widget::MoveLoopResult DesktopNativeWidgetAura::RunMoveLoop(
      const gfx::Point& drag_offset) {
  return Widget::MOVE_LOOP_CANCELED;
}

void DesktopNativeWidgetAura::EndMoveLoop() {
}

void DesktopNativeWidgetAura::SetVisibilityChangedAnimationsEnabled(
    bool value) {
}

////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, aura::WindowDelegate implementation:

gfx::Size DesktopNativeWidgetAura::GetMinimumSize() const {
  return gfx::Size(100, 100);
}

void DesktopNativeWidgetAura::OnBoundsChanged(const gfx::Rect& old_bounds,
                               const gfx::Rect& new_bounds) {
}

void DesktopNativeWidgetAura::OnFocus(aura::Window* old_focused_window) {
}

void DesktopNativeWidgetAura::OnBlur() {
}

bool DesktopNativeWidgetAura::OnKeyEvent(ui::KeyEvent* event) {
  return false;
}

gfx::NativeCursor DesktopNativeWidgetAura::GetCursor(const gfx::Point& point) {
  return gfx::kNullCursor;
}

int DesktopNativeWidgetAura::GetNonClientComponent(
    const gfx::Point& point) const {
  return HTCLIENT;
}

bool DesktopNativeWidgetAura::ShouldDescendIntoChildForEventHandling(
      aura::Window* child,
      const gfx::Point& location) {
  return true;
}

bool DesktopNativeWidgetAura::OnMouseEvent(ui::MouseEvent* event) {
  return false;
}

ui::TouchStatus DesktopNativeWidgetAura::OnTouchEvent(ui::TouchEvent* event) {
  return ui::TOUCH_STATUS_UNKNOWN;
}

ui::EventResult DesktopNativeWidgetAura::OnGestureEvent(
    ui::GestureEvent* event) {
  return ui::ER_UNHANDLED;
}

bool DesktopNativeWidgetAura::CanFocus() {
  return true;
}

void DesktopNativeWidgetAura::OnCaptureLost() {
}

void DesktopNativeWidgetAura::OnPaint(gfx::Canvas* canvas) {
}

void DesktopNativeWidgetAura::OnDeviceScaleFactorChanged(
    float device_scale_factor) {
}

void DesktopNativeWidgetAura::OnWindowDestroying() {
}

void DesktopNativeWidgetAura::OnWindowDestroyed() {
}

void DesktopNativeWidgetAura::OnWindowTargetVisibilityChanged(bool visible) {
}

bool DesktopNativeWidgetAura::HasHitTestMask() const {
  return false;
}

void DesktopNativeWidgetAura::GetHitTestMask(gfx::Path* mask) const {
}

}  // namespace views
<|endoftext|>


<commit_before>#include <vw/Plate/ToastDem.h>
#include <vw/Plate/PlateManager.h>
#include <vw/Plate/PlateFile.h>
#include <vw/Core.h>
#include <boost/shared_ptr.hpp>
#include <boost/foreach.hpp>

#include <boost/program_options.hpp>
namespace po = boost::program_options;

#include <iostream>

using namespace std;
using namespace vw;
using namespace vw::platefile;

// There isn't much abstraction here. A Filter takes a platefile and writes a
// new platefile. This rules out lazy filters for the moment. The
// col/row/level/transaction_id is for the input value, the output can feel
// free to write things elsewhere.

// The function will be called for every input tile, including all transaction
// ids. The output function should feel no obligation to write a tile for every
// input.

template <typename ImplT>
struct FilterBase {
  inline ImplT& impl()             { return static_cast<ImplT&>(*this); }
  inline ImplT const& impl() const { return static_cast<ImplT const&>(*this); }

  inline void init(PlateFile& output, const PlateFile& input, int output_transaction_id) {
    return impl().init(output, input, output_transaction_id);
  }
  inline void fini(PlateFile& output, const PlateFile& input, int output_transaction_id) {
    return impl().fini(output, input, output_transaction_id);
  }

#   define lookup(name, type) type name(type data) const { return impl().name(data); }
    lookup(mode, string);
    lookup(tile_size, int);
    lookup(filetype, string);
    lookup(pixel_format, PixelFormatEnum);
    lookup(channel_type, ChannelTypeEnum);
#   undef lookup

  inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 input_transaction_id, int32 output_transaction_id) {
    impl()(output, input, col, row, level, input_transaction_id, output_transaction_id);
  }
};

struct Identity : public FilterBase<Identity> {
#   define lookup(name, type) type name(type data) const { return data; }
    lookup(mode, string);
    lookup(tile_size, int);
    lookup(filetype, string);
    lookup(pixel_format, PixelFormatEnum);
    lookup(channel_type, ChannelTypeEnum);
#   undef lookup

  inline void init(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_request(); }
  inline void fini(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_complete(); }

  inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 input_transaction_id, int32 output_transaction_id) {
    ImageView<PixelRGBA<double> > tile;
    TileHeader hdr = input.read(tile, col, row, level, input_transaction_id);
    output.write_update(tile, col, row, level, output_transaction_id);
  }
};

struct ToastDem : public FilterBase<ToastDem> {
  string mode(string) const { return "toast_dem"; }
  int tile_size(int)  const { return 32; }
  string filetype(string) const { return "toast_dem_v1"; }
  PixelFormatEnum pixel_format(PixelFormatEnum) const { return VW_PIXEL_SCALAR; }
  ChannelTypeEnum channel_type(ChannelTypeEnum) const { return VW_CHANNEL_UINT8; }

  inline void init(PlateFile& output, const PlateFile& input, int output_transaction_id) {
    output.write_request();

    // Write null tiles for the levels we don't have data for
    int level_difference = log(input.default_tile_size()/float(output.default_tile_size())) / log(2.) + 0.5;

    vw_out(InfoMessage, "plate.tools.plate2plate") << "Creating null tiles for a level difference of " << level_difference << std::endl;

    uint64 bytes;
    boost::shared_array<uint8> null_tile = toast_dem_null_tile(bytes);

    for (int level = 0; level < level_difference; ++level) {
      int region_size = 1 << level;
      for (int col = 0; col < region_size; ++col)
        for (int row = 0; row < region_size; ++row)
          output.write_update(null_tile, bytes, col, row, level, output_transaction_id);
    }
  }

  inline void fini(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) {
    output.write_complete();
  }

  struct DemWriter : public ToastDemWriter {
    PlateFile& platefile;
    DemWriter(PlateFile& output) : platefile(output) { }
    inline void operator()(const boost::shared_array<uint8> data, uint64 data_size,
                           int32 dem_col, int32 dem_row,
                           int32 dem_level, int32 output_transaction_id) const {
      platefile.write_update(data, data_size, dem_col, dem_row,
                             dem_level, output_transaction_id);
    }
  };

  inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 input_transaction_id, int32 output_transaction_id) {
    DemWriter writer(output);
    make_toast_dem_tile(writer, input, col, row, level, input_transaction_id, output_transaction_id);
  }
};

struct Options {
  string input_name;
  string output_name;

  string mode;
  string description;
  int tile_size;
  string filetype;
  PixelFormatEnum pixel_format;
  ChannelTypeEnum channel_type;
  int bottom_level;

  string filter;

  Options() :
    tile_size(0), pixel_format(VW_PIXEL_UNKNOWN), channel_type(VW_CHANNEL_UNKNOWN) {}
};

VW_DEFINE_EXCEPTION(Usage, Exception);

void handle_arguments(int argc, char *argv[], Options& opt) {
  po::options_description options("Options");
  options.add_options()
    ("output-name,o",    po::value(&opt.output_name),  "Specify the URL of the input platefile.")
    ("input-name,i",     po::value(&opt.input_name),   "Specify the URL of the output platefile.")
    ("file-type",        po::value(&opt.filetype),     "Output file type")
    ("mode",             po::value(&opt.mode),         "Output mode [toast, kml]")
    ("tile-size",        po::value(&opt.tile_size),    "Output size, in pixels")
    ("filter",           po::value(&opt.filter),       "Filters to run")
    ("bottom-level",     po::value(&opt.bottom_level), "Bottom level to process")
    ("help,h",           "Display this help message.");

  po::variables_map vm;
  try {
    po::store( po::command_line_parser( argc, argv ).options(options).run(), vm );
    po::notify( vm );
  } catch (po::error &e) {
    vw_throw(Usage() << "Error parsing input:\n\t" << e.what() << "\n" << options );
  }

  if (opt.output_name.empty() || opt.input_name.empty() || opt.filter.empty())
    vw_throw(Usage() << options);
}

template <typename FilterT>
void run(Options& opt, FilterBase<FilterT>& filter) {
  PlateFile input(opt.input_name);

  // Use given option first, then use filter recommendation (it will probably
  // just recommend the value from the input platefile)

  if (opt.mode.empty())
    opt.mode = filter.mode(input.index_header().type());
  if (opt.tile_size == 0)
    opt.tile_size = filter.tile_size(input.default_tile_size());
  if (opt.filetype.empty())
    opt.filetype = filter.filetype(input.default_file_type());
  if (opt.pixel_format == VW_PIXEL_UNKNOWN)
    opt.pixel_format = filter.pixel_format(input.pixel_format());
  if (opt.channel_type == VW_CHANNEL_UNKNOWN)
    opt.channel_type = filter.channel_type(input.channel_type());

  PlateFile output(opt.output_name, opt.mode, opt.description, opt.tile_size, opt.filetype, opt.pixel_format, opt.channel_type);

  int output_transaction_id = output.transaction_request("plate2plate, reporting for duty", -1);

  filter.init(output, input, output_transaction_id);

  VW_ASSERT(input.num_levels() < 31, ArgumentErr() << "Can't handle plates deeper than 32 levels");

  int bottom_level = min(input.num_levels(), opt.bottom_level+1);

  for (int level = 0; level < bottom_level; ++level) {
    vw_out(InfoMessage) << "\nProcessing level " << level << " of " << bottom_level-1 << ".  ";
    TerminalProgressCallback tpc("plate.plate2plate.progress", "");
    vw::Timer timer( "\t    Processing time in seconds" );

    // The entire region contains 2^level tiles.
    int32 region_size = 1 << level;
    int subdivided_region_size = 1024;
    if (subdivided_region_size < region_size) subdivided_region_size = region_size;

    BBox2i full_region(0,0,region_size,region_size);
    std::list<BBox2i> boxes1 = bbox_tiles(full_region,
                                          subdivided_region_size,
                                          subdivided_region_size);

    vw_out(InfoMessage) << "Region"   << full_region << " has " << boxes1.size() << " bboxes\n";

    float region_counter = 0;
    BOOST_FOREACH( const BBox2i& region1, boxes1 ) {
      std::cout << "\n\t--> Sub-region: " << region1 << "\n";
      std::list<TileHeader> tiles = input.search_by_region(level, region1, 0,
                                                           input.transaction_cursor(), true);
      //      if (tiles.size() > 0)
      //      std::cout << "\t--> Region " << region1 << " has " << tiles.size() << " tiles.\n";
      std::ostringstream ostr;
      ostr << "\t    Converting " << tiles.size() << " tiles: ";
      tpc.set_progress_text(ostr.str());
      SubProgressCallback sub_progress(tpc,
                                       region_counter / boxes1.size(),
                                       (region_counter+1.0) / boxes1.size());
      BOOST_FOREACH( const TileHeader& tile, tiles ) {
        // ++n;
        // if (n % 100 == 0)
        //   std::cout << "n = " << n << "  --  "<< tile.col() << " " << tile.row() << " " << tile.level() << " " << tile.transaction_id() << "\n";
        filter(output, input, tile.col(), tile.row(), tile.level(),
               tile.transaction_id(), output_transaction_id);
        sub_progress.report_incremental_progress(1.0/tiles.size());
      }
      sub_progress.report_finished();
      region_counter++;
    }
    tpc.report_finished();
    output.sync();
  }

  filter.fini(output, input, output_transaction_id);

  output.transaction_complete(output_transaction_id, true);
}

// Blah blah boilerplate
int main(int argc, char *argv[])
{
  Options opt;
  try {
    handle_arguments(argc, argv, opt);
    boost::to_lower(opt.filter);
    if (opt.filter == "identity") {
      Identity f;
      run(opt, f);
    } else if (opt.filter == "toast_dem") {
      ToastDem f;
      run(opt, f);
    }
  } catch (const Usage& e) {
    std::cout << e.what() << std::endl;
    return 1;
  } catch (const Exception& e) {
    std::cerr << "Error: " << e.what() << std::endl;
    return 1;
  }
  return 0;
}
<commit_msg>Added skim mode for plate2plate<commit_after>#include <vw/Plate/ToastDem.h>
#include <vw/Plate/PlateManager.h>
#include <vw/Plate/PlateFile.h>
#include <vw/Core.h>
#include <boost/shared_ptr.hpp>
#include <boost/foreach.hpp>

#include <boost/program_options.hpp>
namespace po = boost::program_options;

#include <iostream>

using namespace std;
using namespace vw;
using namespace vw::platefile;

// There isn't much abstraction here. A Filter takes a platefile and writes a
// new platefile. This rules out lazy filters for the moment. The
// col/row/level/transaction_id is for the input value, the output can feel
// free to write things elsewhere.

// The function will be called for every input tile, including all transaction
// ids. The output function should feel no obligation to write a tile for every
// input.

template <typename ImplT>
struct FilterBase {
  inline ImplT& impl()             { return static_cast<ImplT&>(*this); }
  inline ImplT const& impl() const { return static_cast<ImplT const&>(*this); }

  inline void init(PlateFile& output, const PlateFile& input, int output_transaction_id) {
    return impl().init(output, input, output_transaction_id);
  }
  inline void fini(PlateFile& output, const PlateFile& input, int output_transaction_id) {
    return impl().fini(output, input, output_transaction_id);
  }

#   define lookup(name, type) type name(type data) const { return impl().name(data); }
    lookup(mode, string);
    lookup(tile_size, int);
    lookup(filetype, string);
    lookup(pixel_format, PixelFormatEnum);
    lookup(channel_type, ChannelTypeEnum);
#   undef lookup

  inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 input_transaction_id, int32 output_transaction_id) {
    impl()(output, input, col, row, level, input_transaction_id, output_transaction_id);
  }
};

struct Identity : public FilterBase<Identity> {
#   define lookup(name, type) type name(type data) const { return data; }
    lookup(mode, string);
    lookup(tile_size, int);
    lookup(filetype, string);
    lookup(pixel_format, PixelFormatEnum);
    lookup(channel_type, ChannelTypeEnum);
#   undef lookup

  inline void init(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_request(); }
  inline void fini(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) { output.write_complete(); }

  inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 input_transaction_id, int32 output_transaction_id) {
    ImageView<PixelRGBA<double> > tile;
    TileHeader hdr = input.read(tile, col, row, level, input_transaction_id);
    output.write_update(tile, col, row, level, output_transaction_id);
  }
};

struct ToastDem : public FilterBase<ToastDem> {
  string mode(string) const { return "toast_dem"; }
  int tile_size(int)  const { return 32; }
  string filetype(string) const { return "toast_dem_v1"; }
  PixelFormatEnum pixel_format(PixelFormatEnum) const { return VW_PIXEL_SCALAR; }
  ChannelTypeEnum channel_type(ChannelTypeEnum) const { return VW_CHANNEL_UINT8; }

  inline void init(PlateFile& output, const PlateFile& input, int output_transaction_id) {
    output.write_request();

    // Write null tiles for the levels we don't have data for
    int level_difference = log(input.default_tile_size()/float(output.default_tile_size())) / log(2.) + 0.5;

    vw_out(InfoMessage, "plate.tools.plate2plate") << "Creating null tiles for a level difference of " << level_difference << std::endl;

    uint64 bytes;
    boost::shared_array<uint8> null_tile = toast_dem_null_tile(bytes);

    for (int level = 0; level < level_difference; ++level) {
      int region_size = 1 << level;
      for (int col = 0; col < region_size; ++col)
        for (int row = 0; row < region_size; ++row)
          output.write_update(null_tile, bytes, col, row, level, output_transaction_id);
    }
  }

  inline void fini(PlateFile& output, const PlateFile& /*input*/, int /*transaction_id*/) {
    output.write_complete();
  }

  struct DemWriter : public ToastDemWriter {
    PlateFile& platefile;
    DemWriter(PlateFile& output) : platefile(output) { }
    inline void operator()(const boost::shared_array<uint8> data, uint64 data_size,
                           int32 dem_col, int32 dem_row,
                           int32 dem_level, int32 output_transaction_id) const {
      platefile.write_update(data, data_size, dem_col, dem_row,
                             dem_level, output_transaction_id);
    }
  };

  inline void operator()( PlateFile& output, const PlateFile& input, int32 col, int32 row, int32 level, int32 input_transaction_id, int32 output_transaction_id) {
    DemWriter writer(output);
    make_toast_dem_tile(writer, input, col, row, level, input_transaction_id, output_transaction_id);
  }
};

struct Options {
  string input_name;
  string output_name;

  string mode;
  string description;
  int tile_size;
  string filetype;
  PixelFormatEnum pixel_format;
  ChannelTypeEnum channel_type;
  int bottom_level;
  bool skim_mode;

  string filter;

  Options() :
    tile_size(0), pixel_format(VW_PIXEL_UNKNOWN), channel_type(VW_CHANNEL_UNKNOWN) {}
};

VW_DEFINE_EXCEPTION(Usage, Exception);

void handle_arguments(int argc, char *argv[], Options& opt) {
  po::options_description options("Options");
  options.add_options()
    ("output-name,o",    po::value(&opt.output_name),  "Specify the URL of the input platefile.")
    ("input-name,i",     po::value(&opt.input_name),   "Specify the URL of the output platefile.")
    ("file-type",        po::value(&opt.filetype),     "Output file type")
    ("mode",             po::value(&opt.mode),         "Output mode [toast, kml]")
    ("tile-size",        po::value(&opt.tile_size),    "Output size, in pixels")
    ("filter",           po::value(&opt.filter),       "Filters to run [identity, toast_dem]")
    ("bottom-level",     po::value(&opt.bottom_level), "Bottom level to process")
    ("skim-last-id-only", "Only process the last transaction id from the input")
    ("help,h",           "Display this help message.");

  po::variables_map vm;
  try {
    po::store( po::command_line_parser( argc, argv ).options(options).run(), vm );
    po::notify( vm );
  } catch (po::error &e) {
    vw_throw(Usage() << "Error parsing input:\n\t" << e.what() << "\n" << options );
  }

  opt.skim_mode = vm.count("skim-last-id-only");

  if (opt.output_name.empty() || opt.input_name.empty())
    vw_throw(Usage() << "Requires input and output defined!\n" << options);
  if ( opt.filter.empty() )
    vw_throw(Usage() << "Requires filter to be defined!\n" << options);
}

template <typename FilterT>
void run(Options& opt, FilterBase<FilterT>& filter) {
  PlateFile input(opt.input_name);

  // Use given option first, then use filter recommendation (it will probably
  // just recommend the value from the input platefile)

  if (opt.mode.empty())
    opt.mode = filter.mode(input.index_header().type());
  if (opt.tile_size == 0)
    opt.tile_size = filter.tile_size(input.default_tile_size());
  if (opt.filetype.empty())
    opt.filetype = filter.filetype(input.default_file_type());
  if (opt.pixel_format == VW_PIXEL_UNKNOWN)
    opt.pixel_format = filter.pixel_format(input.pixel_format());
  if (opt.channel_type == VW_CHANNEL_UNKNOWN)
    opt.channel_type = filter.channel_type(input.channel_type());

  PlateFile output(opt.output_name, opt.mode, opt.description, opt.tile_size, opt.filetype, opt.pixel_format, opt.channel_type);

  int output_transaction_id = output.transaction_request("plate2plate, reporting for duty", -1);

  filter.init(output, input, output_transaction_id);

  VW_ASSERT(input.num_levels() < 31, ArgumentErr() << "Can't handle plates deeper than 32 levels");

  int bottom_level = min(input.num_levels(), opt.bottom_level+1);

  for (int level = 0; level < bottom_level; ++level) {
    vw_out(InfoMessage) << "\nProcessing level " << level << " of " << bottom_level-1 << ".  ";
    TerminalProgressCallback tpc("plate.plate2plate.progress", "");
    vw::Timer timer( "\t    Processing time in seconds" );

    // The entire region contains 2^level tiles.
    int32 region_size = 1 << level;
    int subdivided_region_size = 1024;
    if (subdivided_region_size < region_size) subdivided_region_size = region_size;

    BBox2i full_region(0,0,region_size,region_size);
    std::list<BBox2i> boxes1 = bbox_tiles(full_region,
                                          subdivided_region_size,
                                          subdivided_region_size);

    vw_out(InfoMessage) << "Region"   << full_region << " has " << boxes1.size() << " bboxes\n";

    float region_counter = 0;
    BOOST_FOREACH( const BBox2i& region1, boxes1 ) {
      std::cout << "\n\t--> Sub-region: " << region1 << "\n";
      std::list<TileHeader> tiles;
      if ( !opt.skim_mode )
        tiles = input.search_by_region(level, region1, 0,
                                       input.transaction_cursor(), true);
      else
        tiles = input.search_by_region(level, region1, -1, -1, true);

      //      if (tiles.size() > 0)
      //      std::cout << "\t--> Region " << region1 << " has " << tiles.size() << " tiles.\n";
      std::ostringstream ostr;
      ostr << "\t    Converting " << tiles.size() << " tiles: ";
      tpc.set_progress_text(ostr.str());
      SubProgressCallback sub_progress(tpc,
                                       region_counter / boxes1.size(),
                                       (region_counter+1.0) / boxes1.size());
      BOOST_FOREACH( const TileHeader& tile, tiles ) {
        // ++n;
        // if (n % 100 == 0)
        //   std::cout << "n = " << n << "  --  "<< tile.col() << " " << tile.row() << " " << tile.level() << " " << tile.transaction_id() << "\n";
        filter(output, input, tile.col(), tile.row(), tile.level(),
               tile.transaction_id(), output_transaction_id);
        sub_progress.report_incremental_progress(1.0/tiles.size());
      }
      sub_progress.report_finished();
      region_counter++;
    }
    tpc.report_finished();
    output.sync();
  }

  filter.fini(output, input, output_transaction_id);

  output.transaction_complete(output_transaction_id, true);
}

// Blah blah boilerplate
int main(int argc, char *argv[])
{
  Options opt;
  try {
    handle_arguments(argc, argv, opt);
    boost::to_lower(opt.filter);
    if (opt.filter == "identity") {
      Identity f;
      run(opt, f);
    } else if (opt.filter == "toast_dem") {
      ToastDem f;
      run(opt, f);
    }
  } catch (const Usage& e) {
    std::cout << e.what() << std::endl;
    return 1;
  } catch (const Exception& e) {
    std::cerr << "Error: " << e.what() << std::endl;
    return 1;
  }
  return 0;
}
<|endoftext|>


<commit_before>/** @file edgeelement.cpp
 * 	@brief Класс, представляющий связь на диаграмме
 * */
#include <QtGui/QStyleOptionGraphicsItem>
#include <QtGui/QStyle>
#include <QtGui/QTextDocument>
#include <QtGui/QMenu>
#include <math.h>

#include "../view/editorviewscene.h"
#include "uml_edgeelement.h"
#include "uml_nodeelement.h"
#include "../model/model.h"

using namespace UML;
using namespace qReal;

#ifndef M_PI
/** @brief Константа ПИ */
#define M_PI 3.14159265358979323846264338327950288419717
/** @brief Константа 1/ПИ */
#define M_1_PI 1/M_PI;
// Реквестирую ещё массу бозона Хиггса!
// Here you are: The God's particle energy (in GeV)
#define HIGGS_BOSON_MASS_APPROX 251
#endif //M_PI

/** @brief Индикатор перемещения связи */
// static bool moving = false;

EdgeElement::EdgeElement()
	: mPenStyle(Qt::SolidLine), mStartArrowStyle(NO_ARROW), mEndArrowStyle(NO_ARROW),
	mSrc(NULL), mDst(NULL), mPortFrom(0), mPortTo(0),
	mDragState(-1), mLongPart(0), mBeginning(NULL), mEnding(NULL)
{
	setZValue(100);
	setFlag(ItemIsMovable, true);
	// FIXME: draws strangely...
	setFlag(ItemClipsToShape, false);

	mLine << QPointF(0, 0) << QPointF(200, 60);
}

EdgeElement::~EdgeElement()
{
	if (mSrc)
		mSrc->delEdge(this);
	if (mDst)
		mDst->delEdge(this);
}

QRectF EdgeElement::boundingRect() const
{
	return mLine.boundingRect().adjusted(-20, -20, 20, 20);
}

static double lineAngle(const QLineF &line)
{
	double angle = ::acos(line.dx() / line.length());
	if (line.dy() >= 0)
		angle = 2 * M_PI - angle;

	return angle * 180 * M_1_PI;
}

void EdgeElement::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget*)
{
	painter->save();
	QPen pen = painter->pen();
	pen.setColor(mColor);
	pen.setStyle(mPenStyle);
	pen.setWidth(1);
	painter->setPen(pen);
	painter->drawPolyline(mLine);
	painter->restore();

	painter->save();
	painter->translate(mLine[0]);
	painter->drawText(QPointF(10, 20), mFromMult);
	painter->rotate(90 - lineAngle(QLineF(mLine[1], mLine[0])));
	drawStartArrow(painter);
	painter->restore();

	painter->save();
	painter->translate(mLine[mLine.size() - 1]);
	painter->drawText(QPointF(10, 20), mToMult);
	painter->rotate(90 - lineAngle(QLineF(mLine[mLine.size() - 2], mLine[mLine.size() - 1])));
	drawEndArrow(painter);
	painter->restore();

	if (option->state & QStyle::State_Selected) {
		painter->setBrush(Qt::SolidPattern);
		foreach (QPointF const point, mLine) {
			QPen pen;
			QColor color;

			color.setNamedColor("#c3dcc4");
			pen.setWidth(11);
			pen.setColor(color);
			painter->setPen(pen);
			painter->drawPoint(point);

			color.setNamedColor("#465945");
			pen.setWidth(3);
			pen.setColor(color);
			painter->setPen(pen);
			painter->drawPoint(point);
		}
	}

	if (!mText.isEmpty()) {
		painter->save();
		QLineF longest(mLine[mLongPart], mLine[mLongPart + 1]);
		painter->translate(mLine[mLongPart]);
		painter->rotate(-lineAngle(longest));

		QTextDocument text;
		text.setHtml(mText);
		text.setTextWidth(longest.length());
		text.drawContents(painter);

		painter->restore();
	}
}

bool canBeConnected(int linkID, int from, int to);

QPainterPath EdgeElement::shape() const
{
	QPainterPath path;
	path.setFillRule(Qt::WindingFill);

	QPainterPathStroker ps;
	ps.setWidth(kvadratik);

	path.addPolygon(mLine);
	path = ps.createStroke(path);

	foreach (QPointF const point, mLine) {
		path.addRect(getPortRect(point));
	}

	return path;
}

QRectF EdgeElement::getPortRect(QPointF const &point)
{
	return QRectF(point - QPointF(kvadratik, kvadratik), QSizeF(kvadratik * 2, kvadratik * 2));
}

int EdgeElement::getPoint(const QPointF &location)
{
	for (int i = 0; i < mLine.size(); ++i)
		if (getPortRect(mLine[i]).contains(location))
			return i;

	return -1;
}

void EdgeElement::updateLongestPart()
{
	qreal maxLen = 0.0;
	int maxIdx = 0;
	for (int i = 0; i < mLine.size() - 1; ++i) {
		qreal newLen = QLineF(mLine[i], mLine[i + 1]).length();
		if (newLen > maxLen) {
			maxLen = newLen;
			maxIdx = i;
		}
	}
	mLongPart = maxIdx;
}

void EdgeElement::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
	mDragState = -1;

	if (isSelected())
		mDragState = getPoint(event->pos());

	if (mDragState == -1)
		Element::mousePressEvent(event);
}

void EdgeElement::connectToPort()
{
	model::Model *model = const_cast<model::Model *>(static_cast<model::Model const *>(mDataIndex.model()));  // TODO: OMG!

	setPos(pos() + mLine.first());
	mLine.translate(-mLine.first());

	mMoving = true;

	// Now we check whether start or end have been connected
	NodeElement *new_src = getNodeAt(mLine.first());
	mPortFrom = new_src ? new_src->getPortId(mapToItem(new_src, mLine.first())) : -1.0;

	if (mSrc) {
		mSrc->delEdge(this);
		mSrc = 0;
	}

	if (mPortFrom >= 0.0) {
		mSrc = new_src;
		mSrc->addEdge(this);
	}

	model->setData(mDataIndex, (mSrc ? mSrc->uuid() : ROOT_ID).toVariant(), roles::fromRole);
	model->setData(mDataIndex, mPortFrom, roles::fromPortRole);

	NodeElement *new_dst = getNodeAt(mLine.last());
	mPortTo = new_dst ? new_dst->getPortId(mapToItem(new_dst, mLine.last())) : -1.0;

	if (mDst) {
		mDst->delEdge(this);
		mDst = 0;
	}

	if (mPortTo >= 0.0) {
		mDst = new_dst;
		mDst->addEdge(this);
	}

	model->setData(mDataIndex, (mDst ? mDst->uuid() : ROOT_ID).toVariant(), roles::toRole);
	model->setData(mDataIndex, mPortTo, roles::toPortRole);

	setFlag(ItemIsMovable, !(mDst || mSrc));

	model->setData(mDataIndex, pos(), roles::positionRole);
	model->setData(mDataIndex, mLine.toPolygon(), roles::configurationRole);

	mMoving = false;

	adjustLink();
}

void EdgeElement::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
	NodeElement *new_src = getNodeAt(mLine.first());
	NodeElement *new_dst = getNodeAt(mLine.back());

	if (mBeginning) {
		if (mBeginning != new_src) {
			mBeginning->setPortsVisible(false);
		}
	}

	if (mEnding) {
		if (mEnding != new_dst) {
			mEnding->setPortsVisible(false);
		}
	}

	mBeginning = new_src;
	mEnding = new_dst;

	if (mBeginning)
		mBeginning->setPortsVisible(true);

	if (mEnding)
		mEnding->setPortsVisible(true);

	if (mDragState == -1) {
		Element::mouseMoveEvent(event);
	} else {
		prepareGeometryChange();
		mLine[mDragState] = event->pos();
		updateLongestPart();
	}
}

void EdgeElement::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
	if (mDragState == -1)
		Element::mouseReleaseEvent(event);
	else
		mDragState = -1;

	connectToPort();

	if (mBeginning)
		mBeginning->setPortsVisible(false);

	if (mEnding)
		mEnding->setPortsVisible(false);

	// cleanup after moving/resizing
	mBeginning = mEnding = NULL;
}

NodeElement *EdgeElement::getNodeAt(QPointF const &position)
{
	QPainterPath circlePath;
	circlePath.addEllipse(mapToScene(position), 12, 12);
	foreach (QGraphicsItem *item, scene()->items(circlePath)) {
		NodeElement *e = dynamic_cast<NodeElement *>(item);
		if (e) {
			return e;
		}
	}
	return NULL;
}

void EdgeElement::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
	QMenu menu;

	QAction *addPointAction = menu.addAction("Add point");
	QAction *delPointAction = menu.addAction("Remove point");
	QAction *squarizeAction = menu.addAction("Squarize");

	if (QAction *selectedAction = menu.exec(event->screenPos())) {
		if (selectedAction == delPointAction) {
			int pointIndex = getPoint(event->pos());
			if (pointIndex != -1) {
				prepareGeometryChange();
				mLine.remove(pointIndex);
				mLongPart = 0;
				update();
			}
		} else if (selectedAction == addPointAction) {
			for (int i = 0; i < mLine.size() - 1; ++i) {
				QPainterPath path;
				QPainterPathStroker ps;
				ps.setWidth(kvadratik);

				path.moveTo(mLine[i]);
				path.lineTo(mLine[i+1]);
				if (ps.createStroke(path).contains(event->pos())) {
					mLine.insert(i + 1, event->pos());
					update();
					break;
				}
			}
		} else if (selectedAction == squarizeAction) {
			prepareGeometryChange();
			for (int i = 0; i < mLine.size() - 1; ++i) {
				QLineF line(mLine[i], mLine[i + 1]);
				if (qAbs(line.dx()) < qAbs(line.dy())) {
					mLine[i + 1].setX(mLine[i].x());
				} else {
					mLine[i + 1].setY(mLine[i].y());
				}
			}
			adjustLink();
			update();
		}
	}
}

void EdgeElement::adjustLink()
{
	prepareGeometryChange();
	if (mSrc)
		mLine.first() = mapFromItem(mSrc, mSrc->getPortPos(mPortFrom));
	if (mDst)
		mLine.last() = mapFromItem(mDst, mDst->getPortPos(mPortTo));
	updateLongestPart();
}

void EdgeElement::updateData()
{
	if (mMoving)
		return;

	Element::updateData();

	setPos(mDataIndex.data(roles::positionRole).toPointF());
	QPolygonF newLine = mDataIndex.data(roles::configurationRole).value<QPolygon>();
	if (!newLine.isEmpty())
		mLine = newLine;

	qReal::Id uuidFrom = mDataIndex.data(roles::fromRole).value<Id>();
	qReal::Id uuidTo = mDataIndex.data(roles::toRole).value<Id>();

	if (mSrc)
		mSrc->delEdge(this);
	if (mDst)
		mDst->delEdge(this);

	mSrc = dynamic_cast<NodeElement *>(static_cast<EditorViewScene *>(scene())->getElem(uuidFrom));
	mDst = dynamic_cast<NodeElement *>(static_cast<EditorViewScene *>(scene())->getElem(uuidTo));

	if (mSrc)
		mSrc->addEdge(this);
	if (mDst)
		mDst->addEdge(this);

	setFlag(ItemIsMovable, !(mDst || mSrc));

	mPortFrom = mDataIndex.data(roles::fromPortRole).toDouble();
	mPortTo = mDataIndex.data(roles::toPortRole).toDouble();

	adjustLink();
}

void EdgeElement::removeLink(UML::NodeElement const *from)
{
	if (mSrc == from)
		mSrc = NULL;

	if (mDst == from)
		mDst = NULL;
}
<commit_msg>Яшины пожелания по поведению линков, +1 к юзабилити.<commit_after>/** @file edgeelement.cpp
 * 	@brief Класс, представляющий связь на диаграмме
 * */
#include <QtGui/QStyleOptionGraphicsItem>
#include <QtGui/QStyle>
#include <QtGui/QTextDocument>
#include <QtGui/QMenu>
#include <math.h>

#include "../view/editorviewscene.h"
#include "uml_edgeelement.h"
#include "uml_nodeelement.h"
#include "../model/model.h"

using namespace UML;
using namespace qReal;

#ifndef M_PI
/** @brief Константа ПИ */
#define M_PI 3.14159265358979323846264338327950288419717
/** @brief Константа 1/ПИ */
#define M_1_PI 1/M_PI;
// Реквестирую ещё массу бозона Хиггса!
// Here you are: The God's particle energy (in GeV)
#define HIGGS_BOSON_MASS_APPROX 251
#endif //M_PI

/** @brief Индикатор перемещения связи */
// static bool moving = false;

EdgeElement::EdgeElement()
	: mPenStyle(Qt::SolidLine), mStartArrowStyle(NO_ARROW), mEndArrowStyle(NO_ARROW),
	mSrc(NULL), mDst(NULL), mPortFrom(0), mPortTo(0),
	mDragState(-1), mLongPart(0), mBeginning(NULL), mEnding(NULL)
{
	setZValue(100);
	setFlag(ItemIsMovable, true);
	// FIXME: draws strangely...
	setFlag(ItemClipsToShape, false);

	mLine << QPointF(0, 0) << QPointF(200, 60);
}

EdgeElement::~EdgeElement()
{
	if (mSrc)
		mSrc->delEdge(this);
	if (mDst)
		mDst->delEdge(this);
}

QRectF EdgeElement::boundingRect() const
{
	return mLine.boundingRect().adjusted(-20, -20, 20, 20);
}

static double lineAngle(const QLineF &line)
{
	double angle = ::acos(line.dx() / line.length());
	if (line.dy() >= 0)
		angle = 2 * M_PI - angle;

	return angle * 180 * M_1_PI;
}

void EdgeElement::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget*)
{
	painter->save();
	QPen pen = painter->pen();
	pen.setColor(mColor);
	pen.setStyle(mPenStyle);
	pen.setWidth(1);
	painter->setPen(pen);
	painter->drawPolyline(mLine);
	painter->restore();

	painter->save();
	painter->translate(mLine[0]);
	painter->drawText(QPointF(10, 20), mFromMult);
	painter->rotate(90 - lineAngle(QLineF(mLine[1], mLine[0])));
	drawStartArrow(painter);
	painter->restore();

	painter->save();
	painter->translate(mLine[mLine.size() - 1]);
	painter->drawText(QPointF(10, 20), mToMult);
	painter->rotate(90 - lineAngle(QLineF(mLine[mLine.size() - 2], mLine[mLine.size() - 1])));
	drawEndArrow(painter);
	painter->restore();

	if (option->state & QStyle::State_Selected) {
		painter->setBrush(Qt::SolidPattern);
		foreach (QPointF const point, mLine) {
			QPen pen;
			QColor color;

			color.setNamedColor("#c3dcc4");
			pen.setWidth(11);
			pen.setColor(color);
			painter->setPen(pen);
			painter->drawPoint(point);

			color.setNamedColor("#465945");
			pen.setWidth(3);
			pen.setColor(color);
			painter->setPen(pen);
			painter->drawPoint(point);
		}
	}

	if (!mText.isEmpty()) {
		painter->save();
		QLineF longest(mLine[mLongPart], mLine[mLongPart + 1]);
		painter->translate(mLine[mLongPart]);
		painter->rotate(-lineAngle(longest));

		QTextDocument text;
		text.setHtml(mText);
		text.setTextWidth(longest.length());
		text.drawContents(painter);

		painter->restore();
	}
}

bool canBeConnected(int linkID, int from, int to);

QPainterPath EdgeElement::shape() const
{
	QPainterPath path;
	path.setFillRule(Qt::WindingFill);

	QPainterPathStroker ps;
	ps.setWidth(kvadratik);

	path.addPolygon(mLine);
	path = ps.createStroke(path);

	foreach (QPointF const point, mLine) {
		path.addRect(getPortRect(point));
	}

	return path;
}

QRectF EdgeElement::getPortRect(QPointF const &point)
{
	return QRectF(point - QPointF(kvadratik, kvadratik), QSizeF(kvadratik * 2, kvadratik * 2));
}

int EdgeElement::getPoint(const QPointF &location)
{
	for (int i = 0; i < mLine.size(); ++i)
		if (getPortRect(mLine[i]).contains(location))
			return i;

	return -1;
}

void EdgeElement::updateLongestPart()
{
	qreal maxLen = 0.0;
	int maxIdx = 0;
	for (int i = 0; i < mLine.size() - 1; ++i) {
		qreal newLen = QLineF(mLine[i], mLine[i + 1]).length();
		if (newLen > maxLen) {
			maxLen = newLen;
			maxIdx = i;
		}
	}
	mLongPart = maxIdx;
}

void EdgeElement::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
	mDragState = -1;

	mDragState = getPoint(event->pos());
	setSelected(true);

	if (mDragState == -1)
		Element::mousePressEvent(event);
}

void EdgeElement::connectToPort()
{
	model::Model *model = const_cast<model::Model *>(static_cast<model::Model const *>(mDataIndex.model()));  // TODO: OMG!

	setPos(pos() + mLine.first());
	mLine.translate(-mLine.first());

	mMoving = true;

	// Now we check whether start or end have been connected
	NodeElement *new_src = getNodeAt(mLine.first());
	mPortFrom = new_src ? new_src->getPortId(mapToItem(new_src, mLine.first())) : -1.0;

	if (mSrc) {
		mSrc->delEdge(this);
		mSrc = 0;
	}

	if (mPortFrom >= 0.0) {
		mSrc = new_src;
		mSrc->addEdge(this);
	}

	model->setData(mDataIndex, (mSrc ? mSrc->uuid() : ROOT_ID).toVariant(), roles::fromRole);
	model->setData(mDataIndex, mPortFrom, roles::fromPortRole);

	NodeElement *new_dst = getNodeAt(mLine.last());
	mPortTo = new_dst ? new_dst->getPortId(mapToItem(new_dst, mLine.last())) : -1.0;

	if (mDst) {
		mDst->delEdge(this);
		mDst = 0;
	}

	if (mPortTo >= 0.0) {
		mDst = new_dst;
		mDst->addEdge(this);
	}

	model->setData(mDataIndex, (mDst ? mDst->uuid() : ROOT_ID).toVariant(), roles::toRole);
	model->setData(mDataIndex, mPortTo, roles::toPortRole);

	setFlag(ItemIsMovable, !(mDst || mSrc));

	model->setData(mDataIndex, pos(), roles::positionRole);
	model->setData(mDataIndex, mLine.toPolygon(), roles::configurationRole);

	mMoving = false;

	adjustLink();
}

void EdgeElement::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
	NodeElement *new_src = getNodeAt(mLine.first());
	NodeElement *new_dst = getNodeAt(mLine.back());

	if (mBeginning) {
		if (mBeginning != new_src) {
			mBeginning->setPortsVisible(false);
		}
	}

	if (mEnding) {
		if (mEnding != new_dst) {
			mEnding->setPortsVisible(false);
		}
	}

	mBeginning = new_src;
	mEnding = new_dst;

	if (mBeginning)
		mBeginning->setPortsVisible(true);

	if (mEnding)
		mEnding->setPortsVisible(true);

	if (mDragState == -1) {
		Element::mouseMoveEvent(event);
	} else {
		prepareGeometryChange();
		mLine[mDragState] = event->pos();
		updateLongestPart();
	}
}

void EdgeElement::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
	if (mDragState == -1)
		Element::mouseReleaseEvent(event);
	else
		mDragState = -1;

	connectToPort();

	if (mBeginning)
		mBeginning->setPortsVisible(false);

	if (mEnding)
		mEnding->setPortsVisible(false);

	// cleanup after moving/resizing
	mBeginning = mEnding = NULL;
}

NodeElement *EdgeElement::getNodeAt(QPointF const &position)
{
	QPainterPath circlePath;
	circlePath.addEllipse(mapToScene(position), 12, 12);
	foreach (QGraphicsItem *item, scene()->items(circlePath)) {
		NodeElement *e = dynamic_cast<NodeElement *>(item);
		if (e) {
			return e;
		}
	}
	return NULL;
}

void EdgeElement::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
	QMenu menu;

	QAction *addPointAction = menu.addAction("Add point");
	QAction *delPointAction = menu.addAction("Remove point");
	QAction *squarizeAction = menu.addAction("Squarize");

	if (QAction *selectedAction = menu.exec(event->screenPos())) {
		if (selectedAction == delPointAction) {
			int pointIndex = getPoint(event->pos());
			if (pointIndex != -1) {
				prepareGeometryChange();
				mLine.remove(pointIndex);
				mLongPart = 0;
				update();
			}
		} else if (selectedAction == addPointAction) {
			for (int i = 0; i < mLine.size() - 1; ++i) {
				QPainterPath path;
				QPainterPathStroker ps;
				ps.setWidth(kvadratik);

				path.moveTo(mLine[i]);
				path.lineTo(mLine[i+1]);
				if (ps.createStroke(path).contains(event->pos())) {
					mLine.insert(i + 1, event->pos());
					update();
					break;
				}
			}
		} else if (selectedAction == squarizeAction) {
			prepareGeometryChange();
			for (int i = 0; i < mLine.size() - 1; ++i) {
				QLineF line(mLine[i], mLine[i + 1]);
				if (qAbs(line.dx()) < qAbs(line.dy())) {
					mLine[i + 1].setX(mLine[i].x());
				} else {
					mLine[i + 1].setY(mLine[i].y());
				}
			}
			adjustLink();
			update();
		}
	}
}

void EdgeElement::adjustLink()
{
	prepareGeometryChange();
	if (mSrc)
		mLine.first() = mapFromItem(mSrc, mSrc->getPortPos(mPortFrom));
	if (mDst)
		mLine.last() = mapFromItem(mDst, mDst->getPortPos(mPortTo));
	updateLongestPart();
}

void EdgeElement::updateData()
{
	if (mMoving)
		return;

	Element::updateData();

	setPos(mDataIndex.data(roles::positionRole).toPointF());
	QPolygonF newLine = mDataIndex.data(roles::configurationRole).value<QPolygon>();
	if (!newLine.isEmpty())
		mLine = newLine;

	qReal::Id uuidFrom = mDataIndex.data(roles::fromRole).value<Id>();
	qReal::Id uuidTo = mDataIndex.data(roles::toRole).value<Id>();

	if (mSrc)
		mSrc->delEdge(this);
	if (mDst)
		mDst->delEdge(this);

	mSrc = dynamic_cast<NodeElement *>(static_cast<EditorViewScene *>(scene())->getElem(uuidFrom));
	mDst = dynamic_cast<NodeElement *>(static_cast<EditorViewScene *>(scene())->getElem(uuidTo));

	if (mSrc)
		mSrc->addEdge(this);
	if (mDst)
		mDst->addEdge(this);

	setFlag(ItemIsMovable, !(mDst || mSrc));

	mPortFrom = mDataIndex.data(roles::fromPortRole).toDouble();
	mPortTo = mDataIndex.data(roles::toPortRole).toDouble();

	adjustLink();
}

void EdgeElement::removeLink(UML::NodeElement const *from)
{
	if (mSrc == from)
		mSrc = NULL;

	if (mDst == from)
		mDst = NULL;
}
<|endoftext|>


<commit_before>/*******************************
Copyright (C) 2013-2016 gregoire ANGERAND

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

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
**********************************/
#include "MaterialCompiler.h"

#include <yave/shaders/ShaderModule.h>
#include <yave/mesh/Vertex.h>
#include <yave/Device.h>

#include <yave/shaders/ShaderProgram.h>

namespace yave {

MaterialCompiler::MaterialCompiler(DevicePtr dptr) : DeviceLinked(dptr) {
}

GraphicPipeline MaterialCompiler::compile(const Material& material, const RenderPass& render_pass, Viewport view) const {
	auto modules = core::vector(material.get_data()._vert, material.get_data()._frag);
	if(!material.get_data()._geom.is_empty()) {
		modules << material.get_data()._geom;
	}

	ShaderProgram program(material.get_device(), modules);
	auto pipeline_shader_stage = program.get_vk_pipeline_stage_info();

	auto binding_description = vk::VertexInputBindingDescription()
			.setBinding(0)
			.setStride(sizeof(Vertex))
			.setInputRate(vk::VertexInputRate::eVertex)
		;

	auto pos_attrib_description = vk::VertexInputAttributeDescription()
			.setBinding(0)
			.setLocation(0)
			.setFormat(vk::Format::eR32G32B32Sfloat)
			.setOffset(offsetof(Vertex, position))
		;

	auto nor_attrib_description = vk::VertexInputAttributeDescription()
			.setBinding(0)
			.setLocation(1)
			.setFormat(vk::Format::eR32G32B32Sfloat)
			.setOffset(offsetof(Vertex, normal))
		;

	auto uv_attrib_description = vk::VertexInputAttributeDescription()
			.setBinding(0)
			.setLocation(2)
			.setFormat(vk::Format::eR32G32Sfloat)
			.setOffset(offsetof(Vertex, uv))
		;

	vk::VertexInputAttributeDescription attribs[] = {pos_attrib_description, nor_attrib_description, uv_attrib_description};

	auto vertex_input = vk::PipelineVertexInputStateCreateInfo()
			.setVertexAttributeDescriptionCount(3)
			.setPVertexAttributeDescriptions(attribs)
			.setVertexBindingDescriptionCount(1)
			.setPVertexBindingDescriptions(&binding_description)
		;

	auto input_assembly = vk::PipelineInputAssemblyStateCreateInfo()
			.setTopology(vk::PrimitiveTopology::eTriangleList)
			.setPrimitiveRestartEnable(false)
		;

	auto viewport = vk::Viewport()
			.setWidth(view.extent.x())
			.setHeight(view.extent.y())
			.setX(view.offset.x())
			.setY(view.offset.y())
			.setMinDepth(view.depth.x())
			.setMaxDepth(view.depth.y())
		;

	auto viewport_state = vk::PipelineViewportStateCreateInfo()
			.setViewportCount(1)
			.setPViewports(&viewport)
			.setScissorCount(1)
		;

	auto rasterizer = vk::PipelineRasterizationStateCreateInfo()
			.setCullMode(vk::CullModeFlagBits::eBack)
			//.setCullMode(vk::CullModeFlagBits::eNone)
			.setPolygonMode(vk::PolygonMode::eFill)
			.setLineWidth(1.0f)
			.setFrontFace(vk::FrontFace::eClockwise)
			.setDepthBiasEnable(false)
			.setDepthClampEnable(false)
		;

	auto multisampling = vk::PipelineMultisampleStateCreateInfo()
			.setSampleShadingEnable(false)
			.setRasterizationSamples(vk::SampleCountFlagBits::e1)
		;

	auto color_blend_attachment = vk::PipelineColorBlendAttachmentState()
			.setBlendEnable(false)
			.setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eA)
		;

	auto att_blends = core::range(usize(0), render_pass.attachment_count()).map([=](usize) { return color_blend_attachment; }).collect<core::Vector>();

	auto color_blending = vk::PipelineColorBlendStateCreateInfo()
			.setLogicOpEnable(false)
			.setLogicOp(vk::LogicOp::eCopy)
			.setAttachmentCount(u32(att_blends.size()))
			.setPAttachments(att_blends.begin())
			.setBlendConstants({{0.0f, 0.0f, 0.0f, 0.0f}})
		;

	auto depth_testing = vk::PipelineDepthStencilStateCreateInfo()
			.setDepthTestEnable(true)
			.setDepthWriteEnable(true)
			.setDepthCompareOp(vk::CompareOp::eLessOrEqual)
		;

	auto pipeline_layout = get_device()->get_vk_device().createPipelineLayout(vk::PipelineLayoutCreateInfo()
			.setSetLayoutCount(u32(program.get_descriptor_layouts().size()))
			.setPSetLayouts(program.get_descriptor_layouts().begin())
		);

	auto pipeline = get_device()->get_vk_device().createGraphicsPipeline(VK_NULL_HANDLE, vk::GraphicsPipelineCreateInfo()
			.setStageCount(u32(pipeline_shader_stage.size()))
			.setPStages(pipeline_shader_stage.begin())
			.setPVertexInputState(&vertex_input)
			.setPInputAssemblyState(&input_assembly)
			.setPViewportState(&viewport_state)
			.setPRasterizationState(&rasterizer)
			.setPMultisampleState(&multisampling)
			.setPColorBlendState(&color_blending)
			.setPDepthStencilState(&depth_testing)
			.setLayout(pipeline_layout)
			.setRenderPass(render_pass.get_vk_render_pass())
			.setSubpass(0)
			.setBasePipelineIndex(-1)
		);

	return GraphicPipeline(material, pipeline, pipeline_layout);
}

}
<commit_msg>Fixed scisor test.<commit_after>/*******************************
Copyright (C) 2013-2016 gregoire ANGERAND

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

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
**********************************/
#include "MaterialCompiler.h"

#include <yave/shaders/ShaderModule.h>
#include <yave/mesh/Vertex.h>
#include <yave/Device.h>

#include <yave/shaders/ShaderProgram.h>

namespace yave {

MaterialCompiler::MaterialCompiler(DevicePtr dptr) : DeviceLinked(dptr) {
}

GraphicPipeline MaterialCompiler::compile(const Material& material, const RenderPass& render_pass, Viewport view) const {
	auto modules = core::vector(material.get_data()._vert, material.get_data()._frag);
	if(!material.get_data()._geom.is_empty()) {
		modules << material.get_data()._geom;
	}

	ShaderProgram program(material.get_device(), modules);
	auto pipeline_shader_stage = program.get_vk_pipeline_stage_info();

	auto binding_description = vk::VertexInputBindingDescription()
			.setBinding(0)
			.setStride(sizeof(Vertex))
			.setInputRate(vk::VertexInputRate::eVertex)
		;

	auto pos_attrib_description = vk::VertexInputAttributeDescription()
			.setBinding(0)
			.setLocation(0)
			.setFormat(vk::Format::eR32G32B32Sfloat)
			.setOffset(offsetof(Vertex, position))
		;

	auto nor_attrib_description = vk::VertexInputAttributeDescription()
			.setBinding(0)
			.setLocation(1)
			.setFormat(vk::Format::eR32G32B32Sfloat)
			.setOffset(offsetof(Vertex, normal))
		;

	auto uv_attrib_description = vk::VertexInputAttributeDescription()
			.setBinding(0)
			.setLocation(2)
			.setFormat(vk::Format::eR32G32Sfloat)
			.setOffset(offsetof(Vertex, uv))
		;

	vk::VertexInputAttributeDescription attribs[] = {pos_attrib_description, nor_attrib_description, uv_attrib_description};

	auto vertex_input = vk::PipelineVertexInputStateCreateInfo()
			.setVertexAttributeDescriptionCount(3)
			.setPVertexAttributeDescriptions(attribs)
			.setVertexBindingDescriptionCount(1)
			.setPVertexBindingDescriptions(&binding_description)
		;

	auto input_assembly = vk::PipelineInputAssemblyStateCreateInfo()
			.setTopology(vk::PrimitiveTopology::eTriangleList)
			.setPrimitiveRestartEnable(false)
		;

	auto viewport = vk::Viewport()
			.setWidth(view.extent.x())
			.setHeight(view.extent.y())
			.setX(view.offset.x())
			.setY(view.offset.y())
			.setMinDepth(view.depth.x())
			.setMaxDepth(view.depth.y())
		;

	auto viewport_state = vk::PipelineViewportStateCreateInfo()
			.setViewportCount(1)
			.setPViewports(&viewport)
			.setScissorCount(0)
		;

	auto rasterizer = vk::PipelineRasterizationStateCreateInfo()
			.setCullMode(vk::CullModeFlagBits::eBack)
			//.setCullMode(vk::CullModeFlagBits::eNone)
			.setPolygonMode(vk::PolygonMode::eFill)
			.setLineWidth(1.0f)
			.setFrontFace(vk::FrontFace::eClockwise)
			.setDepthBiasEnable(false)
			.setDepthClampEnable(false)
		;

	auto multisampling = vk::PipelineMultisampleStateCreateInfo()
			.setSampleShadingEnable(false)
			.setRasterizationSamples(vk::SampleCountFlagBits::e1)
		;

	auto color_blend_attachment = vk::PipelineColorBlendAttachmentState()
			.setBlendEnable(false)
			.setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eA)
		;

	auto att_blends = core::range(usize(0), render_pass.attachment_count()).map([=](usize) { return color_blend_attachment; }).collect<core::Vector>();

	auto color_blending = vk::PipelineColorBlendStateCreateInfo()
			.setLogicOpEnable(false)
			.setLogicOp(vk::LogicOp::eCopy)
			.setAttachmentCount(u32(att_blends.size()))
			.setPAttachments(att_blends.begin())
			.setBlendConstants({{0.0f, 0.0f, 0.0f, 0.0f}})
		;

	auto depth_testing = vk::PipelineDepthStencilStateCreateInfo()
			.setDepthTestEnable(true)
			.setDepthWriteEnable(true)
			.setDepthCompareOp(vk::CompareOp::eLessOrEqual)
		;

	auto pipeline_layout = get_device()->get_vk_device().createPipelineLayout(vk::PipelineLayoutCreateInfo()
			.setSetLayoutCount(u32(program.get_descriptor_layouts().size()))
			.setPSetLayouts(program.get_descriptor_layouts().begin())
		);

	auto pipeline = get_device()->get_vk_device().createGraphicsPipeline(VK_NULL_HANDLE, vk::GraphicsPipelineCreateInfo()
			.setStageCount(u32(pipeline_shader_stage.size()))
			.setPStages(pipeline_shader_stage.begin())
			.setPVertexInputState(&vertex_input)
			.setPInputAssemblyState(&input_assembly)
			.setPViewportState(&viewport_state)
			.setPRasterizationState(&rasterizer)
			.setPMultisampleState(&multisampling)
			.setPColorBlendState(&color_blending)
			.setPDepthStencilState(&depth_testing)
			.setLayout(pipeline_layout)
			.setRenderPass(render_pass.get_vk_render_pass())
			.setSubpass(0)
			.setBasePipelineIndex(-1)
		);

	return GraphicPipeline(material, pipeline, pipeline_layout);
}

}
<|endoftext|>


<commit_before>#include "net/http/HttpContext.h"
#include "net/NetBuffer.h"
#include "base/Timestamp.h"
using zl::base::Timestamp;
NAMESPACE_ZL_NET_START

/// parse:
/// request line     \r\n
/// request header   \r\n
///                  \r\n
/// request body
// 使用chorme浏览器请求127.0.0.1:8888/index.html时，server收到的http消息头
// GET /index.html HTTP/1.1
// Host: 127.0.0.1:8888
// Connection: keep-alive
// Cache-Control: max-age=0
// Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*; q = 0.8
// User - Agent: Mozilla / 5.0 (Windows NT 6.1; WOW64) AppleWebKit / 537.36 (KHTML, like
// Gecko) Chrome / 35.0.1916.153 Safari / 537.36
// Accept - Encoding : gzip, deflate, sdch
// Accept - Language : zh - CN, zh; q = 0.8
// RA - Ver: 2.2.22
// RA - Sid : 7B747245 - 20140622 - 042030 - f79ea7 - 5f07a8
bool HttpContext::parseRequest(NetBuffer *buf, Timestamp receiveTime)
{
    static int count = 0;
    HttpContext *context = this;
    assert(context);
    printf("----------------parseRequest------------[%d]\n", ++count);
    bool ok = true;
    bool hasMore = true;
    while (hasMore)
    {
        if (context->expectRequestLine())
        {
            const char* crlf = buf->findCRLF();
            if (crlf)
            {
                ok = processRequestLine(buf->peek(), crlf);  // 解析请求行
                if (ok)
                {
                    //context->request().setReceiveTime(receiveTime);
                    buf->retrieveUntil(crlf + 2);
                    context->receiveRequestLine();     // 请求行解析完成，下一步要解析消息头中的参数
                }
                else
                {
                    hasMore = false;
                }
            }
            else
            {
                hasMore = false;
            }
        }
        else if (context->expectHeaders())     // 解析消息头中的参数
        {
            printf("context->expectHeaders() [%d]\n", context);
            const char* crlf = buf->findCRLF();
            if (crlf)    //按行添加消息头中的参数
            {
                //const char *colon = std::find(buf->peek(), crlf, ':'); //一行一行遍历
                if(!processReqestHeader(buf->peek(), crlf))
                {
                    // empty line, end of header
                    context->receiveHeaders();     // 消息头解析完成，下一步应该按get/post来区分是否解析消息体
                    hasMore = !context->gotAll();
                    printf("parse headers [%d]\n", hasMore);
                    map<string, string> headers = context->request().headers();
                    for(map<string, string>::iterator it = headers.begin(); it!=headers.end(); ++it)
                        std::cout << it->first << " : " << it->second << "\n";
                }
                buf->retrieveUntil(crlf + 2);
            }
            else
            {
                hasMore = false;
            }
        }
        else if (context->expectBody())       // 解析消息体
        {
            // FIXME:
            printf("context->expectBody() [%d]\n", context);
        }
    }
    return ok;
}

/// request line: httpmethod path httpversion
bool HttpContext::processRequestLine(const char *begin, const char *end)
{
    bool succeed = false;
    const char* start = begin;
    const char* space = std::find(start, end, ' ');
    HttpRequest& request = this->request();
    string method(start, space);
    if (space != end && request.setMethod(method))
    {
        start = space+1;
        space = std::find(start, end, ' ');
        if (space != end)
        {
            const char* question = std::find(start, space, '?');
            if (question != space)
            {
                string u(start, question);
                request.setPath(u);
                u.assign(question, space);
                request.setQuery(u);
            }
            else
            {
                string u(start, question);
                request.setPath(u);
            }

            start = space+1;
            succeed = end-start == 8 && std::equal(start, end-1, "HTTP/1.");
            if (succeed)
            {
                if (*(end-1) == '1')
                {
                    request.setVersion(HTTP_VERSION_1_1);
                }
                else if (*(end-1) == '0')
                {
                    request.setVersion(HTTP_VERSION_1_0);
                }
                else
                {
                    succeed = false;
                }
            }
        }
    }
    printf("-----%d %s %d----\n", request.method(), request.path().c_str(), request.version());
    return succeed;
}

/// request header
bool HttpContext::processReqestHeader(const char *begin, const char *end)
{
    const char *colon = std::find(begin, end, ':'); //一行一行遍历
    if (colon != end)
    {
        string field(begin, colon);
        ++colon;
        while (colon < end && isspace(*colon))
        {
            ++colon;
        }
        string value(colon, end);
        while (!value.empty() && isspace(value[value.size()-1]))
        {
            value.resize(value.size()-1);
        }
        request_.addHeader(field, value);
        return true;
    }
    else
    {
        // empty line, end of header
        return false;
    }
}

NAMESPACE_ZL_NET_END
<commit_msg>update HttpContext.cpp<commit_after>#include "net/http/HttpContext.h"
#include "net/NetBuffer.h"
#include "base/Timestamp.h"
using zl::base::Timestamp;
NAMESPACE_ZL_NET_START

/// parse:
/// request line     \r\n
/// request header   \r\n
///                  \r\n
/// request body
// 使用chorme浏览器请求127.0.0.1:8888/index.html时，server收到的http消息头
// GET /index.html HTTP/1.1
// Host: 127.0.0.1:8888
// Connection: keep-alive
// Cache-Control: max-age=0
// Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*; q = 0.8
// User - Agent: Mozilla / 5.0 (Windows NT 6.1; WOW64) AppleWebKit / 537.36 (KHTML, like
// Gecko) Chrome / 35.0.1916.153 Safari / 537.36
// Accept - Encoding : gzip, deflate, sdch
// Accept - Language : zh - CN, zh; q = 0.8
// RA - Ver: 2.2.22
// RA - Sid : 7B747245 - 20140622 - 042030 - f79ea7 - 5f07a8
bool HttpContext::parseRequest(NetBuffer *buf, Timestamp receiveTime)
{
    bool ok = true;
    bool hasMore = true;
    while (hasMore)
    {
        if (this->expectRequestLine())
        {
            const char* crlf = buf->findCRLF();
            if (crlf)
            {
                ok = processRequestLine(buf->peek(), crlf);  // 解析请求行
                if (ok)
                {
                    this->request().setReceiveTime(receiveTime);
                    buf->retrieveUntil(crlf + 2);
                    this->receiveRequestLine();     // 请求行解析完成，下一步要解析消息头中的参数
                }
                else
                {
                    hasMore = false;
                }
            }
            else
            {
                hasMore = false;
            }
        }
        else if (this->expectHeaders())     // 解析消息头中的参数
        {
            printf("context->expectHeaders() [%d]\n", this);
            const char* crlf = buf->findCRLF();
            if (crlf)    //按行添加消息头中的参数
            {
                //const char *colon = std::find(buf->peek(), crlf, ':'); //一行一行遍历
                if(!processReqestHeader(buf->peek(), crlf))
                {
                    // empty line, end of header
                    this->receiveHeaders();     // 消息头解析完成，下一步应该按get/post来区分是否解析消息体
                    hasMore = !this->gotAll();
                    printf("parse headers [%d]\n", hasMore);
                    map<string, string> headers = this->request().headers();
                    for(map<string, string>::iterator it = headers.begin(); it!=headers.end(); ++it)
                        std::cout << it->first << " : " << it->second << "\n";
                }
                buf->retrieveUntil(crlf + 2);
            }
            else
            {
                hasMore = false;
            }
        }
        else if (this->expectBody())       // 解析消息体  // FIXME:
        {
            printf("context->expectBody() [%d]\n", this);
        }
    }
    return ok;
}

/// request line: httpmethod path httpversion
bool HttpContext::processRequestLine(const char *begin, const char *end)
{
    const char* start = begin;
    const char* space = std::find(start, end, ' ');
    HttpRequest& request = this->request();
    string method(start, space);
    if (space != end && request.setMethod(method))
    {
        // parse url path
        start = space+1;
        space = std::find(start, end, ' ');
        if (space != end)
        {
            const char* question = std::find(start, space, '?');
            if (question != space)
            {
                string u(start, question);
                request.setPath(u);
                u.assign(question, space);
                request.setQuery(u);
            }
            else
            {
                string u(start, question);
                request.setPath(u);
            }

            // parse http version
            start = space + 1;
            if(end - start != 8)  // neither HTTP/1.1 nor HTTP/1.0
            {
                  return false;
            }

            if(std::equal(start, end, "HTTP/1.1"))
                request.setVersion(HTTP_VERSION_1_1);
            else if(std::equal(start, end, "HTTP/1.0"))
                request.setVersion(HTTP_VERSION_1_0);

            return true;
        }
    }
    return false;
}

/// request header
bool HttpContext::processReqestHeader(const char *begin, const char *end)
{
    //while(true)    //TODO
    {
        const char *colon = std::find(begin, end, ':'); //一行一行遍历
        if (colon != end)
        {
            string field(begin, colon);
            ++colon;
            while (colon < end && isspace(*colon))
            {
                ++colon;
            }
            string value(colon, end);
            while (!value.empty() && isspace(value[value.size()-1]))
            {
                value.resize(value.size()-1);
            }
            request_.addHeader(field, value);
            return true;
        }
        else
        {
            // empty line, end of header
            return false;
        }
    }
}

NAMESPACE_ZL_NET_END<|endoftext|>


<commit_before>#include <vector>
#include <memory>
#include <iostream>
#include <cmath>

#include <ad/ad.h>

std::pair<Eigen::MatrixXd, Eigen::MatrixXd> GenDataset(int nb_examples) {
    // dataset
    Eigen::MatrixXd x(2, nb_examples);
    Eigen::MatrixXd y(1, nb_examples);
    for (int k = 0; k < nb_examples; ++k) {
        float x1 = (rand() % 30 - 15) / 15.;
        float x2 = (rand() % 30 - 15) / 15.;
        x(0, k) = x1;
        x(1, k) = x2;
        y(0, k) =  x1 * 8 + x2 * 3 + 5;
    }
    return std::make_pair(x, y);
}

int main() {
    using namespace ad;
    const int nb_examples = 1;

    auto a_weights = std::make_shared<Eigen::MatrixXd>(1, 2);
    *a_weights << 3, 4;
    auto b_weights = std::make_shared<Eigen::MatrixXd>(1, 1);
    *b_weights << 6;

    for (int i = 0; i < 100; ++ i) {
        ComputationGraph g;
        auto dataset = GenDataset(nb_examples);

        Var x = g.CreateParam(dataset.first);
        Var y = g.CreateParam(dataset.second);
        Var a = g.CreateParam(a_weights);
        Var b = g.CreateParam(b_weights);

        Var h = a * x + b;
        Var j = MSE(h, y) + 0.001 * (Mean(EltSquare(a)) + Mean(EltSquare(b)));

        std::cout << "COST = " << j.value() << "\n";

        opt::SGD sgd(0.1 / nb_examples);
        g.BackpropFrom(j);
        g.Update(sgd, {&a, &b});
    }

    std::cout << "a = " << *a_weights << " b = " << *b_weights << std::endl;
    return 0;
}

<commit_msg>Update linear regression example to use NN<commit_after>#include <vector>
#include <memory>
#include <iostream>
#include <cmath>

#include <ad/ad.h>

std::pair<Eigen::MatrixXd, Eigen::MatrixXd> GenDataset(int nb_examples) {
    // dataset
    Eigen::MatrixXd x(2, nb_examples);
    Eigen::MatrixXd y(1, nb_examples);
    for (int k = 0; k < nb_examples; ++k) {
        float x1 = (rand() % 30 - 15) / 15.;
        float x2 = (rand() % 30 - 15) / 15.;
        x(0, k) = x1;
        x(1, k) = x2;
        y(0, k) =  x1 * 8 + x2 * 3 + 5;
    }
    return std::make_pair(x, y);
}

int main() {
    using namespace ad;
    const int nb_examples = 1;

    nn::FullyConnLayer fc(1, 2);

    for (int i = 0; i < 100; ++ i) {
        ComputationGraph g;
        auto dataset = GenDataset(nb_examples);

        Var x = g.CreateParam(dataset.first);
        Var y = g.CreateParam(dataset.second);

        auto input = nn::InputLayer(x);
        auto output = fc.Compute(input);
        Var j = MSE(output.out, y) + 0.001 * nn::L2ForAllParams(output);

        std::cout << "COST = " << j.value() << "\n";

        opt::SGD sgd(0.1 / nb_examples);
        g.BackpropFrom(j);
        g.Update(sgd, *output.params);
    }

    std::cout << "w = " << fc.w() << "\nb = " << fc.b() << "\n";

    return 0;
}

<|endoftext|>