text
stringlengths 54
60.6k
|
|---|
<commit_before>
// FILE: main.cc
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-//
//
//
// Main Startup Code for the Cutplane Editor
// (Faster, Stronger, and Much Much More Powerful)
//
// Authors: LJE and WAK Date: December 27,1989
//
// Copyright (C) 1987,1988,1989,1990 The Board of Trustees of The Leland
// Stanford Junior University, and William Kessler and Larry Edwards.
// All Rights Reserved.
//
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-//
#define MAINMODULE
#include <config.h>
#include <platform_gl.h>
#include <platform_glu.h>
#include <platform_glut.h>
#include <stdio.h>
#ifndef _WIN32
#include <signal.h>
#endif
#ifdef __APPLE__
#include <sys/malloc.h>
#else
#include <malloc.h>
#endif
#include <time.h>
#include <cutplane.h>
#include <globals.h>
#include <init.h>
#include <grafx.h> // for definition of black
#include <update.h>
#include <tools.h>
#include "device.h"
// things we are testing today:
/*
#define Createfullworkspace
#define Copslikedonuts
#define Timetest
#define Testboolbeam
#define Testboolholes
#define Testboolcube
#define Testsegments
#define Aliasvs3formdemo
#define Twolbeams
#define Stocksdemo
#define Onelbeam
#define Createtools
#define Shipcube
*/
char *className = "3Form";
char *windowName = "3Form";
// FIXE ME -- LJE
// HDC hDC;
// HGLRC hGLRC;
// HPALETTE hPalette;
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-//
// Stuff from OGLSDK's cube.c begins here, adapted for cutplane usage.
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-//
#if 0
void
set_pc_window_values(int new_winLeft, int new_winTop,
int new_winWidth, int new_winHeight)
{
if (new_winLeft > -1) {
pc_winLeft = new_winLeft;
pc_winTop = new_winTop;
} else {
pc_winLeft = 10;
pc_winTop = 10;
}
if (new_winWidth > -1) {
pc_winWidth = new_winWidth;
pc_winHeight = new_winHeight;
}
pc_xMargin = pc_winWidth * pc_windowMargin;
pc_yMargin = pc_winHeight * pc_windowMargin;
pc_winRight = pc_winLeft + pc_winWidth;
pc_winBottom = pc_winTop + pc_winHeight;
pc_innerLeft = pc_winLeft + pc_xMargin;
pc_innerRight = pc_winRight - pc_xMargin;
pc_innerTop = pc_winTop + pc_yMargin;
pc_innerBottom = pc_winBottom - pc_yMargin;
}
void
setupPalette(HDC hDC)
{
int pixelFormat = GetPixelFormat(hDC);
PIXELFORMATDESCRIPTOR pfd;
LOGPALETTE* pPal;
int paletteSize;
DescribePixelFormat(hDC, pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
if (pfd.dwFlags & PFD_NEED_PALETTE) {
paletteSize = 1 << pfd.cColorBits;
} else {
return;
}
pPal = (LOGPALETTE*)
malloc(sizeof(LOGPALETTE) + paletteSize * sizeof(PALETTEENTRY));
pPal->palVersion = 0x300;
pPal->palNumEntries = paletteSize;
// build a simple RGB color palette
{
int redMask = (1 << pfd.cRedBits) - 1;
int greenMask = (1 << pfd.cGreenBits) - 1;
int blueMask = (1 << pfd.cBlueBits) - 1;
int i;
for (i=0; i<paletteSize; ++i) {
pPal->palPalEntry[i].peRed =
(((i >> pfd.cRedShift) & redMask) * 255) / redMask;
pPal->palPalEntry[i].peGreen =
(((i >> pfd.cGreenShift) & greenMask) * 255) / greenMask;
pPal->palPalEntry[i].peBlue =
(((i >> pfd.cBlueShift) & blueMask) * 255) / blueMask;
pPal->palPalEntry[i].peFlags = 0;
}
}
hPalette = CreatePalette(pPal);
free(pPal);
if (hPalette) {
SelectPalette(hDC, hPalette, FALSE);
RealizePalette(hDC);
}
}
LRESULT APIENTRY
WndProc(
HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam)
{
int new_winLeft, new_winTop, new_winWidth, new_winHeight;
switch (message) {
case WM_CREATE:
init_dbgdump("./tmptest");
// initialize OpenGL rendering
hDC = GetDC(hWnd);
setupPixelFormat(hDC);
setupPalette(hDC);
hGLRC = wglCreateContext(hDC);
wglMakeCurrent(hDC, hGLRC);
init_grafx(hDC);
init_3form();
toggle_cpldebug();
ShowCursor(FALSE);
// Initially, move cursor to ctr of screen.
#if 0
SetCursorPos(pc_winLeft + (pc_winWidth / 2),
pc_winTop + (pc_winHeight /2));
#endif
return 0;
case WM_DESTROY:
close_dbgdump();
// finish OpenGL rendering
if (hGLRC) {
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hGLRC);
}
if (hPalette) {
DeleteObject(hPalette);
}
ReleaseDC(hWnd, hDC);
PostQuitMessage(0);
ShowCursor(TRUE);
return 0;
case WM_MOVE:
// track window size changes
if (hGLRC) {
new_winLeft = (int) LOWORD(lParam);
new_winTop = (int) HIWORD(lParam);
set_pc_window_values(new_winLeft, new_winTop,-1,-1);
reset_pc_valuator_store();
grafx_resize(pc_winWidth, pc_winHeight);
new_user_input(world_list,state,oldstate, hDC);
return 0;
}
case WM_SIZE:
// track window size changes
if (hGLRC) {
new_winWidth = (int) LOWORD(lParam);
new_winHeight = (int) HIWORD(lParam);
set_pc_window_values(-1,-1,new_winWidth, new_winHeight);
reset_pc_valuator_store();
grafx_resize(pc_winWidth, pc_winHeight);
new_user_input(world_list,state,oldstate, hDC);
return 0;
}
case WM_PALETTECHANGED:
// realize palette if this is *not* the current window
if (hGLRC && hPalette && (HWND) wParam != hWnd) {
UnrealizeObject(hPalette);
SelectPalette(hDC, hPalette, FALSE);
RealizePalette(hDC);
redraw_grafx(hDC);
break;
}
break;
case WM_QUERYNEWPALETTE:
// realize palette if this is the current window
if (hGLRC && hPalette) {
UnrealizeObject(hPalette);
SelectPalette(hDC, hPalette, FALSE);
RealizePalette(hDC);
redraw_grafx(hDC);
return TRUE;
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
BeginPaint(hWnd, &ps);
if (hGLRC) {
redraw_grafx(hDC);
new_user_input(world_list,state,oldstate, hDC);
}
EndPaint(hWnd, &ps);
return 0;
}
break;
case WM_MOUSEMOVE:
if (hGLRC) {
int x = ((int) LOWORD(lParam) << 16) >> 16;
int y = ((int) HIWORD(lParam) << 16) >> 16;
// Translate from pc devices->iris universe.
scan_pc_buttons();
set_pc_valuators(x,y);
// Now run 3form's user input handling code.
new_user_input(world_list,state,oldstate, hDC);
break;
}
case WM_LBUTTONDOWN:
pc_queue_push(PICKBUTTON, (short) 1);
new_user_input(world_list,state,oldstate, hDC);
break;
case WM_LBUTTONUP:
pc_queue_push(PICKBUTTON, (short) -1);
// Now run 3form's user input handling code.
new_user_input(world_list,state,oldstate, hDC);
break;
case WM_RBUTTONDOWN:
pc_queue_push(PLANEMOVEBUTTON, (short) 1);
break;
case WM_RBUTTONUP:
pc_queue_push(PLANEMOVEBUTTON, (short) -1);
break;
case WM_CHAR:
// handle keyboard input
switch ((int)wParam) {
case VK_ESCAPE:
DestroyWindow(hWnd);
return 0;
default:
break;
}
break;
default:
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
int APIENTRY
WinMain(
HINSTANCE hCurrentInst,
HINSTANCE hPreviousInst,
LPSTR lpszCmdLine,
int nCmdShow)
{
WNDCLASS wndClass;
HWND hWnd;
MSG msg;
// Presumably handle a crash gracefully?
// Only for unix, really.
#ifdef IRIS
signal(SIGSEGV, error_handler);
#endif
// register window class
wndClass.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
wndClass.lpfnWndProc = WndProc;
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 0;
wndClass.hInstance = hCurrentInst;
wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndClass.hbrBackground = GetStockObject(BLACK_BRUSH);
wndClass.lpszMenuName = NULL;
wndClass.lpszClassName = className;
RegisterClass(&wndClass);
pc_windowMargin = .25;
set_pc_window_values(10,10,500,500);
// create window
hWnd = CreateWindow(
className, windowName,
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
pc_winLeft, pc_winTop, pc_winWidth, pc_winHeight,
NULL, NULL, hCurrentInst, NULL);
// display window
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
// process messages
while (GetMessage(&msg, NULL, 0, 0) == TRUE) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
#endif
void
Init()
{
GLfloat light_diffuse[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat light_direction[] = { 1.0, 1.0, 1.0, 0.0 };
// Enable a single OpenGL light.
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_POSITION, light_direction);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
// Use depth buffering for hidden surface elimination.
glEnable(GL_DEPTH_TEST);
// Setup the view
glMatrixMode(GL_PROJECTION);
gluPerspective(40.0, // FOV in degrees
1.0, // aspect ratio
1.0, // Z near
10.0); // Z far
glMatrixMode(GL_MODELVIEW);
gluLookAt(0.0, 0.0, 5.0, // Eye point
0.0, 0.0, 0.0, // Reference point
0.0, 1.0, 0.); // Up vector (+Y axis)
}
void
Render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw the scene...
new_user_input(world_list, state, oldstate);
glutSwapBuffers();
}
int
main(int argc, char *argv[])
{
init_dbgdump("./debug-dump.txt");
#ifndef WIN32
init_error_handling();
#endif
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow(windowName);
glutDisplayFunc(Render);
glutReshapeFunc(grafx_resize);
// void processMouse(int button, int state, int x, int y)
//
// Button will recieve an integer constant identified by a name in all
// caps. These identifiers have names like GLUT_DOWN, GLUT_UP etc. and
// represent the current state of the mouse buttons (using 0 and 1 for
// true or false). x and y are the position of the mouse measured from
// the upper left corner of the current window. The callback for
// glutMotionFunc should have the format:
//
// void processMouseActiveMotion(int x, int y)
glutKeyboardFunc(keyboard_event_handler);
// Triggered when a mouse button is pressed...
glutMouseFunc(mouse_button_event_handler);
// Triggered when the mouse moves within a window and buttons are
// pressed...
glutMotionFunc(drag_event_handler);
// Triggered when the mouse moves within a window and no buttons are
// pressed...
glutPassiveMotionFunc(motion_event_handler);
init_grafx();
init_3form();
// toggle_cpldebug();
glutDisplayFunc(update_display);
glutMainLoop();
return 0;
}
<commit_msg>Added const qualifiers to char strings to get rid of warnings.<commit_after>
// FILE: main.cc
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-//
//
//
// Main Startup Code for the Cutplane Editor
// (Faster, Stronger, and Much Much More Powerful)
//
// Authors: LJE and WAK Date: December 27,1989
//
// Copyright (C) 1987,1988,1989,1990 The Board of Trustees of The Leland
// Stanford Junior University, and William Kessler and Larry Edwards.
// All Rights Reserved.
//
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-//
#define MAINMODULE
#include <config.h>
#include <platform_gl.h>
#include <platform_glu.h>
#include <platform_glut.h>
#include <stdio.h>
#ifndef _WIN32
#include <signal.h>
#endif
#ifdef __APPLE__
#include <sys/malloc.h>
#else
#include <malloc.h>
#endif
#include <time.h>
#include <cutplane.h>
#include <globals.h>
#include <init.h>
#include <grafx.h> // for definition of black
#include <update.h>
#include <tools.h>
#include "device.h"
// things we are testing today:
/*
#define Createfullworkspace
#define Copslikedonuts
#define Timetest
#define Testboolbeam
#define Testboolholes
#define Testboolcube
#define Testsegments
#define Aliasvs3formdemo
#define Twolbeams
#define Stocksdemo
#define Onelbeam
#define Createtools
#define Shipcube
*/
const char className[] = { "3Form" };
const char windowName[] = { "3Form" };
// FIXE ME -- LJE
// HDC hDC;
// HGLRC hGLRC;
// HPALETTE hPalette;
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-//
// Stuff from OGLSDK's cube.c begins here, adapted for cutplane usage.
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-//
#if 0
void
set_pc_window_values(int new_winLeft, int new_winTop,
int new_winWidth, int new_winHeight)
{
if (new_winLeft > -1) {
pc_winLeft = new_winLeft;
pc_winTop = new_winTop;
} else {
pc_winLeft = 10;
pc_winTop = 10;
}
if (new_winWidth > -1) {
pc_winWidth = new_winWidth;
pc_winHeight = new_winHeight;
}
pc_xMargin = pc_winWidth * pc_windowMargin;
pc_yMargin = pc_winHeight * pc_windowMargin;
pc_winRight = pc_winLeft + pc_winWidth;
pc_winBottom = pc_winTop + pc_winHeight;
pc_innerLeft = pc_winLeft + pc_xMargin;
pc_innerRight = pc_winRight - pc_xMargin;
pc_innerTop = pc_winTop + pc_yMargin;
pc_innerBottom = pc_winBottom - pc_yMargin;
}
void
setupPalette(HDC hDC)
{
int pixelFormat = GetPixelFormat(hDC);
PIXELFORMATDESCRIPTOR pfd;
LOGPALETTE* pPal;
int paletteSize;
DescribePixelFormat(hDC, pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
if (pfd.dwFlags & PFD_NEED_PALETTE) {
paletteSize = 1 << pfd.cColorBits;
} else {
return;
}
pPal = (LOGPALETTE*)
malloc(sizeof(LOGPALETTE) + paletteSize * sizeof(PALETTEENTRY));
pPal->palVersion = 0x300;
pPal->palNumEntries = paletteSize;
// build a simple RGB color palette
{
int redMask = (1 << pfd.cRedBits) - 1;
int greenMask = (1 << pfd.cGreenBits) - 1;
int blueMask = (1 << pfd.cBlueBits) - 1;
int i;
for (i=0; i<paletteSize; ++i) {
pPal->palPalEntry[i].peRed =
(((i >> pfd.cRedShift) & redMask) * 255) / redMask;
pPal->palPalEntry[i].peGreen =
(((i >> pfd.cGreenShift) & greenMask) * 255) / greenMask;
pPal->palPalEntry[i].peBlue =
(((i >> pfd.cBlueShift) & blueMask) * 255) / blueMask;
pPal->palPalEntry[i].peFlags = 0;
}
}
hPalette = CreatePalette(pPal);
free(pPal);
if (hPalette) {
SelectPalette(hDC, hPalette, FALSE);
RealizePalette(hDC);
}
}
LRESULT APIENTRY
WndProc(
HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam)
{
int new_winLeft, new_winTop, new_winWidth, new_winHeight;
switch (message) {
case WM_CREATE:
init_dbgdump("./tmptest");
// initialize OpenGL rendering
hDC = GetDC(hWnd);
setupPixelFormat(hDC);
setupPalette(hDC);
hGLRC = wglCreateContext(hDC);
wglMakeCurrent(hDC, hGLRC);
init_grafx(hDC);
init_3form();
toggle_cpldebug();
ShowCursor(FALSE);
// Initially, move cursor to ctr of screen.
#if 0
SetCursorPos(pc_winLeft + (pc_winWidth / 2),
pc_winTop + (pc_winHeight /2));
#endif
return 0;
case WM_DESTROY:
close_dbgdump();
// finish OpenGL rendering
if (hGLRC) {
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hGLRC);
}
if (hPalette) {
DeleteObject(hPalette);
}
ReleaseDC(hWnd, hDC);
PostQuitMessage(0);
ShowCursor(TRUE);
return 0;
case WM_MOVE:
// track window size changes
if (hGLRC) {
new_winLeft = (int) LOWORD(lParam);
new_winTop = (int) HIWORD(lParam);
set_pc_window_values(new_winLeft, new_winTop,-1,-1);
reset_pc_valuator_store();
grafx_resize(pc_winWidth, pc_winHeight);
new_user_input(world_list,state,oldstate, hDC);
return 0;
}
case WM_SIZE:
// track window size changes
if (hGLRC) {
new_winWidth = (int) LOWORD(lParam);
new_winHeight = (int) HIWORD(lParam);
set_pc_window_values(-1,-1,new_winWidth, new_winHeight);
reset_pc_valuator_store();
grafx_resize(pc_winWidth, pc_winHeight);
new_user_input(world_list,state,oldstate, hDC);
return 0;
}
case WM_PALETTECHANGED:
// realize palette if this is *not* the current window
if (hGLRC && hPalette && (HWND) wParam != hWnd) {
UnrealizeObject(hPalette);
SelectPalette(hDC, hPalette, FALSE);
RealizePalette(hDC);
redraw_grafx(hDC);
break;
}
break;
case WM_QUERYNEWPALETTE:
// realize palette if this is the current window
if (hGLRC && hPalette) {
UnrealizeObject(hPalette);
SelectPalette(hDC, hPalette, FALSE);
RealizePalette(hDC);
redraw_grafx(hDC);
return TRUE;
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
BeginPaint(hWnd, &ps);
if (hGLRC) {
redraw_grafx(hDC);
new_user_input(world_list,state,oldstate, hDC);
}
EndPaint(hWnd, &ps);
return 0;
}
break;
case WM_MOUSEMOVE:
if (hGLRC) {
int x = ((int) LOWORD(lParam) << 16) >> 16;
int y = ((int) HIWORD(lParam) << 16) >> 16;
// Translate from pc devices->iris universe.
scan_pc_buttons();
set_pc_valuators(x,y);
// Now run 3form's user input handling code.
new_user_input(world_list,state,oldstate, hDC);
break;
}
case WM_LBUTTONDOWN:
pc_queue_push(PICKBUTTON, (short) 1);
new_user_input(world_list,state,oldstate, hDC);
break;
case WM_LBUTTONUP:
pc_queue_push(PICKBUTTON, (short) -1);
// Now run 3form's user input handling code.
new_user_input(world_list,state,oldstate, hDC);
break;
case WM_RBUTTONDOWN:
pc_queue_push(PLANEMOVEBUTTON, (short) 1);
break;
case WM_RBUTTONUP:
pc_queue_push(PLANEMOVEBUTTON, (short) -1);
break;
case WM_CHAR:
// handle keyboard input
switch ((int)wParam) {
case VK_ESCAPE:
DestroyWindow(hWnd);
return 0;
default:
break;
}
break;
default:
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
int APIENTRY
WinMain(
HINSTANCE hCurrentInst,
HINSTANCE hPreviousInst,
LPSTR lpszCmdLine,
int nCmdShow)
{
WNDCLASS wndClass;
HWND hWnd;
MSG msg;
// Presumably handle a crash gracefully?
// Only for unix, really.
#ifdef IRIS
signal(SIGSEGV, error_handler);
#endif
// register window class
wndClass.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
wndClass.lpfnWndProc = WndProc;
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 0;
wndClass.hInstance = hCurrentInst;
wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndClass.hbrBackground = GetStockObject(BLACK_BRUSH);
wndClass.lpszMenuName = NULL;
wndClass.lpszClassName = className;
RegisterClass(&wndClass);
pc_windowMargin = .25;
set_pc_window_values(10,10,500,500);
// create window
hWnd = CreateWindow(
className, windowName,
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
pc_winLeft, pc_winTop, pc_winWidth, pc_winHeight,
NULL, NULL, hCurrentInst, NULL);
// display window
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
// process messages
while (GetMessage(&msg, NULL, 0, 0) == TRUE) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
#endif
void
Init()
{
GLfloat light_diffuse[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat light_direction[] = { 1.0, 1.0, 1.0, 0.0 };
// Enable a single OpenGL light.
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_POSITION, light_direction);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
// Use depth buffering for hidden surface elimination.
glEnable(GL_DEPTH_TEST);
// Setup the view
glMatrixMode(GL_PROJECTION);
gluPerspective(40.0, // FOV in degrees
1.0, // aspect ratio
1.0, // Z near
10.0); // Z far
glMatrixMode(GL_MODELVIEW);
gluLookAt(0.0, 0.0, 5.0, // Eye point
0.0, 0.0, 0.0, // Reference point
0.0, 1.0, 0.); // Up vector (+Y axis)
}
void
Render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw the scene...
new_user_input(world_list, state, oldstate);
glutSwapBuffers();
}
int
main(int argc, char *argv[])
{
init_dbgdump("./debug-dump.txt");
#ifndef WIN32
init_error_handling();
#endif
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow(windowName);
glutDisplayFunc(Render);
glutReshapeFunc(grafx_resize);
// void processMouse(int button, int state, int x, int y)
//
// Button will recieve an integer constant identified by a name in all
// caps. These identifiers have names like GLUT_DOWN, GLUT_UP etc. and
// represent the current state of the mouse buttons (using 0 and 1 for
// true or false). x and y are the position of the mouse measured from
// the upper left corner of the current window. The callback for
// glutMotionFunc should have the format:
//
// void processMouseActiveMotion(int x, int y)
glutKeyboardFunc(keyboard_event_handler);
// Triggered when a mouse button is pressed...
glutMouseFunc(mouse_button_event_handler);
// Triggered when the mouse moves within a window and buttons are
// pressed...
glutMotionFunc(drag_event_handler);
// Triggered when the mouse moves within a window and no buttons are
// pressed...
glutPassiveMotionFunc(motion_event_handler);
init_grafx();
init_3form();
// toggle_cpldebug();
glutDisplayFunc(update_display);
glutMainLoop();
return 0;
}
<|endoftext|>
|
<commit_before>//===--------------- LLVMContextImpl.cpp - Implementation ------*- C++ -*--===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements LLVMContextImpl, the opaque implementation
// of LLVMContext.
//
//===----------------------------------------------------------------------===//
#include "LLVMContextImpl.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/LLVMContext.h"
#include "llvm/Metadata.h"
using namespace llvm;
LLVMContextImpl::LLVMContextImpl(LLVMContext &C) :
Context(C), TheTrueVal(0), TheFalseVal(0) { }<commit_msg>Fix no newline at end of LLVMContextImpl.cpp<commit_after>//===--------------- LLVMContextImpl.cpp - Implementation ------*- C++ -*--===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements LLVMContextImpl, the opaque implementation
// of LLVMContext.
//
//===----------------------------------------------------------------------===//
#include "LLVMContextImpl.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/LLVMContext.h"
#include "llvm/Metadata.h"
using namespace llvm;
LLVMContextImpl::LLVMContextImpl(LLVMContext &C) :
Context(C), TheTrueVal(0), TheFalseVal(0) { }
<|endoftext|>
|
<commit_before>#define GLEW_STATIC
#define RUN_GRAPHICS_DISPLAY 0x00;
#define GLM_FORCE_RADIANS
#include <GL/glew.h>
#include <GL/gl.h>
#include <SDL2/SDL.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <iostream>
#include <memory>
#include <boost/program_options.hpp>
#include "common.h"
#include "GameWorld.h"
// Lousy global variables
const Uint8* keyboard_input;
SDL_Window * _window;
int window_width, window_height;
bool fullscreen = false;
/*
* SDL timers run in separate threads. In the timer thread
* push an event onto the event queue. This event signifies
* to call display() from the thread in which the OpenGL
* context was created.
*/
Uint32 tick(Uint32 interval, void *param)
{
SDL_Event event;
event.type = SDL_USEREVENT;
event.user.code = RUN_GRAPHICS_DISPLAY;
event.user.data1 = 0;
event.user.data2 = 0;
SDL_PushEvent(&event);
return interval;
}
struct SDLWindowDeleter
{
inline void operator()(SDL_Window* window)
{
SDL_DestroyWindow(window);
}
};
/*
* Handles input
*/
void HandleInput(const std::shared_ptr<GameWorld> game_world)
{
// Camera controller
int x, y;
SDL_PumpEvents();
SDL_GetMouseState(&x, &y);
SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
SDL_WarpMouseInWindow(_window, window_width/2, window_height/2);
SDL_EventState(SDL_MOUSEMOTION, SDL_ENABLE);
SDL_PumpEvents();
game_world->MoveCamera(glm::vec2(x,y), glm::vec2(window_width, window_height));
// Update game_world camera
if(keyboard_input[SDL_SCANCODE_W])
game_world->CameraController(1); // forward
if(keyboard_input[SDL_SCANCODE_A])
game_world->CameraController(2); // left
if(keyboard_input[SDL_SCANCODE_S])
game_world->CameraController(3); // back
if(keyboard_input[SDL_SCANCODE_D])
game_world->CameraController(4); // right
if(keyboard_input[SDL_SCANCODE_SPACE])
game_world->CameraController(9); // player: +y ("fly" up)
if(keyboard_input[SDL_SCANCODE_LCTRL])
game_world->CameraController(10); // player: -y ("fly" down)
if(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT))
game_world->DoAction(1);
if(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_RIGHT))
game_world->DoAction(2);
if(keyboard_input[SDL_SCANCODE_G])
game_world->DoAction(3);
if(keyboard_input[SDL_SCANCODE_H])
game_world->DoAction(4);
if(keyboard_input[SDL_SCANCODE_E])
game_world->ChangeBlockDist(1);
if(keyboard_input[SDL_SCANCODE_Q])
game_world->ChangeBlockDist(-1);
if(keyboard_input[SDL_SCANCODE_ESCAPE])
SDL_Quit();
}
/*
* Draws the game world and handles buffer switching.
*/
void Draw(const std::shared_ptr<SDL_Window> window, const std::shared_ptr<GameWorld> game_world)
{
// Background colour for the window
glClearColor(0.0f, 0.2f, 0.2f, 0.3f);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
// Draw the gameworld
game_world->Draw();
// Swap buffers
SDL_GL_SwapWindow(window.get());
}
/*
* Handles the initialisation of the game world.
* Configures the SDL window and initialises GLEW
*/
std::shared_ptr<SDL_Window> InitWorld()
{
// Window properties
std::shared_ptr<SDL_Window> window;
// Glew will later ensure that OpenGL 3 *is* supported
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
// Do double buffering in GL
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
// Initialise SDL - when using C/C++ it's common to have to
// initialise libraries by calling a function within them.
if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER) < 0)
{
std::cout << "Failed to initialise SDL: " << SDL_GetError() << std::endl;
return nullptr;
}
SDL_GetError();
// When we close a window quit the SDL application
atexit(SDL_Quit);
SDL_ShowCursor(0);
if(fullscreen)
{
SDL_DisplayMode display;
SDL_GetCurrentDisplayMode(0, &display);
window_width = display.w;
window_height = display.h;
}
else
{
window_width = 1024;
window_height = 768;
}
// Create a new window with an OpenGL surface
_window = SDL_CreateWindow("BlockWorld"
, SDL_WINDOWPOS_CENTERED
, SDL_WINDOWPOS_CENTERED
, window_width
, window_height
, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
if(fullscreen)
{
SDL_SetWindowFullscreen(_window, SDL_WINDOW_FULLSCREEN);
}
if(!_window)
{
std::cout << "Failed to create SDL window: " << SDL_GetError() << std::endl;
return nullptr;
}
SDL_GLContext glContext = SDL_GL_CreateContext(_window);
if (!glContext)
{
std::cout << "Failed to create OpenGL context: " << SDL_GetError() << std::endl;
return nullptr;
}
// Initialise GLEW - an easy way to ensure OpenGl 3.0+
// The *must* be done after we have set the video mode - otherwise we have no
// OpenGL context to test.
glewInit();
if(!glewIsSupported("GL_VERSION_3_0"))
{
std::cerr << "OpenGL 3.0 not available" << std::endl;
return nullptr;
}
// OpenGL settings
glDisable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
window.reset(_window, SDL_DestroyWindow);
return window;
}
ApplicationMode ParseOptions (int argc, char ** argv)
{
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
("help", "print this help message")
("fullscreen", "Runs the game in fullscreen")
("translate", "Show translation example (default)")
("rotate", "Show rotation example")
("scale", "Show scale example");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if(vm.count("help"))
{
std::cout << desc << std::endl;
exit(0);
}
if(vm.count("fullscreen"))
{
fullscreen = true;
}
if(vm.count("rotate"))
{
return ROTATE;
}
if(vm.count("scale"))
{
return SCALE;
}
// The default
return TRANSFORM;
}
int main(int argc, char ** argv) {
Uint32 delay = 1000/60; // in milliseconds
auto mode = ParseOptions(argc, argv);
auto window = InitWorld();
auto game_world = std::make_shared<GameWorld>(mode);
if(!window)
{
SDL_Quit();
}
keyboard_input = SDL_GetKeyboardState(NULL);
// Call the function "tick" every delay milliseconds
SDL_AddTimer(delay, tick, NULL);
// Add the main event loop
SDL_Event event;
while (SDL_WaitEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
SDL_Quit();
break;
case SDL_USEREVENT:
Draw(window, game_world);
HandleInput(game_world);
break;
default:
break;
}
}
}
<commit_msg>Capitalise global variables<commit_after>#define GLEW_STATIC
#define RUN_GRAPHICS_DISPLAY 0x00;
#define GLM_FORCE_RADIANS
#include <GL/glew.h>
#include <GL/gl.h>
#include <SDL2/SDL.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <iostream>
#include <memory>
#include <boost/program_options.hpp>
#include "common.h"
#include "GameWorld.h"
/**
* Global variables
*/
const Uint8* KEYBOARD_INPUT;
SDL_Window * _WINDOW;
int WINDOW_WIDTH, WINDOW_HEIGHT;
bool FULLSCREEN = false;
/*
* SDL timers run in separate threads. In the timer thread
* push an event onto the event queue. This event signifies
* to call display() from the thread in which the OpenGL
* context was created.
*/
Uint32 tick(Uint32 interval, void *param)
{
SDL_Event event;
event.type = SDL_USEREVENT;
event.user.code = RUN_GRAPHICS_DISPLAY;
event.user.data1 = 0;
event.user.data2 = 0;
SDL_PushEvent(&event);
return interval;
}
struct SDLWindowDeleter
{
inline void operator()(SDL_Window* window)
{
SDL_DestroyWindow(window);
}
};
/*
* Handles input
*/
void HandleInput(const std::shared_ptr<GameWorld> game_world)
{
// Camera controller
int x, y;
SDL_PumpEvents();
SDL_GetMouseState(&x, &y);
SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
SDL_WarpMouseInWindow(_WINDOW, WINDOW_WIDTH/2, WINDOW_HEIGHT/2);
SDL_EventState(SDL_MOUSEMOTION, SDL_ENABLE);
SDL_PumpEvents();
game_world->MoveCamera(glm::vec2(x,y), glm::vec2(WINDOW_WIDTH, WINDOW_HEIGHT));
// Update game_world camera
if(KEYBOARD_INPUT[SDL_SCANCODE_W])
game_world->CameraController(1); // forward
if(KEYBOARD_INPUT[SDL_SCANCODE_A])
game_world->CameraController(2); // left
if(KEYBOARD_INPUT[SDL_SCANCODE_S])
game_world->CameraController(3); // back
if(KEYBOARD_INPUT[SDL_SCANCODE_D])
game_world->CameraController(4); // right
if(KEYBOARD_INPUT[SDL_SCANCODE_SPACE])
game_world->CameraController(9); // player: +y ("fly" up)
if(KEYBOARD_INPUT[SDL_SCANCODE_LCTRL])
game_world->CameraController(10); // player: -y ("fly" down)
if(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT))
game_world->DoAction(1);
if(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_RIGHT))
game_world->DoAction(2);
if(KEYBOARD_INPUT[SDL_SCANCODE_G])
game_world->DoAction(3);
if(KEYBOARD_INPUT[SDL_SCANCODE_H])
game_world->DoAction(4);
if(KEYBOARD_INPUT[SDL_SCANCODE_E])
game_world->ChangeBlockDist(1);
if(KEYBOARD_INPUT[SDL_SCANCODE_Q])
game_world->ChangeBlockDist(-1);
if(KEYBOARD_INPUT[SDL_SCANCODE_ESCAPE])
SDL_Quit();
}
/*
* Draws the game world and handles buffer switching.
*/
void Draw(const std::shared_ptr<SDL_Window> window, const std::shared_ptr<GameWorld> game_world)
{
// Background colour for the window
glClearColor(0.0f, 0.2f, 0.2f, 0.3f);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
// Draw the gameworld
game_world->Draw();
// Swap buffers
SDL_GL_SwapWindow(window.get());
}
/*
* Handles the initialisation of the game world.
* Configures the SDL window and initialises GLEW
*/
std::shared_ptr<SDL_Window> InitWorld()
{
// Window properties
std::shared_ptr<SDL_Window> window;
// Glew will later ensure that OpenGL 3 *is* supported
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
// Do double buffering in GL
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
// Initialise SDL - when using C/C++ it's common to have to
// initialise libraries by calling a function within them.
if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER) < 0)
{
std::cout << "Failed to initialise SDL: " << SDL_GetError() << std::endl;
return nullptr;
}
SDL_GetError();
// When we close a window quit the SDL application
atexit(SDL_Quit);
SDL_ShowCursor(0);
if(FULLSCREEN)
{
SDL_DisplayMode display;
SDL_GetCurrentDisplayMode(0, &display);
WINDOW_WIDTH = display.w;
WINDOW_HEIGHT = display.h;
}
else
{
WINDOW_WIDTH = 1024;
WINDOW_HEIGHT = 768;
}
// Create a new window with an OpenGL surface
_WINDOW = SDL_CreateWindow("BlockWorld"
, SDL_WindowPOS_CENTERED
, SDL_WindowPOS_CENTERED
, WINDOW_WIDTH
, WINDOW_HEIGHT
, SDL_Window_OPENGL | SDL_Window_SHOWN);
if(FULLSCREEN)
{
SDL_SetWindowFULLSCREEN(_WINDOW, SDL_Window_FULLSCREEN);
}
if(!_WINDOW)
{
std::cout << "Failed to create SDL window: " << SDL_GetError() << std::endl;
return nullptr;
}
SDL_GLContext glContext = SDL_GL_CreateContext(_WINDOW);
if (!glContext)
{
std::cout << "Failed to create OpenGL context: " << SDL_GetError() << std::endl;
return nullptr;
}
// Initialise GLEW - an easy way to ensure OpenGl 3.0+
// The *must* be done after we have set the video mode - otherwise we have no
// OpenGL context to test.
glewInit();
if(!glewIsSupported("GL_VERSION_3_0"))
{
std::cerr << "OpenGL 3.0 not available" << std::endl;
return nullptr;
}
// OpenGL settings
glDisable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
window.reset(_WINDOW, SDL_DestroyWindow);
return window;
}
ApplicationMode ParseOptions (int argc, char ** argv)
{
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
("help", "print this help message")
("FULLSCREEN", "Runs the game in FULLSCREEN")
("translate", "Show translation example (default)")
("rotate", "Show rotation example")
("scale", "Show scale example");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if(vm.count("help"))
{
std::cout << desc << std::endl;
exit(0);
}
if(vm.count("FULLSCREEN"))
{
FULLSCREEN = true;
}
if(vm.count("rotate"))
{
return ROTATE;
}
if(vm.count("scale"))
{
return SCALE;
}
// The default
return TRANSFORM;
}
int main(int argc, char ** argv) {
Uint32 delay = 1000/60; // in milliseconds
auto mode = ParseOptions(argc, argv);
auto window = InitWorld();
auto game_world = std::make_shared<GameWorld>(mode);
if(!window)
{
SDL_Quit();
}
KEYBOARD_INPUT = SDL_GetKeyboardState(NULL);
// Call the function "tick" every delay milliseconds
SDL_AddTimer(delay, tick, NULL);
// Add the main event loop
SDL_Event event;
while (SDL_WaitEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
SDL_Quit();
break;
case SDL_USEREVENT:
Draw(window, game_world);
HandleInput(game_world);
break;
default:
break;
}
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2013, William Magato
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ''AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the copyright holder(s) or contributors.
*/
#include <iostream>
#include <llamaos/api/pci/BAR.h>
#include <llamaos/api/pci/Command.h>
#include <llamaos/api/pci/PCI.h>
#include <llamaos/api/pci/Status.h>
#include <llamaos/api/sleep.h>
using namespace std;
using namespace llamaos::api;
using namespace llamaos::api::pci;
int main (int /* argc */, char ** /* argv [] */)
{
cout << "running 80003es2lan llamaNET domain...\n" << endl;
PCI pci;
sleep (1);
cout << "PCI config:" << endl;
cout << pci << endl;
cout << "checking PCI config for valid 80003es2lan..." << endl;
uint16_t vendor_id = pci.read_config_word (0);
uint16_t device_id = pci.read_config_word (2);
uint32_t class_code = (pci.read_config_byte (11) << 16) | (pci.read_config_byte (10) << 8) | pci.read_config_byte(9);
uint16_t subvendor_id = pci.read_config_word (44);
if ( (vendor_id != 0x8086)
|| ( (device_id != 0x1096)
&& (device_id != 0x10ba))
|| (class_code != 0x020000)
|| (subvendor_id != 0x8086))
{
cout << "PCI hardware detected is NOT 80003es2lan" << endl;
cout << hex << " vendor: " << vendor_id << endl;
cout << hex << " devide: " << device_id << endl;
cout << hex << " class: " << class_code << endl;
cout << hex << "subvendor: " << subvendor_id << endl << endl;
cout << "waiting 3 sec, then exit..." << endl;
cout.flush ();
sleep (3);
return -1;
}
else
{
cout << "valid hardware detected." << endl;
}
cout << "waiting 3 sec, then exit..." << endl;
cout.flush ();
sleep (3);
return 0;
}
<commit_msg>minor change to intel driver<commit_after>/*
Copyright (c) 2013, William Magato
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ''AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the copyright holder(s) or contributors.
*/
#include <iostream>
#include <llamaos/api/pci/BAR.h>
#include <llamaos/api/pci/Command.h>
#include <llamaos/api/pci/PCI.h>
#include <llamaos/api/pci/Status.h>
#include <llamaos/api/sleep.h>
using namespace std;
using namespace llamaos::api;
using namespace llamaos::api::pci;
int main (int /* argc */, char ** /* argv [] */)
{
cout << "running 80003es2lan llamaNET domain...\n" << endl;
PCI pci;
sleep (1);
cout << "PCI config:" << endl;
cout << pci << endl;
cout << "checking PCI config for valid 80003es2lan..." << endl;
uint16_t vendor_id = pci.read_config_word (0);
uint16_t device_id = pci.read_config_word (2);
uint32_t class_code = (pci.read_config_byte (11) << 16) | (pci.read_config_byte (10) << 8) | pci.read_config_byte(9);
uint16_t subvendor_id = pci.read_config_word (44);
if ( (vendor_id != 0x8086)
|| (device_id != 0x1096)
// && (device_id != 0x10ba))
|| (class_code != 0x020000))
// || (subvendor_id != 0x8086))
{
cout << "PCI hardware detected is NOT 80003es2lan" << endl;
cout << hex << " vendor: " << vendor_id << endl;
cout << hex << " devide: " << device_id << endl;
cout << hex << " class: " << class_code << endl;
cout << hex << "subvendor: " << subvendor_id << endl << endl;
cout << "waiting 3 sec, then exit..." << endl;
cout.flush ();
sleep (3);
return -1;
}
else
{
cout << "valid hardware detected." << endl;
}
cout << "waiting 3 sec, then exit..." << endl;
cout.flush ();
sleep (3);
return 0;
}
<|endoftext|>
|
<commit_before>#include "ros/ros.h"
#include <string>
#include <boost/format.hpp>
#include "constants.h"
#include "uinput_device.h"
#include "viewport_mapper.h"
#include "ros_event_relay.h"
#include "lg_mirror/EvdevDeviceInfo.h"
const char* DEVICE_NAME_BASE = "Virtual Touchscreen (%s)";
const char* VIEWPORT_PARAM = "viewport";
using lg_mirror::DEVICE_INFO_SERVICE;
using lg_mirror::TOUCH_ROUTE_TOPIC;
bool init(ros::NodeHandle n) {
std::string viewport_name;
std::string device_name;
std::string viewport_geometry;
ViewportMapper *viewport_mapper = NULL;
/* grab parameters */
if (!n.getParam(VIEWPORT_PARAM, viewport_name)) {
ROS_ERROR("'viewport' parameter is required");
return false;
}
device_name = str(boost::format(DEVICE_NAME_BASE) % viewport_name);
/* discover viewport geometry */
std::ostringstream viewport_geometry_key;
viewport_geometry_key << "/viewport/" << viewport_name;
if (!n.getParam(viewport_geometry_key.str(), viewport_geometry)) {
ROS_ERROR_STREAM("Viewport " << viewport_name << " was not found");
return false;
}
/* create viewport mapper */
try {
viewport_mapper = new ViewportMapper(device_name, viewport_geometry);
} catch(ViewportMapperStringError e) {
ROS_ERROR_STREAM("ViewportMapper: " << e.what());
return false;
}
/* call the device_info service before creating the device */
ros::ServiceClient client = n.serviceClient<lg_mirror::EvdevDeviceInfo>(DEVICE_INFO_SERVICE);
lg_mirror::EvdevDeviceInfo srv;
client.waitForExistence();
if (!client.call(srv)) {
ROS_ERROR("Failed to call the device_info service");
return false;
}
/* spin up the uinput device */
UinputDevice uinput_device(device_name);
ROS_DEBUG_STREAM("Creating device: " << device_name << " for viewport " << viewport_name);
if (!uinput_device.Init(srv.response)) {
ROS_ERROR("Failed to create uinput device");
return false;
}
/* wait for xinput to reflect the new device */
if (!uinput_device.WaitForXinput()) {
ROS_ERROR("xinput query was cancelled");
return false;
}
/* instantiate an event relay */
RosEventRelay relay(n, viewport_name, uinput_device, *viewport_mapper);
n.subscribe(TOUCH_ROUTE_TOPIC, 10, &RosEventRelay::HandleRouterMessage, &relay);
return true;
}
int main(int argc, char** argv) {
/* initialize ros */
ros::init(argc, argv, "lg_mirror_receiver");
ros::NodeHandle n("~");
bool init_success = init(n);
if (!init_success) {
ros::shutdown();
exit(EXIT_FAILURE);
}
/* react until termination */
ros::spin();
}
<commit_msg>Prevent mirror route subscriber descoping<commit_after>#include "ros/ros.h"
#include <string>
#include <boost/format.hpp>
#include "constants.h"
#include "uinput_device.h"
#include "viewport_mapper.h"
#include "ros_event_relay.h"
#include "lg_mirror/EvdevDeviceInfo.h"
const char* DEVICE_NAME_BASE = "Virtual Touchscreen (%s)";
const char* VIEWPORT_PARAM = "viewport";
using lg_mirror::DEVICE_INFO_SERVICE;
using lg_mirror::TOUCH_ROUTE_TOPIC;
void fail() {
ros::shutdown();
exit(EXIT_FAILURE);
}
int main(int argc, char** argv) {
/* initialize ros */
ros::init(argc, argv, "lg_mirror_receiver");
ros::NodeHandle n("~");
std::string viewport_name;
std::string device_name;
std::string viewport_geometry;
ViewportMapper *viewport_mapper = NULL;
/* grab parameters */
if (!n.getParam(VIEWPORT_PARAM, viewport_name)) {
ROS_ERROR("'viewport' parameter is required");
fail();
}
device_name = str(boost::format(DEVICE_NAME_BASE) % viewport_name);
/* discover viewport geometry */
std::ostringstream viewport_geometry_key;
viewport_geometry_key << "/viewport/" << viewport_name;
if (!n.getParam(viewport_geometry_key.str(), viewport_geometry)) {
ROS_ERROR_STREAM("Viewport " << viewport_name << " was not found");
fail();
}
/* create viewport mapper */
try {
viewport_mapper = new ViewportMapper(device_name, viewport_geometry);
} catch(ViewportMapperStringError e) {
ROS_ERROR_STREAM("ViewportMapper: " << e.what());
fail();
}
/* call the device_info service before creating the device */
ros::ServiceClient client = n.serviceClient<lg_mirror::EvdevDeviceInfo>(DEVICE_INFO_SERVICE);
lg_mirror::EvdevDeviceInfo srv;
client.waitForExistence();
if (!client.call(srv)) {
ROS_ERROR("Failed to call the device_info service");
fail();
}
/* spin up the uinput device */
UinputDevice uinput_device(device_name);
ROS_DEBUG_STREAM("Creating device: " << device_name << " for viewport " << viewport_name);
if (!uinput_device.Init(srv.response)) {
ROS_ERROR("Failed to create uinput device");
fail();
}
/* wait for xinput to reflect the new device */
if (!uinput_device.WaitForXinput()) {
ROS_ERROR("xinput query was cancelled");
fail();
}
/* instantiate an event relay */
RosEventRelay relay(n, viewport_name, uinput_device, *viewport_mapper);
ros::Subscriber relay_sub = n.subscribe(TOUCH_ROUTE_TOPIC, 10, &RosEventRelay::HandleRouterMessage, &relay);
/* react until termination */
ros::spin();
}
<|endoftext|>
|
<commit_before>/*
NUI3 - C++ cross-platform GUI framework for OpenGL based applications
Copyright (C) 2002-2003 Sebastien Metrot
licence: see nui3/LICENCE.TXT
*/
#include "nui.h"
#include "nuiSeparator.h"
nuiSeparator::nuiSeparator(nuiOrientation orientation)
: nuiWidget()
{
SetObjectClass(_T("nuiSeparator"));
mOrientation = orientation;
}
nuiSeparator::~nuiSeparator()
{
}
nuiRect nuiSeparator::CalcIdealSize()
{
nuiContainer* pParent = GetParent();
nuiRect rect(0,0,32, 32);
if (pParent)
rect = pParent->GetRect();
nuiRect res;
switch (mOrientation)
{
case nuiHorizontal:
res.Set(0.0f, 0.0f, rect.GetWidth(), 2.0f);
break;
case nuiVertical:
res.Set(0.0f, 0.0f, 2.0f, rect.GetHeight());
break;
}
return res;
}
bool nuiSeparator::Draw(nuiDrawContext *pContext)
{
nuiRect r(GetRect());
pContext->SetBlendFunc(nuiBlendTransp);
pContext->EnableBlending(true);
pContext->SetStrokeColor(nuiColor(255, 255, 255, 120));
pContext->DrawLine(r.Left(), 0, r.Right(), 0);
pContext->SetStrokeColor(nuiColor(0, 0, 0, 32));
pContext->DrawLine(r.Left(), 1, r.Right(), 1);
return true;
}
<commit_msg>minor update on nuiSeparator<commit_after>/*
NUI3 - C++ cross-platform GUI framework for OpenGL based applications
Copyright (C) 2002-2003 Sebastien Metrot
licence: see nui3/LICENCE.TXT
*/
#include "nui.h"
#include "nuiSeparator.h"
nuiSeparator::nuiSeparator(nuiOrientation orientation)
: nuiWidget()
{
SetObjectClass(_T("nuiSeparator"));
mOrientation = orientation;
}
nuiSeparator::~nuiSeparator()
{
}
nuiRect nuiSeparator::CalcIdealSize()
{
nuiContainer* pParent = GetParent();
nuiRect rect(0,0,32, 32);
if (pParent)
rect = pParent->GetRect();
nuiRect res;
switch (mOrientation)
{
case nuiHorizontal:
res.Set(0.0f, 0.0f, rect.GetWidth(), 3.0f);
break;
case nuiVertical:
res.Set(0.0f, 0.0f, 3.0f, rect.GetHeight());
break;
}
return res;
}
bool nuiSeparator::Draw(nuiDrawContext *pContext)
{
nuiRect r(GetRect());
// TODO : vertical draw
pContext->SetStrokeColor(nuiColor(255, 255, 255));
pContext->DrawLine(r.Left(), 0, r.Right(), 0);
pContext->SetStrokeColor(nuiColor(0, 0, 0, 56));
pContext->DrawLine(r.Left(), 1.5, r.Right(), 1.5);
return true;
}
<|endoftext|>
|
<commit_before>#ifndef FACTOR_ENCODER
#define FACTOR_ENCODER
#include <map>
#include <string>
#include <vector>
int read_vocab(const char* fname,
std::map<std::string, double> &vocab,
int &maxlen);
void viterbi(const std::map<std::string, double> &vocab,
int maxlen,
const std::string &sentence,
std::vector<std::string> &best_path);
#endif
<commit_msg>roughly working code for removing subwords.<commit_after>#ifndef FACTOR_ENCODER
#define FACTOR_ENCODER
#include <map>
#include <string>
#include <vector>
int read_vocab(const char* fname,
std::map<std::string, double> &vocab,
int &maxlen);
int write_vocab(const char* fname,
const std::map<std::string, double> &vocab);
void sort_vocab(const std::map<std::string, double> &vocab,
std::vector<std::pair<std::string, double> > &sorted_vocab);
void viterbi(const std::map<std::string, double> &vocab,
int maxlen,
const std::string &sentence,
std::vector<std::string> &best_path,
bool reverse=true);
#endif
<|endoftext|>
|
<commit_before>//===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the AsmPrinter class.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/Constants.h"
#include "llvm/Module.h"
#include "llvm/Support/Mangler.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;
/// SwitchSection - Switch to the specified section of the executable if we
/// are not already in it!
///
void AsmPrinter::SwitchSection(const char *NewSection, const GlobalValue *GV) {
std::string NS;
if (GV && GV->hasSection())
NS = ".section " + GV->getSection();
else
NS = NewSection;
if (CurrentSection != NS) {
CurrentSection = NS;
if (!CurrentSection.empty())
O << "\t" << CurrentSection << "\n";
}
}
bool AsmPrinter::doInitialization(Module &M) {
Mang = new Mangler(M, GlobalPrefix);
SwitchSection("", 0); // Reset back to no section.
return false;
}
bool AsmPrinter::doFinalization(Module &M) {
delete Mang; Mang = 0;
return false;
}
void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
// What's my mangled name?
CurrentFnName = Mang->getValueName(MF.getFunction());
}
// EmitAlignment - Emit an alignment directive to the specified power of two.
void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
if (GV && GV->getAlignment())
NumBits = Log2_32(GV->getAlignment());
if (NumBits == 0) return; // No need to emit alignment.
if (AlignmentIsInBytes) NumBits = 1 << NumBits;
O << AlignDirective << NumBits << "\n";
}
/// EmitZeros - Emit a block of zeros.
///
void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
if (NumZeros) {
if (ZeroDirective)
O << ZeroDirective << NumZeros << "\n";
else {
for (; NumZeros; --NumZeros)
O << Data8bitsDirective << "0\n";
}
}
}
// Print out the specified constant, without a storage class. Only the
// constants valid in constant expressions can occur here.
void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
if (CV->isNullValue() || isa<UndefValue>(CV))
O << "0";
else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
assert(CB == ConstantBool::True);
O << "1";
} else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
if (((CI->getValue() << 32) >> 32) == CI->getValue())
O << CI->getValue();
else
O << (uint64_t)CI->getValue();
else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
O << CI->getValue();
else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
// This is a constant address for a global variable or function. Use the
// name of the variable or function as the address value, possibly
// decorating it with GlobalVarAddrPrefix/Suffix or
// FunctionAddrPrefix/Suffix (these all default to "" )
if (isa<Function>(GV))
O << FunctionAddrPrefix << Mang->getValueName(GV) << FunctionAddrSuffix;
else
O << GlobalVarAddrPrefix << Mang->getValueName(GV) << GlobalVarAddrSuffix;
} else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
const TargetData &TD = TM.getTargetData();
switch(CE->getOpcode()) {
case Instruction::GetElementPtr: {
// generate a symbolic expression for the byte address
const Constant *ptrVal = CE->getOperand(0);
std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
if (int64_t Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
if (Offset)
O << "(";
EmitConstantValueOnly(ptrVal);
if (Offset > 0)
O << ") + " << Offset;
else if (Offset < 0)
O << ") - " << -Offset;
} else {
EmitConstantValueOnly(ptrVal);
}
break;
}
case Instruction::Cast: {
// Support only non-converting or widening casts for now, that is, ones
// that do not involve a change in value. This assertion is really gross,
// and may not even be a complete check.
Constant *Op = CE->getOperand(0);
const Type *OpTy = Op->getType(), *Ty = CE->getType();
// Remember, kids, pointers can be losslessly converted back and forth
// into 32-bit or wider integers, regardless of signedness. :-P
assert(((isa<PointerType>(OpTy)
&& (Ty == Type::LongTy || Ty == Type::ULongTy
|| Ty == Type::IntTy || Ty == Type::UIntTy))
|| (isa<PointerType>(Ty)
&& (OpTy == Type::LongTy || OpTy == Type::ULongTy
|| OpTy == Type::IntTy || OpTy == Type::UIntTy))
|| (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
&& OpTy->isLosslesslyConvertibleTo(Ty))))
&& "FIXME: Don't yet support this kind of constant cast expr");
EmitConstantValueOnly(Op);
break;
}
case Instruction::Add:
O << "(";
EmitConstantValueOnly(CE->getOperand(0));
O << ") + (";
EmitConstantValueOnly(CE->getOperand(1));
O << ")";
break;
default:
assert(0 && "Unsupported operator!");
}
} else {
assert(0 && "Unknown constant value!");
}
}
/// toOctal - Convert the low order bits of X into an octal digit.
///
static inline char toOctal(int X) {
return (X&7)+'0';
}
/// printAsCString - Print the specified array as a C compatible string, only if
/// the predicate isString is true.
///
static void printAsCString(std::ostream &O, const ConstantArray *CVA,
unsigned LastElt) {
assert(CVA->isString() && "Array is not string compatible!");
O << "\"";
for (unsigned i = 0; i != LastElt; ++i) {
unsigned char C =
(unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
if (C == '"') {
O << "\\\"";
} else if (C == '\\') {
O << "\\\\";
} else if (isprint(C)) {
O << C;
} else {
switch(C) {
case '\b': O << "\\b"; break;
case '\f': O << "\\f"; break;
case '\n': O << "\\n"; break;
case '\r': O << "\\r"; break;
case '\t': O << "\\t"; break;
default:
O << '\\';
O << toOctal(C >> 6);
O << toOctal(C >> 3);
O << toOctal(C >> 0);
break;
}
}
}
O << "\"";
}
/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
///
void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
const TargetData &TD = TM.getTargetData();
if (CV->isNullValue() || isa<UndefValue>(CV)) {
EmitZeros(TD.getTypeSize(CV->getType()));
return;
} else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
if (CVA->isString()) {
unsigned NumElts = CVA->getNumOperands();
if (AscizDirective && NumElts &&
cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
O << AscizDirective;
printAsCString(O, CVA, NumElts-1);
} else {
O << AsciiDirective;
printAsCString(O, CVA, NumElts);
}
O << "\n";
} else { // Not a string. Print the values in successive locations
for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
EmitGlobalConstant(CVA->getOperand(i));
}
return;
} else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
// Print the fields in successive locations. Pad to align if needed!
const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
uint64_t sizeSoFar = 0;
for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
const Constant* field = CVS->getOperand(i);
// Check if padding is needed and insert one or more 0s.
uint64_t fieldSize = TD.getTypeSize(field->getType());
uint64_t padSize = ((i == e-1? cvsLayout->StructSize
: cvsLayout->MemberOffsets[i+1])
- cvsLayout->MemberOffsets[i]) - fieldSize;
sizeSoFar += fieldSize + padSize;
// Now print the actual field value
EmitGlobalConstant(field);
// Insert the field padding unless it's zero bytes...
EmitZeros(padSize);
}
assert(sizeSoFar == cvsLayout->StructSize &&
"Layout of constant struct may be incorrect!");
return;
} else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
// FP Constants are printed as integer constants to avoid losing
// precision...
double Val = CFP->getValue();
if (CFP->getType() == Type::DoubleTy) {
if (Data64bitsDirective)
O << Data64bitsDirective << DoubleToBits(Val) << "\t" << CommentString
<< " double value: " << Val << "\n";
else if (TD.isBigEndian()) {
O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
<< "\t" << CommentString << " double most significant word "
<< Val << "\n";
O << Data32bitsDirective << unsigned(DoubleToBits(Val))
<< "\t" << CommentString << " double least significant word "
<< Val << "\n";
} else {
O << Data32bitsDirective << unsigned(DoubleToBits(Val))
<< "\t" << CommentString << " double least significant word " << Val
<< "\n";
O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
<< "\t" << CommentString << " double most significant word " << Val
<< "\n";
}
return;
} else {
O << Data32bitsDirective << FloatToBits(Val) << "\t" << CommentString
<< " float " << Val << "\n";
return;
}
} else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
uint64_t Val = CI->getRawValue();
if (Data64bitsDirective)
O << Data64bitsDirective << Val << "\n";
else if (TD.isBigEndian()) {
O << Data32bitsDirective << unsigned(Val >> 32)
<< "\t" << CommentString << " Double-word most significant word "
<< Val << "\n";
O << Data32bitsDirective << unsigned(Val)
<< "\t" << CommentString << " Double-word least significant word "
<< Val << "\n";
} else {
O << Data32bitsDirective << unsigned(Val)
<< "\t" << CommentString << " Double-word least significant word "
<< Val << "\n";
O << Data32bitsDirective << unsigned(Val >> 32)
<< "\t" << CommentString << " Double-word most significant word "
<< Val << "\n";
}
return;
}
}
const Type *type = CV->getType();
switch (type->getTypeID()) {
case Type::BoolTyID:
case Type::UByteTyID: case Type::SByteTyID:
O << Data8bitsDirective;
break;
case Type::UShortTyID: case Type::ShortTyID:
O << Data16bitsDirective;
break;
case Type::PointerTyID:
if (TD.getPointerSize() == 8) {
O << Data64bitsDirective;
break;
}
//Fall through for pointer size == int size
case Type::UIntTyID: case Type::IntTyID:
O << Data32bitsDirective;
break;
case Type::ULongTyID: case Type::LongTyID:
assert(Data64bitsDirective &&"Target cannot handle 64-bit constant exprs!");
O << Data64bitsDirective;
break;
case Type::FloatTyID: case Type::DoubleTyID:
assert (0 && "Should have already output floating point constant.");
default:
assert (0 && "Can't handle printing this type of thing");
break;
}
EmitConstantValueOnly(CV);
O << "\n";
}
<commit_msg>increment the function number in SetupMachineFunction<commit_after>//===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the AsmPrinter class.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/Constants.h"
#include "llvm/Module.h"
#include "llvm/Support/Mangler.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;
/// SwitchSection - Switch to the specified section of the executable if we
/// are not already in it!
///
void AsmPrinter::SwitchSection(const char *NewSection, const GlobalValue *GV) {
std::string NS;
if (GV && GV->hasSection())
NS = ".section " + GV->getSection();
else
NS = NewSection;
if (CurrentSection != NS) {
CurrentSection = NS;
if (!CurrentSection.empty())
O << "\t" << CurrentSection << "\n";
}
}
bool AsmPrinter::doInitialization(Module &M) {
Mang = new Mangler(M, GlobalPrefix);
SwitchSection("", 0); // Reset back to no section.
return false;
}
bool AsmPrinter::doFinalization(Module &M) {
delete Mang; Mang = 0;
return false;
}
void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
// What's my mangled name?
CurrentFnName = Mang->getValueName(MF.getFunction());
IncrementFunctionNumber();
}
// EmitAlignment - Emit an alignment directive to the specified power of two.
void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
if (GV && GV->getAlignment())
NumBits = Log2_32(GV->getAlignment());
if (NumBits == 0) return; // No need to emit alignment.
if (AlignmentIsInBytes) NumBits = 1 << NumBits;
O << AlignDirective << NumBits << "\n";
}
/// EmitZeros - Emit a block of zeros.
///
void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
if (NumZeros) {
if (ZeroDirective)
O << ZeroDirective << NumZeros << "\n";
else {
for (; NumZeros; --NumZeros)
O << Data8bitsDirective << "0\n";
}
}
}
// Print out the specified constant, without a storage class. Only the
// constants valid in constant expressions can occur here.
void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
if (CV->isNullValue() || isa<UndefValue>(CV))
O << "0";
else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
assert(CB == ConstantBool::True);
O << "1";
} else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
if (((CI->getValue() << 32) >> 32) == CI->getValue())
O << CI->getValue();
else
O << (uint64_t)CI->getValue();
else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
O << CI->getValue();
else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
// This is a constant address for a global variable or function. Use the
// name of the variable or function as the address value, possibly
// decorating it with GlobalVarAddrPrefix/Suffix or
// FunctionAddrPrefix/Suffix (these all default to "" )
if (isa<Function>(GV))
O << FunctionAddrPrefix << Mang->getValueName(GV) << FunctionAddrSuffix;
else
O << GlobalVarAddrPrefix << Mang->getValueName(GV) << GlobalVarAddrSuffix;
} else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
const TargetData &TD = TM.getTargetData();
switch(CE->getOpcode()) {
case Instruction::GetElementPtr: {
// generate a symbolic expression for the byte address
const Constant *ptrVal = CE->getOperand(0);
std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
if (int64_t Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
if (Offset)
O << "(";
EmitConstantValueOnly(ptrVal);
if (Offset > 0)
O << ") + " << Offset;
else if (Offset < 0)
O << ") - " << -Offset;
} else {
EmitConstantValueOnly(ptrVal);
}
break;
}
case Instruction::Cast: {
// Support only non-converting or widening casts for now, that is, ones
// that do not involve a change in value. This assertion is really gross,
// and may not even be a complete check.
Constant *Op = CE->getOperand(0);
const Type *OpTy = Op->getType(), *Ty = CE->getType();
// Remember, kids, pointers can be losslessly converted back and forth
// into 32-bit or wider integers, regardless of signedness. :-P
assert(((isa<PointerType>(OpTy)
&& (Ty == Type::LongTy || Ty == Type::ULongTy
|| Ty == Type::IntTy || Ty == Type::UIntTy))
|| (isa<PointerType>(Ty)
&& (OpTy == Type::LongTy || OpTy == Type::ULongTy
|| OpTy == Type::IntTy || OpTy == Type::UIntTy))
|| (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
&& OpTy->isLosslesslyConvertibleTo(Ty))))
&& "FIXME: Don't yet support this kind of constant cast expr");
EmitConstantValueOnly(Op);
break;
}
case Instruction::Add:
O << "(";
EmitConstantValueOnly(CE->getOperand(0));
O << ") + (";
EmitConstantValueOnly(CE->getOperand(1));
O << ")";
break;
default:
assert(0 && "Unsupported operator!");
}
} else {
assert(0 && "Unknown constant value!");
}
}
/// toOctal - Convert the low order bits of X into an octal digit.
///
static inline char toOctal(int X) {
return (X&7)+'0';
}
/// printAsCString - Print the specified array as a C compatible string, only if
/// the predicate isString is true.
///
static void printAsCString(std::ostream &O, const ConstantArray *CVA,
unsigned LastElt) {
assert(CVA->isString() && "Array is not string compatible!");
O << "\"";
for (unsigned i = 0; i != LastElt; ++i) {
unsigned char C =
(unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
if (C == '"') {
O << "\\\"";
} else if (C == '\\') {
O << "\\\\";
} else if (isprint(C)) {
O << C;
} else {
switch(C) {
case '\b': O << "\\b"; break;
case '\f': O << "\\f"; break;
case '\n': O << "\\n"; break;
case '\r': O << "\\r"; break;
case '\t': O << "\\t"; break;
default:
O << '\\';
O << toOctal(C >> 6);
O << toOctal(C >> 3);
O << toOctal(C >> 0);
break;
}
}
}
O << "\"";
}
/// EmitGlobalConstant - Print a general LLVM constant to the .s file.
///
void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
const TargetData &TD = TM.getTargetData();
if (CV->isNullValue() || isa<UndefValue>(CV)) {
EmitZeros(TD.getTypeSize(CV->getType()));
return;
} else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
if (CVA->isString()) {
unsigned NumElts = CVA->getNumOperands();
if (AscizDirective && NumElts &&
cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
O << AscizDirective;
printAsCString(O, CVA, NumElts-1);
} else {
O << AsciiDirective;
printAsCString(O, CVA, NumElts);
}
O << "\n";
} else { // Not a string. Print the values in successive locations
for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
EmitGlobalConstant(CVA->getOperand(i));
}
return;
} else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
// Print the fields in successive locations. Pad to align if needed!
const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
uint64_t sizeSoFar = 0;
for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
const Constant* field = CVS->getOperand(i);
// Check if padding is needed and insert one or more 0s.
uint64_t fieldSize = TD.getTypeSize(field->getType());
uint64_t padSize = ((i == e-1? cvsLayout->StructSize
: cvsLayout->MemberOffsets[i+1])
- cvsLayout->MemberOffsets[i]) - fieldSize;
sizeSoFar += fieldSize + padSize;
// Now print the actual field value
EmitGlobalConstant(field);
// Insert the field padding unless it's zero bytes...
EmitZeros(padSize);
}
assert(sizeSoFar == cvsLayout->StructSize &&
"Layout of constant struct may be incorrect!");
return;
} else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
// FP Constants are printed as integer constants to avoid losing
// precision...
double Val = CFP->getValue();
if (CFP->getType() == Type::DoubleTy) {
if (Data64bitsDirective)
O << Data64bitsDirective << DoubleToBits(Val) << "\t" << CommentString
<< " double value: " << Val << "\n";
else if (TD.isBigEndian()) {
O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
<< "\t" << CommentString << " double most significant word "
<< Val << "\n";
O << Data32bitsDirective << unsigned(DoubleToBits(Val))
<< "\t" << CommentString << " double least significant word "
<< Val << "\n";
} else {
O << Data32bitsDirective << unsigned(DoubleToBits(Val))
<< "\t" << CommentString << " double least significant word " << Val
<< "\n";
O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
<< "\t" << CommentString << " double most significant word " << Val
<< "\n";
}
return;
} else {
O << Data32bitsDirective << FloatToBits(Val) << "\t" << CommentString
<< " float " << Val << "\n";
return;
}
} else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
uint64_t Val = CI->getRawValue();
if (Data64bitsDirective)
O << Data64bitsDirective << Val << "\n";
else if (TD.isBigEndian()) {
O << Data32bitsDirective << unsigned(Val >> 32)
<< "\t" << CommentString << " Double-word most significant word "
<< Val << "\n";
O << Data32bitsDirective << unsigned(Val)
<< "\t" << CommentString << " Double-word least significant word "
<< Val << "\n";
} else {
O << Data32bitsDirective << unsigned(Val)
<< "\t" << CommentString << " Double-word least significant word "
<< Val << "\n";
O << Data32bitsDirective << unsigned(Val >> 32)
<< "\t" << CommentString << " Double-word most significant word "
<< Val << "\n";
}
return;
}
}
const Type *type = CV->getType();
switch (type->getTypeID()) {
case Type::BoolTyID:
case Type::UByteTyID: case Type::SByteTyID:
O << Data8bitsDirective;
break;
case Type::UShortTyID: case Type::ShortTyID:
O << Data16bitsDirective;
break;
case Type::PointerTyID:
if (TD.getPointerSize() == 8) {
O << Data64bitsDirective;
break;
}
//Fall through for pointer size == int size
case Type::UIntTyID: case Type::IntTyID:
O << Data32bitsDirective;
break;
case Type::ULongTyID: case Type::LongTyID:
assert(Data64bitsDirective &&"Target cannot handle 64-bit constant exprs!");
O << Data64bitsDirective;
break;
case Type::FloatTyID: case Type::DoubleTyID:
assert (0 && "Should have already output floating point constant.");
default:
assert (0 && "Can't handle printing this type of thing");
break;
}
EmitConstantValueOnly(CV);
O << "\n";
}
<|endoftext|>
|
<commit_before>//===- lib/Driver/GnuLdDriver.cpp -----------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// Concrete instance of the Driver for GNU's ld.
///
//===----------------------------------------------------------------------===//
#include "lld/Driver/Driver.h"
#include "lld/Driver/GnuLdInputGraph.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Signals.h"
using namespace lld;
namespace {
// Create enum with OPT_xxx values for each option in GnuLdOptions.td
enum {
OPT_INVALID = 0,
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELP, META) \
OPT_##ID,
#include "GnuLdOptions.inc"
#undef OPTION
};
// Create prefix string literals used in GnuLdOptions.td
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#include "GnuLdOptions.inc"
#undef PREFIX
// Create table mapping all options defined in GnuLdOptions.td
static const llvm::opt::OptTable::Info infoTable[] = {
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR) \
{ PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, llvm::opt::Option::KIND##Class, \
PARAM, FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS },
#include "GnuLdOptions.inc"
#undef OPTION
};
// Create OptTable class for parsing actual command line arguments
class GnuLdOptTable : public llvm::opt::OptTable {
public:
GnuLdOptTable() : OptTable(infoTable, llvm::array_lengthof(infoTable)){}
};
} // namespace
llvm::ErrorOr<StringRef> ELFFileNode::getPath(const LinkingContext &) const {
if (!_isDashlPrefix)
return _path;
return _elfLinkingContext.searchLibrary(_path, _libraryPaths);
}
std::string ELFFileNode::errStr(llvm::error_code errc) {
if (errc == llvm::errc::no_such_file_or_directory) {
if (_isDashlPrefix)
return (Twine("Unable to find library -l") + _path).str();
return (Twine("Unable to find file ") + _path).str();
}
return FileNode::errStr(errc);
}
bool GnuLdDriver::linkELF(int argc, const char *argv[],
raw_ostream &diagnostics) {
std::unique_ptr<ELFLinkingContext> options;
if (!parse(argc, argv, options, diagnostics))
return false;
if (!options)
return true;
return link(*options, diagnostics);
}
bool GnuLdDriver::parse(int argc, const char *argv[],
std::unique_ptr<ELFLinkingContext> &context,
raw_ostream &diagnostics) {
// Parse command line options using GnuLdOptions.td
std::unique_ptr<llvm::opt::InputArgList> parsedArgs;
GnuLdOptTable table;
unsigned missingIndex;
unsigned missingCount;
parsedArgs.reset(
table.ParseArgs(&argv[1], &argv[argc], missingIndex, missingCount));
if (missingCount) {
diagnostics << "error: missing arg value for '"
<< parsedArgs->getArgString(missingIndex) << "' expected "
<< missingCount << " argument(s).\n";
return false;
}
// Handle --help
if (parsedArgs->getLastArg(OPT_help)) {
table.PrintHelp(llvm::outs(), argv[0], "LLVM Linker", false);
return true;
}
// Use -target or use default target triple to instantiate LinkingContext
llvm::Triple triple;
if (llvm::opt::Arg *trip = parsedArgs->getLastArg(OPT_target))
triple = llvm::Triple(trip->getValue());
else
triple = getDefaultTarget(argv[0]);
std::unique_ptr<ELFLinkingContext> ctx(ELFLinkingContext::create(triple));
if (!ctx) {
diagnostics << "unknown target triple\n";
return false;
}
std::unique_ptr<InputGraph> inputGraph(new InputGraph());
std::stack<InputElement *> controlNodeStack;
// Positional options for an Input File
std::vector<StringRef> searchPath;
bool isWholeArchive = false;
bool asNeeded = false;
bool _outputOptionSet = false;
// Create a dynamic executable by default
ctx->setOutputELFType(llvm::ELF::ET_EXEC);
ctx->setIsStaticExecutable(false);
ctx->setAllowShlibUndefines(false);
ctx->setUseShlibUndefines(true);
int index = 0;
// Process all the arguments and create Input Elements
for (auto inputArg : *parsedArgs) {
switch (inputArg->getOption().getID()) {
case OPT_mllvm:
ctx->appendLLVMOption(inputArg->getValue());
break;
case OPT_relocatable:
ctx->setOutputELFType(llvm::ELF::ET_REL);
ctx->setPrintRemainingUndefines(false);
ctx->setAllowRemainingUndefines(true);
break;
case OPT_static:
ctx->setOutputELFType(llvm::ELF::ET_EXEC);
ctx->setIsStaticExecutable(true);
break;
case OPT_shared:
ctx->setOutputELFType(llvm::ELF::ET_DYN);
ctx->setAllowShlibUndefines(true);
ctx->setUseShlibUndefines(false);
break;
case OPT_e:
ctx->setEntrySymbolName(inputArg->getValue());
break;
case OPT_output:
_outputOptionSet = true;
ctx->setOutputPath(inputArg->getValue());
break;
case OPT_noinhibit_exec:
ctx->setAllowRemainingUndefines(true);
break;
case OPT_merge_strings:
ctx->setMergeCommonStrings(true);
break;
case OPT_t:
ctx->setLogInputFiles(true);
break;
case OPT_no_allow_shlib_undefs:
ctx->setAllowShlibUndefines(false);
break;
case OPT_allow_shlib_undefs:
ctx->setAllowShlibUndefines(true);
break;
case OPT_use_shlib_undefs:
ctx->setUseShlibUndefines(true);
break;
case OPT_dynamic_linker:
ctx->setInterpreter(inputArg->getValue());
break;
case OPT_nmagic:
ctx->setOutputMagic(ELFLinkingContext::OutputMagic::NMAGIC);
ctx->setIsStaticExecutable(true);
break;
case OPT_omagic:
ctx->setOutputMagic(ELFLinkingContext::OutputMagic::OMAGIC);
ctx->setIsStaticExecutable(true);
break;
case OPT_no_omagic:
ctx->setOutputMagic(ELFLinkingContext::OutputMagic::DEFAULT);
ctx->setNoAllowDynamicLibraries();
break;
case OPT_u:
ctx->addInitialUndefinedSymbol(inputArg->getValue());
break;
case OPT_init:
ctx->addInitFunction(inputArg->getValue());
break;
case OPT_fini:
ctx->addFiniFunction(inputArg->getValue());
break;
case OPT_output_filetype:
ctx->setOutputFileType(inputArg->getValue());
break;
case OPT_no_whole_archive:
isWholeArchive = false;
break;
case OPT_whole_archive:
isWholeArchive = true;
break;
case OPT_as_needed:
asNeeded = true;
break;
case OPT_no_as_needed:
asNeeded = false;
break;
case OPT_L:
searchPath.push_back(inputArg->getValue());
break;
case OPT_start_group: {
std::unique_ptr<InputElement> controlStart(new ELFGroup(*ctx, index++));
controlNodeStack.push(controlStart.get());
(llvm::dyn_cast<ControlNode>)(controlNodeStack.top())
->processControlEnter();
inputGraph->addInputElement(std::move(controlStart));
break;
}
case OPT_end_group:
(llvm::dyn_cast<ControlNode>)(controlNodeStack.top())
->processControlExit();
controlNodeStack.pop();
break;
case OPT_INPUT:
case OPT_l: {
std::unique_ptr<InputElement> inputFile =
std::move(std::unique_ptr<InputElement>(new ELFFileNode(
*ctx, inputArg->getValue(), searchPath, index++, isWholeArchive,
asNeeded, inputArg->getOption().getID() == OPT_l)));
if (controlNodeStack.empty())
inputGraph->addInputElement(std::move(inputFile));
else
(llvm::dyn_cast<ControlNode>)(controlNodeStack.top())
->processInputElement(std::move(inputFile));
break;
}
case OPT_rpath: {
SmallVector<StringRef, 2> rpaths;
StringRef(inputArg->getValue()).split(rpaths, ":");
for (auto path : rpaths)
ctx->addRpath(path);
break;
}
case OPT_rpath_link: {
SmallVector<StringRef, 2> rpaths;
StringRef(inputArg->getValue()).split(rpaths, ":");
for (auto path : rpaths)
ctx->addRpathLink(path);
break;
}
case OPT_sysroot:
ctx->setSysroot(inputArg->getValue());
break;
case OPT_soname:
ctx->setSharedObjectName(inputArg->getValue());
break;
default:
break;
} // end switch on option ID
} // end for
if (!inputGraph->size()) {
diagnostics << "No input files\n";
return false;
}
// Set default output file name if the output file was not
// specified.
if (!_outputOptionSet) {
switch (ctx->outputFileType()) {
case LinkingContext::OutputFileType::YAML:
ctx->setOutputPath("-");
break;
case LinkingContext::OutputFileType::Native:
ctx->setOutputPath("a.native");
break;
default:
ctx->setOutputPath("a.out");
break;
}
}
if (ctx->outputFileType() == LinkingContext::OutputFileType::YAML)
inputGraph->dump(diagnostics);
// Validate the combination of options used.
if (!ctx->validate(diagnostics))
return false;
ctx->setInputGraph(std::move(inputGraph));
context.swap(ctx);
return true;
}
/// Get the default target triple based on either the program name
/// (e.g. "x86-ibm-linux-lld") or the primary target llvm was configured for.
llvm::Triple GnuLdDriver::getDefaultTarget(const char *progName) {
SmallVector<StringRef, 4> components;
llvm::SplitString(llvm::sys::path::stem(progName), components, "-");
// If has enough parts to be start with a triple.
if (components.size() >= 4) {
llvm::Triple triple(components[0], components[1], components[2],
components[3]);
// If first component looks like an arch.
if (triple.getArch() != llvm::Triple::UnknownArch)
return triple;
}
// Fallback to use whatever default triple llvm was configured for.
return llvm::Triple(llvm::sys::getDefaultTargetTriple());
}
<commit_msg>Simplify unique_ptr instantiation. No functionality change.<commit_after>//===- lib/Driver/GnuLdDriver.cpp -----------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// Concrete instance of the Driver for GNU's ld.
///
//===----------------------------------------------------------------------===//
#include "lld/Driver/Driver.h"
#include "lld/Driver/GnuLdInputGraph.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Signals.h"
using namespace lld;
namespace {
// Create enum with OPT_xxx values for each option in GnuLdOptions.td
enum {
OPT_INVALID = 0,
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELP, META) \
OPT_##ID,
#include "GnuLdOptions.inc"
#undef OPTION
};
// Create prefix string literals used in GnuLdOptions.td
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#include "GnuLdOptions.inc"
#undef PREFIX
// Create table mapping all options defined in GnuLdOptions.td
static const llvm::opt::OptTable::Info infoTable[] = {
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
HELPTEXT, METAVAR) \
{ PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, llvm::opt::Option::KIND##Class, \
PARAM, FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS },
#include "GnuLdOptions.inc"
#undef OPTION
};
// Create OptTable class for parsing actual command line arguments
class GnuLdOptTable : public llvm::opt::OptTable {
public:
GnuLdOptTable() : OptTable(infoTable, llvm::array_lengthof(infoTable)){}
};
} // namespace
llvm::ErrorOr<StringRef> ELFFileNode::getPath(const LinkingContext &) const {
if (!_isDashlPrefix)
return _path;
return _elfLinkingContext.searchLibrary(_path, _libraryPaths);
}
std::string ELFFileNode::errStr(llvm::error_code errc) {
if (errc == llvm::errc::no_such_file_or_directory) {
if (_isDashlPrefix)
return (Twine("Unable to find library -l") + _path).str();
return (Twine("Unable to find file ") + _path).str();
}
return FileNode::errStr(errc);
}
bool GnuLdDriver::linkELF(int argc, const char *argv[],
raw_ostream &diagnostics) {
std::unique_ptr<ELFLinkingContext> options;
if (!parse(argc, argv, options, diagnostics))
return false;
if (!options)
return true;
return link(*options, diagnostics);
}
bool GnuLdDriver::parse(int argc, const char *argv[],
std::unique_ptr<ELFLinkingContext> &context,
raw_ostream &diagnostics) {
// Parse command line options using GnuLdOptions.td
std::unique_ptr<llvm::opt::InputArgList> parsedArgs;
GnuLdOptTable table;
unsigned missingIndex;
unsigned missingCount;
parsedArgs.reset(
table.ParseArgs(&argv[1], &argv[argc], missingIndex, missingCount));
if (missingCount) {
diagnostics << "error: missing arg value for '"
<< parsedArgs->getArgString(missingIndex) << "' expected "
<< missingCount << " argument(s).\n";
return false;
}
// Handle --help
if (parsedArgs->getLastArg(OPT_help)) {
table.PrintHelp(llvm::outs(), argv[0], "LLVM Linker", false);
return true;
}
// Use -target or use default target triple to instantiate LinkingContext
llvm::Triple triple;
if (llvm::opt::Arg *trip = parsedArgs->getLastArg(OPT_target))
triple = llvm::Triple(trip->getValue());
else
triple = getDefaultTarget(argv[0]);
std::unique_ptr<ELFLinkingContext> ctx(ELFLinkingContext::create(triple));
if (!ctx) {
diagnostics << "unknown target triple\n";
return false;
}
std::unique_ptr<InputGraph> inputGraph(new InputGraph());
std::stack<InputElement *> controlNodeStack;
// Positional options for an Input File
std::vector<StringRef> searchPath;
bool isWholeArchive = false;
bool asNeeded = false;
bool _outputOptionSet = false;
// Create a dynamic executable by default
ctx->setOutputELFType(llvm::ELF::ET_EXEC);
ctx->setIsStaticExecutable(false);
ctx->setAllowShlibUndefines(false);
ctx->setUseShlibUndefines(true);
int index = 0;
// Process all the arguments and create Input Elements
for (auto inputArg : *parsedArgs) {
switch (inputArg->getOption().getID()) {
case OPT_mllvm:
ctx->appendLLVMOption(inputArg->getValue());
break;
case OPT_relocatable:
ctx->setOutputELFType(llvm::ELF::ET_REL);
ctx->setPrintRemainingUndefines(false);
ctx->setAllowRemainingUndefines(true);
break;
case OPT_static:
ctx->setOutputELFType(llvm::ELF::ET_EXEC);
ctx->setIsStaticExecutable(true);
break;
case OPT_shared:
ctx->setOutputELFType(llvm::ELF::ET_DYN);
ctx->setAllowShlibUndefines(true);
ctx->setUseShlibUndefines(false);
break;
case OPT_e:
ctx->setEntrySymbolName(inputArg->getValue());
break;
case OPT_output:
_outputOptionSet = true;
ctx->setOutputPath(inputArg->getValue());
break;
case OPT_noinhibit_exec:
ctx->setAllowRemainingUndefines(true);
break;
case OPT_merge_strings:
ctx->setMergeCommonStrings(true);
break;
case OPT_t:
ctx->setLogInputFiles(true);
break;
case OPT_no_allow_shlib_undefs:
ctx->setAllowShlibUndefines(false);
break;
case OPT_allow_shlib_undefs:
ctx->setAllowShlibUndefines(true);
break;
case OPT_use_shlib_undefs:
ctx->setUseShlibUndefines(true);
break;
case OPT_dynamic_linker:
ctx->setInterpreter(inputArg->getValue());
break;
case OPT_nmagic:
ctx->setOutputMagic(ELFLinkingContext::OutputMagic::NMAGIC);
ctx->setIsStaticExecutable(true);
break;
case OPT_omagic:
ctx->setOutputMagic(ELFLinkingContext::OutputMagic::OMAGIC);
ctx->setIsStaticExecutable(true);
break;
case OPT_no_omagic:
ctx->setOutputMagic(ELFLinkingContext::OutputMagic::DEFAULT);
ctx->setNoAllowDynamicLibraries();
break;
case OPT_u:
ctx->addInitialUndefinedSymbol(inputArg->getValue());
break;
case OPT_init:
ctx->addInitFunction(inputArg->getValue());
break;
case OPT_fini:
ctx->addFiniFunction(inputArg->getValue());
break;
case OPT_output_filetype:
ctx->setOutputFileType(inputArg->getValue());
break;
case OPT_no_whole_archive:
isWholeArchive = false;
break;
case OPT_whole_archive:
isWholeArchive = true;
break;
case OPT_as_needed:
asNeeded = true;
break;
case OPT_no_as_needed:
asNeeded = false;
break;
case OPT_L:
searchPath.push_back(inputArg->getValue());
break;
case OPT_start_group: {
std::unique_ptr<InputElement> controlStart(new ELFGroup(*ctx, index++));
controlNodeStack.push(controlStart.get());
(llvm::dyn_cast<ControlNode>)(controlNodeStack.top())
->processControlEnter();
inputGraph->addInputElement(std::move(controlStart));
break;
}
case OPT_end_group:
(llvm::dyn_cast<ControlNode>)(controlNodeStack.top())
->processControlExit();
controlNodeStack.pop();
break;
case OPT_INPUT:
case OPT_l: {
std::unique_ptr<InputElement> inputFile(new ELFFileNode(
*ctx, inputArg->getValue(), searchPath, index++, isWholeArchive,
asNeeded, inputArg->getOption().getID() == OPT_l));
if (controlNodeStack.empty())
inputGraph->addInputElement(std::move(inputFile));
else
(llvm::dyn_cast<ControlNode>)(controlNodeStack.top())
->processInputElement(std::move(inputFile));
break;
}
case OPT_rpath: {
SmallVector<StringRef, 2> rpaths;
StringRef(inputArg->getValue()).split(rpaths, ":");
for (auto path : rpaths)
ctx->addRpath(path);
break;
}
case OPT_rpath_link: {
SmallVector<StringRef, 2> rpaths;
StringRef(inputArg->getValue()).split(rpaths, ":");
for (auto path : rpaths)
ctx->addRpathLink(path);
break;
}
case OPT_sysroot:
ctx->setSysroot(inputArg->getValue());
break;
case OPT_soname:
ctx->setSharedObjectName(inputArg->getValue());
break;
default:
break;
} // end switch on option ID
} // end for
if (!inputGraph->size()) {
diagnostics << "No input files\n";
return false;
}
// Set default output file name if the output file was not
// specified.
if (!_outputOptionSet) {
switch (ctx->outputFileType()) {
case LinkingContext::OutputFileType::YAML:
ctx->setOutputPath("-");
break;
case LinkingContext::OutputFileType::Native:
ctx->setOutputPath("a.native");
break;
default:
ctx->setOutputPath("a.out");
break;
}
}
if (ctx->outputFileType() == LinkingContext::OutputFileType::YAML)
inputGraph->dump(diagnostics);
// Validate the combination of options used.
if (!ctx->validate(diagnostics))
return false;
ctx->setInputGraph(std::move(inputGraph));
context.swap(ctx);
return true;
}
/// Get the default target triple based on either the program name
/// (e.g. "x86-ibm-linux-lld") or the primary target llvm was configured for.
llvm::Triple GnuLdDriver::getDefaultTarget(const char *progName) {
SmallVector<StringRef, 4> components;
llvm::SplitString(llvm::sys::path::stem(progName), components, "-");
// If has enough parts to be start with a triple.
if (components.size() >= 4) {
llvm::Triple triple(components[0], components[1], components[2],
components[3]);
// If first component looks like an arch.
if (triple.getArch() != llvm::Triple::UnknownArch)
return triple;
}
// Fallback to use whatever default triple llvm was configured for.
return llvm::Triple(llvm::sys::getDefaultTargetTriple());
}
<|endoftext|>
|
<commit_before>//===--- GenClangType.cpp - Swift IR Generation For Types -----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements generation of Clang AST types from Swift AST types
// for types that are representable in Objective-C interfaces.
//
//===----------------------------------------------------------------------===//
#include "GenClangType.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/Type.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CanonicalType.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Type.h"
using namespace swift;
using namespace irgen;
static Type getNamedSwiftType(DeclContext *DC, StringRef name) {
assert(DC && "Unexpected null declaration context!");
auto &astContext = DC->getASTContext();
UnqualifiedLookup lookup(astContext.getIdentifier(name), DC, nullptr);
if (auto type = lookup.getSingleTypeResult())
return type->getDeclaredType();
return Type();
}
static const clang::CanQualType getClangBuiltinTypeFromKind(
const clang::ASTContext &context,
clang::BuiltinType::Kind kind) {
switch (kind) {
#define BUILTIN_TYPE(Id, SingletonId) \
case clang::BuiltinType::Id: return context.SingletonId;
#include "clang/AST/BuiltinTypes.def"
}
}
static clang::CanQualType getClangSelectorType(
const clang::ASTContext &clangCtx) {
return clangCtx.getPointerType(clangCtx.ObjCBuiltinSelTy);
}
static clang::CanQualType getClangIdType(
const clang::ASTContext &clangCtx) {
clang::QualType clangType =
clangCtx.getObjCObjectType(clangCtx.ObjCBuiltinIdTy, 0, 0);
clangType = clangCtx.getObjCObjectPointerType(clangType);
return clangCtx.getCanonicalType(clangType);
}
clang::CanQualType GenClangType::visitStructType(CanStructType type) {
// First attempt a lookup in our map of imported structs.
auto *decl = type->getDecl();
if (auto *clangDecl = decl->getClangDecl()) {
auto *typeDecl = cast<clang::TypeDecl>(clangDecl);
return typeDecl->getTypeForDecl()->getCanonicalTypeUnqualified();
}
auto const &clangCtx = getClangASTContext();
#define MAP_BUILTIN_TYPE(CLANG_BUILTIN_KIND, SWIFT_TYPE_NAME) { \
auto lookupTy = getNamedSwiftType(decl->getDeclContext(), \
#SWIFT_TYPE_NAME); \
if (lookupTy && lookupTy->isEqual(type)) \
return getClangBuiltinTypeFromKind(clangCtx, \
clang::BuiltinType::CLANG_BUILTIN_KIND); \
}
#include "swift/ClangImporter/BuiltinMappedTypes.def"
#undef MAP_BUILTIN_TYPE
// Handle other imported types.
#define CHECK_CLANG_TYPE_MATCH(TYPE, NAME, RESULT) \
if (auto lookupTy = getNamedSwiftType((TYPE)->getDecl()->getDeclContext(), \
(NAME))) \
if (lookupTy->isEqual(type)) \
return (RESULT);
CHECK_CLANG_TYPE_MATCH(type, "COpaquePointer", clangCtx.VoidPtrTy);
CHECK_CLANG_TYPE_MATCH(type, "ObjCBool", clangCtx.ObjCBuiltinBoolTy);
// FIXME: This is sufficient for ABI type generation, but should
// probably be const char* for type encoding.
CHECK_CLANG_TYPE_MATCH(type, "CString", clangCtx.VoidPtrTy);
CHECK_CLANG_TYPE_MATCH(type, "Selector", getClangSelectorType(clangCtx));
#undef CHECK_CLANG_TYPE_MATCH
// FIXME: Handle other structs resulting from imported non-struct Clang types.
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitTupleType(CanTupleType type) {
if (type->getNumElements() == 0)
return getClangASTContext().VoidTy;
llvm_unreachable("Unexpected tuple type in Clang type generation!");
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitProtocolType(CanProtocolType type) {
if (auto lookupTy = getNamedSwiftType(type->getDecl()->getDeclContext(),
"DynamicLookup"))
if (lookupTy->isEqual(type))
return getClangIdType(getClangASTContext());
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitMetatypeType(CanMetatypeType type) {
auto const &clangCtx = getClangASTContext();
clang::QualType clangType =
clangCtx.getObjCObjectType(clangCtx.ObjCBuiltinClassTy, 0, 0);
clangType = clangCtx.getObjCObjectPointerType(clangType);
return clangCtx.getCanonicalType(clangType);
}
clang::CanQualType GenClangType::visitClassType(CanClassType type) {
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitBoundGenericStructType(
CanBoundGenericStructType type) {
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitEnumType(CanEnumType type) {
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitFunctionType(CanFunctionType type) {
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitProtocolCompositionType(
CanProtocolCompositionType type) {
// Any protocol composition type in Swift that shows up in an @objc
// method maps 1-1 to "id <SomeProto>"; with clang's encoding
// ignoring the protocol list.
return getClangIdType(getClangASTContext());
}
clang::CanQualType GenClangType::visitType(CanType type) {
llvm_unreachable("Unhandled type in Clang type generation.");
return clang::CanQualType();
}
const clang::ASTContext &GenClangType::getClangASTContext() const {
auto *CI = static_cast<ClangImporter*>(&*Context.getClangModuleLoader());
return CI->getClangASTContext();
}
<commit_msg>Generate the same Clang type for all protocol types.<commit_after>//===--- GenClangType.cpp - Swift IR Generation For Types -----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements generation of Clang AST types from Swift AST types
// for types that are representable in Objective-C interfaces.
//
//===----------------------------------------------------------------------===//
#include "GenClangType.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/Type.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CanonicalType.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Type.h"
using namespace swift;
using namespace irgen;
static Type getNamedSwiftType(DeclContext *DC, StringRef name) {
assert(DC && "Unexpected null declaration context!");
auto &astContext = DC->getASTContext();
UnqualifiedLookup lookup(astContext.getIdentifier(name), DC, nullptr);
if (auto type = lookup.getSingleTypeResult())
return type->getDeclaredType();
return Type();
}
static const clang::CanQualType getClangBuiltinTypeFromKind(
const clang::ASTContext &context,
clang::BuiltinType::Kind kind) {
switch (kind) {
#define BUILTIN_TYPE(Id, SingletonId) \
case clang::BuiltinType::Id: return context.SingletonId;
#include "clang/AST/BuiltinTypes.def"
}
}
static clang::CanQualType getClangSelectorType(
const clang::ASTContext &clangCtx) {
return clangCtx.getPointerType(clangCtx.ObjCBuiltinSelTy);
}
static clang::CanQualType getClangIdType(
const clang::ASTContext &clangCtx) {
clang::QualType clangType =
clangCtx.getObjCObjectType(clangCtx.ObjCBuiltinIdTy, 0, 0);
clangType = clangCtx.getObjCObjectPointerType(clangType);
return clangCtx.getCanonicalType(clangType);
}
clang::CanQualType GenClangType::visitStructType(CanStructType type) {
// First attempt a lookup in our map of imported structs.
auto *decl = type->getDecl();
if (auto *clangDecl = decl->getClangDecl()) {
auto *typeDecl = cast<clang::TypeDecl>(clangDecl);
return typeDecl->getTypeForDecl()->getCanonicalTypeUnqualified();
}
auto const &clangCtx = getClangASTContext();
#define MAP_BUILTIN_TYPE(CLANG_BUILTIN_KIND, SWIFT_TYPE_NAME) { \
auto lookupTy = getNamedSwiftType(decl->getDeclContext(), \
#SWIFT_TYPE_NAME); \
if (lookupTy && lookupTy->isEqual(type)) \
return getClangBuiltinTypeFromKind(clangCtx, \
clang::BuiltinType::CLANG_BUILTIN_KIND); \
}
#include "swift/ClangImporter/BuiltinMappedTypes.def"
#undef MAP_BUILTIN_TYPE
// Handle other imported types.
#define CHECK_CLANG_TYPE_MATCH(TYPE, NAME, RESULT) \
if (auto lookupTy = getNamedSwiftType((TYPE)->getDecl()->getDeclContext(), \
(NAME))) \
if (lookupTy->isEqual(type)) \
return (RESULT);
CHECK_CLANG_TYPE_MATCH(type, "COpaquePointer", clangCtx.VoidPtrTy);
CHECK_CLANG_TYPE_MATCH(type, "ObjCBool", clangCtx.ObjCBuiltinBoolTy);
// FIXME: This is sufficient for ABI type generation, but should
// probably be const char* for type encoding.
CHECK_CLANG_TYPE_MATCH(type, "CString", clangCtx.VoidPtrTy);
CHECK_CLANG_TYPE_MATCH(type, "Selector", getClangSelectorType(clangCtx));
#undef CHECK_CLANG_TYPE_MATCH
// FIXME: Handle other structs resulting from imported non-struct Clang types.
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitTupleType(CanTupleType type) {
if (type->getNumElements() == 0)
return getClangASTContext().VoidTy;
llvm_unreachable("Unexpected tuple type in Clang type generation!");
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitProtocolType(CanProtocolType type) {
return getClangIdType(getClangASTContext());
}
clang::CanQualType GenClangType::visitMetatypeType(CanMetatypeType type) {
auto const &clangCtx = getClangASTContext();
clang::QualType clangType =
clangCtx.getObjCObjectType(clangCtx.ObjCBuiltinClassTy, 0, 0);
clangType = clangCtx.getObjCObjectPointerType(clangType);
return clangCtx.getCanonicalType(clangType);
}
clang::CanQualType GenClangType::visitClassType(CanClassType type) {
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitBoundGenericStructType(
CanBoundGenericStructType type) {
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitEnumType(CanEnumType type) {
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitFunctionType(CanFunctionType type) {
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitProtocolCompositionType(
CanProtocolCompositionType type) {
// Any protocol composition type in Swift that shows up in an @objc
// method maps 1-1 to "id <SomeProto>"; with clang's encoding
// ignoring the protocol list.
return getClangIdType(getClangASTContext());
}
clang::CanQualType GenClangType::visitType(CanType type) {
llvm_unreachable("Unhandled type in Clang type generation.");
return clang::CanQualType();
}
const clang::ASTContext &GenClangType::getClangASTContext() const {
auto *CI = static_cast<ClangImporter*>(&*Context.getClangModuleLoader());
return CI->getClangASTContext();
}
<|endoftext|>
|
<commit_before>//===--- GenClangType.cpp - Swift IR Generation For Types -----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements generation of Clang AST types from Swift AST types
// for types that are representable in Objective-C interfaces.
//
//===----------------------------------------------------------------------===//
#include "GenClangType.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/Type.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CanonicalType.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Type.h"
using namespace swift;
using namespace irgen;
static Type getNamedSwiftType(DeclContext *DC, StringRef name) {
assert(DC && "Unexpected null declaration context!");
auto &astContext = DC->getASTContext();
UnqualifiedLookup lookup(astContext.getIdentifier(name), DC, nullptr);
if (auto type = lookup.getSingleTypeResult())
return type->getDeclaredType();
return Type();
}
static const clang::CanQualType getClangBuiltinTypeFromKind(
const clang::ASTContext &context,
clang::BuiltinType::Kind kind) {
switch (kind) {
#define BUILTIN_TYPE(Id, SingletonId) \
case clang::BuiltinType::Id: return context.SingletonId;
#include "clang/AST/BuiltinTypes.def"
}
}
static clang::CanQualType getClangSelectorType(
const clang::ASTContext &clangCtx) {
return clangCtx.getPointerType(clangCtx.ObjCBuiltinSelTy);
}
static clang::CanQualType getClangMetatypeType(
const clang::ASTContext &clangCtx) {
clang::QualType clangType =
clangCtx.getObjCObjectType(clangCtx.ObjCBuiltinClassTy, 0, 0);
clangType = clangCtx.getObjCObjectPointerType(clangType);
return clangCtx.getCanonicalType(clangType);
}
static clang::CanQualType getClangIdType(
const clang::ASTContext &clangCtx) {
clang::QualType clangType =
clangCtx.getObjCObjectType(clangCtx.ObjCBuiltinIdTy, 0, 0);
clangType = clangCtx.getObjCObjectPointerType(clangType);
return clangCtx.getCanonicalType(clangType);
}
clang::CanQualType GenClangType::visitStructType(CanStructType type) {
// First attempt a lookup in our map of imported structs.
auto *decl = type->getDecl();
if (auto *clangDecl = decl->getClangDecl()) {
auto *typeDecl = cast<clang::TypeDecl>(clangDecl);
return typeDecl->getTypeForDecl()->getCanonicalTypeUnqualified();
}
auto const &clangCtx = getClangASTContext();
#define MAP_BUILTIN_TYPE(CLANG_BUILTIN_KIND, SWIFT_TYPE_NAME) { \
auto lookupTy = getNamedSwiftType(decl->getDeclContext(), \
#SWIFT_TYPE_NAME); \
if (lookupTy && lookupTy->isEqual(type)) \
return getClangBuiltinTypeFromKind(clangCtx, \
clang::BuiltinType::CLANG_BUILTIN_KIND); \
}
#include "swift/ClangImporter/BuiltinMappedTypes.def"
#undef MAP_BUILTIN_TYPE
// Handle other imported types.
#define CHECK_CLANG_TYPE_MATCH(TYPE, NAME, RESULT) \
if (auto lookupTy = getNamedSwiftType((TYPE)->getDecl()->getDeclContext(), \
(NAME))) \
if (lookupTy->isEqual(type)) \
return (RESULT);
CHECK_CLANG_TYPE_MATCH(type, "COpaquePointer", clangCtx.VoidPtrTy);
CHECK_CLANG_TYPE_MATCH(type, "ObjCBool", clangCtx.ObjCBuiltinBoolTy);
// FIXME: This is sufficient for ABI type generation, but should
// probably be const char* for type encoding.
CHECK_CLANG_TYPE_MATCH(type, "CString", clangCtx.VoidPtrTy);
CHECK_CLANG_TYPE_MATCH(type, "Selector", getClangSelectorType(clangCtx));
#undef CHECK_CLANG_TYPE_MATCH
// FIXME: Handle other structs resulting from imported non-struct Clang types.
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitTupleType(CanTupleType type) {
if (type->getNumElements() == 0)
return getClangASTContext().VoidTy;
llvm_unreachable("Unexpected tuple type in Clang type generation!");
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitProtocolType(CanProtocolType type) {
return getClangIdType(getClangASTContext());
}
clang::CanQualType GenClangType::visitMetatypeType(CanMetatypeType type) {
return getClangMetatypeType(getClangASTContext());
}
clang::CanQualType GenClangType::visitClassType(CanClassType type) {
// Any @objc class type in Swift that shows up in an @objc method maps 1-1 to
// "id <SomeProto>"; with clang's encoding ignoring the protocol list.
return getClangIdType(getClangASTContext());
}
clang::CanQualType GenClangType::visitBoundGenericStructType(
CanBoundGenericStructType type) {
// We only expect UnsafePointer<T>.
auto swiftStructDecl = type->getDecl();
assert(swiftStructDecl->getName().str() == "UnsafePointer" &&
"Unexpected bound generic struct in imported Clang module!");
(void) swiftStructDecl;
auto args = type->getGenericArgs();
assert(args.size() == 1 &&
"UnsafePointer<> should have a single generic argument!");
// Convert the bound type to the appropriate clang type and return a
// pointer to that type.
auto clangCanTy = visit(args.front()->getCanonicalType());
return getClangASTContext().getPointerType(clangCanTy);
}
clang::CanQualType GenClangType::visitEnumType(CanEnumType type) {
// Typedef enums have a Clang Decl available.
auto *decl = type->getDecl();
if (auto *clangDecl = decl->getClangDecl()) {
auto *typeDecl = cast<clang::TypeDecl>(clangDecl);
return typeDecl->getTypeForDecl()->getCanonicalTypeUnqualified();
}
// Plain enums just have the raw type set.
assert(!decl->getRawType() &&
"Expected raw type for Clang-imported enum!");
return visit(decl->getRawType()->getCanonicalType());
}
clang::CanQualType GenClangType::visitFunctionType(CanFunctionType type) {
// FIXME: We hit this building Foundation, with a call on the type
// encoding path.
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitProtocolCompositionType(
CanProtocolCompositionType type) {
// Any protocol composition type in Swift that shows up in an @objc
// method maps 1-1 to "id <SomeProto>"; with clang's encoding
// ignoring the protocol list.
return getClangIdType(getClangASTContext());
}
clang::CanQualType GenClangType::visitBuiltinRawPointerType(
CanBuiltinRawPointerType type) {
return getClangASTContext().VoidPtrTy;
}
clang::CanQualType GenClangType::visitBuiltinObjCPointerType(
CanBuiltinObjCPointerType type) {
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitArchetypeType(CanArchetypeType type) {
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitSILFunctionType(CanSILFunctionType type) {
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitDynamicSelfType(CanDynamicSelfType type) {
// DynamicSelf is equivalent to 'instancetype', which is treated as
// 'id' within the Objective-C type system.
return getClangIdType(getClangASTContext());
}
// FIXME: We should not be seeing these by the time we generate Clang types.
clang::CanQualType GenClangType::visitGenericTypeParamType(
CanGenericTypeParamType type) {
return clang::CanQualType();
}
clang::CanQualType GenClangType::visitType(CanType type) {
llvm_unreachable("Unexpected type in Clang type generation.");
return clang::CanQualType();
}
const clang::ASTContext &GenClangType::getClangASTContext() const {
auto *CI = static_cast<ClangImporter*>(&*Context.getClangModuleLoader());
return CI->getClangASTContext();
}
<commit_msg>Add getUnhandledType() in Clang type generation.<commit_after>//===--- GenClangType.cpp - Swift IR Generation For Types -----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements generation of Clang AST types from Swift AST types
// for types that are representable in Objective-C interfaces.
//
//===----------------------------------------------------------------------===//
#include "GenClangType.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/Type.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CanonicalType.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Type.h"
using namespace swift;
using namespace irgen;
static Type getNamedSwiftType(DeclContext *DC, StringRef name) {
assert(DC && "Unexpected null declaration context!");
auto &astContext = DC->getASTContext();
UnqualifiedLookup lookup(astContext.getIdentifier(name), DC, nullptr);
if (auto type = lookup.getSingleTypeResult())
return type->getDeclaredType();
return Type();
}
static const clang::CanQualType getClangBuiltinTypeFromKind(
const clang::ASTContext &context,
clang::BuiltinType::Kind kind) {
switch (kind) {
#define BUILTIN_TYPE(Id, SingletonId) \
case clang::BuiltinType::Id: return context.SingletonId;
#include "clang/AST/BuiltinTypes.def"
}
}
static clang::CanQualType getUnhandledType() {
return clang::CanQualType();
}
static clang::CanQualType getClangSelectorType(
const clang::ASTContext &clangCtx) {
return clangCtx.getPointerType(clangCtx.ObjCBuiltinSelTy);
}
static clang::CanQualType getClangMetatypeType(
const clang::ASTContext &clangCtx) {
clang::QualType clangType =
clangCtx.getObjCObjectType(clangCtx.ObjCBuiltinClassTy, 0, 0);
clangType = clangCtx.getObjCObjectPointerType(clangType);
return clangCtx.getCanonicalType(clangType);
}
static clang::CanQualType getClangIdType(
const clang::ASTContext &clangCtx) {
clang::QualType clangType =
clangCtx.getObjCObjectType(clangCtx.ObjCBuiltinIdTy, 0, 0);
clangType = clangCtx.getObjCObjectPointerType(clangType);
return clangCtx.getCanonicalType(clangType);
}
clang::CanQualType GenClangType::visitStructType(CanStructType type) {
// First attempt a lookup in our map of imported structs.
auto *decl = type->getDecl();
if (auto *clangDecl = decl->getClangDecl()) {
auto *typeDecl = cast<clang::TypeDecl>(clangDecl);
return typeDecl->getTypeForDecl()->getCanonicalTypeUnqualified();
}
auto const &clangCtx = getClangASTContext();
#define MAP_BUILTIN_TYPE(CLANG_BUILTIN_KIND, SWIFT_TYPE_NAME) { \
auto lookupTy = getNamedSwiftType(decl->getDeclContext(), \
#SWIFT_TYPE_NAME); \
if (lookupTy && lookupTy->isEqual(type)) \
return getClangBuiltinTypeFromKind(clangCtx, \
clang::BuiltinType::CLANG_BUILTIN_KIND); \
}
#include "swift/ClangImporter/BuiltinMappedTypes.def"
#undef MAP_BUILTIN_TYPE
// Handle other imported types.
#define CHECK_CLANG_TYPE_MATCH(TYPE, NAME, RESULT) \
if (auto lookupTy = getNamedSwiftType((TYPE)->getDecl()->getDeclContext(), \
(NAME))) \
if (lookupTy->isEqual(type)) \
return (RESULT);
CHECK_CLANG_TYPE_MATCH(type, "COpaquePointer", clangCtx.VoidPtrTy);
CHECK_CLANG_TYPE_MATCH(type, "ObjCBool", clangCtx.ObjCBuiltinBoolTy);
// FIXME: This is sufficient for ABI type generation, but should
// probably be const char* for type encoding.
CHECK_CLANG_TYPE_MATCH(type, "CString", clangCtx.VoidPtrTy);
CHECK_CLANG_TYPE_MATCH(type, "Selector", getClangSelectorType(clangCtx));
#undef CHECK_CLANG_TYPE_MATCH
// FIXME: Handle other structs resulting from imported non-struct Clang types.
return getUnhandledType();
}
clang::CanQualType GenClangType::visitTupleType(CanTupleType type) {
if (type->getNumElements() == 0)
return getClangASTContext().VoidTy;
llvm_unreachable("Unexpected tuple type in Clang type generation!");
return getUnhandledType();
}
clang::CanQualType GenClangType::visitProtocolType(CanProtocolType type) {
return getClangIdType(getClangASTContext());
}
clang::CanQualType GenClangType::visitMetatypeType(CanMetatypeType type) {
return getClangMetatypeType(getClangASTContext());
}
clang::CanQualType GenClangType::visitClassType(CanClassType type) {
// Any @objc class type in Swift that shows up in an @objc method maps 1-1 to
// "id <SomeProto>"; with clang's encoding ignoring the protocol list.
return getClangIdType(getClangASTContext());
}
clang::CanQualType GenClangType::visitBoundGenericStructType(
CanBoundGenericStructType type) {
// We only expect UnsafePointer<T>.
auto swiftStructDecl = type->getDecl();
assert(swiftStructDecl->getName().str() == "UnsafePointer" &&
"Unexpected bound generic struct in imported Clang module!");
(void) swiftStructDecl;
auto args = type->getGenericArgs();
assert(args.size() == 1 &&
"UnsafePointer<> should have a single generic argument!");
// Convert the bound type to the appropriate clang type and return a
// pointer to that type.
auto clangCanTy = visit(args.front()->getCanonicalType());
return getClangASTContext().getPointerType(clangCanTy);
}
clang::CanQualType GenClangType::visitEnumType(CanEnumType type) {
// Typedef enums have a Clang Decl available.
auto *decl = type->getDecl();
if (auto *clangDecl = decl->getClangDecl()) {
auto *typeDecl = cast<clang::TypeDecl>(clangDecl);
return typeDecl->getTypeForDecl()->getCanonicalTypeUnqualified();
}
// Plain enums just have the raw type set.
assert(!decl->getRawType() &&
"Expected raw type for Clang-imported enum!");
return visit(decl->getRawType()->getCanonicalType());
}
clang::CanQualType GenClangType::visitFunctionType(CanFunctionType type) {
// FIXME: We hit this building Foundation, with a call on the type
// encoding path.
return getUnhandledType();
}
clang::CanQualType GenClangType::visitProtocolCompositionType(
CanProtocolCompositionType type) {
// Any protocol composition type in Swift that shows up in an @objc
// method maps 1-1 to "id <SomeProto>"; with clang's encoding
// ignoring the protocol list.
return getClangIdType(getClangASTContext());
}
clang::CanQualType GenClangType::visitBuiltinRawPointerType(
CanBuiltinRawPointerType type) {
return getClangASTContext().VoidPtrTy;
}
clang::CanQualType GenClangType::visitBuiltinObjCPointerType(
CanBuiltinObjCPointerType type) {
return getUnhandledType();
}
clang::CanQualType GenClangType::visitArchetypeType(CanArchetypeType type) {
return getUnhandledType();
}
clang::CanQualType GenClangType::visitSILFunctionType(CanSILFunctionType type) {
return getUnhandledType();
}
clang::CanQualType GenClangType::visitDynamicSelfType(CanDynamicSelfType type) {
// DynamicSelf is equivalent to 'instancetype', which is treated as
// 'id' within the Objective-C type system.
return getClangIdType(getClangASTContext());
}
// FIXME: We should not be seeing these by the time we generate Clang types.
clang::CanQualType GenClangType::visitGenericTypeParamType(
CanGenericTypeParamType type) {
return getUnhandledType();
}
clang::CanQualType GenClangType::visitType(CanType type) {
llvm_unreachable("Unexpected type in Clang type generation.");
return getUnhandledType();
}
const clang::ASTContext &GenClangType::getClangASTContext() const {
auto *CI = static_cast<ClangImporter*>(&*Context.getClangModuleLoader());
return CI->getClangASTContext();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2016 DeNA Co., Ltd., Kazuho Oku
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <cassert>
#include <cstdlib>
#include <vector>
#include <zlib.h>
#include "h2o.h"
#include "encode.h"
namespace {
class brotli_context : public h2o_compress_context_t {
protected:
brotli::BrotliCompressor *brotli_;
brotli::BrotliParams params_;
std::vector<h2o_iovec_t> bufs_; // all bufs_[nnn].base must be free(3)ed
public:
brotli_context() : brotli_(NULL) {
name = h2o_iovec_init(H2O_STRLIT("br"));
compress = _compress;
}
~brotli_context() {
_clear_bufs();
delete brotli_;
}
static void dispose(void *_self) {
brotli_context *self = static_cast<brotli_context *>(_self);
self->~brotli_context();
}
private:
void _clear_bufs();
void _duplicate_last_buf();
void _compress_block(const void *src, size_t len, bool is_last, bool force_flush);
void _compress(h2o_iovec_t *inbufs, size_t inbufcnt, int is_final, h2o_iovec_t **outbufs, size_t *outbufcnt);
static void _compress(h2o_compress_context_t *self, h2o_iovec_t *inbufs, size_t inbufcnt, int is_final,
h2o_iovec_t **outbufs, size_t *outbufcnt) {
static_cast<brotli_context*>(self)->_compress(inbufs, inbufcnt, is_final, outbufs, outbufcnt);
}
};
}
void brotli_context::_clear_bufs()
{
for (std::vector<h2o_iovec_t>::iterator i = bufs_.begin(); i != bufs_.end(); ++i)
free(i->base);
bufs_.clear();
}
void brotli_context::_compress_block(const void *src, size_t len, bool is_last, bool force_flush)
{
uint8_t *output;
size_t out_size;
brotli_->CopyInputToRingBuffer(len, static_cast<const uint8_t *>(src));
bool ret = brotli_->WriteBrotliData(is_last, force_flush, &out_size, &output);
assert(ret);
if (out_size != 0)
bufs_.push_back(h2o_strdup(NULL, reinterpret_cast<const char *>(output), out_size));
}
void brotli_context::_compress(h2o_iovec_t *inbufs, size_t inbufcnt, int is_final, h2o_iovec_t **outbufs, size_t *outbufcnt)
{
if (brotli_ == NULL)
brotli_ = new brotli::BrotliCompressor(params_);
_clear_bufs();
if (inbufcnt != 0) {
size_t max_block_size = brotli_->input_block_size();
for (size_t inbufindex = 0; inbufindex != inbufcnt; ++inbufindex) {
for (size_t offset = 0; offset != inbufs[inbufindex].len;) {
size_t block_size = std::min(inbufs[inbufindex].len - offset, max_block_size);
bool is_last = inbufindex == inbufcnt - 1 && offset + block_size == inbufs[inbufindex].len;
_compress_block(inbufs[inbufindex].base + offset, block_size, is_last && is_final, is_last && !is_final);
offset += block_size;
}
}
} else {
if (is_final)
_compress_block("", 0, true, false);
}
if (is_final) {
delete brotli_;
brotli_ = NULL;
}
*outbufs = &bufs_.front();
*outbufcnt = bufs_.size();
}
h2o_compress_context_t *h2o_compress_brotli_open(h2o_mem_pool_t *pool)
{
brotli_context *ctx = static_cast<brotli_context *>(h2o_mem_alloc_shared(pool, sizeof(*ctx), brotli_context::dispose));
return new (ctx) brotli_context();
}
<commit_msg>encode as much as possible at once<commit_after>/*
* Copyright (c) 2016 DeNA Co., Ltd., Kazuho Oku
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <cassert>
#include <cstdlib>
#include <vector>
#include <zlib.h>
#include "h2o.h"
#include "encode.h"
namespace {
class brotli_context : public h2o_compress_context_t {
protected:
brotli::BrotliCompressor *brotli_;
brotli::BrotliParams params_;
std::vector<h2o_iovec_t> bufs_; // all bufs_[nnn].base must be free(3)ed
public:
brotli_context() : brotli_(NULL) {
name = h2o_iovec_init(H2O_STRLIT("br"));
compress = _compress;
}
~brotli_context() {
_clear_bufs();
delete brotli_;
}
static void dispose(void *_self) {
brotli_context *self = static_cast<brotli_context *>(_self);
self->~brotli_context();
}
private:
void _clear_bufs();
void _emit(bool is_last, bool force_flush);
void _compress(h2o_iovec_t *inbufs, size_t inbufcnt, int is_final, h2o_iovec_t **outbufs, size_t *outbufcnt);
static void _compress(h2o_compress_context_t *self, h2o_iovec_t *inbufs, size_t inbufcnt, int is_final,
h2o_iovec_t **outbufs, size_t *outbufcnt) {
static_cast<brotli_context*>(self)->_compress(inbufs, inbufcnt, is_final, outbufs, outbufcnt);
}
};
}
void brotli_context::_clear_bufs()
{
for (std::vector<h2o_iovec_t>::iterator i = bufs_.begin(); i != bufs_.end(); ++i)
free(i->base);
bufs_.clear();
}
void brotli_context::_emit(bool is_last, bool force_flush)
{
uint8_t *output;
size_t out_size;
bool ret = brotli_->WriteBrotliData(is_last, force_flush, &out_size, &output);
assert(ret);
if (out_size != 0)
bufs_.push_back(h2o_strdup(NULL, reinterpret_cast<const char *>(output), out_size));
}
void brotli_context::_compress(h2o_iovec_t *inbufs, size_t inbufcnt, int is_final, h2o_iovec_t **outbufs, size_t *outbufcnt)
{
if (brotli_ == NULL)
brotli_ = new brotli::BrotliCompressor(params_);
_clear_bufs();
if (inbufcnt != 0) {
size_t inbufindex = 0, offset = 0, block_space = brotli_->input_block_size();
while (inbufindex != inbufcnt) {
size_t copy_len = std::min(block_space, inbufs[inbufindex].len - offset);
brotli_->CopyInputToRingBuffer(copy_len, reinterpret_cast<const uint8_t *>(inbufs[inbufindex].base) + offset);
offset += copy_len;
if (inbufs[inbufindex].len == offset)
if (++inbufindex == inbufcnt)
break;
if (block_space == 0) {
_emit(false, false);
block_space = brotli_->input_block_size();
}
}
_emit(is_final, !is_final);
} else {
if (is_final)
_emit(true, false);
}
if (is_final) {
delete brotli_;
brotli_ = NULL;
}
*outbufs = &bufs_.front();
*outbufcnt = bufs_.size();
}
h2o_compress_context_t *h2o_compress_brotli_open(h2o_mem_pool_t *pool)
{
brotli_context *ctx = static_cast<brotli_context *>(h2o_mem_alloc_shared(pool, sizeof(*ctx), brotli_context::dispose));
return new (ctx) brotli_context();
}
<|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 "base/command_line.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "content/test/net/url_request_mock_http_job.h"
using content::BrowserThread;
namespace {
void SetUrlRequestMock(const FilePath& path) {
URLRequestMockHTTPJob::AddUrlHandler(path);
}
}
class PluginTest : public InProcessBrowserTest {
protected:
PluginTest() {}
virtual void SetUpCommandLine(CommandLine* command_line) {
// Some NPAPI tests schedule garbage collection to force object tear-down.
command_line->AppendSwitchASCII(switches::kJavaScriptFlags, "--expose_gc");
// For OpenPopupWindowWithPlugin.
command_line->AppendSwitch(switches::kDisablePopupBlocking);
#if defined(OS_MACOSX)
FilePath plugin_dir;
PathService::Get(base::DIR_MODULE, &plugin_dir);
plugin_dir = plugin_dir.AppendASCII("plugins");
// The plugins directory isn't read by default on the Mac, so it needs to be
// explicitly registered.
command_line->AppendSwitchPath(switches::kExtraPluginDir, plugin_dir);
#endif
}
virtual void SetUpOnMainThread() OVERRIDE {
FilePath path = ui_test_utils::GetTestFilePath(FilePath(), FilePath());
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE, base::Bind(&SetUrlRequestMock, path));
}
void LoadAndWait(const GURL& url, const char* title) {
string16 expected_title(ASCIIToUTF16(title));
ui_test_utils::TitleWatcher title_watcher(
browser()->GetSelectedWebContents(), expected_title);
title_watcher.AlsoWaitForTitle(ASCIIToUTF16("FAIL"));
ui_test_utils::NavigateToURL(browser(), url);
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
GURL GetURL(const char* filename) {
return ui_test_utils::GetTestUrl(
FilePath().AppendASCII("npapi"), FilePath().AppendASCII(filename));
}
void NavigateAway() {
GURL url = ui_test_utils::GetTestUrl(
FilePath(), FilePath().AppendASCII("simple.html"));
LoadAndWait(url, "simple.html");
}
};
// Make sure that navigating away from a plugin referenced by JS doesn't
// crash.
IN_PROC_BROWSER_TEST_F(PluginTest, UnloadNoCrash) {
LoadAndWait(GetURL("layout_test_plugin.html"), "Layout Test Plugin Test");
NavigateAway();
}
// Tests if a plugin executing a self deleting script using NPN_GetURL
// works without crashing or hanging
// Flaky: http://crbug.com/59327
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginGetUrl) {
LoadAndWait(GetURL("self_delete_plugin_geturl.html"), "OK");
}
// Tests if a plugin executing a self deleting script using Invoke
// works without crashing or hanging
// Flaky. See http://crbug.com/30702
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInvoke) {
LoadAndWait(GetURL("self_delete_plugin_invoke.html"), "OK");
}
IN_PROC_BROWSER_TEST_F(PluginTest, NPObjectReleasedOnDestruction) {
ui_test_utils::NavigateToURL(
browser(), GetURL("npobject_released_on_destruction.html"));
NavigateAway();
}
// Test that a dialog is properly created when a plugin throws an
// exception. Should be run for in and out of process plugins, but
// the more interesting case is out of process, where we must route
// the exception to the correct renderer.
IN_PROC_BROWSER_TEST_F(PluginTest, NPObjectSetException) {
LoadAndWait(GetURL("npobject_set_exception.html"), "OK");
}
#if defined(OS_WIN)
// Tests if a plugin executing a self deleting script in the context of
// a synchronous mouseup works correctly.
// This was never ported to Mac. The only thing remaining is to make
// ui_test_utils::SimulateMouseClick get to Mac plugins, currently it doesn't
// work.
IN_PROC_BROWSER_TEST_F(PluginTest,
SelfDeletePluginInvokeInSynchronousMouseUp) {
ui_test_utils::NavigateToURL(
browser(), GetURL("execute_script_delete_in_mouse_up.html"));
string16 expected_title(ASCIIToUTF16("OK"));
ui_test_utils::TitleWatcher title_watcher(
browser()->GetSelectedWebContents(), expected_title);
title_watcher.AlsoWaitForTitle(ASCIIToUTF16("FAIL"));
ui_test_utils::SimulateMouseClick(
browser()->GetSelectedWebContents(), 150, 250);
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
#endif
// Flaky, http://crbug.com/60071.
IN_PROC_BROWSER_TEST_F(PluginTest, GetURLRequest404Response) {
GURL url(URLRequestMockHTTPJob::GetMockUrl(
FilePath().AppendASCII("npapi").
AppendASCII("plugin_url_request_404.html")));
LoadAndWait(url, "OK");
}
// Tests if a plugin executing a self deleting script using Invoke with
// a modal dialog showing works without crashing or hanging
// Disabled, flakily exceeds timeout, http://crbug.com/46257.
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInvokeAlert) {
ui_test_utils::NavigateToURL(
browser(), GetURL("self_delete_plugin_invoke_alert.html"));
string16 expected_title(ASCIIToUTF16("OK"));
ui_test_utils::TitleWatcher title_watcher(
browser()->GetSelectedWebContents(), expected_title);
title_watcher.AlsoWaitForTitle(ASCIIToUTF16("FAIL"));
ui_test_utils::WaitForAppModalDialogAndCloseIt();
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
// Test passing arguments to a plugin.
IN_PROC_BROWSER_TEST_F(PluginTest, Arguments) {
LoadAndWait(GetURL("arguments.html"), "OK");
}
// Test invoking many plugins within a single page.
IN_PROC_BROWSER_TEST_F(PluginTest, ManyPlugins) {
LoadAndWait(GetURL("many_plugins.html"), "OK");
}
// Test various calls to GetURL from a plugin.
IN_PROC_BROWSER_TEST_F(PluginTest, GetURL) {
LoadAndWait(GetURL("geturl.html"), "OK");
}
// Test various calls to GetURL for javascript URLs with
// non NULL targets from a plugin.
IN_PROC_BROWSER_TEST_F(PluginTest, GetJavaScriptURL) {
LoadAndWait(GetURL("get_javascript_url.html"), "OK");
}
// Test that calling GetURL with a javascript URL and target=_self
// works properly when the plugin is embedded in a subframe.
IN_PROC_BROWSER_TEST_F(PluginTest, GetJavaScriptURL2) {
LoadAndWait(GetURL("get_javascript_url2.html"), "OK");
}
// Test is flaky on linux/cros/win builders. http://crbug.com/71904
IN_PROC_BROWSER_TEST_F(PluginTest, GetURLRedirectNotification) {
LoadAndWait(GetURL("geturl_redirect_notify.html"), "OK");
}
// Tests that identity is preserved for NPObjects passed from a plugin
// into JavaScript.
IN_PROC_BROWSER_TEST_F(PluginTest, NPObjectIdentity) {
LoadAndWait(GetURL("npobject_identity.html"), "OK");
}
// Tests that if an NPObject is proxies back to its original process, the
// original pointer is returned and not a proxy. If this fails the plugin
// will crash.
IN_PROC_BROWSER_TEST_F(PluginTest, NPObjectProxy) {
LoadAndWait(GetURL("npobject_proxy.html"), "OK");
}
#if defined(OS_WIN) || defined(OS_MACOSX)
// Tests if a plugin executing a self deleting script in the context of
// a synchronous paint event works correctly
// http://crbug.com/44960
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInvokeInSynchronousPaint) {
LoadAndWait(GetURL("execute_script_delete_in_paint.html"), "OK");
}
#endif
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInNewStream) {
LoadAndWait(GetURL("self_delete_plugin_stream.html"), "OK");
}
// If this test flakes use http://crbug.com/95558.
IN_PROC_BROWSER_TEST_F(PluginTest, DeletePluginInDeallocate) {
LoadAndWait(GetURL("plugin_delete_in_deallocate.html"), "OK");
}
#if defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(PluginTest, VerifyPluginWindowRect) {
LoadAndWait(GetURL("verify_plugin_window_rect.html"), "OK");
}
// Tests that creating a new instance of a plugin while another one is handling
// a paint message doesn't cause deadlock.
IN_PROC_BROWSER_TEST_F(PluginTest, CreateInstanceInPaint) {
LoadAndWait(GetURL("create_instance_in_paint.html"), "OK");
}
// Tests that putting up an alert in response to a paint doesn't deadlock.
IN_PROC_BROWSER_TEST_F(PluginTest, AlertInWindowMessage) {
ui_test_utils::NavigateToURL(
browser(), GetURL("alert_in_window_message.html"));
ui_test_utils::WaitForAppModalDialogAndCloseIt();
ui_test_utils::WaitForAppModalDialogAndCloseIt();
}
IN_PROC_BROWSER_TEST_F(PluginTest, VerifyNPObjectLifetimeTest) {
LoadAndWait(GetURL("npobject_lifetime_test.html"), "OK");
}
// Tests that we don't crash or assert if NPP_New fails
IN_PROC_BROWSER_TEST_F(PluginTest, NewFails) {
LoadAndWait(GetURL("new_fails.html"), "OK");
}
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInNPNEvaluate) {
LoadAndWait(GetURL("execute_script_delete_in_npn_evaluate.html"), "OK");
}
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeleteCreatePluginInNPNEvaluate) {
LoadAndWait(GetURL("npn_plugin_delete_create_in_evaluate.html"), "OK");
}
#endif // OS_WIN
// If this flakes, reopen http://crbug.com/17645
// As of 6 July 2011, this test is flaky on Windows (perhaps due to timing out).
#if !defined(OS_MACOSX)
// Disabled on Mac because the plugin side isn't implemented yet, see
// "TODO(port)" in plugin_javascript_open_popup.cc.
IN_PROC_BROWSER_TEST_F(PluginTest, OpenPopupWindowWithPlugin) {
LoadAndWait(GetURL("get_javascript_open_popup_with_plugin.html"), "OK");
}
#endif
// Test checking the privacy mode is off.
IN_PROC_BROWSER_TEST_F(PluginTest, PrivateDisabled) {
LoadAndWait(GetURL("private.html"), "OK");
}
IN_PROC_BROWSER_TEST_F(PluginTest, ScheduleTimer) {
LoadAndWait(GetURL("schedule_timer.html"), "OK");
}
IN_PROC_BROWSER_TEST_F(PluginTest, PluginThreadAsyncCall) {
LoadAndWait(GetURL("plugin_thread_async_call.html"), "OK");
}
// Test checking the privacy mode is on.
// If this flakes on Linux, use http://crbug.com/104380
IN_PROC_BROWSER_TEST_F(PluginTest, PrivateEnabled) {
LoadAndWait(GetURL("private.html"), "OK");
}
#if defined(OS_WIN) || defined(OS_MACOSX)
// Test a browser hang due to special case of multiple
// plugin instances indulged in sync calls across renderer.
IN_PROC_BROWSER_TEST_F(PluginTest, MultipleInstancesSyncCalls) {
LoadAndWait(GetURL("multiple_instances_sync_calls.html"), "OK");
}
#endif
IN_PROC_BROWSER_TEST_F(PluginTest, GetURLRequestFailWrite) {
GURL url(URLRequestMockHTTPJob::GetMockUrl(
FilePath().AppendASCII("npapi").
AppendASCII("plugin_url_request_fail_write.html")));
LoadAndWait(url, "OK");
}
#if defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(PluginTest, EnsureScriptingWorksInDestroy) {
LoadAndWait(GetURL("ensure_scripting_works_in_destroy.html"), "OK");
}
// This test uses a Windows Event to signal to the plugin that it should crash
// on NP_Initialize.
IN_PROC_BROWSER_TEST_F(PluginTest, NoHangIfInitCrashes) {
HANDLE crash_event = CreateEvent(NULL, TRUE, FALSE, L"TestPluginCrashOnInit");
SetEvent(crash_event);
LoadAndWait(GetURL("no_hang_if_init_crashes.html"), "OK");
CloseHandle(crash_event);
}
#endif
// If this flakes on Mac, use http://crbug.com/111508
IN_PROC_BROWSER_TEST_F(PluginTest, PluginReferrerTest) {
GURL url(URLRequestMockHTTPJob::GetMockUrl(
FilePath().AppendASCII("npapi").
AppendASCII("plugin_url_request_referrer_test.html")));
LoadAndWait(url, "OK");
}
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(PluginTest, PluginConvertPointTest) {
gfx::NativeWindow window = NULL;
gfx::Rect bounds(50, 50, 400, 400);
ui_test_utils::GetNativeWindow(browser(), &window);
ui_test_utils::SetWindowBounds(window, bounds);
ui_test_utils::NavigateToURL(browser(), GetURL("convert_point.html"));
string16 expected_title(ASCIIToUTF16("OK"));
ui_test_utils::TitleWatcher title_watcher(
browser()->GetSelectedWebContents(), expected_title);
title_watcher.AlsoWaitForTitle(ASCIIToUTF16("FAIL"));
// TODO(stuartmorgan): When the automation system supports sending clicks,
// change the test to trigger on mouse-down rather than window focus.
static_cast<content::WebContentsDelegate*>(browser())->
ActivateContents(browser()->GetSelectedWebContents());
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
#endif
<commit_msg>Don't run PluginTest.DeletePluginInDeallocate on mac debug since it asserts<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 "base/command_line.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "content/test/net/url_request_mock_http_job.h"
using content::BrowserThread;
namespace {
void SetUrlRequestMock(const FilePath& path) {
URLRequestMockHTTPJob::AddUrlHandler(path);
}
}
class PluginTest : public InProcessBrowserTest {
protected:
PluginTest() {}
virtual void SetUpCommandLine(CommandLine* command_line) {
// Some NPAPI tests schedule garbage collection to force object tear-down.
command_line->AppendSwitchASCII(switches::kJavaScriptFlags, "--expose_gc");
// For OpenPopupWindowWithPlugin.
command_line->AppendSwitch(switches::kDisablePopupBlocking);
#if defined(OS_MACOSX)
FilePath plugin_dir;
PathService::Get(base::DIR_MODULE, &plugin_dir);
plugin_dir = plugin_dir.AppendASCII("plugins");
// The plugins directory isn't read by default on the Mac, so it needs to be
// explicitly registered.
command_line->AppendSwitchPath(switches::kExtraPluginDir, plugin_dir);
#endif
}
virtual void SetUpOnMainThread() OVERRIDE {
FilePath path = ui_test_utils::GetTestFilePath(FilePath(), FilePath());
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE, base::Bind(&SetUrlRequestMock, path));
}
void LoadAndWait(const GURL& url, const char* title) {
string16 expected_title(ASCIIToUTF16(title));
ui_test_utils::TitleWatcher title_watcher(
browser()->GetSelectedWebContents(), expected_title);
title_watcher.AlsoWaitForTitle(ASCIIToUTF16("FAIL"));
ui_test_utils::NavigateToURL(browser(), url);
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
GURL GetURL(const char* filename) {
return ui_test_utils::GetTestUrl(
FilePath().AppendASCII("npapi"), FilePath().AppendASCII(filename));
}
void NavigateAway() {
GURL url = ui_test_utils::GetTestUrl(
FilePath(), FilePath().AppendASCII("simple.html"));
LoadAndWait(url, "simple.html");
}
};
// Make sure that navigating away from a plugin referenced by JS doesn't
// crash.
IN_PROC_BROWSER_TEST_F(PluginTest, UnloadNoCrash) {
LoadAndWait(GetURL("layout_test_plugin.html"), "Layout Test Plugin Test");
NavigateAway();
}
// Tests if a plugin executing a self deleting script using NPN_GetURL
// works without crashing or hanging
// Flaky: http://crbug.com/59327
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginGetUrl) {
LoadAndWait(GetURL("self_delete_plugin_geturl.html"), "OK");
}
// Tests if a plugin executing a self deleting script using Invoke
// works without crashing or hanging
// Flaky. See http://crbug.com/30702
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInvoke) {
LoadAndWait(GetURL("self_delete_plugin_invoke.html"), "OK");
}
IN_PROC_BROWSER_TEST_F(PluginTest, NPObjectReleasedOnDestruction) {
ui_test_utils::NavigateToURL(
browser(), GetURL("npobject_released_on_destruction.html"));
NavigateAway();
}
// Test that a dialog is properly created when a plugin throws an
// exception. Should be run for in and out of process plugins, but
// the more interesting case is out of process, where we must route
// the exception to the correct renderer.
IN_PROC_BROWSER_TEST_F(PluginTest, NPObjectSetException) {
LoadAndWait(GetURL("npobject_set_exception.html"), "OK");
}
#if defined(OS_WIN)
// Tests if a plugin executing a self deleting script in the context of
// a synchronous mouseup works correctly.
// This was never ported to Mac. The only thing remaining is to make
// ui_test_utils::SimulateMouseClick get to Mac plugins, currently it doesn't
// work.
IN_PROC_BROWSER_TEST_F(PluginTest,
SelfDeletePluginInvokeInSynchronousMouseUp) {
ui_test_utils::NavigateToURL(
browser(), GetURL("execute_script_delete_in_mouse_up.html"));
string16 expected_title(ASCIIToUTF16("OK"));
ui_test_utils::TitleWatcher title_watcher(
browser()->GetSelectedWebContents(), expected_title);
title_watcher.AlsoWaitForTitle(ASCIIToUTF16("FAIL"));
ui_test_utils::SimulateMouseClick(
browser()->GetSelectedWebContents(), 150, 250);
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
#endif
// Flaky, http://crbug.com/60071.
IN_PROC_BROWSER_TEST_F(PluginTest, GetURLRequest404Response) {
GURL url(URLRequestMockHTTPJob::GetMockUrl(
FilePath().AppendASCII("npapi").
AppendASCII("plugin_url_request_404.html")));
LoadAndWait(url, "OK");
}
// Tests if a plugin executing a self deleting script using Invoke with
// a modal dialog showing works without crashing or hanging
// Disabled, flakily exceeds timeout, http://crbug.com/46257.
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInvokeAlert) {
ui_test_utils::NavigateToURL(
browser(), GetURL("self_delete_plugin_invoke_alert.html"));
string16 expected_title(ASCIIToUTF16("OK"));
ui_test_utils::TitleWatcher title_watcher(
browser()->GetSelectedWebContents(), expected_title);
title_watcher.AlsoWaitForTitle(ASCIIToUTF16("FAIL"));
ui_test_utils::WaitForAppModalDialogAndCloseIt();
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
// Test passing arguments to a plugin.
IN_PROC_BROWSER_TEST_F(PluginTest, Arguments) {
LoadAndWait(GetURL("arguments.html"), "OK");
}
// Test invoking many plugins within a single page.
IN_PROC_BROWSER_TEST_F(PluginTest, ManyPlugins) {
LoadAndWait(GetURL("many_plugins.html"), "OK");
}
// Test various calls to GetURL from a plugin.
IN_PROC_BROWSER_TEST_F(PluginTest, GetURL) {
LoadAndWait(GetURL("geturl.html"), "OK");
}
// Test various calls to GetURL for javascript URLs with
// non NULL targets from a plugin.
IN_PROC_BROWSER_TEST_F(PluginTest, GetJavaScriptURL) {
LoadAndWait(GetURL("get_javascript_url.html"), "OK");
}
// Test that calling GetURL with a javascript URL and target=_self
// works properly when the plugin is embedded in a subframe.
IN_PROC_BROWSER_TEST_F(PluginTest, GetJavaScriptURL2) {
LoadAndWait(GetURL("get_javascript_url2.html"), "OK");
}
// Test is flaky on linux/cros/win builders. http://crbug.com/71904
IN_PROC_BROWSER_TEST_F(PluginTest, GetURLRedirectNotification) {
LoadAndWait(GetURL("geturl_redirect_notify.html"), "OK");
}
// Tests that identity is preserved for NPObjects passed from a plugin
// into JavaScript.
IN_PROC_BROWSER_TEST_F(PluginTest, NPObjectIdentity) {
LoadAndWait(GetURL("npobject_identity.html"), "OK");
}
// Tests that if an NPObject is proxies back to its original process, the
// original pointer is returned and not a proxy. If this fails the plugin
// will crash.
IN_PROC_BROWSER_TEST_F(PluginTest, NPObjectProxy) {
LoadAndWait(GetURL("npobject_proxy.html"), "OK");
}
#if defined(OS_WIN) || defined(OS_MACOSX)
// Tests if a plugin executing a self deleting script in the context of
// a synchronous paint event works correctly
// http://crbug.com/44960
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInvokeInSynchronousPaint) {
LoadAndWait(GetURL("execute_script_delete_in_paint.html"), "OK");
}
#endif
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInNewStream) {
LoadAndWait(GetURL("self_delete_plugin_stream.html"), "OK");
}
// This test asserts on Mac in plugin_host in the NPNVWindowNPObject case.
#if !(defined(OS_MACOSX) && !defined(NDEBUG))
// If this test flakes use http://crbug.com/95558.
IN_PROC_BROWSER_TEST_F(PluginTest, DeletePluginInDeallocate) {
LoadAndWait(GetURL("plugin_delete_in_deallocate.html"), "OK");
}
#endif
#if defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(PluginTest, VerifyPluginWindowRect) {
LoadAndWait(GetURL("verify_plugin_window_rect.html"), "OK");
}
// Tests that creating a new instance of a plugin while another one is handling
// a paint message doesn't cause deadlock.
IN_PROC_BROWSER_TEST_F(PluginTest, CreateInstanceInPaint) {
LoadAndWait(GetURL("create_instance_in_paint.html"), "OK");
}
// Tests that putting up an alert in response to a paint doesn't deadlock.
IN_PROC_BROWSER_TEST_F(PluginTest, AlertInWindowMessage) {
ui_test_utils::NavigateToURL(
browser(), GetURL("alert_in_window_message.html"));
ui_test_utils::WaitForAppModalDialogAndCloseIt();
ui_test_utils::WaitForAppModalDialogAndCloseIt();
}
IN_PROC_BROWSER_TEST_F(PluginTest, VerifyNPObjectLifetimeTest) {
LoadAndWait(GetURL("npobject_lifetime_test.html"), "OK");
}
// Tests that we don't crash or assert if NPP_New fails
IN_PROC_BROWSER_TEST_F(PluginTest, NewFails) {
LoadAndWait(GetURL("new_fails.html"), "OK");
}
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInNPNEvaluate) {
LoadAndWait(GetURL("execute_script_delete_in_npn_evaluate.html"), "OK");
}
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeleteCreatePluginInNPNEvaluate) {
LoadAndWait(GetURL("npn_plugin_delete_create_in_evaluate.html"), "OK");
}
#endif // OS_WIN
// If this flakes, reopen http://crbug.com/17645
// As of 6 July 2011, this test is flaky on Windows (perhaps due to timing out).
#if !defined(OS_MACOSX)
// Disabled on Mac because the plugin side isn't implemented yet, see
// "TODO(port)" in plugin_javascript_open_popup.cc.
IN_PROC_BROWSER_TEST_F(PluginTest, OpenPopupWindowWithPlugin) {
LoadAndWait(GetURL("get_javascript_open_popup_with_plugin.html"), "OK");
}
#endif
// Test checking the privacy mode is off.
IN_PROC_BROWSER_TEST_F(PluginTest, PrivateDisabled) {
LoadAndWait(GetURL("private.html"), "OK");
}
IN_PROC_BROWSER_TEST_F(PluginTest, ScheduleTimer) {
LoadAndWait(GetURL("schedule_timer.html"), "OK");
}
IN_PROC_BROWSER_TEST_F(PluginTest, PluginThreadAsyncCall) {
LoadAndWait(GetURL("plugin_thread_async_call.html"), "OK");
}
// Test checking the privacy mode is on.
// If this flakes on Linux, use http://crbug.com/104380
IN_PROC_BROWSER_TEST_F(PluginTest, PrivateEnabled) {
LoadAndWait(GetURL("private.html"), "OK");
}
#if defined(OS_WIN) || defined(OS_MACOSX)
// Test a browser hang due to special case of multiple
// plugin instances indulged in sync calls across renderer.
IN_PROC_BROWSER_TEST_F(PluginTest, MultipleInstancesSyncCalls) {
LoadAndWait(GetURL("multiple_instances_sync_calls.html"), "OK");
}
#endif
IN_PROC_BROWSER_TEST_F(PluginTest, GetURLRequestFailWrite) {
GURL url(URLRequestMockHTTPJob::GetMockUrl(
FilePath().AppendASCII("npapi").
AppendASCII("plugin_url_request_fail_write.html")));
LoadAndWait(url, "OK");
}
#if defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(PluginTest, EnsureScriptingWorksInDestroy) {
LoadAndWait(GetURL("ensure_scripting_works_in_destroy.html"), "OK");
}
// This test uses a Windows Event to signal to the plugin that it should crash
// on NP_Initialize.
IN_PROC_BROWSER_TEST_F(PluginTest, NoHangIfInitCrashes) {
HANDLE crash_event = CreateEvent(NULL, TRUE, FALSE, L"TestPluginCrashOnInit");
SetEvent(crash_event);
LoadAndWait(GetURL("no_hang_if_init_crashes.html"), "OK");
CloseHandle(crash_event);
}
#endif
// If this flakes on Mac, use http://crbug.com/111508
IN_PROC_BROWSER_TEST_F(PluginTest, PluginReferrerTest) {
GURL url(URLRequestMockHTTPJob::GetMockUrl(
FilePath().AppendASCII("npapi").
AppendASCII("plugin_url_request_referrer_test.html")));
LoadAndWait(url, "OK");
}
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(PluginTest, PluginConvertPointTest) {
gfx::NativeWindow window = NULL;
gfx::Rect bounds(50, 50, 400, 400);
ui_test_utils::GetNativeWindow(browser(), &window);
ui_test_utils::SetWindowBounds(window, bounds);
ui_test_utils::NavigateToURL(browser(), GetURL("convert_point.html"));
string16 expected_title(ASCIIToUTF16("OK"));
ui_test_utils::TitleWatcher title_watcher(
browser()->GetSelectedWebContents(), expected_title);
title_watcher.AlsoWaitForTitle(ASCIIToUTF16("FAIL"));
// TODO(stuartmorgan): When the automation system supports sending clicks,
// change the test to trigger on mouse-down rather than window focus.
static_cast<content::WebContentsDelegate*>(browser())->
ActivateContents(browser()->GetSelectedWebContents());
EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
#endif
<|endoftext|>
|
<commit_before><commit_msg>jnitools: fix spelling in error message<commit_after><|endoftext|>
|
<commit_before><commit_msg>fix a bug about degree measure and radian measure.<commit_after><|endoftext|>
|
<commit_before>//-----------------------------------------------------------------------------
#include "socket.h"
//-----------------------------------------------------------------------------
Socket::Socket(unsigned int port)
:status(false)
{
int error = WSAStartup (0x0202, &wsaData); // Fill in WSA info
SOCKADDR_IN addr; // The address structure for a TCP socket
if (error)
exit(1);
//Did we get the right Winsock version?
if (wsaData.wVersion != 0x0202)
{
WSACleanup(); //Clean up Winsock
exit(1);
}
addr.sin_family = AF_INET; // Address family
addr.sin_port = htons (port); // Assign port to this socket
addr.sin_addr.s_addr = htonl (INADDR_ANY);
sockfd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); // Create socket
}
//-----------------------------------------------------------------------------
Socket::~Socket() {
// TODO Auto-generated destructor stub
}
//-----------------------------------------------------------------------------
<commit_msg>Close Socket for windows<commit_after>//-----------------------------------------------------------------------------
#include "socket.h"
//-----------------------------------------------------------------------------
Socket::Socket(unsigned int port)
:status(false)
{
int error = WSAStartup (0x0202, &wsaData); // Fill in WSA info
SOCKADDR_IN addr; // The address structure for a TCP socket
if (error)
exit(1);
//Did we get the right Winsock version?
if (wsaData.wVersion != 0x0202)
{
WSACleanup(); //Clean up Winsock
exit(1);
}
addr.sin_family = AF_INET; // Address family
addr.sin_port = htons (port); // Assign port to this socket
addr.sin_addr.s_addr = htonl (INADDR_ANY);
sockfd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); // Create socket
}
//-----------------------------------------------------------------------------
Socket::~Socket() {
if (sockfd)
closesocket(sockfd);
WSACleanup(); //Clean up Winsock
}
//-----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkDisplacementFieldToBSplineImageFilter.h"
int itkDisplacementFieldToBSplineImageFilterTest( int, char * [] )
{
const unsigned int ImageDimension = 2;
typedef itk::Vector<float, ImageDimension> VectorType;
typedef itk::Image<VectorType, ImageDimension> DisplacementFieldType;
typedef itk::PointSet<VectorType, ImageDimension> PointSetType;
// Create a displacement field
DisplacementFieldType::PointType origin;
DisplacementFieldType::SpacingType spacing;
DisplacementFieldType::SizeType size;
DisplacementFieldType::DirectionType direction;
direction.SetIdentity();
origin.Fill( 0.0 );
spacing.Fill( 0.5 );
size.Fill( 100 );
VectorType ones( 1 );
DisplacementFieldType::Pointer field = DisplacementFieldType::New();
field->SetOrigin( origin );
field->SetSpacing( spacing );
field->SetRegions( size );
field->SetDirection( direction );
field->Allocate();
field->FillBuffer( ones );
typedef itk::DisplacementFieldToBSplineImageFilter
<DisplacementFieldType, PointSetType> BSplineFilterType;
typedef BSplineFilterType::RealImageType RealImageType;
RealImageType::Pointer confidenceImage = RealImageType::New();
confidenceImage->CopyInformation( field );
confidenceImage->SetRegions( size );
confidenceImage->Allocate();
confidenceImage->FillBuffer( 1.0 );
PointSetType::Pointer pointSet = PointSetType::New();
pointSet->Initialize();
// Assign some random points within the b-spline domain
PointSetType::PointType point1;
point1[0] = 23.75;
point1[1] = 5.125;
pointSet->SetPoint( 0, point1 );
pointSet->SetPointData( 0, ones );
PointSetType::PointType point2;
point2[0] = 1.75;
point2[1] = 45.125;
pointSet->SetPoint( 1, point2 );
pointSet->SetPointData( 1, ones );
PointSetType::PointType point3;
point3[0] = 45.75;
point3[1] = 2.125;
pointSet->SetPoint( 2, point3 );
pointSet->SetPointData( 2, ones );
BSplineFilterType::ArrayType numberOfControlPoints;
numberOfControlPoints.Fill( 4 );
BSplineFilterType::Pointer bspliner = BSplineFilterType::New();
bspliner->SetDisplacementField( field );
bspliner->SetConfidenceImage( confidenceImage );
bspliner->SetPointSet( pointSet );
bspliner->SetUseInputFieldToDefineTheBSplineDomain( true );
bspliner->SetNumberOfControlPoints( numberOfControlPoints );
bspliner->SetSplineOrder( 3 );
bspliner->SetNumberOfFittingLevels( 8 );
bspliner->EnforceStationaryBoundaryOff();
bspliner->EnforceStationaryBoundaryOn();
bspliner->SetEnforceStationaryBoundary( false );
bspliner->EstimateInverseOff();
bspliner->EstimateInverseOn();
bspliner->SetEstimateInverse( false );
bspliner->Update();
std::cout << "spline order: " << bspliner->GetSplineOrder() << std::endl;
std::cout << "number of control points: " << bspliner->GetNumberOfControlPoints() << std::endl;
std::cout << "number of fitting levels: " << bspliner->GetNumberOfFittingLevels() << std::endl;
std::cout << "enforce stationary boundary: " << bspliner->GetEnforceStationaryBoundary() << std::endl;
std::cout << "estimate inverse: " << bspliner->GetEstimateInverse() << std::endl;
try
{
bspliner->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception thrown " << std::endl;
std::cerr << excp << std::endl;
}
DisplacementFieldType::IndexType index;
index[0] = 50;
index[1] = 50;
VectorType v = bspliner->GetOutput()->GetPixel( index );
if( vnl_math_abs( v.GetNorm() - 1.414214 ) >= 0.01 )
{
std::cerr << "Failed to find the correct forward displacement vector." << std::endl;
return EXIT_FAILURE;
}
bspliner->SetNumberOfControlPoints( numberOfControlPoints );
bspliner->SetSplineOrder( 3 );
bspliner->SetNumberOfFittingLevels( 5 );
bspliner->EnforceStationaryBoundaryOff();
bspliner->EnforceStationaryBoundaryOn();
bspliner->SetEnforceStationaryBoundary( false );
bspliner->SetEstimateInverse( true );
bspliner->Update();
v = bspliner->GetOutput()->GetPixel( index );
if( vnl_math_abs( v.GetNorm() - 1.414214 ) >= 0.01 )
{
std::cerr << "Failed to find the correct inverse displacement vector." << std::endl;
return EXIT_FAILURE;
}
bspliner->Print( std::cout, 3 );
/** do a second run using only the point set. */
BSplineFilterType::Pointer bspliner2 = BSplineFilterType::New();
bspliner2->SetPointSet( pointSet );
bspliner2->SetUseInputFieldToDefineTheBSplineDomain( false );
bspliner2->SetBSplineDomainFromImage( field );
bspliner2->SetNumberOfControlPoints( numberOfControlPoints );
bspliner2->SetSplineOrder( 3 );
bspliner2->SetNumberOfFittingLevels( 8 );
bspliner2->EnforceStationaryBoundaryOff();
bspliner2->EnforceStationaryBoundaryOn();
bspliner2->SetEnforceStationaryBoundary( false );
bspliner2->EstimateInverseOff();
bspliner2->EstimateInverseOn();
bspliner2->SetEstimateInverse( false );
bspliner2->Update();
try
{
bspliner2->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception thrown " << std::endl;
std::cerr << excp << std::endl;
}
return EXIT_SUCCESS;
}
<commit_msg>COMP: Fixed the compiler error of itkDisplacementFieldToBSplineImageFilterTest<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkDisplacementFieldToBSplineImageFilter.h"
int itkDisplacementFieldToBSplineImageFilterTest( int, char * [] )
{
const unsigned int ImageDimension = 2;
typedef itk::Vector<float, ImageDimension> VectorType;
typedef itk::Image<VectorType, ImageDimension> DisplacementFieldType;
typedef itk::PointSet<VectorType, ImageDimension> PointSetType;
// Create a displacement field
DisplacementFieldType::PointType origin;
DisplacementFieldType::SpacingType spacing;
DisplacementFieldType::SizeType size;
DisplacementFieldType::DirectionType direction;
direction.SetIdentity();
origin.Fill( 0.0 );
spacing.Fill( 0.5 );
size.Fill( 100 );
VectorType ones( 1 );
DisplacementFieldType::Pointer field = DisplacementFieldType::New();
field->SetOrigin( origin );
field->SetSpacing( spacing );
field->SetRegions( size );
field->SetDirection( direction );
field->Allocate();
field->FillBuffer( ones );
typedef itk::DisplacementFieldToBSplineImageFilter
<DisplacementFieldType, PointSetType> BSplineFilterType;
typedef BSplineFilterType::RealImageType RealImageType;
RealImageType::Pointer confidenceImage = RealImageType::New();
confidenceImage->CopyInformation( field );
confidenceImage->SetRegions( size );
confidenceImage->Allocate();
confidenceImage->FillBuffer( 1.0 );
PointSetType::Pointer pointSet = PointSetType::New();
pointSet->Initialize();
VectorType ones_points( 1.0 );
// Assign some random points within the b-spline domain
PointSetType::PointType point1;
point1[0] = 23.75;
point1[1] = 5.125;
pointSet->SetPoint( 0, point1 );
pointSet->SetPointData( 0, ones_points );
PointSetType::PointType point2;
point2[0] = 1.75;
point2[1] = 45.125;
pointSet->SetPoint( 1, point2 );
pointSet->SetPointData( 1, ones_points );
PointSetType::PointType point3;
point3[0] = 45.75;
point3[1] = 2.125;
pointSet->SetPoint( 2, point3 );
pointSet->SetPointData( 2, ones_points );
BSplineFilterType::ArrayType numberOfControlPoints;
numberOfControlPoints.Fill( 4 );
BSplineFilterType::Pointer bspliner = BSplineFilterType::New();
bspliner->SetDisplacementField( field );
bspliner->SetConfidenceImage( confidenceImage );
bspliner->SetPointSet( pointSet );
bspliner->SetUseInputFieldToDefineTheBSplineDomain( true );
bspliner->SetNumberOfControlPoints( numberOfControlPoints );
bspliner->SetSplineOrder( 3 );
bspliner->SetNumberOfFittingLevels( 8 );
bspliner->EnforceStationaryBoundaryOff();
bspliner->EnforceStationaryBoundaryOn();
bspliner->SetEnforceStationaryBoundary( false );
bspliner->EstimateInverseOff();
bspliner->EstimateInverseOn();
bspliner->SetEstimateInverse( false );
bspliner->Update();
std::cout << "spline order: " << bspliner->GetSplineOrder() << std::endl;
std::cout << "number of control points: " << bspliner->GetNumberOfControlPoints() << std::endl;
std::cout << "number of fitting levels: " << bspliner->GetNumberOfFittingLevels() << std::endl;
std::cout << "enforce stationary boundary: " << bspliner->GetEnforceStationaryBoundary() << std::endl;
std::cout << "estimate inverse: " << bspliner->GetEstimateInverse() << std::endl;
try
{
bspliner->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception thrown " << std::endl;
std::cerr << excp << std::endl;
}
DisplacementFieldType::IndexType index;
index[0] = 50;
index[1] = 50;
VectorType v = bspliner->GetOutput()->GetPixel( index );
if( vnl_math_abs( v.GetNorm() - 1.414214 ) >= 0.01 )
{
std::cerr << "Failed to find the correct forward displacement vector." << std::endl;
return EXIT_FAILURE;
}
bspliner->SetNumberOfControlPoints( numberOfControlPoints );
bspliner->SetSplineOrder( 3 );
bspliner->SetNumberOfFittingLevels( 5 );
bspliner->EnforceStationaryBoundaryOff();
bspliner->EnforceStationaryBoundaryOn();
bspliner->SetEnforceStationaryBoundary( false );
bspliner->SetEstimateInverse( true );
bspliner->Update();
v = bspliner->GetOutput()->GetPixel( index );
if( vnl_math_abs( v.GetNorm() - 1.414214 ) >= 0.01 )
{
std::cerr << "Failed to find the correct inverse displacement vector." << std::endl;
return EXIT_FAILURE;
}
bspliner->Print( std::cout, 3 );
/** do a second run using only the point set. */
BSplineFilterType::Pointer bspliner2 = BSplineFilterType::New();
bspliner2->SetPointSet( pointSet );
bspliner2->SetUseInputFieldToDefineTheBSplineDomain( false );
bspliner2->SetBSplineDomainFromImage( field );
bspliner2->SetNumberOfControlPoints( numberOfControlPoints );
bspliner2->SetSplineOrder( 3 );
bspliner2->SetNumberOfFittingLevels( 8 );
bspliner2->EnforceStationaryBoundaryOff();
bspliner2->EnforceStationaryBoundaryOn();
bspliner2->SetEnforceStationaryBoundary( false );
bspliner2->EstimateInverseOff();
bspliner2->EstimateInverseOn();
bspliner2->SetEstimateInverse( false );
bspliner2->Update();
try
{
bspliner2->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception thrown " << std::endl;
std::cerr << excp << std::endl;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "build_skins.h"
#include "build_common.h"
#include "platform/platform.hpp"
#include <array>
#include <algorithm>
#include <exception>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <fstream>
#include <QtCore/QDir>
namespace
{
enum SkinType
{
SkinMDPI,
SkinHDPI,
SkinXHDPI,
SkinXXHDPI,
Skin6Plus,
SkinXXXHDPI,
// SkinCount MUST BE last
SkinCount
};
using SkinInfo = std::tuple<const char*, int, bool>;
SkinInfo const g_skinInfo[SkinCount] =
{
std::make_tuple("mdpi", 18, false),
std::make_tuple("hdpi", 27, false),
std::make_tuple("xhdpi", 36, false),
std::make_tuple("xxhdpi", 54, false),
std::make_tuple("6plus", 54, false),
std::make_tuple("xxxhdpi", 64, false),
};
std::array<SkinType, SkinCount> const g_skinTypes =
{{
SkinMDPI,
SkinHDPI,
SkinXHDPI,
SkinXXHDPI,
Skin6Plus,
SkinXXXHDPI,
}};
inline const char * SkinSuffix(SkinType s) { return std::get<0>(g_skinInfo[s]); }
inline int SkinSize(SkinType s) { return std::get<1>(g_skinInfo[s]); }
inline bool SkinCoorrectColor(SkinType s) { return std::get<2>(g_skinInfo[s]); }
QString GetSkinGeneratorPath()
{
QString path = GetExternalPath("skin_generator_tool", "skin_generator_tool.app/Contents/MacOS", "");
if (path.isEmpty())
throw std::runtime_error("Can't find skin_generator_tool");
ASSERT(QFileInfo::exists(path), (path.toStdString()));
return path;
}
class RAII
{
public:
RAII(std::function<void()> && f) : m_f(std::move(f)) {}
~RAII() { m_f(); }
private:
function<void()> const m_f;
};
std::string trim(std::string && s)
{
s.erase(std::remove_if(s.begin(), s.end(), &isspace), s.end());
return s;
}
} // namespace
namespace build_style
{
std::unordered_map<string, int> GetSkinSizes(QString const & file)
{
std::unordered_map<string, int> skinSizes;
for (SkinType s : g_skinTypes)
skinSizes.insert(make_pair(SkinSuffix(s), SkinSize(s)));
try
{
std::ifstream ifs(to_string(file));
std::string line;
while (std::getline(ifs, line))
{
size_t const pos = line.find('=');
if (pos == std::string::npos)
continue;
std::string name(line.begin(), line.begin() + pos);
std::string valueTxt(line.begin() + pos + 1, line.end());
name = trim(std::move(name));
int value = std::stoi(trim(std::move(valueTxt)));
if (value <= 0)
continue;
skinSizes[name] = value;
}
}
catch (std::exception const & e)
{
// reset
for (SkinType s : g_skinTypes)
skinSizes[SkinSuffix(s)] = SkinSize(s);
}
return skinSizes;
}
void BuildSkinImpl(QString const & styleDir, QString const & suffix,
int size, bool colorCorrection, QString const & outputDir)
{
QString const symbolsDir = JoinPathQt({styleDir, "symbols"});
// Check symbols directory exists
if (!QDir(symbolsDir).exists())
throw std::runtime_error("Symbols directory does not exist");
// Caller ensures that output directory is clear
if (QDir(outputDir).exists())
throw std::runtime_error("Output directory is not clear");
// Create output skin directory
if (!QDir().mkdir(outputDir))
throw std::runtime_error("Cannot create output skin directory");
// Create symbolic link for symbols/png
QString const pngOriginDir = styleDir + suffix;
QString const pngDir = JoinPathQt({styleDir, "symbols", "png"});
QFile::remove(pngDir);
if (!QFile::link(pngOriginDir, pngDir))
throw std::runtime_error("Unable to create symbols/png link");
RAII const cleaner([=]() { QFile::remove(pngDir); });
// Prepare command line
QStringList params;
params << GetSkinGeneratorPath() <<
"--symbolWidth" << to_string(size).c_str() <<
"--symbolHeight" << to_string(size).c_str() <<
"--symbolsDir" << symbolsDir <<
"--skinName" << JoinPathQt({outputDir, "basic"}) <<
"--skinSuffix=\"\"";
if (colorCorrection)
params << "--colorCorrection true";
QString const cmd = params.join(' ');
// Run the script
auto res = ExecProcess(cmd);
// If script returns non zero then it is error
if (res.first != 0)
{
QString msg = QString("System error ") + to_string(res.first).c_str();
if (!res.second.isEmpty())
msg = msg + "\n" + res.second;
throw std::runtime_error(to_string(msg));
}
// Check files were created
if (QFile(JoinPathQt({outputDir, "symbols.png"})).size() == 0 ||
QFile(JoinPathQt({outputDir, "symbols.sdf"})).size() == 0)
{
throw std::runtime_error("Skin files have not been created");
}
}
void BuildSkins(QString const & styleDir, QString const & outputDir)
{
QString const resolutionFilePath = JoinPathQt({styleDir, "resolutions.txt"});
auto const resolution2size = GetSkinSizes(resolutionFilePath);
for (SkinType s : g_skinTypes)
{
QString const suffix = SkinSuffix(s);
QString const outputSkinDir = JoinPathQt({outputDir, "resources-" + suffix + "_design"});
int const size = resolution2size.at(to_string(suffix)); // SkinSize(s);
bool const colorCorrection = SkinCoorrectColor(s);
BuildSkinImpl(styleDir, suffix, size, colorCorrection, outputSkinDir);
}
}
void ApplySkins(QString const & outputDir)
{
QString const resourceDir = GetPlatform().ResourcesDir().c_str();
for (SkinType s : g_skinTypes)
{
QString const suffix = SkinSuffix(s);
QString const outputSkinDir = JoinPathQt({outputDir, "resources-" + suffix + "_design"});
QString const resourceSkinDir = JoinPathQt({resourceDir, "resources-" + suffix + "_design"});
if (!QFileInfo::exists(resourceSkinDir) && !QDir().mkdir(resourceSkinDir))
throw std::runtime_error("Cannot create resource skin directory: " + resourceSkinDir.toStdString());
if (!CopyFile(JoinPathQt({outputSkinDir, "symbols.png"}),
JoinPathQt({resourceSkinDir, "symbols.png"})) ||
!CopyFile(JoinPathQt({outputSkinDir, "symbols.sdf"}),
JoinPathQt({resourceSkinDir, "symbols.sdf"})))
{
throw std::runtime_error("Cannot copy skins files");
}
}
}
} // namespace build_style
<commit_msg>[qt] fix warning<commit_after>#include "build_skins.h"
#include "build_common.h"
#include "platform/platform.hpp"
#include <array>
#include <algorithm>
#include <exception>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <fstream>
#include <QtCore/QDir>
namespace
{
enum SkinType
{
SkinMDPI,
SkinHDPI,
SkinXHDPI,
SkinXXHDPI,
Skin6Plus,
SkinXXXHDPI,
// SkinCount MUST BE last
SkinCount
};
using SkinInfo = std::tuple<const char*, int, bool>;
SkinInfo const g_skinInfo[SkinCount] =
{
std::make_tuple("mdpi", 18, false),
std::make_tuple("hdpi", 27, false),
std::make_tuple("xhdpi", 36, false),
std::make_tuple("xxhdpi", 54, false),
std::make_tuple("6plus", 54, false),
std::make_tuple("xxxhdpi", 64, false),
};
std::array<SkinType, SkinCount> const g_skinTypes =
{{
SkinMDPI,
SkinHDPI,
SkinXHDPI,
SkinXXHDPI,
Skin6Plus,
SkinXXXHDPI,
}};
inline const char * SkinSuffix(SkinType s) { return std::get<0>(g_skinInfo[s]); }
inline int SkinSize(SkinType s) { return std::get<1>(g_skinInfo[s]); }
inline bool SkinCoorrectColor(SkinType s) { return std::get<2>(g_skinInfo[s]); }
QString GetSkinGeneratorPath()
{
QString path = GetExternalPath("skin_generator_tool", "skin_generator_tool.app/Contents/MacOS", "");
if (path.isEmpty())
throw std::runtime_error("Can't find skin_generator_tool");
ASSERT(QFileInfo::exists(path), (path.toStdString()));
return path;
}
class RAII
{
public:
RAII(std::function<void()> && f) : m_f(std::move(f)) {}
~RAII() { m_f(); }
private:
function<void()> const m_f;
};
std::string trim(std::string && s)
{
s.erase(std::remove_if(s.begin(), s.end(), &isspace), s.end());
return std::move(s);
}
} // namespace
namespace build_style
{
std::unordered_map<string, int> GetSkinSizes(QString const & file)
{
std::unordered_map<string, int> skinSizes;
for (SkinType s : g_skinTypes)
skinSizes.insert(make_pair(SkinSuffix(s), SkinSize(s)));
try
{
std::ifstream ifs(to_string(file));
std::string line;
while (std::getline(ifs, line))
{
size_t const pos = line.find('=');
if (pos == std::string::npos)
continue;
std::string name(line.begin(), line.begin() + pos);
std::string valueTxt(line.begin() + pos + 1, line.end());
name = trim(std::move(name));
int value = std::stoi(trim(std::move(valueTxt)));
if (value <= 0)
continue;
skinSizes[name] = value;
}
}
catch (std::exception const & e)
{
// reset
for (SkinType s : g_skinTypes)
skinSizes[SkinSuffix(s)] = SkinSize(s);
}
return skinSizes;
}
void BuildSkinImpl(QString const & styleDir, QString const & suffix,
int size, bool colorCorrection, QString const & outputDir)
{
QString const symbolsDir = JoinPathQt({styleDir, "symbols"});
// Check symbols directory exists
if (!QDir(symbolsDir).exists())
throw std::runtime_error("Symbols directory does not exist");
// Caller ensures that output directory is clear
if (QDir(outputDir).exists())
throw std::runtime_error("Output directory is not clear");
// Create output skin directory
if (!QDir().mkdir(outputDir))
throw std::runtime_error("Cannot create output skin directory");
// Create symbolic link for symbols/png
QString const pngOriginDir = styleDir + suffix;
QString const pngDir = JoinPathQt({styleDir, "symbols", "png"});
QFile::remove(pngDir);
if (!QFile::link(pngOriginDir, pngDir))
throw std::runtime_error("Unable to create symbols/png link");
RAII const cleaner([=]() { QFile::remove(pngDir); });
// Prepare command line
QStringList params;
params << GetSkinGeneratorPath() <<
"--symbolWidth" << to_string(size).c_str() <<
"--symbolHeight" << to_string(size).c_str() <<
"--symbolsDir" << symbolsDir <<
"--skinName" << JoinPathQt({outputDir, "basic"}) <<
"--skinSuffix=\"\"";
if (colorCorrection)
params << "--colorCorrection true";
QString const cmd = params.join(' ');
// Run the script
auto res = ExecProcess(cmd);
// If script returns non zero then it is error
if (res.first != 0)
{
QString msg = QString("System error ") + to_string(res.first).c_str();
if (!res.second.isEmpty())
msg = msg + "\n" + res.second;
throw std::runtime_error(to_string(msg));
}
// Check files were created
if (QFile(JoinPathQt({outputDir, "symbols.png"})).size() == 0 ||
QFile(JoinPathQt({outputDir, "symbols.sdf"})).size() == 0)
{
throw std::runtime_error("Skin files have not been created");
}
}
void BuildSkins(QString const & styleDir, QString const & outputDir)
{
QString const resolutionFilePath = JoinPathQt({styleDir, "resolutions.txt"});
auto const resolution2size = GetSkinSizes(resolutionFilePath);
for (SkinType s : g_skinTypes)
{
QString const suffix = SkinSuffix(s);
QString const outputSkinDir = JoinPathQt({outputDir, "resources-" + suffix + "_design"});
int const size = resolution2size.at(to_string(suffix)); // SkinSize(s);
bool const colorCorrection = SkinCoorrectColor(s);
BuildSkinImpl(styleDir, suffix, size, colorCorrection, outputSkinDir);
}
}
void ApplySkins(QString const & outputDir)
{
QString const resourceDir = GetPlatform().ResourcesDir().c_str();
for (SkinType s : g_skinTypes)
{
QString const suffix = SkinSuffix(s);
QString const outputSkinDir = JoinPathQt({outputDir, "resources-" + suffix + "_design"});
QString const resourceSkinDir = JoinPathQt({resourceDir, "resources-" + suffix + "_design"});
if (!QFileInfo::exists(resourceSkinDir) && !QDir().mkdir(resourceSkinDir))
throw std::runtime_error("Cannot create resource skin directory: " + resourceSkinDir.toStdString());
if (!CopyFile(JoinPathQt({outputSkinDir, "symbols.png"}),
JoinPathQt({resourceSkinDir, "symbols.png"})) ||
!CopyFile(JoinPathQt({outputSkinDir, "symbols.sdf"}),
JoinPathQt({resourceSkinDir, "symbols.sdf"})))
{
throw std::runtime_error("Cannot copy skins files");
}
}
}
} // namespace build_style
<|endoftext|>
|
<commit_before>//===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the auto-upgrade helper functions
//
//===----------------------------------------------------------------------===//
#include "llvm/AutoUpgrade.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Instruction.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/IRBuilder.h"
#include <cstring>
using namespace llvm;
static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
assert(F && "Illegal to upgrade a non-existent Function.");
// Quickly eliminate it, if it's not a candidate.
StringRef Name = F->getName();
if (Name.size() <= 8 || !Name.startswith("llvm."))
return false;
Name = Name.substr(5); // Strip off "llvm."
switch (Name[0]) {
default: break;
case 'c': {
if (Name.startswith("ctlz.") && F->arg_size() == 1) {
F->setName(Name + ".old");
NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
F->arg_begin()->getType());
return true;
}
if (Name.startswith("cttz.") && F->arg_size() == 1) {
F->setName(Name + ".old");
NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz,
F->arg_begin()->getType());
return true;
}
break;
}
}
// This may not belong here. This function is effectively being overloaded
// to both detect an intrinsic which needs upgrading, and to provide the
// upgraded form of the intrinsic. We should perhaps have two separate
// functions for this.
return false;
}
bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
NewFn = 0;
bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
// Upgrade intrinsic attributes. This does not change the function.
if (NewFn)
F = NewFn;
if (unsigned id = F->getIntrinsicID())
F->setAttributes(Intrinsic::getAttributes((Intrinsic::ID)id));
return Upgraded;
}
bool llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
// Nothing to do yet.
return false;
}
// UpgradeIntrinsicCall - Upgrade a call to an old intrinsic to be a call the
// upgraded intrinsic. All argument and return casting must be provided in
// order to seamlessly integrate with existing context.
void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
Function *F = CI->getCalledFunction();
LLVMContext &C = CI->getContext();
assert(F && "CallInst has no function associated with it.");
if (!NewFn) return;
IRBuilder<> Builder(C);
Builder.SetInsertPoint(CI->getParent(), CI);
switch (NewFn->getIntrinsicID()) {
default:
llvm_unreachable("Unknown function for CallInst upgrade.");
case Intrinsic::ctlz:
case Intrinsic::cttz:
assert(CI->getNumArgOperands() == 1 &&
"Mismatch between function args and call args");
StringRef Name = CI->getName();
CI->setName(Name + ".old");
CI->replaceAllUsesWith(Builder.CreateCall2(NewFn, CI->getArgOperand(0),
Builder.getFalse(), Name));
CI->eraseFromParent();
return;
}
}
// This tests each Function to determine if it needs upgrading. When we find
// one we are interested in, we then upgrade all calls to reflect the new
// function.
void llvm::UpgradeCallsToIntrinsic(Function* F) {
assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
// Upgrade the function and check if it is a totaly new function.
Function *NewFn;
if (UpgradeIntrinsicFunction(F, NewFn)) {
if (NewFn != F) {
// Replace all uses to the old function with the new one if necessary.
for (Value::use_iterator UI = F->use_begin(), UE = F->use_end();
UI != UE; ) {
if (CallInst *CI = dyn_cast<CallInst>(*UI++))
UpgradeIntrinsicCall(CI, NewFn);
}
// Remove old function, no longer used, from the module.
F->eraseFromParent();
}
}
}
<commit_msg>Fix unused value warning for value used only in assert.<commit_after>//===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the auto-upgrade helper functions
//
//===----------------------------------------------------------------------===//
#include "llvm/AutoUpgrade.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Instruction.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/IRBuilder.h"
#include <cstring>
using namespace llvm;
static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
assert(F && "Illegal to upgrade a non-existent Function.");
// Quickly eliminate it, if it's not a candidate.
StringRef Name = F->getName();
if (Name.size() <= 8 || !Name.startswith("llvm."))
return false;
Name = Name.substr(5); // Strip off "llvm."
switch (Name[0]) {
default: break;
case 'c': {
if (Name.startswith("ctlz.") && F->arg_size() == 1) {
F->setName(Name + ".old");
NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
F->arg_begin()->getType());
return true;
}
if (Name.startswith("cttz.") && F->arg_size() == 1) {
F->setName(Name + ".old");
NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz,
F->arg_begin()->getType());
return true;
}
break;
}
}
// This may not belong here. This function is effectively being overloaded
// to both detect an intrinsic which needs upgrading, and to provide the
// upgraded form of the intrinsic. We should perhaps have two separate
// functions for this.
return false;
}
bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
NewFn = 0;
bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
// Upgrade intrinsic attributes. This does not change the function.
if (NewFn)
F = NewFn;
if (unsigned id = F->getIntrinsicID())
F->setAttributes(Intrinsic::getAttributes((Intrinsic::ID)id));
return Upgraded;
}
bool llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
// Nothing to do yet.
return false;
}
// UpgradeIntrinsicCall - Upgrade a call to an old intrinsic to be a call the
// upgraded intrinsic. All argument and return casting must be provided in
// order to seamlessly integrate with existing context.
void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
assert(CI->getCalledFunction() && "Intrinsic call is not direct?");
if (!NewFn) return;
LLVMContext &C = CI->getContext();
IRBuilder<> Builder(C);
Builder.SetInsertPoint(CI->getParent(), CI);
switch (NewFn->getIntrinsicID()) {
default:
llvm_unreachable("Unknown function for CallInst upgrade.");
case Intrinsic::ctlz:
case Intrinsic::cttz:
assert(CI->getNumArgOperands() == 1 &&
"Mismatch between function args and call args");
StringRef Name = CI->getName();
CI->setName(Name + ".old");
CI->replaceAllUsesWith(Builder.CreateCall2(NewFn, CI->getArgOperand(0),
Builder.getFalse(), Name));
CI->eraseFromParent();
return;
}
}
// This tests each Function to determine if it needs upgrading. When we find
// one we are interested in, we then upgrade all calls to reflect the new
// function.
void llvm::UpgradeCallsToIntrinsic(Function* F) {
assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
// Upgrade the function and check if it is a totaly new function.
Function *NewFn;
if (UpgradeIntrinsicFunction(F, NewFn)) {
if (NewFn != F) {
// Replace all uses to the old function with the new one if necessary.
for (Value::use_iterator UI = F->use_begin(), UE = F->use_end();
UI != UE; ) {
if (CallInst *CI = dyn_cast<CallInst>(*UI++))
UpgradeIntrinsicCall(CI, NewFn);
}
// Remove old function, no longer used, from the module.
F->eraseFromParent();
}
}
}
<|endoftext|>
|
<commit_before>
#include <functional>
#include <string>
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "quantities/astronomy.hpp"
#include "quantities/BIPM.hpp"
#include "quantities/constants.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "quantities/uk.hpp"
#include "testing_utilities/algebra.hpp"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/numerics.hpp"
#include "testing_utilities/vanishes_before.hpp"
namespace principia {
using astronomy::EarthMass;
using astronomy::JulianYear;
using astronomy::JupiterMass;
using astronomy::LightYear;
using astronomy::LunarDistance;
using astronomy::Parsec;
using astronomy::SolarMass;
using constants::ElectronMass;
using constants::GravitationalConstant;
using constants::SpeedOfLight;
using constants::StandardGravity;
using constants::VacuumPermeability;
using constants::VacuumPermittivity;
using si::Ampere;
using si::AstronomicalUnit;
using si::Candela;
using si::Cycle;
using si::Day;
using si::Degree;
using si::Hour;
using si::Kelvin;
using si::Kilogram;
using si::Mega;
using si::Metre;
using si::Mole;
using si::Radian;
using si::Second;
using si::Steradian;
using testing_utilities::AlmostEquals;
using testing_utilities::RelativeError;
using testing_utilities::VanishesBefore;
using uk::Foot;
using uk::Furlong;
using uk::Mile;
using uk::Rood;
using ::testing::Lt;
using ::testing::MatchesRegex;
namespace quantities {
class QuantitiesTest : public testing::Test {
protected:
};
using QuantitiesDeathTest = QuantitiesTest;
TEST_F(QuantitiesTest, AbsoluteValue) {
EXPECT_EQ(Abs(-1729), 1729);
EXPECT_EQ(Abs(1729), 1729);
}
TEST_F(QuantitiesTest, DimensionfulComparisons) {
testing_utilities::TestOrder(EarthMass, JupiterMass);
testing_utilities::TestOrder(LightYear, Parsec);
testing_utilities::TestOrder(-SpeedOfLight, SpeedOfLight);
testing_utilities::TestOrder(SpeedOfLight * Day, LightYear);
}
TEST_F(QuantitiesTest, DimensionlfulOperations) {
testing_utilities::TestVectorSpace(
0 * Metre / Second, SpeedOfLight, 88 * Mile / Hour,
-340.29 * Metre / Second, 0.0, 1.0, -2 * π, 1729.0, 0, 2);
// Dimensionful multiplication is a tensor product, see [Tao 2012].
testing_utilities::TestBilinearMap(
std::multiplies<>(), SolarMass,
ElectronMass, SpeedOfLight, 1 * Furlong / JulianYear, -e, 0, 2);
}
TEST_F(QuantitiesTest, DimensionlessExponentiation) {
double const number = π - 42;
double positivePower = 1;
double negativePower = 1;
EXPECT_EQ(positivePower, Pow<0>(number));
positivePower *= number;
negativePower /= number;
EXPECT_EQ(positivePower, Pow<1>(number));
EXPECT_EQ(negativePower, Pow<-1>(number));
positivePower *= number;
negativePower /= number;
EXPECT_EQ(positivePower, Pow<2>(number));
EXPECT_EQ(negativePower, Pow<-2>(number));
positivePower *= number;
negativePower /= number;
EXPECT_EQ(positivePower, Pow<3>(number));
EXPECT_EQ(negativePower, Pow<-3>(number));
positivePower *= number;
negativePower /= number;
// This one calls |std::pow|.
EXPECT_THAT(positivePower, AlmostEquals(Pow<4>(number), 0, 1));
EXPECT_THAT(negativePower, AlmostEquals(Pow<-4>(number), 0, 1));
}
// The Greek letters cause a warning when stringified by the macros, because
// apparently Visual Studio doesn't encode strings in UTF-8 by default.
#pragma warning(disable: 4566)
TEST_F(QuantitiesTest, Formatting) {
auto const all_the_units = 1 * Metre * Kilogram * Second * Ampere * Kelvin /
(Mole * Candela * Cycle * Radian * Steradian);
std::string const expected = std::string("+1e+00 m kg s A K mol^-1") +
" cd^-1 cycle^-1 rad^-1 sr^-1";
std::string const actual = DebugString(all_the_units, 0);
EXPECT_EQ(expected, actual);
std::string const π17 = "\\+3\\.1415926535897931.e\\+00";
EXPECT_THAT(DebugString(π), MatchesRegex(π17));
std::string const minus_e17 = "\\-2\\.718281828459045..e\\+00";
EXPECT_THAT(DebugString(-e), MatchesRegex(minus_e17));
}
TEST_F(QuantitiesTest, PhysicalConstants) {
// By definition.
EXPECT_THAT(1 / Pow<2>(SpeedOfLight),
AlmostEquals(VacuumPermittivity * VacuumPermeability, 1));
// The Keplerian approximation for the mass of the Sun
// is fairly accurate.
EXPECT_THAT(RelativeError(
4 * Pow<2>(π) * Pow<3>(AstronomicalUnit) /
(GravitationalConstant * Pow<2>(JulianYear)),
SolarMass),
Lt(4E-5));
EXPECT_THAT(RelativeError(1 * Parsec, 3.26156 * LightYear), Lt(2E-6));
// The Keplerian approximation for the mass of the Earth
// is pretty bad, but the error is still only 1%.
EXPECT_THAT(RelativeError(
4 * Pow<2>(π) * Pow<3>(LunarDistance) /
(GravitationalConstant * Pow<2>(27.321582 * Day)),
EarthMass),
Lt(1E-2));
EXPECT_THAT(RelativeError(1 * SolarMass, 1047 * JupiterMass), Lt(4E-4));
// Delambre & Méchain.
EXPECT_THAT(RelativeError(
GravitationalConstant * EarthMass /
Pow<2>(40 * Mega(Metre) / (2 * π)),
StandardGravity),
Lt(4E-3));
// Talleyrand.
EXPECT_THAT(RelativeError(π * Sqrt(1 * Metre / StandardGravity), 1 * Second),
Lt(4E-3));
}
#pragma warning(default: 4566)
TEST_F(QuantitiesTest, TrigonometricFunctions) {
EXPECT_EQ(Cos(0 * Degree), 1);
EXPECT_EQ(Sin(0 * Degree), 0);
EXPECT_THAT(Cos(90 * Degree), VanishesBefore(1.0, 0));
EXPECT_EQ(Sin(90 * Degree), 1);
EXPECT_EQ(Cos(180 * Degree), -1);
EXPECT_THAT(Sin(180 * Degree), VanishesBefore(1.0, 1));
EXPECT_THAT(Cos(-90 * Degree), VanishesBefore(1.0, 0));
EXPECT_EQ(Sin(-90 * Degree), -1);
for (int k = 1; k < 360; ++k) {
// Don't test for multiples of 90 degrees as zeros lead to horrible
// conditioning.
if (k % 90 != 0) {
EXPECT_THAT(Cos((90 - k) * Degree),
AlmostEquals(Sin(k * Degree), 0, 46));
EXPECT_THAT(Sin(k * Degree) / Cos(k * Degree),
AlmostEquals(Tan(k * Degree), 0, 2));
EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
AlmostEquals(ArcTan(Sin(k * Degree), Cos(k * Degree)),
0, 77));
EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
AlmostEquals(ArcTan(Sin(k * Degree) * AstronomicalUnit,
Cos(k * Degree) * AstronomicalUnit),
0, 77));
EXPECT_THAT(Cos(ArcCos(Cos(k * Degree))),
AlmostEquals(Cos(k * Degree), 0, 7));
EXPECT_THAT(Sin(ArcSin(Sin(k * Degree))),
AlmostEquals(Sin(k * Degree), 0, 1));
}
}
// Horribly conditioned near 0, so not in the loop above.
EXPECT_EQ(Tan(ArcTan(Tan(-42 * Degree))), Tan(-42 * Degree));
}
TEST_F(QuantitiesTest, HyperbolicFunctions) {
EXPECT_EQ(Sinh(0 * Radian), 0);
EXPECT_EQ(Cosh(0 * Radian), 1);
EXPECT_EQ(Tanh(0 * Radian), 0);
// Limits:
EXPECT_EQ(Sinh(20 * Radian), Cosh(20 * Radian));
EXPECT_EQ(Tanh(20 * Radian), 1);
EXPECT_EQ(Sinh(-20 * Radian), -Cosh(-20 * Radian));
EXPECT_EQ(Tanh(-20 * Radian), -1);
EXPECT_THAT(Sinh(2 * Radian) / Cosh(2 * Radian),
AlmostEquals(Tanh(2 * Radian), 0, 1));
EXPECT_THAT(ArcSinh(Sinh(-10 * Degree)),
AlmostEquals(-10 * Degree, 0, 1));
EXPECT_THAT(ArcCosh(Cosh(-10 * Degree)),
AlmostEquals(10 * Degree, 19, 20));
EXPECT_THAT(ArcTanh(Tanh(-10 * Degree)),
AlmostEquals(-10 * Degree, 0, 1));
}
TEST_F(QuantitiesTest, ExpLogAndSqrt) {
EXPECT_THAT(std::exp(std::log(2) / 2), AlmostEquals(Sqrt(2), 1));
EXPECT_EQ(std::exp(std::log(Rood / Pow<2>(Foot)) / 2) * Foot, Sqrt(Rood));
}
TEST_F(QuantitiesDeathTest, SerializationError) {
EXPECT_DEATH({
serialization::Quantity message;
message.set_dimensions(0x7C00);
message.set_magnitude(1.0);
Speed const speed_of_light = Speed::ReadFromMessage(message);
}, "representation.*dimensions");
}
TEST_F(QuantitiesTest, SerializationSuccess) {
serialization::Quantity message;
SpeedOfLight.WriteToMessage(&message);
EXPECT_EQ(0x7C01, message.dimensions());
EXPECT_EQ(299792458.0, message.magnitude());
Speed const speed_of_light = Speed::ReadFromMessage(message);
EXPECT_EQ(SpeedOfLight, speed_of_light);
}
} // namespace quantities
} // namespace principia
<commit_msg>Trig.<commit_after>
#include <functional>
#include <string>
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "quantities/astronomy.hpp"
#include "quantities/BIPM.hpp"
#include "quantities/constants.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "quantities/uk.hpp"
#include "testing_utilities/algebra.hpp"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/numerics.hpp"
#include "testing_utilities/vanishes_before.hpp"
namespace principia {
using astronomy::EarthMass;
using astronomy::JulianYear;
using astronomy::JupiterMass;
using astronomy::LightYear;
using astronomy::LunarDistance;
using astronomy::Parsec;
using astronomy::SolarMass;
using constants::ElectronMass;
using constants::GravitationalConstant;
using constants::SpeedOfLight;
using constants::StandardGravity;
using constants::VacuumPermeability;
using constants::VacuumPermittivity;
using si::Ampere;
using si::AstronomicalUnit;
using si::Candela;
using si::Cycle;
using si::Day;
using si::Degree;
using si::Hour;
using si::Kelvin;
using si::Kilogram;
using si::Mega;
using si::Metre;
using si::Mole;
using si::Radian;
using si::Second;
using si::Steradian;
using testing_utilities::AlmostEquals;
using testing_utilities::RelativeError;
using testing_utilities::VanishesBefore;
using uk::Foot;
using uk::Furlong;
using uk::Mile;
using uk::Rood;
using ::testing::Lt;
using ::testing::MatchesRegex;
namespace quantities {
class QuantitiesTest : public testing::Test {
protected:
};
using QuantitiesDeathTest = QuantitiesTest;
TEST_F(QuantitiesTest, AbsoluteValue) {
EXPECT_EQ(Abs(-1729), 1729);
EXPECT_EQ(Abs(1729), 1729);
}
TEST_F(QuantitiesTest, DimensionfulComparisons) {
testing_utilities::TestOrder(EarthMass, JupiterMass);
testing_utilities::TestOrder(LightYear, Parsec);
testing_utilities::TestOrder(-SpeedOfLight, SpeedOfLight);
testing_utilities::TestOrder(SpeedOfLight * Day, LightYear);
}
TEST_F(QuantitiesTest, DimensionlfulOperations) {
testing_utilities::TestVectorSpace(
0 * Metre / Second, SpeedOfLight, 88 * Mile / Hour,
-340.29 * Metre / Second, 0.0, 1.0, -2 * π, 1729.0, 0, 2);
// Dimensionful multiplication is a tensor product, see [Tao 2012].
testing_utilities::TestBilinearMap(
std::multiplies<>(), SolarMass,
ElectronMass, SpeedOfLight, 1 * Furlong / JulianYear, -e, 0, 2);
}
TEST_F(QuantitiesTest, DimensionlessExponentiation) {
double const number = π - 42;
double positivePower = 1;
double negativePower = 1;
EXPECT_EQ(positivePower, Pow<0>(number));
positivePower *= number;
negativePower /= number;
EXPECT_EQ(positivePower, Pow<1>(number));
EXPECT_EQ(negativePower, Pow<-1>(number));
positivePower *= number;
negativePower /= number;
EXPECT_EQ(positivePower, Pow<2>(number));
EXPECT_EQ(negativePower, Pow<-2>(number));
positivePower *= number;
negativePower /= number;
EXPECT_EQ(positivePower, Pow<3>(number));
EXPECT_EQ(negativePower, Pow<-3>(number));
positivePower *= number;
negativePower /= number;
// This one calls |std::pow|.
EXPECT_THAT(positivePower, AlmostEquals(Pow<4>(number), 0, 1));
EXPECT_THAT(negativePower, AlmostEquals(Pow<-4>(number), 0, 1));
}
// The Greek letters cause a warning when stringified by the macros, because
// apparently Visual Studio doesn't encode strings in UTF-8 by default.
#pragma warning(disable: 4566)
TEST_F(QuantitiesTest, Formatting) {
auto const all_the_units = 1 * Metre * Kilogram * Second * Ampere * Kelvin /
(Mole * Candela * Cycle * Radian * Steradian);
std::string const expected = std::string("+1e+00 m kg s A K mol^-1") +
" cd^-1 cycle^-1 rad^-1 sr^-1";
std::string const actual = DebugString(all_the_units, 0);
EXPECT_EQ(expected, actual);
std::string const π17 = "\\+3\\.1415926535897931.e\\+00";
EXPECT_THAT(DebugString(π), MatchesRegex(π17));
std::string const minus_e17 = "\\-2\\.718281828459045..e\\+00";
EXPECT_THAT(DebugString(-e), MatchesRegex(minus_e17));
}
TEST_F(QuantitiesTest, PhysicalConstants) {
// By definition.
EXPECT_THAT(1 / Pow<2>(SpeedOfLight),
AlmostEquals(VacuumPermittivity * VacuumPermeability, 1));
// The Keplerian approximation for the mass of the Sun
// is fairly accurate.
EXPECT_THAT(RelativeError(
4 * Pow<2>(π) * Pow<3>(AstronomicalUnit) /
(GravitationalConstant * Pow<2>(JulianYear)),
SolarMass),
Lt(4E-5));
EXPECT_THAT(RelativeError(1 * Parsec, 3.26156 * LightYear), Lt(2E-6));
// The Keplerian approximation for the mass of the Earth
// is pretty bad, but the error is still only 1%.
EXPECT_THAT(RelativeError(
4 * Pow<2>(π) * Pow<3>(LunarDistance) /
(GravitationalConstant * Pow<2>(27.321582 * Day)),
EarthMass),
Lt(1E-2));
EXPECT_THAT(RelativeError(1 * SolarMass, 1047 * JupiterMass), Lt(4E-4));
// Delambre & Méchain.
EXPECT_THAT(RelativeError(
GravitationalConstant * EarthMass /
Pow<2>(40 * Mega(Metre) / (2 * π)),
StandardGravity),
Lt(4E-3));
// Talleyrand.
EXPECT_THAT(RelativeError(π * Sqrt(1 * Metre / StandardGravity), 1 * Second),
Lt(4E-3));
}
#pragma warning(default: 4566)
TEST_F(QuantitiesTest, TrigonometricFunctions) {
EXPECT_EQ(Cos(0 * Degree), 1);
EXPECT_EQ(Sin(0 * Degree), 0);
EXPECT_THAT(Cos(90 * Degree), VanishesBefore(1.0, 0));
EXPECT_EQ(Sin(90 * Degree), 1);
EXPECT_EQ(Cos(180 * Degree), -1);
EXPECT_THAT(Sin(180 * Degree), VanishesBefore(1.0, 1));
EXPECT_THAT(Cos(-90 * Degree), VanishesBefore(1.0, 0));
EXPECT_EQ(Sin(-90 * Degree), -1);
for (int k = 1; k < 360; ++k) {
// Don't test for multiples of 90 degrees as zeros lead to horrible
// conditioning.
if (k % 90 != 0) {
EXPECT_THAT(Cos((90 - k) * Degree),
AlmostEquals(Sin(k * Degree), 0, 47));
EXPECT_THAT(Sin(k * Degree) / Cos(k * Degree),
AlmostEquals(Tan(k * Degree), 0, 2));
EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
AlmostEquals(ArcTan(Sin(k * Degree), Cos(k * Degree)),
0, 77));
EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
AlmostEquals(ArcTan(Sin(k * Degree) * AstronomicalUnit,
Cos(k * Degree) * AstronomicalUnit),
0, 77));
EXPECT_THAT(Cos(ArcCos(Cos(k * Degree))),
AlmostEquals(Cos(k * Degree), 0, 7));
EXPECT_THAT(Sin(ArcSin(Sin(k * Degree))),
AlmostEquals(Sin(k * Degree), 0, 1));
}
}
// Horribly conditioned near 0, so not in the loop above.
EXPECT_EQ(Tan(ArcTan(Tan(-42 * Degree))), Tan(-42 * Degree));
}
TEST_F(QuantitiesTest, HyperbolicFunctions) {
EXPECT_EQ(Sinh(0 * Radian), 0);
EXPECT_EQ(Cosh(0 * Radian), 1);
EXPECT_EQ(Tanh(0 * Radian), 0);
// Limits:
EXPECT_EQ(Sinh(20 * Radian), Cosh(20 * Radian));
EXPECT_EQ(Tanh(20 * Radian), 1);
EXPECT_EQ(Sinh(-20 * Radian), -Cosh(-20 * Radian));
EXPECT_EQ(Tanh(-20 * Radian), -1);
EXPECT_THAT(Sinh(2 * Radian) / Cosh(2 * Radian),
AlmostEquals(Tanh(2 * Radian), 0, 1));
EXPECT_THAT(ArcSinh(Sinh(-10 * Degree)),
AlmostEquals(-10 * Degree, 0, 1));
EXPECT_THAT(ArcCosh(Cosh(-10 * Degree)),
AlmostEquals(10 * Degree, 19, 20));
EXPECT_THAT(ArcTanh(Tanh(-10 * Degree)),
AlmostEquals(-10 * Degree, 0, 1));
}
TEST_F(QuantitiesTest, ExpLogAndSqrt) {
EXPECT_THAT(std::exp(std::log(2) / 2), AlmostEquals(Sqrt(2), 1));
EXPECT_EQ(std::exp(std::log(Rood / Pow<2>(Foot)) / 2) * Foot, Sqrt(Rood));
}
TEST_F(QuantitiesDeathTest, SerializationError) {
EXPECT_DEATH({
serialization::Quantity message;
message.set_dimensions(0x7C00);
message.set_magnitude(1.0);
Speed const speed_of_light = Speed::ReadFromMessage(message);
}, "representation.*dimensions");
}
TEST_F(QuantitiesTest, SerializationSuccess) {
serialization::Quantity message;
SpeedOfLight.WriteToMessage(&message);
EXPECT_EQ(0x7C01, message.dimensions());
EXPECT_EQ(299792458.0, message.magnitude());
Speed const speed_of_light = Speed::ReadFromMessage(message);
EXPECT_EQ(SpeedOfLight, speed_of_light);
}
} // namespace quantities
} // namespace principia
<|endoftext|>
|
<commit_before><commit_msg>Always send Retrieve in Network::registerCaller()<commit_after><|endoftext|>
|
<commit_before>// Copyright (C) 2011 The Libphonenumber Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Author: Philippe Liard
#include <iostream>
#include <gtest/gtest.h>
#include "phonenumbers/unicodestring.h"
using std::ostream;
// Used by GTest to print the expected and actual results in case of failure.
ostream& operator<<(ostream& out, const i18n::phonenumbers::UnicodeString& s) {
string utf8;
s.toUTF8String(utf8);
out << utf8;
return out;
}
namespace i18n {
namespace phonenumbers {
TEST(UnicodeString, ToUTF8StringWithEmptyString) {
UnicodeString s;
string utf8;
s.toUTF8String(utf8);
EXPECT_EQ("", utf8);
}
TEST(UnicodeString, ToUTF8String) {
UnicodeString s("hello");
string utf8;
s.toUTF8String(utf8);
EXPECT_EQ("hello", utf8);
}
TEST(UnicodeString, ToUTF8StringWithNonAscii) {
UnicodeString s("\xEF\xBC\x95\xEF\xBC\x93" /* "53" */);
string utf8;
s.toUTF8String(utf8);
EXPECT_EQ("\xEF\xBC\x95\xEF\xBC\x93", utf8);
}
TEST(UnicodeString, AppendCodepoint) {
UnicodeString s;
s.append('h');
ASSERT_EQ(UnicodeString("h"), s);
s.append('e');
EXPECT_EQ(UnicodeString("he"), s);
}
TEST(UnicodeString, AppendCodepointWithNonAscii) {
UnicodeString s;
s.append(0xFF15 /* 5 */);
ASSERT_EQ(UnicodeString("\xEF\xBC\x95" /* 5 */), s);
s.append(0xFF13 /* 3 */);
EXPECT_EQ(UnicodeString("\xEF\xBC\x95\xEF\xBC\x93" /* 53 */), s);
}
TEST(UnicodeString, AppendUnicodeString) {
UnicodeString s;
s.append(UnicodeString("he"));
ASSERT_EQ(UnicodeString("he"), s);
s.append(UnicodeString("llo"));
EXPECT_EQ(UnicodeString("hello"), s);
}
TEST(UnicodeString, AppendUnicodeStringWithNonAscii) {
UnicodeString s;
s.append(UnicodeString("\xEF\xBC\x95" /* 5 */));
ASSERT_EQ(UnicodeString("\xEF\xBC\x95"), s);
s.append(UnicodeString("\xEF\xBC\x93" /* 3 */));
EXPECT_EQ(UnicodeString("\xEF\xBC\x95\xEF\xBC\x93" /* 53 */), s);
}
TEST(UnicodeString, IndexOf) {
UnicodeString s("hello");
EXPECT_EQ(0, s.indexOf('h'));
EXPECT_EQ(2, s.indexOf('l'));
EXPECT_EQ(4, s.indexOf('o'));
}
TEST(UnicodeString, IndexOfWithNonAscii) {
UnicodeString s("\xEF\xBC\x95\xEF\xBC\x93" /* 53 */);
EXPECT_EQ(1, s.indexOf(0xFF13 /* 3 */));
}
TEST(UnicodeString, ReplaceWithEmptyInputs) {
UnicodeString s;
s.replace(0, 0, UnicodeString(""));
EXPECT_EQ(UnicodeString(""), s);
}
TEST(UnicodeString, ReplaceWithEmptyReplacement) {
UnicodeString s("hello");
s.replace(0, 5, UnicodeString(""));
EXPECT_EQ(UnicodeString(""), s);
}
TEST(UnicodeString, ReplaceBegining) {
UnicodeString s("hello world");
s.replace(0, 5, UnicodeString("HELLO"));
EXPECT_EQ(UnicodeString("HELLO world"), s);
}
TEST(UnicodeString, ReplaceMiddle) {
UnicodeString s("hello world");
s.replace(5, 1, UnicodeString("AB"));
EXPECT_EQ(UnicodeString("helloABworld"), s);
}
TEST(UnicodeString, ReplaceEnd) {
UnicodeString s("hello world");
s.replace(10, 1, UnicodeString("AB"));
EXPECT_EQ(UnicodeString("hello worlAB"), s);
}
TEST(UnicodeString, ReplaceWithNonAscii) {
UnicodeString s("hello world");
s.replace(3, 2, UnicodeString("\xEF\xBC\x91\xEF\xBC\x90" /* 10 */));
EXPECT_EQ(UnicodeString("hel\xEF\xBC\x91\xEF\xBC\x90 world"), s);
}
TEST(UnicodeString, SetCharBegining) {
UnicodeString s("hello");
s.setCharAt(0, 'H');
EXPECT_EQ(UnicodeString("Hello"), s);
}
TEST(UnicodeString, SetCharMiddle) {
UnicodeString s("hello");
s.setCharAt(2, 'L');
EXPECT_EQ(UnicodeString("heLlo"), s);
}
TEST(UnicodeString, SetCharEnd) {
UnicodeString s("hello");
s.setCharAt(4, 'O');
EXPECT_EQ(UnicodeString("hellO"), s);
}
TEST(UnicodeString, SetCharWithNonAscii) {
UnicodeString s("hello");
s.setCharAt(4, 0xFF10 /* 0 */);
EXPECT_EQ(UnicodeString("hell\xEF\xBC\x90" /* 0 */), s);
}
TEST(UnicodeString, TempSubStringWithEmptyString) {
EXPECT_EQ(UnicodeString(""), UnicodeString().tempSubString(0, 0));
}
TEST(UnicodeString, TempSubStringWithInvalidInputs) {
UnicodeString s("hello");
// tempSubString() returns an empty unicode string if one of the provided
// paramaters is out of range.
EXPECT_EQ(UnicodeString(""), s.tempSubString(6));
EXPECT_EQ(UnicodeString(""), s.tempSubString(2, 6));
}
TEST(UnicodeString, TempSubString) {
UnicodeString s("hello");
EXPECT_EQ(UnicodeString(""), s.tempSubString(0, 0));
EXPECT_EQ(UnicodeString("h"), s.tempSubString(0, 1));
EXPECT_EQ(UnicodeString("hello"), s.tempSubString(0, 5));
EXPECT_EQ(UnicodeString("llo"), s.tempSubString(2, 3));
}
TEST(UnicodeString, TempSubStringWithNoLength) {
UnicodeString s("hello");
EXPECT_EQ(UnicodeString("hello"), s.tempSubString(0));
EXPECT_EQ(UnicodeString("llo"), s.tempSubString(2));
}
TEST(UnicodeString, TempSubStringWithNonAscii) {
UnicodeString s("hel\xEF\xBC\x91\xEF\xBC\x90" /* 10 */);
EXPECT_EQ(UnicodeString("\xEF\xBC\x91" /* 1 */), s.tempSubString(3, 1));
}
TEST(UnicodeString, OperatorEqual) {
UnicodeString s("hello");
s = UnicodeString("Hello");
EXPECT_EQ(UnicodeString("Hello"), s);
}
TEST(UnicodeString, OperatorEqualWithNonAscii) {
UnicodeString s("hello");
s = UnicodeString("hel\xEF\xBC\x91\xEF\xBC\x90" /* 10 */);
EXPECT_EQ(UnicodeString("hel\xEF\xBC\x91\xEF\xBC\x90"), s);
}
TEST(UnicodeString, OperatorBracket) {
UnicodeString s("hello");
EXPECT_EQ('h', s[0]);
EXPECT_EQ('e', s[1]);
EXPECT_EQ('l', s[2]);
EXPECT_EQ('l', s[3]);
EXPECT_EQ('o', s[4]);
}
TEST(UnicodeString, OperatorBracketWithNonAscii) {
UnicodeString s("hel\xEF\xBC\x91\xEF\xBC\x90" /* 10 */);
EXPECT_EQ('h', s[0]);
EXPECT_EQ('e', s[1]);
EXPECT_EQ('l', s[2]);
EXPECT_EQ(0xFF11 /* 1 */, s[3]);
EXPECT_EQ(0xFF10 /* 0 */, s[4]);
}
TEST(UnicodeString, OperatorBracketWithIteratorCacheInvalidation) {
UnicodeString s("hello");
EXPECT_EQ('h', s[0]);
EXPECT_EQ('e', s[1]);
// Modify the string which should invalidate the iterator cache.
s.setCharAt(1, 'E');
EXPECT_EQ(UnicodeString("hEllo"), s);
EXPECT_EQ('E', s[1]);
// Get the previous character which should invalidate the iterator cache.
EXPECT_EQ('h', s[0]);
EXPECT_EQ('o', s[4]);
}
} // namespace phonenumbers
} // namespace i18n
<commit_msg>CPP: Fix compilation error on Clang. Patch contributed by KushalP.<commit_after>// Copyright (C) 2011 The Libphonenumber Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Author: Philippe Liard
#include <iostream>
#include <gtest/gtest.h>
#include "phonenumbers/unicodestring.h"
using std::ostream;
namespace i18n {
namespace phonenumbers {
// Used by GTest to print the expected and actual results in case of failure.
ostream& operator<<(ostream& out, const UnicodeString& s) {
string utf8;
s.toUTF8String(utf8);
out << utf8;
return out;
}
TEST(UnicodeString, ToUTF8StringWithEmptyString) {
UnicodeString s;
string utf8;
s.toUTF8String(utf8);
EXPECT_EQ("", utf8);
}
TEST(UnicodeString, ToUTF8String) {
UnicodeString s("hello");
string utf8;
s.toUTF8String(utf8);
EXPECT_EQ("hello", utf8);
}
TEST(UnicodeString, ToUTF8StringWithNonAscii) {
UnicodeString s("\xEF\xBC\x95\xEF\xBC\x93" /* "53" */);
string utf8;
s.toUTF8String(utf8);
EXPECT_EQ("\xEF\xBC\x95\xEF\xBC\x93", utf8);
}
TEST(UnicodeString, AppendCodepoint) {
UnicodeString s;
s.append('h');
ASSERT_EQ(UnicodeString("h"), s);
s.append('e');
EXPECT_EQ(UnicodeString("he"), s);
}
TEST(UnicodeString, AppendCodepointWithNonAscii) {
UnicodeString s;
s.append(0xFF15 /* 5 */);
ASSERT_EQ(UnicodeString("\xEF\xBC\x95" /* 5 */), s);
s.append(0xFF13 /* 3 */);
EXPECT_EQ(UnicodeString("\xEF\xBC\x95\xEF\xBC\x93" /* 53 */), s);
}
TEST(UnicodeString, AppendUnicodeString) {
UnicodeString s;
s.append(UnicodeString("he"));
ASSERT_EQ(UnicodeString("he"), s);
s.append(UnicodeString("llo"));
EXPECT_EQ(UnicodeString("hello"), s);
}
TEST(UnicodeString, AppendUnicodeStringWithNonAscii) {
UnicodeString s;
s.append(UnicodeString("\xEF\xBC\x95" /* 5 */));
ASSERT_EQ(UnicodeString("\xEF\xBC\x95"), s);
s.append(UnicodeString("\xEF\xBC\x93" /* 3 */));
EXPECT_EQ(UnicodeString("\xEF\xBC\x95\xEF\xBC\x93" /* 53 */), s);
}
TEST(UnicodeString, IndexOf) {
UnicodeString s("hello");
EXPECT_EQ(0, s.indexOf('h'));
EXPECT_EQ(2, s.indexOf('l'));
EXPECT_EQ(4, s.indexOf('o'));
}
TEST(UnicodeString, IndexOfWithNonAscii) {
UnicodeString s("\xEF\xBC\x95\xEF\xBC\x93" /* 53 */);
EXPECT_EQ(1, s.indexOf(0xFF13 /* 3 */));
}
TEST(UnicodeString, ReplaceWithEmptyInputs) {
UnicodeString s;
s.replace(0, 0, UnicodeString(""));
EXPECT_EQ(UnicodeString(""), s);
}
TEST(UnicodeString, ReplaceWithEmptyReplacement) {
UnicodeString s("hello");
s.replace(0, 5, UnicodeString(""));
EXPECT_EQ(UnicodeString(""), s);
}
TEST(UnicodeString, ReplaceBegining) {
UnicodeString s("hello world");
s.replace(0, 5, UnicodeString("HELLO"));
EXPECT_EQ(UnicodeString("HELLO world"), s);
}
TEST(UnicodeString, ReplaceMiddle) {
UnicodeString s("hello world");
s.replace(5, 1, UnicodeString("AB"));
EXPECT_EQ(UnicodeString("helloABworld"), s);
}
TEST(UnicodeString, ReplaceEnd) {
UnicodeString s("hello world");
s.replace(10, 1, UnicodeString("AB"));
EXPECT_EQ(UnicodeString("hello worlAB"), s);
}
TEST(UnicodeString, ReplaceWithNonAscii) {
UnicodeString s("hello world");
s.replace(3, 2, UnicodeString("\xEF\xBC\x91\xEF\xBC\x90" /* 10 */));
EXPECT_EQ(UnicodeString("hel\xEF\xBC\x91\xEF\xBC\x90 world"), s);
}
TEST(UnicodeString, SetCharBegining) {
UnicodeString s("hello");
s.setCharAt(0, 'H');
EXPECT_EQ(UnicodeString("Hello"), s);
}
TEST(UnicodeString, SetCharMiddle) {
UnicodeString s("hello");
s.setCharAt(2, 'L');
EXPECT_EQ(UnicodeString("heLlo"), s);
}
TEST(UnicodeString, SetCharEnd) {
UnicodeString s("hello");
s.setCharAt(4, 'O');
EXPECT_EQ(UnicodeString("hellO"), s);
}
TEST(UnicodeString, SetCharWithNonAscii) {
UnicodeString s("hello");
s.setCharAt(4, 0xFF10 /* 0 */);
EXPECT_EQ(UnicodeString("hell\xEF\xBC\x90" /* 0 */), s);
}
TEST(UnicodeString, TempSubStringWithEmptyString) {
EXPECT_EQ(UnicodeString(""), UnicodeString().tempSubString(0, 0));
}
TEST(UnicodeString, TempSubStringWithInvalidInputs) {
UnicodeString s("hello");
// tempSubString() returns an empty unicode string if one of the provided
// paramaters is out of range.
EXPECT_EQ(UnicodeString(""), s.tempSubString(6));
EXPECT_EQ(UnicodeString(""), s.tempSubString(2, 6));
}
TEST(UnicodeString, TempSubString) {
UnicodeString s("hello");
EXPECT_EQ(UnicodeString(""), s.tempSubString(0, 0));
EXPECT_EQ(UnicodeString("h"), s.tempSubString(0, 1));
EXPECT_EQ(UnicodeString("hello"), s.tempSubString(0, 5));
EXPECT_EQ(UnicodeString("llo"), s.tempSubString(2, 3));
}
TEST(UnicodeString, TempSubStringWithNoLength) {
UnicodeString s("hello");
EXPECT_EQ(UnicodeString("hello"), s.tempSubString(0));
EXPECT_EQ(UnicodeString("llo"), s.tempSubString(2));
}
TEST(UnicodeString, TempSubStringWithNonAscii) {
UnicodeString s("hel\xEF\xBC\x91\xEF\xBC\x90" /* 10 */);
EXPECT_EQ(UnicodeString("\xEF\xBC\x91" /* 1 */), s.tempSubString(3, 1));
}
TEST(UnicodeString, OperatorEqual) {
UnicodeString s("hello");
s = UnicodeString("Hello");
EXPECT_EQ(UnicodeString("Hello"), s);
}
TEST(UnicodeString, OperatorEqualWithNonAscii) {
UnicodeString s("hello");
s = UnicodeString("hel\xEF\xBC\x91\xEF\xBC\x90" /* 10 */);
EXPECT_EQ(UnicodeString("hel\xEF\xBC\x91\xEF\xBC\x90"), s);
}
TEST(UnicodeString, OperatorBracket) {
UnicodeString s("hello");
EXPECT_EQ('h', s[0]);
EXPECT_EQ('e', s[1]);
EXPECT_EQ('l', s[2]);
EXPECT_EQ('l', s[3]);
EXPECT_EQ('o', s[4]);
}
TEST(UnicodeString, OperatorBracketWithNonAscii) {
UnicodeString s("hel\xEF\xBC\x91\xEF\xBC\x90" /* 10 */);
EXPECT_EQ('h', s[0]);
EXPECT_EQ('e', s[1]);
EXPECT_EQ('l', s[2]);
EXPECT_EQ(0xFF11 /* 1 */, s[3]);
EXPECT_EQ(0xFF10 /* 0 */, s[4]);
}
TEST(UnicodeString, OperatorBracketWithIteratorCacheInvalidation) {
UnicodeString s("hello");
EXPECT_EQ('h', s[0]);
EXPECT_EQ('e', s[1]);
// Modify the string which should invalidate the iterator cache.
s.setCharAt(1, 'E');
EXPECT_EQ(UnicodeString("hEllo"), s);
EXPECT_EQ('E', s[1]);
// Get the previous character which should invalidate the iterator cache.
EXPECT_EQ('h', s[0]);
EXPECT_EQ('o', s[4]);
}
} // namespace phonenumbers
} // namespace i18n
<|endoftext|>
|
<commit_before>/*
* Copyright 2012 Coherent Theory LLC
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, 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
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "bodegamodel.h"
#include "session.h"
#include "channelsjob.h"
#include <QtCore/QVariant>
#include <QtCore/QDebug>
#include <QtCore/QMetaEnum>
using namespace Bodega;
static const int DEFAULT_PAGE_SIZE = 50;
class Node
{
public:
Node(ChannelInfo channelInfo, AssetInfo assetInfo, Node *parent = 0);
~Node();
void appendChild(Node *child);
Node *child(int row);
int childCount() const;
int row() const;
Node *parent();
bool isChannel() const;
const AssetInfo& assetInfo() const;
const ChannelInfo& channelInfo() const;
void setCompletelyPopulated(bool complete);
bool isCompletelyPopulated() const;
int lastFetchedOffset() const;
void setLastFetchedOffset(int offset);
private:
QList<Node*> m_childNodes;
Node *m_parentNode;
ChannelInfo m_channelInfo;
AssetInfo m_assetInfo;
bool m_completelyPopulated;
int m_lastFetchedOffset;
};
Node::Node(ChannelInfo channelInfo, AssetInfo assetInfo, Node *parent)
: m_parentNode(parent),
m_assetInfo(assetInfo),
m_channelInfo(channelInfo),
m_completelyPopulated(false),
m_lastFetchedOffset(0)
{
}
Node::~Node()
{
qDeleteAll(m_childNodes);
}
void Node::appendChild(Node *item)
{
m_childNodes.append(item);
}
Node *Node::child(int row)
{
return m_childNodes.value(row);
}
int Node::childCount() const
{
return m_childNodes.count();
}
Node *Node::parent()
{
return m_parentNode;
}
int Node::row() const
{
if (m_parentNode)
return m_parentNode->m_childNodes.indexOf(const_cast<Node*>(this));
return 0;
}
const AssetInfo &Node::assetInfo() const
{
return m_assetInfo;
}
const ChannelInfo &Node::channelInfo() const
{
return m_channelInfo;
}
bool Node::isChannel() const
{
return !m_channelInfo.id.isEmpty();
}
void Node::setCompletelyPopulated(bool complete)
{
m_completelyPopulated = complete;
}
bool Node::isCompletelyPopulated() const
{
return m_completelyPopulated;
}
int Node::lastFetchedOffset() const
{
return m_lastFetchedOffset;
}
void Node::setLastFetchedOffset(int offset)
{
m_lastFetchedOffset = offset;
}
class Model::Private {
public:
Private()
{}
void init(Model *parent);
void channelsJobFinished(Bodega::NetworkJob *job);
void reloadFromNetwork();
Model *q;
Session *session;
QString topChannel;
QString searchQuery;
Node *topNode;
//NEVER access those values outside channelsJobFinished(), Session will delete them
//QPersistentModelIndex parent of this ChannelsJob 1/1 correspondence with Node
QHash<ChannelsJob *, QPersistentModelIndex> indexForJobs;
//job correspondednt to this index
QHash<QPersistentModelIndex, QList<ChannelsJob *> > jobsForIndex;
};
void Model::Private::init(Model *parent)
{
q = parent;
ChannelInfo rootChanInfo;
AssetInfo rootAssetInfo;
topNode = new Node(rootChanInfo, rootAssetInfo, 0);
session = 0;
}
void Model::Private::channelsJobFinished(Bodega::NetworkJob *job)
{
ChannelsJob *channelsJob = qobject_cast<ChannelsJob *>(job);
Q_ASSERT(channelsJob);
Q_ASSERT(indexForJobs.contains(channelsJob));
QPersistentModelIndex idx = indexForJobs.value(channelsJob);
//remove from bookkeeping
indexForJobs.remove(channelsJob);
jobsForIndex[idx].removeAll(channelsJob);
if (jobsForIndex[idx].isEmpty()) {
jobsForIndex.remove(idx);
}
if (channelsJob->channels().isEmpty() && channelsJob->assets().isEmpty()) {
return;
}
Node *node;
if (idx.isValid()) {
node = static_cast<Node*>(idx.internalPointer());
} else {
node = topNode;
}
node->setCompletelyPopulated(!channelsJob->hasMoreAssets());
node->setLastFetchedOffset(channelsJob->offset() + DEFAULT_PAGE_SIZE);
if (!channelsJob->channels().isEmpty()) {
q->beginInsertRows(idx, node->childCount(),
node->childCount() + channelsJob->channels().count()-1);
AssetInfo dummyAssetInfo;
foreach (const ChannelInfo &info, channelsJob->channels()) {
node->appendChild(new Node(info, dummyAssetInfo, node));
}
q->endInsertRows();
}
if (!channelsJob->assets().isEmpty()) {
q->beginInsertRows(idx, node->childCount(),
node->childCount() + channelsJob->assets().count()-1);
ChannelInfo dummyChannelInfo;
foreach (const AssetInfo &info, channelsJob->assets()) {
node->appendChild(new Node(dummyChannelInfo, info, node));
}
q->endInsertRows();
}
}
void Model::Private::reloadFromNetwork()
{
if (!session || !session->isAuthenticated()) {
return;
}
//FIXME: not safe, at this point most of jobs will be deleted by session
foreach (const QList<ChannelsJob *> &list, jobsForIndex) {
foreach (ChannelsJob *job, list) {
disconnect(job, 0, q, 0);
}
}
jobsForIndex.clear();
indexForJobs.clear();
//reset topnode, remove all the contents of the model
q->beginResetModel();
delete topNode;
ChannelInfo rootChanInfo;
AssetInfo rootAssetInfo;
topNode = new Node(rootChanInfo, rootAssetInfo, 0);
q->endResetModel();
ChannelsJob *channelsJob;
if (searchQuery.isEmpty()) {
channelsJob = session->channels(topChannel, 0, DEFAULT_PAGE_SIZE);
} else {
channelsJob = session->search(searchQuery, topChannel,
0, DEFAULT_PAGE_SIZE);
}
connect(channelsJob, SIGNAL(jobFinished(Bodega::NetworkJob *)),
q, SLOT(channelsJobFinished(Bodega::NetworkJob *)));
//TODO: manage errors
QPersistentModelIndex idx = QPersistentModelIndex(QModelIndex());
indexForJobs[channelsJob] = idx;
jobsForIndex[idx] << channelsJob;
}
Model::Model(QObject *parent)
: QAbstractItemModel(parent),
d(new Private)
{
d->init(this);
// set the role names based on the values of the DisplayRoles enum for
// the sake of QML
QHash<int, QByteArray> roles;
roles.insert(Qt::DisplayRole, "DisplayRole");
roles.insert(Qt::DecorationRole, "DecorationRole");
QMetaEnum e = metaObject()->enumerator(metaObject()->indexOfEnumerator("DisplayRoles"));
for (int i = 0; i < e.keyCount(); ++i) {
roles.insert(e.value(i), e.key(i));
}
setRoleNames(roles);
}
Model::~Model()
{
delete d;
}
bool Model::canFetchMore(const QModelIndex &parent) const
{
if (!parent.isValid()) {
return false;
}
Node *node = static_cast<Node*>(parent.internalPointer());
return node->isChannel() && !node->isCompletelyPopulated() &&
!d->jobsForIndex.contains(parent);
}
int Model::columnCount(const QModelIndex &parent) const
{
return 1;
}
QVariant Model::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
Node *node = static_cast<Node*>(index.internalPointer());
if (node->isChannel()) {
switch (role) {
case Qt::DisplayRole:
return node->channelInfo().name;
case ChannelIdRole:
return node->channelInfo().id;
case ChannelNameRole:
return node->channelInfo().name;
case ChannelDescriptionRole:
return node->channelInfo().description;
case ChannelAssetCountRole:
return node->channelInfo().assetCount;
case ImageTinyRole:
return node->channelInfo().images.value(Bodega::ImageTiny);
case ImageSmallRole:
return node->channelInfo().images.value(Bodega::ImageSmall);
case ImageMediumRole:
return node->channelInfo().images.value(Bodega::ImageMedium);
case ImageLargeRole:
return node->channelInfo().images.value(Bodega::ImageLarge);
case ImageHugeRole:
return node->channelInfo().images.value(Bodega::ImageHuge);
case ImagePreviewsRole:
return node->channelInfo().images.value(Bodega::ImagePreviews);
default:
return QVariant();
}
} else {
switch (role) {
case Qt::DisplayRole:
return node->assetInfo().name;
case AssetIdRole:
return node->assetInfo().id;
case AssetNameRole:
return node->assetInfo().name;
case AssetVersionRole:
return node->assetInfo().version;
case AssetFilenameRole:
return node->assetInfo().filename;
case ImageTinyRole:
return node->assetInfo().images.value(Bodega::ImageTiny);
case ImageSmallRole:
return node->assetInfo().images.value(Bodega::ImageSmall);
case ImageMediumRole:
return node->assetInfo().images.value(Bodega::ImageMedium);
case ImageLargeRole:
return node->assetInfo().images.value(Bodega::ImageLarge);
case ImageHugeRole:
return node->assetInfo().images.value(Bodega::ImageHuge);
case ImagePreviewsRole:
return node->assetInfo().images.value(Bodega::ImagePreviews);
case AssetDescriptionRole:
return node->assetInfo().description;
case AssetPointsRole:
return node->assetInfo().points;
default:
return QVariant();
}
}
}
void Model::fetchMore(const QModelIndex &parent)
{
if (!parent.isValid() || !d->session || !canFetchMore(parent) ||
!d->session->isAuthenticated()) {
return;
}
QPersistentModelIndex idx = QPersistentModelIndex(parent);
Node *node = static_cast<Node*>(idx.internalPointer());
ChannelsJob *channelsJob;
if (d->searchQuery.isEmpty()) {
channelsJob = d->session->channels(node->channelInfo().id,
node->lastFetchedOffset(),
DEFAULT_PAGE_SIZE);
} else {
channelsJob = d->session->search(d->searchQuery,
d->topChannel,
node->lastFetchedOffset(),
DEFAULT_PAGE_SIZE);
}
connect(channelsJob, SIGNAL(jobFinished(Bodega::NetworkJob *)),
this, SLOT(channelsJobFinished(Bodega::NetworkJob *)));
//TODO: manage errors
d->indexForJobs[channelsJob] = idx;
d->jobsForIndex[idx] << channelsJob;
}
Qt::ItemFlags Model::flags(const QModelIndex &index) const
{
if (index.isValid()) {
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
} else {
return Qt::NoItemFlags;
}
}
bool Model::hasChildren(const QModelIndex &parent) const
{
if (!parent.isValid()) {
return true;
}
return static_cast<Node*>(parent.internalPointer())->isChannel();
}
QVariant Model::headerData(int section, Qt::Orientation orientation,
int role) const
{
return QVariant();
}
QModelIndex Model::index(int row, int column,
const QModelIndex &parent) const
{
if (!hasIndex(row, column, parent)) {
return QModelIndex();
}
Node *parentNode;
if (!parent.isValid()) {
parentNode = d->topNode;
} else {
parentNode = static_cast<Node*>(parent.internalPointer());
}
Node *childNode = parentNode->child(row);
if (childNode) {
return createIndex(row, column, childNode);
} else {
return QModelIndex();
}
}
QMap<int, QVariant> Model::itemData(const QModelIndex &index) const
{
return QMap<int, QVariant>();
}
QModelIndex Model::parent(const QModelIndex &index) const
{
if (!index.isValid()) {
return QModelIndex();
}
Node *childNode = static_cast<Node*>(index.internalPointer());
Node *parentNode = childNode->parent();
if (parentNode == d->topNode) {
return QModelIndex();
}
return createIndex(parentNode->row(), 0, parentNode);
}
int Model::rowCount(const QModelIndex &parent) const
{
Node *parentNode;
if (parent.column() > 0) {
return 0;
}
if (!parent.isValid()) {
parentNode = d->topNode;
} else {
parentNode = static_cast<Node*>(parent.internalPointer());
}
return parentNode->childCount();
}
void Model::setSession(Session *session)
{
if (session == d->session) {
return;
}
if (d->session) {
//not connected directly, so disconnect everything
//delete d->channelsJob;
//TODO: delete all the jobs
}
d->session = session;
connect(d->session, SIGNAL(authenticated(bool)),
this, SLOT(reloadFromNetwork()));
d->reloadFromNetwork();
}
Session *Model::session() const
{
return d->session;
}
void Model::setTopChannel(const QString &topChannel)
{
if (d->topChannel == topChannel) {
return;
}
d->topChannel = topChannel;
if (!d->session) {
return;
}
//Search queries win against channel listing
if (!d->searchQuery.isEmpty()) {
d->reloadFromNetwork();
}
emit topChannelChanged();
}
QString Model::topChannel() const
{
return d->topChannel;
}
void Model::setSearchQuery(const QString &query)
{
if (d->searchQuery == query) {
return;
}
d->searchQuery = query;
if (!d->session) {
return;
}
d->reloadFromNetwork();
emit searchQueryChanged();
}
QString Model::searchQuery() const
{
return d->searchQuery;
}
#include "bodegamodel.moc"
<commit_msg>handle setting a second session a little more gracefully<commit_after>/*
* Copyright 2012 Coherent Theory LLC
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2, 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
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "bodegamodel.h"
#include "session.h"
#include "channelsjob.h"
#include <QtCore/QVariant>
#include <QtCore/QDebug>
#include <QtCore/QMetaEnum>
using namespace Bodega;
static const int DEFAULT_PAGE_SIZE = 50;
class Node
{
public:
Node(ChannelInfo channelInfo, AssetInfo assetInfo, Node *parent = 0);
~Node();
void appendChild(Node *child);
Node *child(int row);
int childCount() const;
int row() const;
Node *parent();
bool isChannel() const;
const AssetInfo& assetInfo() const;
const ChannelInfo& channelInfo() const;
void setCompletelyPopulated(bool complete);
bool isCompletelyPopulated() const;
int lastFetchedOffset() const;
void setLastFetchedOffset(int offset);
private:
QList<Node*> m_childNodes;
Node *m_parentNode;
ChannelInfo m_channelInfo;
AssetInfo m_assetInfo;
bool m_completelyPopulated;
int m_lastFetchedOffset;
};
Node::Node(ChannelInfo channelInfo, AssetInfo assetInfo, Node *parent)
: m_parentNode(parent),
m_assetInfo(assetInfo),
m_channelInfo(channelInfo),
m_completelyPopulated(false),
m_lastFetchedOffset(0)
{
}
Node::~Node()
{
qDeleteAll(m_childNodes);
}
void Node::appendChild(Node *item)
{
m_childNodes.append(item);
}
Node *Node::child(int row)
{
return m_childNodes.value(row);
}
int Node::childCount() const
{
return m_childNodes.count();
}
Node *Node::parent()
{
return m_parentNode;
}
int Node::row() const
{
if (m_parentNode) {
return m_parentNode->m_childNodes.indexOf(const_cast<Node*>(this));
}
return 0;
}
const AssetInfo &Node::assetInfo() const
{
return m_assetInfo;
}
const ChannelInfo &Node::channelInfo() const
{
return m_channelInfo;
}
bool Node::isChannel() const
{
return !m_channelInfo.id.isEmpty();
}
void Node::setCompletelyPopulated(bool complete)
{
m_completelyPopulated = complete;
}
bool Node::isCompletelyPopulated() const
{
return m_completelyPopulated;
}
int Node::lastFetchedOffset() const
{
return m_lastFetchedOffset;
}
void Node::setLastFetchedOffset(int offset)
{
m_lastFetchedOffset = offset;
}
class Model::Private {
public:
Private(Model *parent) :
q(parent),
session(0),
topNode(0)
{
init();
}
void init();
void channelsJobFinished(Bodega::NetworkJob *job);
void reloadFromNetwork();
Model *q;
Session *session;
QString topChannel;
QString searchQuery;
Node *topNode;
//NEVER access those values outside channelsJobFinished(), Session will delete them
//QPersistentModelIndex parent of this ChannelsJob 1/1 correspondence with Node
QHash<ChannelsJob *, QPersistentModelIndex> indexForJobs;
//job correspondednt to this index
QHash<QPersistentModelIndex, QList<ChannelsJob *> > jobsForIndex;
};
void Model::Private::init()
{
ChannelInfo rootChanInfo;
AssetInfo rootAssetInfo;
delete topNode;
topNode = new Node(rootChanInfo, rootAssetInfo, 0);
indexForJobs.clear();
jobsForIndex.clear();
session = 0;
}
void Model::Private::channelsJobFinished(Bodega::NetworkJob *job)
{
ChannelsJob *channelsJob = qobject_cast<ChannelsJob *>(job);
Q_ASSERT(channelsJob);
Q_ASSERT(indexForJobs.contains(channelsJob));
QPersistentModelIndex idx = indexForJobs.value(channelsJob);
//remove from bookkeeping
indexForJobs.remove(channelsJob);
jobsForIndex[idx].removeAll(channelsJob);
if (jobsForIndex[idx].isEmpty()) {
jobsForIndex.remove(idx);
}
if (channelsJob->channels().isEmpty() && channelsJob->assets().isEmpty()) {
return;
}
Node *node;
if (idx.isValid()) {
node = static_cast<Node*>(idx.internalPointer());
} else {
node = topNode;
}
node->setCompletelyPopulated(!channelsJob->hasMoreAssets());
node->setLastFetchedOffset(channelsJob->offset() + DEFAULT_PAGE_SIZE);
if (!channelsJob->channels().isEmpty()) {
q->beginInsertRows(idx, node->childCount(),
node->childCount() + channelsJob->channels().count()-1);
AssetInfo dummyAssetInfo;
foreach (const ChannelInfo &info, channelsJob->channels()) {
node->appendChild(new Node(info, dummyAssetInfo, node));
}
q->endInsertRows();
}
if (!channelsJob->assets().isEmpty()) {
q->beginInsertRows(idx, node->childCount(),
node->childCount() + channelsJob->assets().count()-1);
ChannelInfo dummyChannelInfo;
foreach (const AssetInfo &info, channelsJob->assets()) {
node->appendChild(new Node(dummyChannelInfo, info, node));
}
q->endInsertRows();
}
}
void Model::Private::reloadFromNetwork()
{
if (!session || !session->isAuthenticated()) {
return;
}
//FIXME: not safe, at this point most of jobs will be deleted by session
foreach (const QList<ChannelsJob *> &list, jobsForIndex) {
foreach (ChannelsJob *job, list) {
disconnect(job, 0, q, 0);
}
}
jobsForIndex.clear();
indexForJobs.clear();
//reset topnode, remove all the contents of the model
q->beginResetModel();
delete topNode;
ChannelInfo rootChanInfo;
AssetInfo rootAssetInfo;
topNode = new Node(rootChanInfo, rootAssetInfo, 0);
q->endResetModel();
ChannelsJob *channelsJob;
if (searchQuery.isEmpty()) {
channelsJob = session->channels(topChannel, 0, DEFAULT_PAGE_SIZE);
} else {
channelsJob = session->search(searchQuery, topChannel,
0, DEFAULT_PAGE_SIZE);
}
connect(channelsJob, SIGNAL(jobFinished(Bodega::NetworkJob *)),
q, SLOT(channelsJobFinished(Bodega::NetworkJob *)));
//TODO: manage errors
QPersistentModelIndex idx = QPersistentModelIndex(QModelIndex());
indexForJobs[channelsJob] = idx;
jobsForIndex[idx] << channelsJob;
}
Model::Model(QObject *parent)
: QAbstractItemModel(parent),
d(new Private(this))
{
// set the role names based on the values of the DisplayRoles enum for
// the sake of QML
QHash<int, QByteArray> roles;
roles.insert(Qt::DisplayRole, "DisplayRole");
roles.insert(Qt::DecorationRole, "DecorationRole");
QMetaEnum e = metaObject()->enumerator(metaObject()->indexOfEnumerator("DisplayRoles"));
for (int i = 0; i < e.keyCount(); ++i) {
roles.insert(e.value(i), e.key(i));
}
setRoleNames(roles);
}
Model::~Model()
{
delete d;
}
bool Model::canFetchMore(const QModelIndex &parent) const
{
if (!parent.isValid()) {
return false;
}
Node *node = static_cast<Node*>(parent.internalPointer());
return node->isChannel() && !node->isCompletelyPopulated() &&
!d->jobsForIndex.contains(parent);
}
int Model::columnCount(const QModelIndex &parent) const
{
return 1;
}
QVariant Model::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
Node *node = static_cast<Node*>(index.internalPointer());
if (node->isChannel()) {
switch (role) {
case Qt::DisplayRole:
return node->channelInfo().name;
case ChannelIdRole:
return node->channelInfo().id;
case ChannelNameRole:
return node->channelInfo().name;
case ChannelDescriptionRole:
return node->channelInfo().description;
case ChannelAssetCountRole:
return node->channelInfo().assetCount;
case ImageTinyRole:
return node->channelInfo().images.value(Bodega::ImageTiny);
case ImageSmallRole:
return node->channelInfo().images.value(Bodega::ImageSmall);
case ImageMediumRole:
return node->channelInfo().images.value(Bodega::ImageMedium);
case ImageLargeRole:
return node->channelInfo().images.value(Bodega::ImageLarge);
case ImageHugeRole:
return node->channelInfo().images.value(Bodega::ImageHuge);
case ImagePreviewsRole:
return node->channelInfo().images.value(Bodega::ImagePreviews);
default:
return QVariant();
}
} else {
switch (role) {
case Qt::DisplayRole:
return node->assetInfo().name;
case AssetIdRole:
return node->assetInfo().id;
case AssetNameRole:
return node->assetInfo().name;
case AssetVersionRole:
return node->assetInfo().version;
case AssetFilenameRole:
return node->assetInfo().filename;
case ImageTinyRole:
return node->assetInfo().images.value(Bodega::ImageTiny);
case ImageSmallRole:
return node->assetInfo().images.value(Bodega::ImageSmall);
case ImageMediumRole:
return node->assetInfo().images.value(Bodega::ImageMedium);
case ImageLargeRole:
return node->assetInfo().images.value(Bodega::ImageLarge);
case ImageHugeRole:
return node->assetInfo().images.value(Bodega::ImageHuge);
case ImagePreviewsRole:
return node->assetInfo().images.value(Bodega::ImagePreviews);
case AssetDescriptionRole:
return node->assetInfo().description;
case AssetPointsRole:
return node->assetInfo().points;
default:
return QVariant();
}
}
}
void Model::fetchMore(const QModelIndex &parent)
{
if (!parent.isValid() || !d->session || !canFetchMore(parent) ||
!d->session->isAuthenticated()) {
return;
}
QPersistentModelIndex idx = QPersistentModelIndex(parent);
Node *node = static_cast<Node*>(idx.internalPointer());
ChannelsJob *channelsJob;
if (d->searchQuery.isEmpty()) {
channelsJob = d->session->channels(node->channelInfo().id,
node->lastFetchedOffset(),
DEFAULT_PAGE_SIZE);
} else {
channelsJob = d->session->search(d->searchQuery,
d->topChannel,
node->lastFetchedOffset(),
DEFAULT_PAGE_SIZE);
}
connect(channelsJob, SIGNAL(jobFinished(Bodega::NetworkJob *)),
this, SLOT(channelsJobFinished(Bodega::NetworkJob *)));
//TODO: manage errors
d->indexForJobs[channelsJob] = idx;
d->jobsForIndex[idx] << channelsJob;
}
Qt::ItemFlags Model::flags(const QModelIndex &index) const
{
if (index.isValid()) {
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
} else {
return Qt::NoItemFlags;
}
}
bool Model::hasChildren(const QModelIndex &parent) const
{
if (!parent.isValid()) {
return true;
}
return static_cast<Node*>(parent.internalPointer())->isChannel();
}
QVariant Model::headerData(int section, Qt::Orientation orientation,
int role) const
{
return QVariant();
}
QModelIndex Model::index(int row, int column,
const QModelIndex &parent) const
{
if (!hasIndex(row, column, parent)) {
return QModelIndex();
}
Node *parentNode;
if (!parent.isValid()) {
parentNode = d->topNode;
} else {
parentNode = static_cast<Node*>(parent.internalPointer());
}
Node *childNode = parentNode->child(row);
if (childNode) {
return createIndex(row, column, childNode);
} else {
return QModelIndex();
}
}
QMap<int, QVariant> Model::itemData(const QModelIndex &index) const
{
return QMap<int, QVariant>();
}
QModelIndex Model::parent(const QModelIndex &index) const
{
if (!index.isValid()) {
return QModelIndex();
}
Node *childNode = static_cast<Node*>(index.internalPointer());
Node *parentNode = childNode->parent();
if (parentNode == d->topNode) {
return QModelIndex();
}
return createIndex(parentNode->row(), 0, parentNode);
}
int Model::rowCount(const QModelIndex &parent) const
{
Node *parentNode;
if (parent.column() > 0) {
return 0;
}
if (!parent.isValid()) {
parentNode = d->topNode;
} else {
parentNode = static_cast<Node*>(parent.internalPointer());
}
return parentNode->childCount();
}
void Model::setSession(Session *session)
{
if (session == d->session) {
return;
}
if (d->session) {
disconnect(d->session, 0, this, 0);
d->init();
beginResetModel();
endResetModel();
}
d->session = session;
connect(d->session, SIGNAL(authenticated(bool)),
this, SLOT(reloadFromNetwork()));
d->reloadFromNetwork();
}
Session *Model::session() const
{
return d->session;
}
void Model::setTopChannel(const QString &topChannel)
{
if (d->topChannel == topChannel) {
return;
}
d->topChannel = topChannel;
if (!d->session) {
return;
}
//Search queries win against channel listing
if (!d->searchQuery.isEmpty()) {
d->reloadFromNetwork();
}
emit topChannelChanged();
}
QString Model::topChannel() const
{
return d->topChannel;
}
void Model::setSearchQuery(const QString &query)
{
if (d->searchQuery == query) {
return;
}
d->searchQuery = query;
if (!d->session) {
return;
}
d->reloadFromNetwork();
emit searchQueryChanged();
}
QString Model::searchQuery() const
{
return d->searchQuery;
}
#include "bodegamodel.moc"
<|endoftext|>
|
<commit_before><commit_msg>Changed data file to start with ".", don't restore that<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2011 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 "chrome/browser/external_protocol/external_protocol_handler.h"
#include "content/test/test_browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
using content::BrowserThread;
class FakeExternalProtocolHandlerWorker
: public ShellIntegration::DefaultProtocolClientWorker {
public:
FakeExternalProtocolHandlerWorker(
ShellIntegration::DefaultWebClientObserver* observer,
const std::string& protocol,
ShellIntegration::DefaultWebClientState os_state)
: ShellIntegration::DefaultProtocolClientWorker(observer, protocol),
os_state_(os_state) {}
private:
virtual ShellIntegration::DefaultWebClientState CheckIsDefault() {
return os_state_;
}
virtual void SetAsDefault() {}
ShellIntegration::DefaultWebClientState os_state_;
};
class FakeExternalProtocolHandlerDelegate
: public ExternalProtocolHandler::Delegate {
public:
FakeExternalProtocolHandlerDelegate()
: block_state_(ExternalProtocolHandler::BLOCK),
os_state_(ShellIntegration::UNKNOWN_DEFAULT_WEB_CLIENT),
has_launched_(false),
has_prompted_(false),
has_blocked_ (false) {}
virtual ShellIntegration::DefaultProtocolClientWorker* CreateShellWorker(
ShellIntegration::DefaultWebClientObserver* observer,
const std::string& protocol) {
return new FakeExternalProtocolHandlerWorker(observer, protocol, os_state_);
}
virtual ExternalProtocolHandler::BlockState GetBlockState(
const std::string& scheme) { return block_state_; }
virtual void BlockRequest() {
ASSERT_TRUE(block_state_ == ExternalProtocolHandler::BLOCK ||
os_state_ == ShellIntegration::IS_DEFAULT_WEB_CLIENT);
has_blocked_ = true;
}
virtual void RunExternalProtocolDialog(const GURL& url,
int render_process_host_id,
int routing_id) {
ASSERT_EQ(block_state_, ExternalProtocolHandler::UNKNOWN);
ASSERT_NE(os_state_, ShellIntegration::IS_DEFAULT_WEB_CLIENT);
has_prompted_ = true;
}
virtual void LaunchUrlWithoutSecurityCheck(const GURL& url) {
ASSERT_EQ(block_state_, ExternalProtocolHandler::DONT_BLOCK);
ASSERT_NE(os_state_, ShellIntegration::IS_DEFAULT_WEB_CLIENT);
has_launched_ = true;
}
virtual void FinishedProcessingCheck() {
MessageLoop::current()->Quit();
}
void set_os_state(ShellIntegration::DefaultWebClientState value) {
os_state_ = value;
}
void set_block_state(ExternalProtocolHandler::BlockState value) {
block_state_ = value;
}
bool has_launched() { return has_launched_; }
bool has_prompted() { return has_prompted_; }
bool has_blocked() { return has_blocked_; }
private:
ExternalProtocolHandler::BlockState block_state_;
ShellIntegration::DefaultWebClientState os_state_;
bool has_launched_;
bool has_prompted_;
bool has_blocked_;
};
class ExternalProtocolHandlerTest : public testing::Test {
protected:
ExternalProtocolHandlerTest()
: ui_thread_(BrowserThread::UI, MessageLoop::current()),
file_thread_(BrowserThread::FILE) {}
virtual void SetUp() {
file_thread_.Start();
}
void DoTest(ExternalProtocolHandler::BlockState block_state,
ShellIntegration::DefaultWebClientState os_state,
bool should_prompt, bool should_launch, bool should_block) {
GURL url("mailto:test@test.com");
ASSERT_FALSE(delegate_.has_prompted());
ASSERT_FALSE(delegate_.has_launched());
ASSERT_FALSE(delegate_.has_blocked());
delegate_.set_block_state(block_state);
delegate_.set_os_state(os_state);
ExternalProtocolHandler::LaunchUrlWithDelegate(url, 0, 0, &delegate_);
if (block_state != ExternalProtocolHandler::BLOCK)
MessageLoop::current()->Run();
ASSERT_EQ(should_prompt, delegate_.has_prompted());
ASSERT_EQ(should_launch, delegate_.has_launched());
ASSERT_EQ(should_block, delegate_.has_blocked());
}
MessageLoopForUI ui_message_loop_;
content::TestBrowserThread ui_thread_;
content::TestBrowserThread file_thread_;
FakeExternalProtocolHandlerDelegate delegate_;
};
TEST_F(ExternalProtocolHandlerTest, TestLaunchSchemeBlockedChromeDefault) {
DoTest(ExternalProtocolHandler::BLOCK,
ShellIntegration::IS_DEFAULT_WEB_CLIENT,
false, false, true);
}
TEST_F(ExternalProtocolHandlerTest, TestLaunchSchemeBlockedChromeNotDefault) {
DoTest(ExternalProtocolHandler::BLOCK,
ShellIntegration::NOT_DEFAULT_WEB_CLIENT,
false, false, true);
}
TEST_F(ExternalProtocolHandlerTest, TestLaunchSchemeBlockedChromeUnknown) {
DoTest(ExternalProtocolHandler::BLOCK,
ShellIntegration::UNKNOWN_DEFAULT_WEB_CLIENT,
false, false, true);
}
TEST_F(ExternalProtocolHandlerTest, TestLaunchSchemeUnBlockedChromeDefault) {
DoTest(ExternalProtocolHandler::DONT_BLOCK,
ShellIntegration::IS_DEFAULT_WEB_CLIENT,
false, false, true);
}
TEST_F(ExternalProtocolHandlerTest, TestLaunchSchemeUnBlockedChromeNotDefault) {
DoTest(ExternalProtocolHandler::DONT_BLOCK,
ShellIntegration::NOT_DEFAULT_WEB_CLIENT,
false, true, false);
}
TEST_F(ExternalProtocolHandlerTest, TestLaunchSchemeUnBlockedChromeUnknown) {
DoTest(ExternalProtocolHandler::DONT_BLOCK,
ShellIntegration::UNKNOWN_DEFAULT_WEB_CLIENT,
false, true, false);
}
TEST_F(ExternalProtocolHandlerTest, TestLaunchSchemeUnknownChromeDefault) {
DoTest(ExternalProtocolHandler::UNKNOWN,
ShellIntegration::IS_DEFAULT_WEB_CLIENT,
false, false, true);
}
TEST_F(ExternalProtocolHandlerTest, TestLaunchSchemeUnknownChromeNotDefault) {
DoTest(ExternalProtocolHandler::UNKNOWN,
ShellIntegration::NOT_DEFAULT_WEB_CLIENT,
true, false, false);
}
TEST_F(ExternalProtocolHandlerTest, TestLaunchSchemeUnknownChromeUnknown) {
DoTest(ExternalProtocolHandler::UNKNOWN,
ShellIntegration::UNKNOWN_DEFAULT_WEB_CLIENT,
true, false, false);
}
<commit_msg>Isolate ExternalProtocolHandlerTest from other tests in the TearDown method.<commit_after>// Copyright (c) 2011 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 "chrome/browser/external_protocol/external_protocol_handler.h"
#include "content/test/test_browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
using content::BrowserThread;
class FakeExternalProtocolHandlerWorker
: public ShellIntegration::DefaultProtocolClientWorker {
public:
FakeExternalProtocolHandlerWorker(
ShellIntegration::DefaultWebClientObserver* observer,
const std::string& protocol,
ShellIntegration::DefaultWebClientState os_state)
: ShellIntegration::DefaultProtocolClientWorker(observer, protocol),
os_state_(os_state) {}
private:
virtual ShellIntegration::DefaultWebClientState CheckIsDefault() {
return os_state_;
}
virtual void SetAsDefault() {}
ShellIntegration::DefaultWebClientState os_state_;
};
class FakeExternalProtocolHandlerDelegate
: public ExternalProtocolHandler::Delegate {
public:
FakeExternalProtocolHandlerDelegate()
: block_state_(ExternalProtocolHandler::BLOCK),
os_state_(ShellIntegration::UNKNOWN_DEFAULT_WEB_CLIENT),
has_launched_(false),
has_prompted_(false),
has_blocked_ (false) {}
virtual ShellIntegration::DefaultProtocolClientWorker* CreateShellWorker(
ShellIntegration::DefaultWebClientObserver* observer,
const std::string& protocol) {
return new FakeExternalProtocolHandlerWorker(observer, protocol, os_state_);
}
virtual ExternalProtocolHandler::BlockState GetBlockState(
const std::string& scheme) { return block_state_; }
virtual void BlockRequest() {
ASSERT_TRUE(block_state_ == ExternalProtocolHandler::BLOCK ||
os_state_ == ShellIntegration::IS_DEFAULT_WEB_CLIENT);
has_blocked_ = true;
}
virtual void RunExternalProtocolDialog(const GURL& url,
int render_process_host_id,
int routing_id) {
ASSERT_EQ(block_state_, ExternalProtocolHandler::UNKNOWN);
ASSERT_NE(os_state_, ShellIntegration::IS_DEFAULT_WEB_CLIENT);
has_prompted_ = true;
}
virtual void LaunchUrlWithoutSecurityCheck(const GURL& url) {
ASSERT_EQ(block_state_, ExternalProtocolHandler::DONT_BLOCK);
ASSERT_NE(os_state_, ShellIntegration::IS_DEFAULT_WEB_CLIENT);
has_launched_ = true;
}
virtual void FinishedProcessingCheck() {
MessageLoop::current()->Quit();
}
void set_os_state(ShellIntegration::DefaultWebClientState value) {
os_state_ = value;
}
void set_block_state(ExternalProtocolHandler::BlockState value) {
block_state_ = value;
}
bool has_launched() { return has_launched_; }
bool has_prompted() { return has_prompted_; }
bool has_blocked() { return has_blocked_; }
private:
ExternalProtocolHandler::BlockState block_state_;
ShellIntegration::DefaultWebClientState os_state_;
bool has_launched_;
bool has_prompted_;
bool has_blocked_;
};
class ExternalProtocolHandlerTest : public testing::Test {
protected:
ExternalProtocolHandlerTest()
: ui_thread_(BrowserThread::UI, MessageLoop::current()),
file_thread_(BrowserThread::FILE) {}
virtual void SetUp() {
file_thread_.Start();
}
virtual void TearDown() {
// Ensure that g_accept_requests gets set back to true after test execution.
ExternalProtocolHandler::PermitLaunchUrl();
}
void DoTest(ExternalProtocolHandler::BlockState block_state,
ShellIntegration::DefaultWebClientState os_state,
bool should_prompt, bool should_launch, bool should_block) {
GURL url("mailto:test@test.com");
ASSERT_FALSE(delegate_.has_prompted());
ASSERT_FALSE(delegate_.has_launched());
ASSERT_FALSE(delegate_.has_blocked());
delegate_.set_block_state(block_state);
delegate_.set_os_state(os_state);
ExternalProtocolHandler::LaunchUrlWithDelegate(url, 0, 0, &delegate_);
if (block_state != ExternalProtocolHandler::BLOCK)
MessageLoop::current()->Run();
ASSERT_EQ(should_prompt, delegate_.has_prompted());
ASSERT_EQ(should_launch, delegate_.has_launched());
ASSERT_EQ(should_block, delegate_.has_blocked());
}
MessageLoopForUI ui_message_loop_;
content::TestBrowserThread ui_thread_;
content::TestBrowserThread file_thread_;
FakeExternalProtocolHandlerDelegate delegate_;
};
TEST_F(ExternalProtocolHandlerTest, TestLaunchSchemeBlockedChromeDefault) {
DoTest(ExternalProtocolHandler::BLOCK,
ShellIntegration::IS_DEFAULT_WEB_CLIENT,
false, false, true);
}
TEST_F(ExternalProtocolHandlerTest, TestLaunchSchemeBlockedChromeNotDefault) {
DoTest(ExternalProtocolHandler::BLOCK,
ShellIntegration::NOT_DEFAULT_WEB_CLIENT,
false, false, true);
}
TEST_F(ExternalProtocolHandlerTest, TestLaunchSchemeBlockedChromeUnknown) {
DoTest(ExternalProtocolHandler::BLOCK,
ShellIntegration::UNKNOWN_DEFAULT_WEB_CLIENT,
false, false, true);
}
TEST_F(ExternalProtocolHandlerTest, TestLaunchSchemeUnBlockedChromeDefault) {
DoTest(ExternalProtocolHandler::DONT_BLOCK,
ShellIntegration::IS_DEFAULT_WEB_CLIENT,
false, false, true);
}
TEST_F(ExternalProtocolHandlerTest, TestLaunchSchemeUnBlockedChromeNotDefault) {
DoTest(ExternalProtocolHandler::DONT_BLOCK,
ShellIntegration::NOT_DEFAULT_WEB_CLIENT,
false, true, false);
}
TEST_F(ExternalProtocolHandlerTest, TestLaunchSchemeUnBlockedChromeUnknown) {
DoTest(ExternalProtocolHandler::DONT_BLOCK,
ShellIntegration::UNKNOWN_DEFAULT_WEB_CLIENT,
false, true, false);
}
TEST_F(ExternalProtocolHandlerTest, TestLaunchSchemeUnknownChromeDefault) {
DoTest(ExternalProtocolHandler::UNKNOWN,
ShellIntegration::IS_DEFAULT_WEB_CLIENT,
false, false, true);
}
TEST_F(ExternalProtocolHandlerTest, TestLaunchSchemeUnknownChromeNotDefault) {
DoTest(ExternalProtocolHandler::UNKNOWN,
ShellIntegration::NOT_DEFAULT_WEB_CLIENT,
true, false, false);
}
TEST_F(ExternalProtocolHandlerTest, TestLaunchSchemeUnknownChromeUnknown) {
DoTest(ExternalProtocolHandler::UNKNOWN,
ShellIntegration::UNKNOWN_DEFAULT_WEB_CLIENT,
true, false, false);
}
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11, c++14
// <memory>
// template <class _Tp>
// void destroy_at(_Tp*);
#include <memory>
#include <cstdlib>
#include <cassert>
struct Counted {
static int count;
static void reset() { count = 0; }
Counted() { ++count; }
Counted(Counted const&) { ++count; }
~Counted() { --count; }
friend void operator&(Counted) = delete;
};
int Counted::count = 0;
struct VCounted {
static int count;
static void reset() { count = 0; }
VCounted() { ++count; }
VCounted(VCounted const&) { ++count; }
virtual ~VCounted() { --count; }
friend void operator&(VCounted) = delete;
};
int VCounted::count = 0;
struct DCounted : VCounted {
friend void operator&(DCounted) = delete;
};
int main()
{
{
void* mem1 = std::malloc(sizeof(Counted));
void* mem2 = std::malloc(sizeof(Counted));
assert(mem1 && mem2);
assert(Counted::count == 0);
Counted* ptr1 = ::new(mem1) Counted();
Counted* ptr2 = ::new(mem2) Counted();
assert(Counted::count == 2);
std::destroy_at(ptr1);
assert(Counted::count == 1);
std::destroy_at(ptr2);
assert(Counted::count == 0);
}
{
void* mem1 = std::malloc(sizeof(DCounted));
void* mem2 = std::malloc(sizeof(DCounted));
assert(mem1 && mem2);
assert(DCounted::count == 0);
DCounted* ptr1 = ::new(mem1) DCounted();
DCounted* ptr2 = ::new(mem2) DCounted();
assert(DCounted::count == 2);
assert(VCounted::count == 2);
std::destroy_at(ptr1);
assert(VCounted::count == 1);
std::destroy_at(ptr2);
assert(VCounted::count == 0);
}
}
<commit_msg>Fix memory leak in test.<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11, c++14
// <memory>
// template <class _Tp>
// void destroy_at(_Tp*);
#include <memory>
#include <cstdlib>
#include <cassert>
struct Counted {
static int count;
static void reset() { count = 0; }
Counted() { ++count; }
Counted(Counted const&) { ++count; }
~Counted() { --count; }
friend void operator&(Counted) = delete;
};
int Counted::count = 0;
struct VCounted {
static int count;
static void reset() { count = 0; }
VCounted() { ++count; }
VCounted(VCounted const&) { ++count; }
virtual ~VCounted() { --count; }
friend void operator&(VCounted) = delete;
};
int VCounted::count = 0;
struct DCounted : VCounted {
friend void operator&(DCounted) = delete;
};
int main()
{
{
void* mem1 = std::malloc(sizeof(Counted));
void* mem2 = std::malloc(sizeof(Counted));
assert(mem1 && mem2);
assert(Counted::count == 0);
Counted* ptr1 = ::new(mem1) Counted();
Counted* ptr2 = ::new(mem2) Counted();
assert(Counted::count == 2);
std::destroy_at(ptr1);
assert(Counted::count == 1);
std::destroy_at(ptr2);
assert(Counted::count == 0);
std::free(mem1);
std::free(mem2);
}
{
void* mem1 = std::malloc(sizeof(DCounted));
void* mem2 = std::malloc(sizeof(DCounted));
assert(mem1 && mem2);
assert(DCounted::count == 0);
DCounted* ptr1 = ::new(mem1) DCounted();
DCounted* ptr2 = ::new(mem2) DCounted();
assert(DCounted::count == 2);
assert(VCounted::count == 2);
std::destroy_at(ptr1);
assert(VCounted::count == 1);
std::destroy_at(ptr2);
assert(VCounted::count == 0);
std::free(mem1);
std::free(mem2);
}
}
<|endoftext|>
|
<commit_before>/**
* @brief Handle on the StdAir library context
* @author Anh Quan Nguyen <quannaus@users.sourceforge.net>
* @date 20/01/2010
* @detail StdAir aims at providing a clean API, and the corresponding
* C++ implementation, for the basis of Airline IT Business Object
* Model (BOM), that is, to be used by several other Open Source
* projects, such as RMOL and OpenTREP<br>
* Install the StdAir library for Airline IT Standard C++ fundaments.
*/
#ifndef __STDAIR_STDAIR_HPP
#define __STDAIR_STDAIR_HPP
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// StdAir
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
namespace stdair {
/// Forward declarations
class BomRoot;
/**
* @brief Interface for the STDAIR Services
*/
class STDAIR_Service {
public:
// ////////// Constructors and destructors //////////
/**
* @brief Default constructor.
*/
STDAIR_Service ();
/**
* @brief Constructor.
* <br>The init() method is called; see the corresponding
* documentation for more details.
* <br>Moreover, a reference on an output stream is given, so
* that log outputs can be directed onto that stream.
* @param[in] const BasLogParams& Parameters for the output log stream.
*/
STDAIR_Service (const BasLogParams&);
/**
* @brief Constructor.
* <br>The init() method is called; see the corresponding
* documentation for more details.
* <br>A reference on an output stream is given, so
* that log outputs can be directed onto that stream.
* <br>Moreover, database connection parameters are given, so
* that database requests can use the corresponding access.
* @param[in] const BasLogParams& Parameters for the output log stream.
* @param[in] const BasDBParams& Parameters for the database session.
*/
STDAIR_Service (const BasLogParams&, const BasDBParams&);
/**
* @brief Destructor.
*/
~STDAIR_Service();
// ///////////////// Getters ///////////////////
/**
* @brief Get a reference on the BomRoot object.
* <br>If the service context has not been initialised, that
* method throws an exception (failing assertion).
* @param[out] BomRoot& Reference on the BomRoot.
*/
BomRoot& getBomRoot () const {
return _bomRoot;
}
private:
// /////// Construction and Destruction helper methods ///////
/**
* @brief Default copy constructor.
* @param[in] const STDAIR_Service& Reference on the STDAIR_Service handler
* to be copied.
*/
STDAIR_Service (const STDAIR_Service&);
/**
* @brief Initialise the log.
* @param[in] const BasLogParams& Parameters for the output log stream.
*/
void logInit (const BasLogParams&);
/**
* @brief Initialise the database session.
* @param[in] const BasDBParams& Parameters for the database session.
*/
void dbInit (const BasDBParams&);
/**
* @brief Initialise.
* <br>The static instance of the log service (Logger object) is created.
* <br>The static instance of the database session manager
* (DBSessionManager object) is created.
* <br>The static instance of the FacSupervisor object, itself referencing
* all the other objects (factories and BOM), is created.
* <br>As those three objects are static, there is no need to store them
* in any service context. However, some lock mechanism may be needed
* in order to secure the access to the corresponding resources.
*/
void init ();
/**
* @brief Finalise.
*/
void finalise ();
private:
// /////////////// Attributes ///////////////
/**
* @brief Root of the BOM tree.
*/
BomRoot& _bomRoot;
};
}
#endif // __STDAIR_STDAIR_HPP
<commit_msg>[Branch 0.9.0][API] Fixed a few compilation errors with the new API.<commit_after>/**
* @brief Handle on the StdAir library context
* @author Anh Quan Nguyen <quannaus@users.sourceforge.net>
* @date 20/01/2010
* @detail StdAir aims at providing a clean API, and the corresponding
* C++ implementation, for the basis of Airline IT Business Object
* Model (BOM), that is, to be used by several other Open Source
* projects, such as RMOL and OpenTREP<br>
* Install the StdAir library for Airline IT Standard C++ fundaments.
*/
#ifndef __STDAIR_STDAIR_HPP
#define __STDAIR_STDAIR_HPP
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// StdAir
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
#include <stdair/stdair_service_types.hpp>
namespace stdair {
/// Forward declarations
class BomRoot;
/**
* @brief Interface for the STDAIR Services
*/
class STDAIR_Service {
public:
// ////////// Constructors and destructors //////////
/**
* @brief Default constructor.
*/
STDAIR_Service ();
/**
* @brief Constructor.
* <br>The init() method is called; see the corresponding
* documentation for more details.
* <br>Moreover, a reference on an output stream is given, so
* that log outputs can be directed onto that stream.
* @param[in] const BasLogParams& Parameters for the output log stream.
*/
STDAIR_Service (const BasLogParams&);
/**
* @brief Constructor.
* <br>The init() method is called; see the corresponding
* documentation for more details.
* <br>A reference on an output stream is given, so
* that log outputs can be directed onto that stream.
* <br>Moreover, database connection parameters are given, so
* that database requests can use the corresponding access.
* @param[in] const BasLogParams& Parameters for the output log stream.
* @param[in] const BasDBParams& Parameters for the database session.
*/
STDAIR_Service (const BasLogParams&, const BasDBParams&);
/**
* @brief Destructor.
*/
~STDAIR_Service();
// ///////////////// Getters ///////////////////
/**
* @brief Get a reference on the BomRoot object.
* <br>If the service context has not been initialised, that
* method throws an exception (failing assertion).
* @param[out] BomRoot& Reference on the BomRoot.
*/
BomRoot& getBomRoot () const {
return _bomRoot;
}
private:
// /////// Construction and Destruction helper methods ///////
/**
* @brief Default copy constructor.
* @param[in] const STDAIR_Service& Reference on the STDAIR_Service handler
* to be copied.
*/
STDAIR_Service (const STDAIR_Service&);
/**
* @brief Initialise the log.
* @param[in] const BasLogParams& Parameters for the output log stream.
*/
void logInit (const BasLogParams&);
/**
* @brief Initialise the database session.
* @param[in] const BasDBParams& Parameters for the database session.
*/
void dbInit (const BasDBParams&);
/**
* @brief Initialise.
* <br>The static instance of the log service (Logger object) is created.
* <br>The static instance of the database session manager
* (DBSessionManager object) is created.
* <br>The static instance of the FacSupervisor object, itself referencing
* all the other objects (factories and BOM), is created.
* <br>As those three objects are static, there is no need to store them
* in any service context. However, some lock mechanism may be needed
* in order to secure the access to the corresponding resources.
*/
void init ();
/**
* @brief Finalise.
*/
void finalise ();
private:
// /////////////// Attributes ///////////////
/**
* @brief Root of the BOM tree.
*/
BomRoot& _bomRoot;
};
}
#endif // __STDAIR_STDAIR_HPP
<|endoftext|>
|
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include <algorithm>
#include <iterator>
#include <map>
#include <string>
#include "caf/string_view.hpp"
namespace caf {
/// Maps strings to values of type `V`, but unlike `std::map<std::string, V>`
/// accepts `string_view` for looking up keys efficiently.
template <class V>
class dictionary {
public:
// -- member types ----------------------------------------------------------
using map_type = std::map<std::string, V>;
using key_type = typename map_type::key_type;
using mapped_type = typename map_type::mapped_type;
using value_type = typename map_type::value_type;
using allocator_type = typename map_type::allocator_type;
using size_type = typename map_type::size_type;
using difference_type = typename map_type::difference_type;
using reference = typename map_type::reference;
using const_reference = typename map_type::const_reference;
using pointer = typename map_type::pointer;
using const_pointer = typename map_type::const_pointer;
using iterator = typename map_type::iterator;
using const_iterator = typename map_type::const_iterator;
using reverse_iterator = typename map_type::reverse_iterator;
using const_reverse_iterator = typename map_type::const_reverse_iterator;
using iterator_bool_pair = std::pair<iterator, bool>;
struct mapped_type_less {
inline bool operator()(const value_type& x, string_view y) const {
return x.first < y;
}
inline bool operator()(const value_type& x, const value_type& y) const {
return x.first < y.first;
}
inline bool operator()(string_view x, const value_type& y) const {
return x < y.first;
}
};
// -- constructors, destructors, and assignment operators -------------------
dictionary() = default;
dictionary(dictionary&&) = default;
dictionary(const dictionary&) = default;
dictionary(std::initializer_list<value_type> xs) : xs_(xs) {
// nop
}
template <class InputIterator>
dictionary(InputIterator first, InputIterator last) : xs_(first, last) {
// nop
}
dictionary& operator=(dictionary&&) = default;
dictionary& operator=(const dictionary&) = default;
// -- iterator access --------------------------------------------------------
iterator begin() noexcept {
return xs_.begin();
}
const_iterator begin() const noexcept {
return xs_.begin();
}
const_iterator cbegin() const noexcept {
return begin();
}
reverse_iterator rbegin() noexcept {
return xs_.rbegin();
}
const_reverse_iterator rbegin() const noexcept {
return xs_.rbegin();
}
const_reverse_iterator crbegin() const noexcept {
return rbegin();
}
iterator end() noexcept {
return xs_.end();
}
const_iterator end() const noexcept {
return xs_.end();
}
const_iterator cend() const noexcept {
return end();
}
reverse_iterator rend() noexcept {
return xs_.rend();
}
const_reverse_iterator rend() const noexcept {
return xs_.rend();
}
const_reverse_iterator crend() const noexcept {
return rend();
}
// -- size -------------------------------------------------------------------
bool empty() const noexcept {
return xs_.empty();
}
size_type size() const noexcept {
return xs_.size();
}
// -- access to members ------------------------------------------------------
/// Gives raw access to the underlying container.
map_type& container() noexcept {
return xs_;
}
/// Gives raw access to the underlying container.
const map_type& container() const noexcept {
return xs_;
}
// -- modifiers -------------------------------------------------------------
void clear() noexcept {
return xs_.clear();
}
void swap(dictionary& other) {
xs_.swap(other.xs_);
}
// -- insertion --------------------------------------------------------------
template <class K, class T>
iterator_bool_pair emplace(K&& key, T&& value) {
auto i = lower_bound(key);
if (i == end())
return xs_.emplace(copy(std::forward<K>(key)), V{std::forward<T>(value)});
if (i->first == key)
return {i, false};
return {xs_.emplace_hint(i, copy(std::forward<K>(key)),
V{std::forward<T>(value)}),
true};
}
iterator_bool_pair insert(value_type kvp) {
return emplace(kvp.first, std::move(kvp.second));
}
iterator insert(iterator hint, value_type kvp) {
return emplace_hint(hint, kvp.first, std::move(kvp.second));
}
template <class T>
iterator_bool_pair insert(string_view key, T&& value) {
return emplace(key, V{std::forward<T>(value)});
}
template <class K, class T>
iterator emplace_hint(iterator hint, K&& key, T&& value) {
if (hint == end() || hint->first > key)
return xs_.emplace(copy(std::forward<K>(key)), V{std::forward<T>(value)})
.first;
if (hint->first == key)
return hint;
return xs_.emplace_hint(hint, copy(std::forward<K>(key)),
V{std::forward<T>(value)});
}
template <class T>
iterator insert(iterator hint, string_view key, T&& value) {
return emplace_hint(hint, key, std::forward<T>(value));
}
void insert(const_iterator first, const_iterator last) {
xs_.insert(first, last);
}
template <class T>
iterator_bool_pair insert_or_assign(string_view key, T&& value) {
auto i = lower_bound(key);
if (i == end())
return xs_.emplace(copy(key), V{std::forward<T>(value)});
if (i->first == key) {
i->second = V{std::forward<T>(value)};
return {i, false};
}
return {xs_.emplace_hint(i, copy(key), V{std::forward<T>(value)}), true};
}
template <class T>
iterator insert_or_assign(iterator hint, string_view key, T&& value) {
if (hint == end() || hint->first > key)
return insert_or_assign(key, std::forward<T>(value)).first;
hint = lower_bound(hint, key);
if (hint != end() && hint->first == key) {
hint->second = std::forward<T>(value);
return hint;
}
return xs_.emplace_hint(hint, copy(key), V{std::forward<T>(value)});
}
// -- lookup -----------------------------------------------------------------
bool contains(string_view key) const noexcept {
auto i = lower_bound(key);
return !(i == end() || i->first != key);
}
size_t count(string_view key) const noexcept {
return contains(key) ? 1u : 0u;
}
iterator find(string_view key) noexcept {
auto i = lower_bound(key);
return i != end() && i->first == key ? i : end();
}
const_iterator find(string_view key) const noexcept {
auto i = lower_bound(key);
return i != end() && i->first == key ? i : end();
}
iterator lower_bound(string_view key) {
return lower_bound(begin(), key);
}
const_iterator lower_bound(string_view key) const {
return lower_bound(begin(), key);
}
iterator upper_bound(string_view key) {
mapped_type_less cmp;
return std::upper_bound(begin(), end(), key, cmp);
}
const_iterator upper_bound(string_view key) const {
mapped_type_less cmp;
return std::upper_bound(begin(), end(), key, cmp);
}
// -- element access ---------------------------------------------------------
mapped_type& operator[](string_view key) {
return insert(key, mapped_type{}).first->second;
}
private:
iterator lower_bound(iterator from, string_view key) {
mapped_type_less cmp;
return std::lower_bound(from, end(), key, cmp);
}
const_iterator lower_bound(const_iterator from, string_view key) const {
mapped_type_less cmp;
return std::lower_bound(from, end(), key, cmp);
}
template <size_t N>
static inline std::string copy(const char (&str)[N]) {
return std::string{str};
}
// Copies the content of `str` into a new string.
static inline std::string copy(string_view str) {
return std::string{str.begin(), str.end()};
}
// Moves the content of `str` into a new string.
static inline std::string copy(std::string str) {
return str;
}
map_type xs_;
};
// -- operators ----------------------------------------------------------------
// @relates dictionary
template <class T>
bool operator==(const dictionary<T>& xs, const dictionary<T>& ys) {
return xs.container() == ys.container();
}
// @relates dictionary
template <class T>
bool operator!=(const dictionary<T>& xs, const dictionary<T>& ys) {
return xs.container() != ys.container();
}
// @relates dictionary
template <class T>
bool operator<(const dictionary<T>& xs, const dictionary<T>& ys) {
return xs.container() < ys.container();
}
// @relates dictionary
template <class T>
bool operator<=(const dictionary<T>& xs, const dictionary<T>& ys) {
return xs.container() <= ys.container();
}
// @relates dictionary
template <class T>
bool operator>(const dictionary<T>& xs, const dictionary<T>& ys) {
return xs.container() > ys.container();
}
// @relates dictionary
template <class T>
bool operator>=(const dictionary<T>& xs, const dictionary<T>& ys) {
return xs.container() >= ys.container();
}
// -- free functions -----------------------------------------------------------
/// Convenience function for calling `dict.insert_or_assign(key, value)`.
// @relates dictionary
template <class T>
void put(dictionary<T>& dict, string_view key, T value) {
dict.insert_or_assign(key, std::move(value));
}
} // namespace caf
<commit_msg>Use perfect forwarding for put parameter<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include <algorithm>
#include <iterator>
#include <map>
#include <string>
#include "caf/string_view.hpp"
namespace caf {
/// Maps strings to values of type `V`, but unlike `std::map<std::string, V>`
/// accepts `string_view` for looking up keys efficiently.
template <class V>
class dictionary {
public:
// -- member types ----------------------------------------------------------
using map_type = std::map<std::string, V>;
using key_type = typename map_type::key_type;
using mapped_type = typename map_type::mapped_type;
using value_type = typename map_type::value_type;
using allocator_type = typename map_type::allocator_type;
using size_type = typename map_type::size_type;
using difference_type = typename map_type::difference_type;
using reference = typename map_type::reference;
using const_reference = typename map_type::const_reference;
using pointer = typename map_type::pointer;
using const_pointer = typename map_type::const_pointer;
using iterator = typename map_type::iterator;
using const_iterator = typename map_type::const_iterator;
using reverse_iterator = typename map_type::reverse_iterator;
using const_reverse_iterator = typename map_type::const_reverse_iterator;
using iterator_bool_pair = std::pair<iterator, bool>;
struct mapped_type_less {
inline bool operator()(const value_type& x, string_view y) const {
return x.first < y;
}
inline bool operator()(const value_type& x, const value_type& y) const {
return x.first < y.first;
}
inline bool operator()(string_view x, const value_type& y) const {
return x < y.first;
}
};
// -- constructors, destructors, and assignment operators -------------------
dictionary() = default;
dictionary(dictionary&&) = default;
dictionary(const dictionary&) = default;
dictionary(std::initializer_list<value_type> xs) : xs_(xs) {
// nop
}
template <class InputIterator>
dictionary(InputIterator first, InputIterator last) : xs_(first, last) {
// nop
}
dictionary& operator=(dictionary&&) = default;
dictionary& operator=(const dictionary&) = default;
// -- iterator access --------------------------------------------------------
iterator begin() noexcept {
return xs_.begin();
}
const_iterator begin() const noexcept {
return xs_.begin();
}
const_iterator cbegin() const noexcept {
return begin();
}
reverse_iterator rbegin() noexcept {
return xs_.rbegin();
}
const_reverse_iterator rbegin() const noexcept {
return xs_.rbegin();
}
const_reverse_iterator crbegin() const noexcept {
return rbegin();
}
iterator end() noexcept {
return xs_.end();
}
const_iterator end() const noexcept {
return xs_.end();
}
const_iterator cend() const noexcept {
return end();
}
reverse_iterator rend() noexcept {
return xs_.rend();
}
const_reverse_iterator rend() const noexcept {
return xs_.rend();
}
const_reverse_iterator crend() const noexcept {
return rend();
}
// -- size -------------------------------------------------------------------
bool empty() const noexcept {
return xs_.empty();
}
size_type size() const noexcept {
return xs_.size();
}
// -- access to members ------------------------------------------------------
/// Gives raw access to the underlying container.
map_type& container() noexcept {
return xs_;
}
/// Gives raw access to the underlying container.
const map_type& container() const noexcept {
return xs_;
}
// -- modifiers -------------------------------------------------------------
void clear() noexcept {
return xs_.clear();
}
void swap(dictionary& other) {
xs_.swap(other.xs_);
}
// -- insertion --------------------------------------------------------------
template <class K, class T>
iterator_bool_pair emplace(K&& key, T&& value) {
auto i = lower_bound(key);
if (i == end())
return xs_.emplace(copy(std::forward<K>(key)), V{std::forward<T>(value)});
if (i->first == key)
return {i, false};
return {xs_.emplace_hint(i, copy(std::forward<K>(key)),
V{std::forward<T>(value)}),
true};
}
iterator_bool_pair insert(value_type kvp) {
return emplace(kvp.first, std::move(kvp.second));
}
iterator insert(iterator hint, value_type kvp) {
return emplace_hint(hint, kvp.first, std::move(kvp.second));
}
template <class T>
iterator_bool_pair insert(string_view key, T&& value) {
return emplace(key, V{std::forward<T>(value)});
}
template <class K, class T>
iterator emplace_hint(iterator hint, K&& key, T&& value) {
if (hint == end() || hint->first > key)
return xs_.emplace(copy(std::forward<K>(key)), V{std::forward<T>(value)})
.first;
if (hint->first == key)
return hint;
return xs_.emplace_hint(hint, copy(std::forward<K>(key)),
V{std::forward<T>(value)});
}
template <class T>
iterator insert(iterator hint, string_view key, T&& value) {
return emplace_hint(hint, key, std::forward<T>(value));
}
void insert(const_iterator first, const_iterator last) {
xs_.insert(first, last);
}
template <class T>
iterator_bool_pair insert_or_assign(string_view key, T&& value) {
auto i = lower_bound(key);
if (i == end())
return xs_.emplace(copy(key), V{std::forward<T>(value)});
if (i->first == key) {
i->second = V{std::forward<T>(value)};
return {i, false};
}
return {xs_.emplace_hint(i, copy(key), V{std::forward<T>(value)}), true};
}
template <class T>
iterator insert_or_assign(iterator hint, string_view key, T&& value) {
if (hint == end() || hint->first > key)
return insert_or_assign(key, std::forward<T>(value)).first;
hint = lower_bound(hint, key);
if (hint != end() && hint->first == key) {
hint->second = std::forward<T>(value);
return hint;
}
return xs_.emplace_hint(hint, copy(key), V{std::forward<T>(value)});
}
// -- lookup -----------------------------------------------------------------
bool contains(string_view key) const noexcept {
auto i = lower_bound(key);
return !(i == end() || i->first != key);
}
size_t count(string_view key) const noexcept {
return contains(key) ? 1u : 0u;
}
iterator find(string_view key) noexcept {
auto i = lower_bound(key);
return i != end() && i->first == key ? i : end();
}
const_iterator find(string_view key) const noexcept {
auto i = lower_bound(key);
return i != end() && i->first == key ? i : end();
}
iterator lower_bound(string_view key) {
return lower_bound(begin(), key);
}
const_iterator lower_bound(string_view key) const {
return lower_bound(begin(), key);
}
iterator upper_bound(string_view key) {
mapped_type_less cmp;
return std::upper_bound(begin(), end(), key, cmp);
}
const_iterator upper_bound(string_view key) const {
mapped_type_less cmp;
return std::upper_bound(begin(), end(), key, cmp);
}
// -- element access ---------------------------------------------------------
mapped_type& operator[](string_view key) {
return insert(key, mapped_type{}).first->second;
}
private:
iterator lower_bound(iterator from, string_view key) {
mapped_type_less cmp;
return std::lower_bound(from, end(), key, cmp);
}
const_iterator lower_bound(const_iterator from, string_view key) const {
mapped_type_less cmp;
return std::lower_bound(from, end(), key, cmp);
}
template <size_t N>
static inline std::string copy(const char (&str)[N]) {
return std::string{str};
}
// Copies the content of `str` into a new string.
static inline std::string copy(string_view str) {
return std::string{str.begin(), str.end()};
}
// Moves the content of `str` into a new string.
static inline std::string copy(std::string str) {
return str;
}
map_type xs_;
};
// -- operators ----------------------------------------------------------------
// @relates dictionary
template <class T>
bool operator==(const dictionary<T>& xs, const dictionary<T>& ys) {
return xs.container() == ys.container();
}
// @relates dictionary
template <class T>
bool operator!=(const dictionary<T>& xs, const dictionary<T>& ys) {
return xs.container() != ys.container();
}
// @relates dictionary
template <class T>
bool operator<(const dictionary<T>& xs, const dictionary<T>& ys) {
return xs.container() < ys.container();
}
// @relates dictionary
template <class T>
bool operator<=(const dictionary<T>& xs, const dictionary<T>& ys) {
return xs.container() <= ys.container();
}
// @relates dictionary
template <class T>
bool operator>(const dictionary<T>& xs, const dictionary<T>& ys) {
return xs.container() > ys.container();
}
// @relates dictionary
template <class T>
bool operator>=(const dictionary<T>& xs, const dictionary<T>& ys) {
return xs.container() >= ys.container();
}
// -- free functions -----------------------------------------------------------
/// Convenience function for calling `dict.insert_or_assign(key, value)`.
// @relates dictionary
template <class T, class V>
void put(dictionary<T>& dict, string_view key, V&& value) {
dict.insert_or_assign(key, std::forward<V>(value));
}
} // namespace caf
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: map.cpp 17 2005-03-08 23:58:43Z pavlenko $,
#include <mapnik/style.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/filter_featureset.hpp>
#include <mapnik/hit_test_filter.hpp>
#include <mapnik/map.hpp>
namespace mapnik
{
Map::Map()
: width_(400),
height_(400),
srs_("+proj=latlong +datum=WGS84") {}
Map::Map(int width,int height, std::string const& srs)
: width_(width),
height_(height),
srs_(srs),
background_(Color(255,255,255)) {}
Map::Map(const Map& rhs)
: width_(rhs.width_),
height_(rhs.height_),
srs_(rhs.srs_),
background_(rhs.background_),
styles_(rhs.styles_),
layers_(rhs.layers_),
currentExtent_(rhs.currentExtent_) {}
Map& Map::operator=(const Map& rhs)
{
if (this==&rhs) return *this;
width_=rhs.width_;
height_=rhs.height_;
srs_=rhs.srs_;
background_=rhs.background_;
styles_=rhs.styles_;
layers_=rhs.layers_;
return *this;
}
Map::style_iterator Map::begin_styles() const
{
return styles_.begin();
}
Map::style_iterator Map::end_styles() const
{
return styles_.end();
}
bool Map::insert_style(std::string const& name,feature_type_style const& style)
{
return styles_.insert(make_pair(name,style)).second;
}
void Map::remove_style(std::string const& name)
{
styles_.erase(name);
}
feature_type_style const& Map::find_style(std::string const& name) const
{
std::map<std::string,feature_type_style>::const_iterator itr = styles_.find(name);
if (itr!=styles_.end())
return itr->second;
static feature_type_style default_style;
return default_style;
}
size_t Map::layerCount() const
{
return layers_.size();
}
void Map::addLayer(const Layer& l)
{
layers_.push_back(l);
}
void Map::removeLayer(size_t index)
{
layers_.erase(layers_.begin()+index);
}
void Map::remove_all()
{
layers_.clear();
styles_.clear();
}
const Layer& Map::getLayer(size_t index) const
{
return layers_[index];
}
Layer& Map::getLayer(size_t index)
{
return layers_[index];
}
std::vector<Layer> const& Map::layers() const
{
return layers_;
}
std::vector<Layer> & Map::layers()
{
return layers_;
}
unsigned Map::getWidth() const
{
return width_;
}
unsigned Map::getHeight() const
{
return height_;
}
void Map::setWidth(unsigned width)
{
if (width >= MIN_MAPSIZE && width <= MAX_MAPSIZE)
{
width_=width;
fixAspectRatio();
}
}
void Map::setHeight(unsigned height)
{
if (height >= MIN_MAPSIZE && height <= MAX_MAPSIZE)
{
height_=height;
fixAspectRatio();
}
}
void Map::resize(unsigned width,unsigned height)
{
if (width >= MIN_MAPSIZE && width <= MAX_MAPSIZE &&
height >= MIN_MAPSIZE && height <= MAX_MAPSIZE)
{
width_=width;
height_=height;
fixAspectRatio();
}
}
std::string const& Map::srs() const
{
return srs_;
}
void Map::set_srs(std::string const& srs)
{
srs_ = srs;
}
void Map::setBackground(const Color& c)
{
background_=c;
}
const Color& Map::getBackground() const
{
return background_;
}
void Map::zoom(double factor)
{
coord2d center = currentExtent_.center();
double w = factor * currentExtent_.width();
double h = factor * currentExtent_.height();
currentExtent_ = Envelope<double>(center.x - 0.5 * w,
center.y - 0.5 * h,
center.x + 0.5 * w,
center.y + 0.5 * h);
fixAspectRatio();
}
void Map::zoom_all()
{
try
{
projection proj0(srs_);
Envelope<double> ext;
bool first = true;
std::vector<Layer>::const_iterator itr = layers_.begin();
std::vector<Layer>::const_iterator end = layers_.end();
while (itr != end)
{
std::string const& layer_srs = itr->srs();
projection proj1(layer_srs);
proj_transform prj_trans(proj0,proj1);
Envelope<double> layerExt = itr->envelope();
double x0 = layerExt.minx();
double y0 = layerExt.miny();
double z0 = 0.0;
double x1 = layerExt.maxx();
double y1 = layerExt.maxy();
double z1 = 0.0;
prj_trans.backward(x0,y0,z0);
prj_trans.backward(x1,y1,z1);
Envelope<double> layerExt2(x0,y0,x1,y1);
#ifdef MAPNIK_DEBUG
std::clog << " layer1 - > " << layerExt << "\n";
std::clog << " layer2 - > " << layerExt2 << "\n";
#endif
if (first)
{
ext = layerExt2;
first = false;
}
else
{
ext.expand_to_include(layerExt2);
}
++itr;
}
zoomToBox(ext);
}
catch (proj_init_error & ex)
{
std::clog << ex.what() << '\n';
}
}
void Map::zoomToBox(const Envelope<double> &box)
{
currentExtent_=box;
fixAspectRatio();
}
void Map::fixAspectRatio()
{
double ratio1 = (double) width_ / (double) height_;
double ratio2 = currentExtent_.width() / currentExtent_.height();
if (ratio2 > ratio1)
{
currentExtent_.height(currentExtent_.width() / ratio1);
}
else if (ratio2 < ratio1)
{
currentExtent_.width(currentExtent_.height() * ratio1);
}
}
const Envelope<double>& Map::getCurrentExtent() const
{
return currentExtent_;
}
void Map::pan(int x,int y)
{
int dx = x - int(0.5 * width_);
int dy = int(0.5 * height_) - y;
double s = width_/currentExtent_.width();
double minx = currentExtent_.minx() + dx/s;
double maxx = currentExtent_.maxx() + dx/s;
double miny = currentExtent_.miny() + dy/s;
double maxy = currentExtent_.maxy() + dy/s;
currentExtent_.init(minx,miny,maxx,maxy);
}
void Map::pan_and_zoom(int x,int y,double factor)
{
pan(x,y);
zoom(factor);
}
double Map::scale() const
{
if (width_>0)
return currentExtent_.width()/width_;
return currentExtent_.width();
}
CoordTransform Map::view_transform() const
{
return CoordTransform(width_,height_,currentExtent_);
}
featureset_ptr Map::query_point(unsigned index, double lat, double lon) const
{
if ( index< layers_.size())
{
mapnik::Layer const& layer = layers_[index];
try
{
double x = lon;
double y = lat;
double z = 0;
mapnik::projection dest(srs_);
dest.forward(x,y);
mapnik::projection source(layer.srs());
proj_transform prj_trans(source,dest);
prj_trans.backward(x,y,z);
double minx = currentExtent_.minx();
double miny = currentExtent_.miny();
double maxx = currentExtent_.maxx();
double maxy = currentExtent_.maxy();
prj_trans.backward(minx,miny,z);
prj_trans.backward(maxx,maxy,z);
double tol = (maxx - minx) / width_ * 3;
mapnik::datasource_ptr ds = layer.datasource();
if (ds)
{
#ifdef MAPNIK_DEBUG
std::clog << " query at point tol = " << tol << " (" << x << "," << y << ")\n";
#endif
featureset_ptr fs(new filter_featureset<hit_test_filter>(ds->features_at_point(mapnik::coord2d(x,y)),
hit_test_filter(x,y,tol)));
return fs;
}
}
catch (...)
{
#ifdef MAPNIK_DEBUG
std::clog << "exception caught in \"query_map_point\"\n";
#endif
}
}
return featureset_ptr();
}
featureset_ptr Map::query_map_point(unsigned index, double x, double y) const
{
if ( index< layers_.size())
{
mapnik::Layer const& layer = layers_[index];
CoordTransform tr = view_transform();
tr.backward(&x,&y);
try
{
mapnik::projection dest(srs_);
mapnik::projection source(layer.srs());
proj_transform prj_trans(source,dest);
double z = 0;
prj_trans.backward(x,y,z);
double minx = currentExtent_.minx();
double miny = currentExtent_.miny();
double maxx = currentExtent_.maxx();
double maxy = currentExtent_.maxy();
prj_trans.backward(minx,miny,z);
prj_trans.backward(maxx,maxy,z);
double tol = (maxx - minx) / width_ * 3;
mapnik::datasource_ptr ds = layer.datasource();
if (ds)
{
#ifdef MAPNIK_DEBUG
std::clog << " query at point tol = " << tol << " (" << x << "," << y << ")\n";
#endif
featureset_ptr fs(new filter_featureset<hit_test_filter>(ds->features_at_point(mapnik::coord2d(x,y)),
hit_test_filter(x,y,tol)));
return fs;
}
}
catch (...)
{
#ifdef MAPNIK_DEBUG
std::clog << "exception caught in \"query_map_point\"\n";
#endif
}
}
return featureset_ptr();
}
Map::~Map() {}
}
<commit_msg>check if featureset is valid before passing to filter_featureset<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: map.cpp 17 2005-03-08 23:58:43Z pavlenko $,
#include <mapnik/style.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/filter_featureset.hpp>
#include <mapnik/hit_test_filter.hpp>
#include <mapnik/map.hpp>
namespace mapnik
{
Map::Map()
: width_(400),
height_(400),
srs_("+proj=latlong +datum=WGS84") {}
Map::Map(int width,int height, std::string const& srs)
: width_(width),
height_(height),
srs_(srs),
background_(Color(255,255,255)) {}
Map::Map(const Map& rhs)
: width_(rhs.width_),
height_(rhs.height_),
srs_(rhs.srs_),
background_(rhs.background_),
styles_(rhs.styles_),
layers_(rhs.layers_),
currentExtent_(rhs.currentExtent_) {}
Map& Map::operator=(const Map& rhs)
{
if (this==&rhs) return *this;
width_=rhs.width_;
height_=rhs.height_;
srs_=rhs.srs_;
background_=rhs.background_;
styles_=rhs.styles_;
layers_=rhs.layers_;
return *this;
}
Map::style_iterator Map::begin_styles() const
{
return styles_.begin();
}
Map::style_iterator Map::end_styles() const
{
return styles_.end();
}
bool Map::insert_style(std::string const& name,feature_type_style const& style)
{
return styles_.insert(make_pair(name,style)).second;
}
void Map::remove_style(std::string const& name)
{
styles_.erase(name);
}
feature_type_style const& Map::find_style(std::string const& name) const
{
std::map<std::string,feature_type_style>::const_iterator itr = styles_.find(name);
if (itr!=styles_.end())
return itr->second;
static feature_type_style default_style;
return default_style;
}
size_t Map::layerCount() const
{
return layers_.size();
}
void Map::addLayer(const Layer& l)
{
layers_.push_back(l);
}
void Map::removeLayer(size_t index)
{
layers_.erase(layers_.begin()+index);
}
void Map::remove_all()
{
layers_.clear();
styles_.clear();
}
const Layer& Map::getLayer(size_t index) const
{
return layers_[index];
}
Layer& Map::getLayer(size_t index)
{
return layers_[index];
}
std::vector<Layer> const& Map::layers() const
{
return layers_;
}
std::vector<Layer> & Map::layers()
{
return layers_;
}
unsigned Map::getWidth() const
{
return width_;
}
unsigned Map::getHeight() const
{
return height_;
}
void Map::setWidth(unsigned width)
{
if (width >= MIN_MAPSIZE && width <= MAX_MAPSIZE)
{
width_=width;
fixAspectRatio();
}
}
void Map::setHeight(unsigned height)
{
if (height >= MIN_MAPSIZE && height <= MAX_MAPSIZE)
{
height_=height;
fixAspectRatio();
}
}
void Map::resize(unsigned width,unsigned height)
{
if (width >= MIN_MAPSIZE && width <= MAX_MAPSIZE &&
height >= MIN_MAPSIZE && height <= MAX_MAPSIZE)
{
width_=width;
height_=height;
fixAspectRatio();
}
}
std::string const& Map::srs() const
{
return srs_;
}
void Map::set_srs(std::string const& srs)
{
srs_ = srs;
}
void Map::setBackground(const Color& c)
{
background_=c;
}
const Color& Map::getBackground() const
{
return background_;
}
void Map::zoom(double factor)
{
coord2d center = currentExtent_.center();
double w = factor * currentExtent_.width();
double h = factor * currentExtent_.height();
currentExtent_ = Envelope<double>(center.x - 0.5 * w,
center.y - 0.5 * h,
center.x + 0.5 * w,
center.y + 0.5 * h);
fixAspectRatio();
}
void Map::zoom_all()
{
try
{
projection proj0(srs_);
Envelope<double> ext;
bool first = true;
std::vector<Layer>::const_iterator itr = layers_.begin();
std::vector<Layer>::const_iterator end = layers_.end();
while (itr != end)
{
std::string const& layer_srs = itr->srs();
projection proj1(layer_srs);
proj_transform prj_trans(proj0,proj1);
Envelope<double> layerExt = itr->envelope();
double x0 = layerExt.minx();
double y0 = layerExt.miny();
double z0 = 0.0;
double x1 = layerExt.maxx();
double y1 = layerExt.maxy();
double z1 = 0.0;
prj_trans.backward(x0,y0,z0);
prj_trans.backward(x1,y1,z1);
Envelope<double> layerExt2(x0,y0,x1,y1);
#ifdef MAPNIK_DEBUG
std::clog << " layer1 - > " << layerExt << "\n";
std::clog << " layer2 - > " << layerExt2 << "\n";
#endif
if (first)
{
ext = layerExt2;
first = false;
}
else
{
ext.expand_to_include(layerExt2);
}
++itr;
}
zoomToBox(ext);
}
catch (proj_init_error & ex)
{
std::clog << ex.what() << '\n';
}
}
void Map::zoomToBox(const Envelope<double> &box)
{
currentExtent_=box;
fixAspectRatio();
}
void Map::fixAspectRatio()
{
double ratio1 = (double) width_ / (double) height_;
double ratio2 = currentExtent_.width() / currentExtent_.height();
if (ratio2 > ratio1)
{
currentExtent_.height(currentExtent_.width() / ratio1);
}
else if (ratio2 < ratio1)
{
currentExtent_.width(currentExtent_.height() * ratio1);
}
}
const Envelope<double>& Map::getCurrentExtent() const
{
return currentExtent_;
}
void Map::pan(int x,int y)
{
int dx = x - int(0.5 * width_);
int dy = int(0.5 * height_) - y;
double s = width_/currentExtent_.width();
double minx = currentExtent_.minx() + dx/s;
double maxx = currentExtent_.maxx() + dx/s;
double miny = currentExtent_.miny() + dy/s;
double maxy = currentExtent_.maxy() + dy/s;
currentExtent_.init(minx,miny,maxx,maxy);
}
void Map::pan_and_zoom(int x,int y,double factor)
{
pan(x,y);
zoom(factor);
}
double Map::scale() const
{
if (width_>0)
return currentExtent_.width()/width_;
return currentExtent_.width();
}
CoordTransform Map::view_transform() const
{
return CoordTransform(width_,height_,currentExtent_);
}
featureset_ptr Map::query_point(unsigned index, double lat, double lon) const
{
if ( index< layers_.size())
{
mapnik::Layer const& layer = layers_[index];
try
{
double x = lon;
double y = lat;
double z = 0;
mapnik::projection dest(srs_);
dest.forward(x,y);
mapnik::projection source(layer.srs());
proj_transform prj_trans(source,dest);
prj_trans.backward(x,y,z);
double minx = currentExtent_.minx();
double miny = currentExtent_.miny();
double maxx = currentExtent_.maxx();
double maxy = currentExtent_.maxy();
prj_trans.backward(minx,miny,z);
prj_trans.backward(maxx,maxy,z);
double tol = (maxx - minx) / width_ * 3;
mapnik::datasource_ptr ds = layer.datasource();
if (ds)
{
#ifdef MAPNIK_DEBUG
std::clog << " query at point tol = " << tol << " (" << x << "," << y << ")\n";
#endif
featureset_ptr fs = ds->features_at_point(mapnik::coord2d(x,y));
if (fs)
return featureset_ptr(new filter_featureset<hit_test_filter>(fs,hit_test_filter(x,y,tol)));
}
}
catch (...)
{
#ifdef MAPNIK_DEBUG
std::clog << "exception caught in \"query_map_point\"\n";
#endif
}
}
return featureset_ptr();
}
featureset_ptr Map::query_map_point(unsigned index, double x, double y) const
{
if ( index< layers_.size())
{
mapnik::Layer const& layer = layers_[index];
CoordTransform tr = view_transform();
tr.backward(&x,&y);
try
{
mapnik::projection dest(srs_);
mapnik::projection source(layer.srs());
proj_transform prj_trans(source,dest);
double z = 0;
prj_trans.backward(x,y,z);
double minx = currentExtent_.minx();
double miny = currentExtent_.miny();
double maxx = currentExtent_.maxx();
double maxy = currentExtent_.maxy();
prj_trans.backward(minx,miny,z);
prj_trans.backward(maxx,maxy,z);
double tol = (maxx - minx) / width_ * 3;
mapnik::datasource_ptr ds = layer.datasource();
if (ds)
{
#ifdef MAPNIK_DEBUG
std::clog << " query at point tol = " << tol << " (" << x << "," << y << ")\n";
#endif
featureset_ptr fs = ds->features_at_point(mapnik::coord2d(x,y));
if (fs)
return featureset_ptr(new filter_featureset<hit_test_filter>(fs,hit_test_filter(x,y,tol)));
}
}
catch (...)
{
#ifdef MAPNIK_DEBUG
std::clog << "exception caught in \"query_map_point\"\n";
#endif
}
}
return featureset_ptr();
}
Map::~Map() {}
}
<|endoftext|>
|
<commit_before>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
namespace cuda
{
namespace kernel
{
template <typename T>
struct SharedMemory
{
// return a pointer to the runtime-sized shared memory array.
__device__ T* getPointer()
{
extern __device__ void Error_UnsupportedType(); // Ensure that we won't compile any un-specialized types
Error_UnsupportedType();
return (T*)0;
}
};
#define SPECIALIZE(T) \
template <> \
struct SharedMemory <T> \
{ \
__device__ T* getPointer() { \
extern __shared__ T ptr_##T##_[]; \
return ptr_##T##_; \
} \
};
SPECIALIZE(float)
SPECIALIZE(cfloat)
SPECIALIZE(double)
SPECIALIZE(cdouble)
SPECIALIZE(char)
SPECIALIZE(int)
SPECIALIZE(uint)
SPECIALIZE(short)
SPECIALIZE(ushort)
SPECIALIZE(uchar)
#undef SPECIALIZE
}
}
<commit_msg>Fix cuda shared memory instantiation for s64 and u64<commit_after>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
namespace cuda
{
namespace kernel
{
template <typename T>
struct SharedMemory
{
// return a pointer to the runtime-sized shared memory array.
__device__ T* getPointer()
{
extern __device__ void Error_UnsupportedType(); // Ensure that we won't compile any un-specialized types
Error_UnsupportedType();
return (T*)0;
}
};
#define SPECIALIZE(T) \
template <> \
struct SharedMemory <T> \
{ \
__device__ T* getPointer() { \
extern __shared__ T ptr_##T##_[]; \
return ptr_##T##_; \
} \
};
SPECIALIZE(float)
SPECIALIZE(cfloat)
SPECIALIZE(double)
SPECIALIZE(cdouble)
SPECIALIZE(char)
SPECIALIZE(int)
SPECIALIZE(uint)
SPECIALIZE(short)
SPECIALIZE(ushort)
SPECIALIZE(uchar)
SPECIALIZE(intl)
SPECIALIZE(uintl)
#undef SPECIALIZE
}
}
<|endoftext|>
|
<commit_before>#include "core/reactor.hh"
#include "core/app-template.hh"
#include "core/sstring.hh"
#include "message/messaging_service.hh"
#include "gms/gossip_digest_syn.hh"
#include "gms/gossip_digest_ack.hh"
#include "gms/gossip_digest_ack2.hh"
#include "gms/gossip_digest.hh"
#include "core/sleep.hh"
#include "api/api.hh"
using namespace std::chrono_literals;
using namespace net;
struct empty_msg {
void serialize(bytes::iterator& out) const {
}
static empty_msg deserialize(bytes_view& v) {
return empty_msg();
}
size_t serialized_size() const {
return 0;
}
friend inline std::ostream& operator<<(std::ostream& os, const empty_msg& ack) {
return os << "empty_msg";
}
};
class tester {
private:
messaging_service& ms;
gms::inet_address _server;
uint32_t _cpuid;
public:
tester()
: ms(get_local_messaging_service()) {
}
using shard_id = net::messaging_service::shard_id;
using inet_address = gms::inet_address;
using endpoint_state = gms::endpoint_state;
shard_id get_shard_id() {
return shard_id{_server, _cpuid};
}
void set_server_ip(sstring ip) {
_server = inet_address(ip);
}
void set_server_cpuid(uint32_t cpu) {
_cpuid = cpu;
}
future<> stop() {
return make_ready_future<>();
}
public:
void init_handler() {
ms.register_handler(messaging_verb::GOSSIP_DIGEST_SYN, [] (gms::gossip_digest_syn msg) {
print("Server got syn msg = %s\n", msg);
auto ep1 = inet_address("1.1.1.1");
auto ep2 = inet_address("2.2.2.2");
int32_t gen = 800;
int32_t ver = 900;
std::vector<gms::gossip_digest> digests{
{ep1, gen++, ver++},
{ep2, gen++, ver++},
};
std::map<inet_address, endpoint_state> eps{
{ep1, endpoint_state()},
{ep2, endpoint_state()},
};
gms::gossip_digest_ack ack(std::move(digests), std::move(eps));
return make_ready_future<gms::gossip_digest_ack>(ack);
});
ms.register_handler(messaging_verb::GOSSIP_DIGEST_ACK2, [] (gms::gossip_digest_ack2 msg) {
print("Server got ack2 msg = %s\n", msg);
return messaging_service::no_wait();
});
ms.register_handler(messaging_verb::GOSSIP_SHUTDOWN, [] (empty_msg msg) {
print("Server got shutdown msg = %s\n", msg);
return messaging_service::no_wait();
});
ms.register_handler(messaging_verb::ECHO, [] (int x, int y) {
print("Server got echo msg = (%d, %ld) \n", x, y);
return make_ready_future<int, long>(x*x, y*y);
});
ms.register_handler(messaging_verb::UNUSED_1, [] (int x, int y) {
print("Server got echo msg = (%d, %ld) \n", x, y);
throw std::runtime_error("I'm throwing runtime_error exception");
long ret = x + y;
return make_ready_future<decltype(ret)>(ret);
});
}
public:
future<> test_gossip_digest() {
print("=== %s ===\n", __func__);
// Prepare gossip_digest_syn message
auto id = get_shard_id();
auto ep1 = inet_address("1.1.1.1");
auto ep2 = inet_address("2.2.2.2");
int32_t gen = 100;
int32_t ver = 900;
std::vector<gms::gossip_digest> digests{
{ep1, gen++, ver++},
{ep2, gen++, ver++},
};
gms::gossip_digest_syn syn("my_cluster", "my_partition", digests);
using RetMsg = gms::gossip_digest_ack;
return ms.send_message<RetMsg>(messaging_verb::GOSSIP_DIGEST_SYN, std::move(id), std::move(syn)).then([this, id] (RetMsg ack) {
print("Client sent gossip_digest_syn got gossip_digest_ack reply = %s\n", ack);
// Prepare gossip_digest_ack2 message
auto ep1 = inet_address("3.3.3.3");
std::map<inet_address, endpoint_state> eps{
{ep1, endpoint_state()},
};
gms::gossip_digest_ack2 ack2(std::move(eps));
return ms.send_message_oneway(messaging_verb::GOSSIP_DIGEST_ACK2, std::move(id), std::move(ack2)).then([] () {
print("Client sent gossip_digest_ack2 got reply = void\n");
return make_ready_future<>();
});
});
}
future<> test_gossip_shutdown() {
print("=== %s ===\n", __func__);
auto id = get_shard_id();
empty_msg msg;
return ms.send_message_oneway(messaging_verb::GOSSIP_SHUTDOWN, std::move(id), std::move(msg)).then([] () {
print("Client sent gossip_shutdown got reply = void\n");
return make_ready_future<>();
});
}
future<> test_echo() {
print("=== %s ===\n", __func__);
auto id = get_shard_id();
using RetMsg = future<int, long>;
return ms.send_message<RetMsg>(messaging_verb::ECHO, id, 30, 60).then_wrapped([] (future<int, long> f) {
try {
auto msg = f.get();
print("Client sent echo got reply = (%d , %ld)\n", std::get<0>(msg), std::get<1>(msg));
return sleep(100ms).then([]{
return make_ready_future<>();
});
} catch (std::runtime_error& e) {
print("test_echo: %s\n", e.what());
}
return make_ready_future<>();
});
}
future<> test_exception() {
print("=== %s ===\n", __func__);
auto id = get_shard_id();
return ms.send_message<long>(messaging_verb::UNUSED_1, id, 3, 6).then_wrapped([] (future<long> f) {
try {
auto ret = std::get<0>(f.get());
print("Client sent UNUSED_1 got reply = %ld\n", ret);
return make_ready_future<>();
} catch (std::runtime_error& e) {
print("Client sent UNUSED_1 got exception: %s\n", e.what());
}
return make_ready_future<>();
});
}
};
namespace bpo = boost::program_options;
int main(int ac, char ** av) {
app_template app;
app.add_options()
("server", bpo::value<std::string>(), "Server ip")
("listen-address", bpo::value<std::string>()->default_value("0.0.0.0"), "IP address to listen")
("api-port", bpo::value<uint16_t>()->default_value(10000), "Http Rest API port")
("stay-alive", bpo::value<bool>()->default_value(false), "Do not kill the test server after the test")
("cpuid", bpo::value<uint32_t>()->default_value(0), "Server cpuid");
distributed<database> db;
return app.run(ac, av, [&app] {
auto config = app.configuration();
uint16_t api_port = config["api-port"].as<uint16_t>();
bool stay_alive = config["stay-alive"].as<bool>();
if (config.count("server")) {
api_port++;
}
const gms::inet_address listen = gms::inet_address(config["listen-address"].as<std::string>());
net::get_messaging_service().start(listen).then([config, api_port, stay_alive] () {
auto testers = new distributed<tester>;
testers->start().then([testers]{
auto& server = net::get_local_messaging_service();
auto port = server.port();
std::cout << "Messaging server listening on port " << port << " ...\n";
return testers->invoke_on_all(&tester::init_handler);
}).then([testers, config, stay_alive] {
auto t = &testers->local();
if (!config.count("server")) {
return;
}
auto ip = config["server"].as<std::string>();
auto cpuid = config["cpuid"].as<uint32_t>();
t->set_server_ip(ip);
t->set_server_cpuid(cpuid);
print("=============TEST START===========\n");
print("Sending to server ....\n");
t->test_gossip_digest().then([testers, t] {
return t->test_gossip_shutdown();
}).then([testers, t] {
return t->test_echo();
}).then([testers, t] {
return t->test_exception();
}).then([testers, t, stay_alive] {
if (stay_alive) {
return;
}
print("=============TEST DONE===========\n");
testers->stop().then([testers] {
delete testers;
net::get_messaging_service().stop().then([]{
engine().exit(0);
});
});
});
});
});
});
}
<commit_msg>tests: Disable tests/urchin/message.cc for now<commit_after>#if 0
#include "core/reactor.hh"
#include "core/app-template.hh"
#include "core/sstring.hh"
#include "message/messaging_service.hh"
#include "gms/gossip_digest_syn.hh"
#include "gms/gossip_digest_ack.hh"
#include "gms/gossip_digest_ack2.hh"
#include "gms/gossip_digest.hh"
#include "core/sleep.hh"
#include "api/api.hh"
using namespace std::chrono_literals;
using namespace net;
struct empty_msg {
void serialize(bytes::iterator& out) const {
}
static empty_msg deserialize(bytes_view& v) {
return empty_msg();
}
size_t serialized_size() const {
return 0;
}
friend inline std::ostream& operator<<(std::ostream& os, const empty_msg& ack) {
return os << "empty_msg";
}
};
class tester {
private:
messaging_service& ms;
gms::inet_address _server;
uint32_t _cpuid;
public:
tester()
: ms(get_local_messaging_service()) {
}
using shard_id = net::messaging_service::shard_id;
using inet_address = gms::inet_address;
using endpoint_state = gms::endpoint_state;
shard_id get_shard_id() {
return shard_id{_server, _cpuid};
}
void set_server_ip(sstring ip) {
_server = inet_address(ip);
}
void set_server_cpuid(uint32_t cpu) {
_cpuid = cpu;
}
future<> stop() {
return make_ready_future<>();
}
public:
void init_handler() {
ms.register_handler(messaging_verb::GOSSIP_DIGEST_SYN, [] (gms::gossip_digest_syn msg) {
print("Server got syn msg = %s\n", msg);
auto ep1 = inet_address("1.1.1.1");
auto ep2 = inet_address("2.2.2.2");
int32_t gen = 800;
int32_t ver = 900;
std::vector<gms::gossip_digest> digests{
{ep1, gen++, ver++},
{ep2, gen++, ver++},
};
std::map<inet_address, endpoint_state> eps{
{ep1, endpoint_state()},
{ep2, endpoint_state()},
};
gms::gossip_digest_ack ack(std::move(digests), std::move(eps));
return make_ready_future<gms::gossip_digest_ack>(ack);
});
ms.register_handler(messaging_verb::GOSSIP_DIGEST_ACK2, [] (gms::gossip_digest_ack2 msg) {
print("Server got ack2 msg = %s\n", msg);
return messaging_service::no_wait();
});
ms.register_handler(messaging_verb::GOSSIP_SHUTDOWN, [] (empty_msg msg) {
print("Server got shutdown msg = %s\n", msg);
return messaging_service::no_wait();
});
ms.register_handler(messaging_verb::ECHO, [] (int x, int y) {
print("Server got echo msg = (%d, %ld) \n", x, y);
return make_ready_future<int, long>(x*x, y*y);
});
ms.register_handler(messaging_verb::UNUSED_1, [] (int x, int y) {
print("Server got echo msg = (%d, %ld) \n", x, y);
throw std::runtime_error("I'm throwing runtime_error exception");
long ret = x + y;
return make_ready_future<decltype(ret)>(ret);
});
}
public:
future<> test_gossip_digest() {
print("=== %s ===\n", __func__);
// Prepare gossip_digest_syn message
auto id = get_shard_id();
auto ep1 = inet_address("1.1.1.1");
auto ep2 = inet_address("2.2.2.2");
int32_t gen = 100;
int32_t ver = 900;
std::vector<gms::gossip_digest> digests{
{ep1, gen++, ver++},
{ep2, gen++, ver++},
};
gms::gossip_digest_syn syn("my_cluster", "my_partition", digests);
using RetMsg = gms::gossip_digest_ack;
return ms.send_message<RetMsg>(messaging_verb::GOSSIP_DIGEST_SYN, std::move(id), std::move(syn)).then([this, id] (RetMsg ack) {
print("Client sent gossip_digest_syn got gossip_digest_ack reply = %s\n", ack);
// Prepare gossip_digest_ack2 message
auto ep1 = inet_address("3.3.3.3");
std::map<inet_address, endpoint_state> eps{
{ep1, endpoint_state()},
};
gms::gossip_digest_ack2 ack2(std::move(eps));
return ms.send_message_oneway(messaging_verb::GOSSIP_DIGEST_ACK2, std::move(id), std::move(ack2)).then([] () {
print("Client sent gossip_digest_ack2 got reply = void\n");
return make_ready_future<>();
});
});
}
future<> test_gossip_shutdown() {
print("=== %s ===\n", __func__);
auto id = get_shard_id();
empty_msg msg;
return ms.send_message_oneway(messaging_verb::GOSSIP_SHUTDOWN, std::move(id), std::move(msg)).then([] () {
print("Client sent gossip_shutdown got reply = void\n");
return make_ready_future<>();
});
}
future<> test_echo() {
print("=== %s ===\n", __func__);
auto id = get_shard_id();
using RetMsg = future<int, long>;
return ms.send_message<RetMsg>(messaging_verb::ECHO, id, 30, 60).then_wrapped([] (future<int, long> f) {
try {
auto msg = f.get();
print("Client sent echo got reply = (%d , %ld)\n", std::get<0>(msg), std::get<1>(msg));
return sleep(100ms).then([]{
return make_ready_future<>();
});
} catch (std::runtime_error& e) {
print("test_echo: %s\n", e.what());
}
return make_ready_future<>();
});
}
future<> test_exception() {
print("=== %s ===\n", __func__);
auto id = get_shard_id();
return ms.send_message<long>(messaging_verb::UNUSED_1, id, 3, 6).then_wrapped([] (future<long> f) {
try {
auto ret = std::get<0>(f.get());
print("Client sent UNUSED_1 got reply = %ld\n", ret);
return make_ready_future<>();
} catch (std::runtime_error& e) {
print("Client sent UNUSED_1 got exception: %s\n", e.what());
}
return make_ready_future<>();
});
}
};
namespace bpo = boost::program_options;
int main(int ac, char ** av) {
app_template app;
app.add_options()
("server", bpo::value<std::string>(), "Server ip")
("listen-address", bpo::value<std::string>()->default_value("0.0.0.0"), "IP address to listen")
("api-port", bpo::value<uint16_t>()->default_value(10000), "Http Rest API port")
("stay-alive", bpo::value<bool>()->default_value(false), "Do not kill the test server after the test")
("cpuid", bpo::value<uint32_t>()->default_value(0), "Server cpuid");
distributed<database> db;
return app.run(ac, av, [&app] {
auto config = app.configuration();
uint16_t api_port = config["api-port"].as<uint16_t>();
bool stay_alive = config["stay-alive"].as<bool>();
if (config.count("server")) {
api_port++;
}
const gms::inet_address listen = gms::inet_address(config["listen-address"].as<std::string>());
net::get_messaging_service().start(listen).then([config, api_port, stay_alive] () {
auto testers = new distributed<tester>;
testers->start().then([testers]{
auto& server = net::get_local_messaging_service();
auto port = server.port();
std::cout << "Messaging server listening on port " << port << " ...\n";
return testers->invoke_on_all(&tester::init_handler);
}).then([testers, config, stay_alive] {
auto t = &testers->local();
if (!config.count("server")) {
return;
}
auto ip = config["server"].as<std::string>();
auto cpuid = config["cpuid"].as<uint32_t>();
t->set_server_ip(ip);
t->set_server_cpuid(cpuid);
print("=============TEST START===========\n");
print("Sending to server ....\n");
t->test_gossip_digest().then([testers, t] {
return t->test_gossip_shutdown();
}).then([testers, t] {
return t->test_echo();
}).then([testers, t] {
return t->test_exception();
}).then([testers, t, stay_alive] {
if (stay_alive) {
return;
}
print("=============TEST DONE===========\n");
testers->stop().then([testers] {
delete testers;
net::get_messaging_service().stop().then([]{
engine().exit(0);
});
});
});
});
});
});
}
#endif
int main(int ac, char ** av) {}
<|endoftext|>
|
<commit_before>#include<ros/ros.h>
#include<keyboard/Key.h>
#include<sstream>
#include<string.h>
std::string intToString(int number){
std::ostringstream oss;
oss << number;
return oss.str();
}
void keyupMessageRecieved(const keyboard::Key& msg){
ROS_INFO("%s",intToString(msg.code).c_str());
}
void keydownMessageRecieved(const keyboard::Key& msg){
ROS_INFO("%s",intToString(msg.code).c_str());
}
int main(int argc, char **argv){
ros::init(argc, argv, "little_mapper_teleop_node");
ros::NodeHandle nh;
ros::Subscriber sub_keydown = nh.subscribe("keyboard_node/keydown", 1000, &keyupMessageRecieved);
ros::Subscriber sub_keyup = nh.subscribe("keyboard_node/keyup", 1000, &keydownMessageRecieved);
ros::spin();
}
<commit_msg>little_mapper_teleop_node.cpp refactored<commit_after>#include<ros/ros.h>
#include<keyboard/Key.h>
#include<sstream>
#include<string.h>
std::string intToString(int number){
std::ostringstream oss;
oss << number;
return oss.str();
}
void keyupMessageRecieved(const keyboard::Key& msg){
ROS_INFO("%s",intToString(msg.code).c_str());
}
void keydownMessageRecieved(const keyboard::Key& msg){
ROS_INFO("%s",intToString(msg.code).c_str());
}
int main(int argc, char **argv){
ros::init(argc, argv, "little_mapper_teleop_node");
ros::NodeHandle nh;
ros::Subscriber sub_keydown = nh.subscribe("keyboard_node/keydown", 1000, &keyupMessageRecieved);
ros::Subscriber sub_keyup = nh.subscribe("keyboard_node/keyup", 1000, &keydownMessageRecieved);
ros::spin();
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
* thrill/api/dia_base.cpp
*
* Part of Project Thrill - http://project-thrill.org
*
* Copyright (C) 2015 Sebastian Lamm <seba.lamm@gmail.com>
* Copyright (C) 2016 Timo Bingmann <tb@panthema.net>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#include <thrill/api/dia_base.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/common/stat_logger.hpp>
#include <thrill/common/stats_timer.hpp>
#include <thrill/mem/allocator.hpp>
#include <algorithm>
#include <chrono>
#include <deque>
#include <functional>
#include <iomanip>
#include <set>
#include <string>
#include <utility>
#include <vector>
namespace thrill {
namespace api {
/******************************************************************************/
// DIABase StageBuilder
static inline
struct tm localtime_from(const time_t& t) {
#if __MINGW32__
return *localtime(&t); // NOLINT
#else
struct tm tm;
memset(&tm, 0, sizeof(tm));
localtime_r(&t, &tm);
return tm;
#endif
}
//! format string using time structure
static inline
std::string format_time(const char* format, const struct tm& t) {
char buffer[256];
strftime(buffer, sizeof(buffer), format, &t);
return buffer;
}
//! format string using time in localtime representation
static inline
std::string format_time(const char* format, const time_t& t) {
return format_time(format, localtime_from(t));
}
class Stage
{
public:
static const bool debug = false;
using system_clock = std::chrono::system_clock;
explicit Stage(const DIABasePtr& node) : node_(node) { }
//! compute a string to show all target nodes into which this Stage pushes.
std::string Targets() const {
std::ostringstream oss;
std::vector<DIABase*> children = node_->children();
std::reverse(children.begin(), children.end());
oss << '[';
while (children.size())
{
DIABase* child = children.back();
children.pop_back();
if (child == nullptr) {
oss << ']';
}
else if (child->type() == DIANodeType::COLLAPSE) {
// push children of Collapse onto stack
std::vector<DIABase*> sub = child->children();
children.push_back(nullptr);
children.insert(children.end(), sub.begin(), sub.end());
oss << *child << ' ' << '[';
}
else {
oss << *child << ' ';
}
}
oss << ']';
return oss.str();
}
void Execute() {
common::StatsTimer<true> timer;
time_t tt = system_clock::to_time_t(system_clock::now());
sLOG << "START (EXECUTE) stage" << *node_ << "targets" << Targets()
<< "time:" << format_time("%T", tt);
timer.Start();
node_->Execute();
node_->set_state(DIAState::EXECUTED);
timer.Stop();
tt = system_clock::to_time_t(system_clock::now());
sLOG << "FINISH (EXECUTE) stage" << *node_ << "targets" << Targets()
<< "took" << timer.Milliseconds() << "ms"
<< "time:" << format_time("%T", tt);
}
void PushData() {
if (node_->context().consume() && node_->consume_counter() == 0) {
sLOG1 << "StageBuilder: attempt to PushData on"
<< "stage" << *node_
<< "failed, it was already consumed. Add .Keep()";
abort();
}
common::StatsTimer<true> timer;
time_t tt = system_clock::to_time_t(system_clock::now());
sLOG << "START (PUSHDATA) stage" << *node_ << "targets" << Targets()
<< "time:" << format_time("%T", tt);
timer.Start();
node_->RunPushData();
node_->RemoveAllChildren();
timer.Stop();
tt = system_clock::to_time_t(system_clock::now());
sLOG << "FINISH (PUSHDATA) stage" << *node_ << "targets" << Targets()
<< "took" << timer.Milliseconds() << "ms"
<< "time:" << format_time("%T", tt);
}
bool operator < (const Stage& s) const { return node_ < s.node_; }
//! shared pointer to node
DIABasePtr node_;
//! temporary marker for toposort to detect cycles
mutable bool cycle_mark_ = false;
//! toposort seen marker
mutable bool topo_seen_ = false;
};
template <typename T>
using mm_set = std::set<T, std::less<T>, mem::Allocator<T> >;
//! Do a BFS on parents to find all DIANodes (Stages) needed to Execute or
//! PushData to calculate this action node.
static void FindStages(const DIABasePtr& action, mm_set<Stage>& stages) {
static const bool debug = Stage::debug;
LOG << "Finding Stages:";
mem::mm_deque<DIABasePtr> bfs_stack(
mem::Allocator<DIABasePtr>(action->mem_manager()));
bfs_stack.push_back(action);
stages.insert(Stage(action));
while (!bfs_stack.empty()) {
DIABasePtr curr = bfs_stack.front();
bfs_stack.pop_front();
for (const DIABasePtr& p : curr->parents()) {
// if parents where not already seen, push onto stages
if (stages.count(Stage(p))) continue;
LOG << " Stage: " << *p;
stages.insert(Stage(p));
if (p->CanExecute()) {
// If parent was not executed push it to the BFS queue and
// continue upwards. if state is EXECUTED, then we only need to
// PushData(), which is already indicated by stages.insert().
if (p->state() == DIAState::NEW)
bfs_stack.push_back(p);
}
else {
// If parent cannot be executed (hold data) continue upward.
bfs_stack.push_back(p);
}
}
}
}
static void TopoSortVisit(
const Stage& s, mm_set<Stage>& stages, mem::mm_vector<Stage>& result) {
// check markers
die_unless(!s.cycle_mark_ && "Cycle in toposort of Stages? Impossible.");
if (s.topo_seen_) return;
s.cycle_mark_ = true;
// iterate over all children of s which are in the to-be-calculate stages
for (DIABase* child : s.node_->children()) {
auto it = stages.find(Stage(child->shared_from_this()));
// child not in stage set
if (it == stages.end()) continue;
// depth-first search
TopoSortVisit(*it, stages, result);
}
s.topo_seen_ = true;
s.cycle_mark_ = false;
result.push_back(s);
}
static void TopoSortStages(mm_set<Stage>& stages, mem::mm_vector<Stage>& result) {
// iterate over all stages and visit nodes in DFS search
for (const Stage& s : stages) {
if (s.topo_seen_) continue;
TopoSortVisit(s, stages, result);
}
}
void DIABase::RunScope() {
static const bool debug = Stage::debug;
LOG << "DIABase::Execute() this=" << *this;
if (!CanExecute())
die("DIA node " << *this << " cannot be executed.");
mm_set<Stage> stages {
mem::Allocator<Stage>(mem_manager())
};
FindStages(shared_from_this(), stages);
mem::mm_vector<Stage> toporder {
mem::Allocator<Stage>(mem_manager())
};
TopoSortStages(stages, toporder);
LOG << "Topological order";
for (auto top = toporder.rbegin(); top != toporder.rend(); ++top) {
LOG << " " << *top->node_;
}
assert(toporder.front().node_.get() == this);
while (toporder.size())
{
Stage& s = toporder.back();
if (!s.node_->CanExecute()) {
toporder.pop_back();
continue;
}
if (debug)
mem::malloc_tracker_print_status();
if (s.node_->state() == DIAState::NEW) {
s.Execute();
if (s.node_.get() != this)
s.PushData();
}
else if (s.node_->state() == DIAState::EXECUTED) {
if (s.node_.get() != this)
s.PushData();
}
// remove from result stack, this may destroy the last shared_ptr
// reference to a node.
toporder.pop_back();
}
}
/******************************************************************************/
// DIABase
//! make ostream-able.
std::ostream& operator << (std::ostream& os, const DIABase& d) {
return os << d.label() << '.' << d.id();
}
//! Returns the state of this DIANode as a string. Used by ToString.
const char* DIABase::state_string() {
switch (state_) {
case DIAState::NEW:
return "NEW";
case DIAState::EXECUTED:
return "EXECUTED";
case DIAState::DISPOSED:
return "DISPOSED";
default:
return "UNDEFINED";
}
}
} // namespace api
} // namespace thrill
/******************************************************************************/
<commit_msg>no localtime_r on windows.<commit_after>/*******************************************************************************
* thrill/api/dia_base.cpp
*
* Part of Project Thrill - http://project-thrill.org
*
* Copyright (C) 2015 Sebastian Lamm <seba.lamm@gmail.com>
* Copyright (C) 2016 Timo Bingmann <tb@panthema.net>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#include <thrill/api/dia_base.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/common/stat_logger.hpp>
#include <thrill/common/stats_timer.hpp>
#include <thrill/mem/allocator.hpp>
#include <algorithm>
#include <chrono>
#include <deque>
#include <functional>
#include <iomanip>
#include <set>
#include <string>
#include <utility>
#include <vector>
namespace thrill {
namespace api {
/******************************************************************************/
// DIABase StageBuilder
static inline
struct tm localtime_from(const time_t& t) {
#if __MINGW32__ || defined(_MSC_VER)
return *localtime(&t); // NOLINT
#else
struct tm tm;
memset(&tm, 0, sizeof(tm));
localtime_r(&t, &tm);
return tm;
#endif
}
//! format string using time structure
static inline
std::string format_time(const char* format, const struct tm& t) {
char buffer[256];
strftime(buffer, sizeof(buffer), format, &t);
return buffer;
}
//! format string using time in localtime representation
static inline
std::string format_time(const char* format, const time_t& t) {
return format_time(format, localtime_from(t));
}
class Stage
{
public:
static const bool debug = false;
using system_clock = std::chrono::system_clock;
explicit Stage(const DIABasePtr& node) : node_(node) { }
//! compute a string to show all target nodes into which this Stage pushes.
std::string Targets() const {
std::ostringstream oss;
std::vector<DIABase*> children = node_->children();
std::reverse(children.begin(), children.end());
oss << '[';
while (children.size())
{
DIABase* child = children.back();
children.pop_back();
if (child == nullptr) {
oss << ']';
}
else if (child->type() == DIANodeType::COLLAPSE) {
// push children of Collapse onto stack
std::vector<DIABase*> sub = child->children();
children.push_back(nullptr);
children.insert(children.end(), sub.begin(), sub.end());
oss << *child << ' ' << '[';
}
else {
oss << *child << ' ';
}
}
oss << ']';
return oss.str();
}
void Execute() {
common::StatsTimer<true> timer;
time_t tt = system_clock::to_time_t(system_clock::now());
sLOG << "START (EXECUTE) stage" << *node_ << "targets" << Targets()
<< "time:" << format_time("%T", tt);
timer.Start();
node_->Execute();
node_->set_state(DIAState::EXECUTED);
timer.Stop();
tt = system_clock::to_time_t(system_clock::now());
sLOG << "FINISH (EXECUTE) stage" << *node_ << "targets" << Targets()
<< "took" << timer.Milliseconds() << "ms"
<< "time:" << format_time("%T", tt);
}
void PushData() {
if (node_->context().consume() && node_->consume_counter() == 0) {
sLOG1 << "StageBuilder: attempt to PushData on"
<< "stage" << *node_
<< "failed, it was already consumed. Add .Keep()";
abort();
}
common::StatsTimer<true> timer;
time_t tt = system_clock::to_time_t(system_clock::now());
sLOG << "START (PUSHDATA) stage" << *node_ << "targets" << Targets()
<< "time:" << format_time("%T", tt);
timer.Start();
node_->RunPushData();
node_->RemoveAllChildren();
timer.Stop();
tt = system_clock::to_time_t(system_clock::now());
sLOG << "FINISH (PUSHDATA) stage" << *node_ << "targets" << Targets()
<< "took" << timer.Milliseconds() << "ms"
<< "time:" << format_time("%T", tt);
}
bool operator < (const Stage& s) const { return node_ < s.node_; }
//! shared pointer to node
DIABasePtr node_;
//! temporary marker for toposort to detect cycles
mutable bool cycle_mark_ = false;
//! toposort seen marker
mutable bool topo_seen_ = false;
};
template <typename T>
using mm_set = std::set<T, std::less<T>, mem::Allocator<T> >;
//! Do a BFS on parents to find all DIANodes (Stages) needed to Execute or
//! PushData to calculate this action node.
static void FindStages(const DIABasePtr& action, mm_set<Stage>& stages) {
static const bool debug = Stage::debug;
LOG << "Finding Stages:";
mem::mm_deque<DIABasePtr> bfs_stack(
mem::Allocator<DIABasePtr>(action->mem_manager()));
bfs_stack.push_back(action);
stages.insert(Stage(action));
while (!bfs_stack.empty()) {
DIABasePtr curr = bfs_stack.front();
bfs_stack.pop_front();
for (const DIABasePtr& p : curr->parents()) {
// if parents where not already seen, push onto stages
if (stages.count(Stage(p))) continue;
LOG << " Stage: " << *p;
stages.insert(Stage(p));
if (p->CanExecute()) {
// If parent was not executed push it to the BFS queue and
// continue upwards. if state is EXECUTED, then we only need to
// PushData(), which is already indicated by stages.insert().
if (p->state() == DIAState::NEW)
bfs_stack.push_back(p);
}
else {
// If parent cannot be executed (hold data) continue upward.
bfs_stack.push_back(p);
}
}
}
}
static void TopoSortVisit(
const Stage& s, mm_set<Stage>& stages, mem::mm_vector<Stage>& result) {
// check markers
die_unless(!s.cycle_mark_ && "Cycle in toposort of Stages? Impossible.");
if (s.topo_seen_) return;
s.cycle_mark_ = true;
// iterate over all children of s which are in the to-be-calculate stages
for (DIABase* child : s.node_->children()) {
auto it = stages.find(Stage(child->shared_from_this()));
// child not in stage set
if (it == stages.end()) continue;
// depth-first search
TopoSortVisit(*it, stages, result);
}
s.topo_seen_ = true;
s.cycle_mark_ = false;
result.push_back(s);
}
static void TopoSortStages(mm_set<Stage>& stages, mem::mm_vector<Stage>& result) {
// iterate over all stages and visit nodes in DFS search
for (const Stage& s : stages) {
if (s.topo_seen_) continue;
TopoSortVisit(s, stages, result);
}
}
void DIABase::RunScope() {
static const bool debug = Stage::debug;
LOG << "DIABase::Execute() this=" << *this;
if (!CanExecute())
die("DIA node " << *this << " cannot be executed.");
mm_set<Stage> stages {
mem::Allocator<Stage>(mem_manager())
};
FindStages(shared_from_this(), stages);
mem::mm_vector<Stage> toporder {
mem::Allocator<Stage>(mem_manager())
};
TopoSortStages(stages, toporder);
LOG << "Topological order";
for (auto top = toporder.rbegin(); top != toporder.rend(); ++top) {
LOG << " " << *top->node_;
}
assert(toporder.front().node_.get() == this);
while (toporder.size())
{
Stage& s = toporder.back();
if (!s.node_->CanExecute()) {
toporder.pop_back();
continue;
}
if (debug)
mem::malloc_tracker_print_status();
if (s.node_->state() == DIAState::NEW) {
s.Execute();
if (s.node_.get() != this)
s.PushData();
}
else if (s.node_->state() == DIAState::EXECUTED) {
if (s.node_.get() != this)
s.PushData();
}
// remove from result stack, this may destroy the last shared_ptr
// reference to a node.
toporder.pop_back();
}
}
/******************************************************************************/
// DIABase
//! make ostream-able.
std::ostream& operator << (std::ostream& os, const DIABase& d) {
return os << d.label() << '.' << d.id();
}
//! Returns the state of this DIANode as a string. Used by ToString.
const char* DIABase::state_string() {
switch (state_) {
case DIAState::NEW:
return "NEW";
case DIAState::EXECUTED:
return "EXECUTED";
case DIAState::DISPOSED:
return "DISPOSED";
default:
return "UNDEFINED";
}
}
} // namespace api
} // namespace thrill
/******************************************************************************/
<|endoftext|>
|
<commit_before>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "QmitkVolumeVisualizationView.h"
#include <vtkSmartVolumeMapper.h>
#include <mitkImage.h>
#include <mitkTransferFunction.h>
#include <mitkTransferFunctionInitializer.h>
#include <mitkTransferFunctionProperty.h>
#include <mitkNodePredicateDataType.h>
#include <mitkNodePredicateDimension.h>
#include <mitkNodePredicateAnd.h>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateOr.h>
#include <mitkNodePredicateProperty.h>
#include <mitkProperties.h>
const std::string QmitkVolumeVisualizationView::VIEW_ID = "org.mitk.views.volumevisualization";
enum
{
DEFAULT_RENDERMODE = 0,
RAYCAST_RENDERMODE = 1,
GPU_RENDERMODE = 2
};
QmitkVolumeVisualizationView::QmitkVolumeVisualizationView()
: QmitkAbstractView()
, m_Controls(nullptr)
{
}
void QmitkVolumeVisualizationView::SetFocus()
{
}
void QmitkVolumeVisualizationView::CreateQtPartControl(QWidget* parent)
{
m_Controls = new Ui::QmitkVolumeVisualizationViewControls;
m_Controls->setupUi(parent);
m_Controls->volumeSelectionWidget->SetDataStorage(GetDataStorage());
m_Controls->volumeSelectionWidget->SetNodePredicate(mitk::NodePredicateAnd::New(
mitk::TNodePredicateDataType<mitk::Image>::New(),
mitk::NodePredicateOr::New(mitk::NodePredicateDimension::New(3), mitk::NodePredicateDimension::New(4)),
mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))));
m_Controls->volumeSelectionWidget->SetSelectionIsOptional(true);
m_Controls->volumeSelectionWidget->SetAutoSelectNewNodes(true);
m_Controls->volumeSelectionWidget->SetEmptyInfo(QString("Please select a 3D / 4D image volume"));
m_Controls->volumeSelectionWidget->SetPopUpTitel(QString("Select image volume"));
// Fill the transfer function presets in the generator widget
std::vector<std::string> names;
mitk::TransferFunctionInitializer::GetPresetNames(names);
for (const auto& name : names)
{
m_Controls->transferFunctionGeneratorWidget->AddPreset(QString::fromStdString(name));
}
// see enum in vtkSmartVolumeMapper
m_Controls->renderMode->addItem("Default");
m_Controls->renderMode->addItem("RayCast");
m_Controls->renderMode->addItem("GPU");
// see vtkVolumeMapper::BlendModes
m_Controls->blendMode->addItem("Comp");
m_Controls->blendMode->addItem("Max");
m_Controls->blendMode->addItem("Min");
m_Controls->blendMode->addItem("Avg");
m_Controls->blendMode->addItem("Add");
connect(m_Controls->volumeSelectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged,
this, &QmitkVolumeVisualizationView::OnCurrentSelectionChanged);
connect(m_Controls->enableRenderingCB, SIGNAL(toggled(bool)), this, SLOT(OnEnableRendering(bool)));
connect(m_Controls->renderMode, SIGNAL(activated(int)), this, SLOT(OnRenderMode(int)));
connect(m_Controls->blendMode, SIGNAL(activated(int)), this, SLOT(OnBlendMode(int)));
connect(m_Controls->transferFunctionGeneratorWidget, SIGNAL(SignalUpdateCanvas()),
m_Controls->transferFunctionWidget, SLOT(OnUpdateCanvas()));
connect(m_Controls->transferFunctionGeneratorWidget, SIGNAL(SignalTransferFunctionModeChanged(int)),
SLOT(OnMitkInternalPreset(int)));
m_Controls->enableRenderingCB->setEnabled(false);
m_Controls->blendMode->setEnabled(false);
m_Controls->renderMode->setEnabled(false);
m_Controls->transferFunctionWidget->setEnabled(false);
m_Controls->transferFunctionGeneratorWidget->setEnabled(false);
m_Controls->volumeSelectionWidget->SetAutoSelectNewNodes(true);
}
void QmitkVolumeVisualizationView::OnMitkInternalPreset(int mode)
{
if (m_SelectedNode.IsExpired())
{
return;
}
auto node = m_SelectedNode.Lock();
mitk::TransferFunctionProperty::Pointer transferFuncProp;
if (node->GetProperty(transferFuncProp, "TransferFunction"))
{
// first item is only information
if (--mode == -1)
return;
// -- Creat new TransferFunction
mitk::TransferFunctionInitializer::Pointer tfInit = mitk::TransferFunctionInitializer::New(transferFuncProp->GetValue());
tfInit->SetTransferFunctionMode(mode);
RequestRenderWindowUpdate();
m_Controls->transferFunctionWidget->OnUpdateCanvas();
}
}
void QmitkVolumeVisualizationView::OnCurrentSelectionChanged(QList<mitk::DataNode::Pointer> nodes)
{
m_SelectedNode = nullptr;
if (nodes.empty() || nodes.front().IsNull())
{
UpdateInterface();
return;
}
auto selectedNode = nodes.front();
auto image = dynamic_cast<mitk::Image*>(selectedNode->GetData());
if (nullptr != image)
{
m_SelectedNode = selectedNode;
}
UpdateInterface();
}
void QmitkVolumeVisualizationView::OnEnableRendering(bool state)
{
if (m_SelectedNode.IsExpired())
{
return;
}
m_SelectedNode.Lock()->SetProperty("volumerendering", mitk::BoolProperty::New(state));
UpdateInterface();
RequestRenderWindowUpdate();
}
void QmitkVolumeVisualizationView::OnRenderMode(int mode)
{
if (m_SelectedNode.IsExpired())
{
return;
}
auto selectedNode = m_SelectedNode.Lock();
bool usegpu = false;
bool useray = false;
if (DEFAULT_RENDERMODE == mode)
{
useray = true;
usegpu = true;
}
else if (GPU_RENDERMODE == mode)
{
usegpu = true;
}
else if (RAYCAST_RENDERMODE == mode)
{
useray = true;
}
selectedNode->SetProperty("volumerendering.usegpu", mitk::BoolProperty::New(usegpu));
selectedNode->SetProperty("volumerendering.useray", mitk::BoolProperty::New(useray));
RequestRenderWindowUpdate();
}
void QmitkVolumeVisualizationView::OnBlendMode(int mode)
{
if (m_SelectedNode.IsExpired())
{
return;
}
auto selectedNode = m_SelectedNode.Lock();
bool usemip = false;
if (vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND == mode)
{
usemip = true;
}
selectedNode->SetProperty("volumerendering.usemip", mitk::BoolProperty::New(usemip));
selectedNode->SetProperty("volumerendering.blendmode", mitk::IntProperty::New(mode));
RequestRenderWindowUpdate();
}
void QmitkVolumeVisualizationView::UpdateInterface()
{
if (m_SelectedNode.IsExpired())
{
// turnoff all
m_Controls->enableRenderingCB->setChecked(false);
m_Controls->enableRenderingCB->setEnabled(false);
m_Controls->blendMode->setCurrentIndex(0);
m_Controls->blendMode->setEnabled(false);
m_Controls->renderMode->setCurrentIndex(0);
m_Controls->renderMode->setEnabled(false);
m_Controls->transferFunctionWidget->SetDataNode(nullptr);
m_Controls->transferFunctionWidget->setEnabled(false);
m_Controls->transferFunctionGeneratorWidget->SetDataNode(nullptr);
m_Controls->transferFunctionGeneratorWidget->setEnabled(false);
return;
}
bool enabled = false;
auto selectedNode = m_SelectedNode.Lock();
selectedNode->GetBoolProperty("volumerendering", enabled);
m_Controls->enableRenderingCB->setEnabled(true);
m_Controls->enableRenderingCB->setChecked(enabled);
if (!enabled)
{
// turnoff all except volumerendering checkbox
m_Controls->blendMode->setCurrentIndex(0);
m_Controls->blendMode->setEnabled(false);
m_Controls->renderMode->setCurrentIndex(0);
m_Controls->renderMode->setEnabled(false);
m_Controls->transferFunctionWidget->SetDataNode(nullptr);
m_Controls->transferFunctionWidget->setEnabled(false);
m_Controls->transferFunctionGeneratorWidget->SetDataNode(nullptr);
m_Controls->transferFunctionGeneratorWidget->setEnabled(false);
return;
}
// otherwise we can activate em all
m_Controls->blendMode->setEnabled(true);
m_Controls->renderMode->setEnabled(true);
// Determine Combo Box mode
{
bool usegpu = false;
bool useray = false;
bool usemip = false;
selectedNode->GetBoolProperty("volumerendering.usegpu", usegpu);
selectedNode->GetBoolProperty("volumerendering.useray", useray);
selectedNode->GetBoolProperty("volumerendering.usemip", usemip);
int blendMode;
if (selectedNode->GetIntProperty("volumerendering.blendmode", blendMode))
m_Controls->blendMode->setCurrentIndex(blendMode);
if (usemip)
m_Controls->blendMode->setCurrentIndex(vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND);
int mode = DEFAULT_RENDERMODE;
if (useray)
mode = RAYCAST_RENDERMODE;
else if (usegpu)
mode = GPU_RENDERMODE;
m_Controls->renderMode->setCurrentIndex(mode);
}
m_Controls->transferFunctionWidget->SetDataNode(selectedNode);
m_Controls->transferFunctionWidget->setEnabled(true);
m_Controls->transferFunctionGeneratorWidget->SetDataNode(selectedNode);
m_Controls->transferFunctionGeneratorWidget->setEnabled(true);
}
<commit_msg>remove duplicate SetAutoSelectNewNodes that blocks correct signal connecting<commit_after>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "QmitkVolumeVisualizationView.h"
#include <vtkSmartVolumeMapper.h>
#include <mitkImage.h>
#include <mitkTransferFunction.h>
#include <mitkTransferFunctionInitializer.h>
#include <mitkTransferFunctionProperty.h>
#include <mitkNodePredicateDataType.h>
#include <mitkNodePredicateDimension.h>
#include <mitkNodePredicateAnd.h>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateOr.h>
#include <mitkNodePredicateProperty.h>
#include <mitkProperties.h>
const std::string QmitkVolumeVisualizationView::VIEW_ID = "org.mitk.views.volumevisualization";
enum
{
DEFAULT_RENDERMODE = 0,
RAYCAST_RENDERMODE = 1,
GPU_RENDERMODE = 2
};
QmitkVolumeVisualizationView::QmitkVolumeVisualizationView()
: QmitkAbstractView()
, m_Controls(nullptr)
{
}
void QmitkVolumeVisualizationView::SetFocus()
{
UpdateInterface();
}
void QmitkVolumeVisualizationView::CreateQtPartControl(QWidget* parent)
{
m_Controls = new Ui::QmitkVolumeVisualizationViewControls;
m_Controls->setupUi(parent);
m_Controls->volumeSelectionWidget->SetDataStorage(GetDataStorage());
m_Controls->volumeSelectionWidget->SetNodePredicate(mitk::NodePredicateAnd::New(
mitk::TNodePredicateDataType<mitk::Image>::New(),
mitk::NodePredicateOr::New(mitk::NodePredicateDimension::New(3), mitk::NodePredicateDimension::New(4)),
mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))));
m_Controls->volumeSelectionWidget->SetSelectionIsOptional(true);
m_Controls->volumeSelectionWidget->SetEmptyInfo(QString("Please select a 3D / 4D image volume"));
m_Controls->volumeSelectionWidget->SetPopUpTitel(QString("Select image volume"));
// Fill the transfer function presets in the generator widget
std::vector<std::string> names;
mitk::TransferFunctionInitializer::GetPresetNames(names);
for (const auto& name : names)
{
m_Controls->transferFunctionGeneratorWidget->AddPreset(QString::fromStdString(name));
}
// see enum in vtkSmartVolumeMapper
m_Controls->renderMode->addItem("Default");
m_Controls->renderMode->addItem("RayCast");
m_Controls->renderMode->addItem("GPU");
// see vtkVolumeMapper::BlendModes
m_Controls->blendMode->addItem("Comp");
m_Controls->blendMode->addItem("Max");
m_Controls->blendMode->addItem("Min");
m_Controls->blendMode->addItem("Avg");
m_Controls->blendMode->addItem("Add");
connect(m_Controls->volumeSelectionWidget, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged,
this, &QmitkVolumeVisualizationView::OnCurrentSelectionChanged);
connect(m_Controls->enableRenderingCB, SIGNAL(toggled(bool)), this, SLOT(OnEnableRendering(bool)));
connect(m_Controls->renderMode, SIGNAL(activated(int)), this, SLOT(OnRenderMode(int)));
connect(m_Controls->blendMode, SIGNAL(activated(int)), this, SLOT(OnBlendMode(int)));
connect(m_Controls->transferFunctionGeneratorWidget, SIGNAL(SignalUpdateCanvas()),
m_Controls->transferFunctionWidget, SLOT(OnUpdateCanvas()));
connect(m_Controls->transferFunctionGeneratorWidget, SIGNAL(SignalTransferFunctionModeChanged(int)),
SLOT(OnMitkInternalPreset(int)));
m_Controls->enableRenderingCB->setEnabled(false);
m_Controls->blendMode->setEnabled(false);
m_Controls->renderMode->setEnabled(false);
m_Controls->transferFunctionWidget->setEnabled(false);
m_Controls->transferFunctionGeneratorWidget->setEnabled(false);
m_Controls->volumeSelectionWidget->SetAutoSelectNewNodes(true);
}
void QmitkVolumeVisualizationView::OnMitkInternalPreset(int mode)
{
if (m_SelectedNode.IsExpired())
{
return;
}
auto node = m_SelectedNode.Lock();
mitk::TransferFunctionProperty::Pointer transferFuncProp;
if (node->GetProperty(transferFuncProp, "TransferFunction"))
{
// first item is only information
if (--mode == -1)
return;
// -- Creat new TransferFunction
mitk::TransferFunctionInitializer::Pointer tfInit = mitk::TransferFunctionInitializer::New(transferFuncProp->GetValue());
tfInit->SetTransferFunctionMode(mode);
RequestRenderWindowUpdate();
m_Controls->transferFunctionWidget->OnUpdateCanvas();
}
}
void QmitkVolumeVisualizationView::OnCurrentSelectionChanged(QList<mitk::DataNode::Pointer> nodes)
{
m_SelectedNode = nullptr;
if (nodes.empty() || nodes.front().IsNull())
{
UpdateInterface();
return;
}
auto selectedNode = nodes.front();
auto image = dynamic_cast<mitk::Image*>(selectedNode->GetData());
if (nullptr != image)
{
m_SelectedNode = selectedNode;
}
UpdateInterface();
}
void QmitkVolumeVisualizationView::OnEnableRendering(bool state)
{
if (m_SelectedNode.IsExpired())
{
return;
}
m_SelectedNode.Lock()->SetProperty("volumerendering", mitk::BoolProperty::New(state));
UpdateInterface();
RequestRenderWindowUpdate();
}
void QmitkVolumeVisualizationView::OnRenderMode(int mode)
{
if (m_SelectedNode.IsExpired())
{
return;
}
auto selectedNode = m_SelectedNode.Lock();
bool usegpu = false;
bool useray = false;
if (DEFAULT_RENDERMODE == mode)
{
useray = true;
usegpu = true;
}
else if (GPU_RENDERMODE == mode)
{
usegpu = true;
}
else if (RAYCAST_RENDERMODE == mode)
{
useray = true;
}
selectedNode->SetProperty("volumerendering.usegpu", mitk::BoolProperty::New(usegpu));
selectedNode->SetProperty("volumerendering.useray", mitk::BoolProperty::New(useray));
RequestRenderWindowUpdate();
}
void QmitkVolumeVisualizationView::OnBlendMode(int mode)
{
if (m_SelectedNode.IsExpired())
{
return;
}
auto selectedNode = m_SelectedNode.Lock();
bool usemip = false;
if (vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND == mode)
{
usemip = true;
}
selectedNode->SetProperty("volumerendering.usemip", mitk::BoolProperty::New(usemip));
selectedNode->SetProperty("volumerendering.blendmode", mitk::IntProperty::New(mode));
RequestRenderWindowUpdate();
}
void QmitkVolumeVisualizationView::UpdateInterface()
{
if (m_SelectedNode.IsExpired())
{
// turnoff all
m_Controls->enableRenderingCB->setChecked(false);
m_Controls->enableRenderingCB->setEnabled(false);
m_Controls->blendMode->setCurrentIndex(0);
m_Controls->blendMode->setEnabled(false);
m_Controls->renderMode->setCurrentIndex(0);
m_Controls->renderMode->setEnabled(false);
m_Controls->transferFunctionWidget->SetDataNode(nullptr);
m_Controls->transferFunctionWidget->setEnabled(false);
m_Controls->transferFunctionGeneratorWidget->SetDataNode(nullptr);
m_Controls->transferFunctionGeneratorWidget->setEnabled(false);
return;
}
bool enabled = false;
auto selectedNode = m_SelectedNode.Lock();
selectedNode->GetBoolProperty("volumerendering", enabled);
m_Controls->enableRenderingCB->setEnabled(true);
m_Controls->enableRenderingCB->setChecked(enabled);
if (!enabled)
{
// turnoff all except volumerendering checkbox
m_Controls->blendMode->setCurrentIndex(0);
m_Controls->blendMode->setEnabled(false);
m_Controls->renderMode->setCurrentIndex(0);
m_Controls->renderMode->setEnabled(false);
m_Controls->transferFunctionWidget->SetDataNode(nullptr);
m_Controls->transferFunctionWidget->setEnabled(false);
m_Controls->transferFunctionGeneratorWidget->SetDataNode(nullptr);
m_Controls->transferFunctionGeneratorWidget->setEnabled(false);
return;
}
// otherwise we can activate em all
m_Controls->blendMode->setEnabled(true);
m_Controls->renderMode->setEnabled(true);
// Determine Combo Box mode
{
bool usegpu = false;
bool useray = false;
bool usemip = false;
selectedNode->GetBoolProperty("volumerendering.usegpu", usegpu);
selectedNode->GetBoolProperty("volumerendering.useray", useray);
selectedNode->GetBoolProperty("volumerendering.usemip", usemip);
int blendMode;
if (selectedNode->GetIntProperty("volumerendering.blendmode", blendMode))
m_Controls->blendMode->setCurrentIndex(blendMode);
if (usemip)
m_Controls->blendMode->setCurrentIndex(vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND);
int mode = DEFAULT_RENDERMODE;
if (useray)
mode = RAYCAST_RENDERMODE;
else if (usegpu)
mode = GPU_RENDERMODE;
m_Controls->renderMode->setCurrentIndex(mode);
}
m_Controls->transferFunctionWidget->SetDataNode(selectedNode);
m_Controls->transferFunctionWidget->setEnabled(true);
m_Controls->transferFunctionGeneratorWidget->SetDataNode(selectedNode);
m_Controls->transferFunctionGeneratorWidget->setEnabled(true);
}
<|endoftext|>
|
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include "FFmpegHeaders.hpp"
#include "FFmpegImageStream.hpp"
#include "FFmpegParameters.hpp"
#include <osgDB/Registry>
#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>
#if LIBAVCODEC_VERSION_MAJOR >= 53 || \
(LIBAVCODEC_VERSION_MAJOR==52 && LIBAVCODEC_VERSION_MINOR>=30) || \
(LIBAVCODEC_VERSION_MAJOR==52 && LIBAVCODEC_VERSION_MINOR==20 && LIBAVCODEC_VERSION_MICRO >= 1)
#define USE_AV_LOCK_MANAGER
#endif
extern "C" {
static void log_to_osg(void* /*ptr*/, int level, const char *fmt, va_list vl)
{
char logbuf[256];
vsnprintf(logbuf, sizeof(logbuf), fmt, vl);
logbuf[sizeof(logbuf) - 1] = '\0';
osg::NotifySeverity severity = osg::DEBUG_FP;
switch (level) {
case AV_LOG_PANIC:
severity = osg::ALWAYS;
break;
case AV_LOG_FATAL:
severity = osg::FATAL;
break;
case AV_LOG_ERROR:
severity = osg::WARN;
break;
case AV_LOG_WARNING:
severity = osg::NOTICE;
break;
case AV_LOG_INFO:
severity = osg::INFO;
break;
case AV_LOG_VERBOSE:
severity = osg::DEBUG_INFO;
break;
default:
case AV_LOG_DEBUG:
severity = osg::DEBUG_FP;
break;
}
// Most av_logs have a trailing newline already
osg::notify(severity) << logbuf;
}
} // extern "C"
/** Implementation heavily inspired by http://www.dranger.com/ffmpeg/ */
class ReaderWriterFFmpeg : public osgDB::ReaderWriter
{
public:
ReaderWriterFFmpeg()
{
supportsProtocol("http","Read video/audio from http using ffmpeg.");
supportsProtocol("rtsp","Read video/audio from rtsp using ffmpeg.");
supportsProtocol("rtp","Read video/audio from rtp using ffmpeg.");
supportsProtocol("tcp","Read video/audio from tcp using ffmpeg.");
supportsExtension("ffmpeg", "");
supportsExtension("avi", "");
supportsExtension("flv", "Flash video");
supportsExtension("mov", "Quicktime");
supportsExtension("ogg", "Theora movie format");
supportsExtension("mpg", "Mpeg movie format");
supportsExtension("mpv", "Mpeg movie format");
supportsExtension("wmv", "Windows Media Video format");
supportsExtension("mkv", "Matroska");
supportsExtension("mjpeg", "Motion JPEG");
supportsExtension("mp4", "MPEG-4");
supportsExtension("m4v", "MPEG-4");
supportsExtension("sav", "Unknown");
supportsExtension("3gp", "3G multi-media format");
supportsExtension("sdp", "Session Description Protocol");
supportsExtension("m2ts", "MPEG-2 Transport Stream");
supportsExtension("ts", "MPEG-2 Transport Stream");
supportsOption("format", "Force setting input format (e.g. vfwcap for Windows webcam)");
supportsOption("pixel_format", "Set pixel format");
supportsOption("frame_size", "Set frame size (e.g. 320x240)");
supportsOption("frame_rate", "Set frame rate (e.g. 25)");
// WARNING: This option is kept for backwards compatibility only, use out_sample_rate instead!
supportsOption("audio_sample_rate", "Set audio sampling rate (e.g. 44100)");
supportsOption("out_sample_format", "Set the output sample format (e.g. AV_SAMPLE_FMT_S16)");
supportsOption("out_sample_rate", "Set the output sample rate or frequency in Hz (e.g. 48000)");
supportsOption("out_nb_channels", "Set the output number of channels (e.g. 2 for stereo)");
supportsOption("context", "AVIOContext* for custom IO");
supportsOption("mad", "Max analyze duration (seconds)");
supportsOption("rtsp_transport", "RTSP transport (udp, tcp, udp_multicast or http)");
av_log_set_callback(log_to_osg);
#ifdef USE_AV_LOCK_MANAGER
// enable thread locking
av_lockmgr_register(&lockMgr);
#endif
// Register all FFmpeg formats/codecs
av_register_all();
avformat_network_init();
}
virtual ~ReaderWriterFFmpeg()
{
}
virtual const char * className() const
{
return "ReaderWriterFFmpeg";
}
virtual ReadResult readImage(const std::string & filename, const osgDB::ReaderWriter::Options* options) const
{
const std::string ext = osgDB::getLowerCaseFileExtension(filename);
const std::string pro = osgDB::getServerProtocol(filename);
if (!acceptsExtension(ext) && !acceptsProtocol(pro)) return ReadResult::FILE_NOT_HANDLED;
if (ext=="ffmpeg") return readImage(osgDB::getNameLessExtension(filename),options);
osg::ref_ptr<osgFFmpeg::FFmpegParameters> parameters(new osgFFmpeg::FFmpegParameters);
parseOptions(parameters.get(), options);
if (filename.compare(0, 5, "/dev/")==0)
{
return readImageStream(filename, parameters.get());
}
#if 1
// NOTE: The original code checks parameters->isFormatAvailable() which returns
// false when a format is not explicitly specified.
// In these cases, the extension is used, which is a problem for videos served
// from URLs without an extension
{
ReadResult rr = readImageStream(filename, parameters.get());
if ( rr.validImage() )
return rr;
}
#else
if (parameters->isFormatAvailable())
{
return readImageStream(filename, parameters.get());
}
#endif
if (! acceptsExtension(ext))
return ReadResult::FILE_NOT_HANDLED;
const std::string path = osgDB::containsServerAddress(filename) ?
filename :
osgDB::findDataFile(filename, options);
if (path.empty())
return ReadResult::FILE_NOT_FOUND;
return readImageStream(path, parameters.get());
}
ReadResult readImageStream(const std::string& filename, osgFFmpeg::FFmpegParameters* parameters) const
{
OSG_INFO << "ReaderWriterFFmpeg::readImage " << filename << std::endl;
osg::ref_ptr<osgFFmpeg::FFmpegImageStream> image_stream(new osgFFmpeg::FFmpegImageStream);
if (! image_stream->open(filename, parameters))
return ReadResult::FILE_NOT_HANDLED;
return image_stream.release();
}
private:
void parseOptions(osgFFmpeg::FFmpegParameters* parameters, const osgDB::ReaderWriter::Options * options) const
{
if (options && options->getNumPluginStringData()>0)
{
const FormatDescriptionMap& supportedOptList = supportedOptions();
for (FormatDescriptionMap::const_iterator itr = supportedOptList.begin();
itr != supportedOptList.end(); ++itr)
{
const std::string& name = itr->first;
parameters->parse(name, options->getPluginStringData(name));
}
}
if (options && options->getNumPluginData()>0)
{
AVIOContext* context = (AVIOContext*)options->getPluginData("context");
if (context != NULL)
{
parameters->setContext(context);
}
}
}
#ifdef USE_AV_LOCK_MANAGER
static int lockMgr(void **mutex, enum AVLockOp op)
{
// returns are 0 success
OpenThreads::Mutex **m=(OpenThreads::Mutex**)mutex;
if (op==AV_LOCK_CREATE)
{
*m=new OpenThreads::Mutex;
return !*m;
}
else if (op==AV_LOCK_DESTROY)
{
delete *m;
return 0;
}
else if (op==AV_LOCK_OBTAIN)
{
(*m)->lock();
return 0;
}
else if (op==AV_LOCK_RELEASE)
{
(*m)->unlock();
return 0;
}
else
{
return -1;
}
}
#endif
};
REGISTER_OSGPLUGIN(ffmpeg, ReaderWriterFFmpeg)
<commit_msg>Fixed indentation, replacing tabs with spaces<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include "FFmpegHeaders.hpp"
#include "FFmpegImageStream.hpp"
#include "FFmpegParameters.hpp"
#include <osgDB/Registry>
#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>
#if LIBAVCODEC_VERSION_MAJOR >= 53 || \
(LIBAVCODEC_VERSION_MAJOR==52 && LIBAVCODEC_VERSION_MINOR>=30) || \
(LIBAVCODEC_VERSION_MAJOR==52 && LIBAVCODEC_VERSION_MINOR==20 && LIBAVCODEC_VERSION_MICRO >= 1)
#define USE_AV_LOCK_MANAGER
#endif
extern "C" {
static void log_to_osg(void* /*ptr*/, int level, const char *fmt, va_list vl)
{
char logbuf[256];
vsnprintf(logbuf, sizeof(logbuf), fmt, vl);
logbuf[sizeof(logbuf) - 1] = '\0';
osg::NotifySeverity severity = osg::DEBUG_FP;
switch (level) {
case AV_LOG_PANIC:
severity = osg::ALWAYS;
break;
case AV_LOG_FATAL:
severity = osg::FATAL;
break;
case AV_LOG_ERROR:
severity = osg::WARN;
break;
case AV_LOG_WARNING:
severity = osg::NOTICE;
break;
case AV_LOG_INFO:
severity = osg::INFO;
break;
case AV_LOG_VERBOSE:
severity = osg::DEBUG_INFO;
break;
default:
case AV_LOG_DEBUG:
severity = osg::DEBUG_FP;
break;
}
// Most av_logs have a trailing newline already
osg::notify(severity) << logbuf;
}
} // extern "C"
/** Implementation heavily inspired by http://www.dranger.com/ffmpeg/ */
class ReaderWriterFFmpeg : public osgDB::ReaderWriter
{
public:
ReaderWriterFFmpeg()
{
supportsProtocol("http","Read video/audio from http using ffmpeg.");
supportsProtocol("rtsp","Read video/audio from rtsp using ffmpeg.");
supportsProtocol("rtp","Read video/audio from rtp using ffmpeg.");
supportsProtocol("tcp","Read video/audio from tcp using ffmpeg.");
supportsExtension("ffmpeg", "");
supportsExtension("avi", "");
supportsExtension("flv", "Flash video");
supportsExtension("mov", "Quicktime");
supportsExtension("ogg", "Theora movie format");
supportsExtension("mpg", "Mpeg movie format");
supportsExtension("mpv", "Mpeg movie format");
supportsExtension("wmv", "Windows Media Video format");
supportsExtension("mkv", "Matroska");
supportsExtension("mjpeg", "Motion JPEG");
supportsExtension("mp4", "MPEG-4");
supportsExtension("m4v", "MPEG-4");
supportsExtension("sav", "Unknown");
supportsExtension("3gp", "3G multi-media format");
supportsExtension("sdp", "Session Description Protocol");
supportsExtension("m2ts", "MPEG-2 Transport Stream");
supportsExtension("ts", "MPEG-2 Transport Stream");
supportsOption("format", "Force setting input format (e.g. vfwcap for Windows webcam)");
supportsOption("pixel_format", "Set pixel format");
supportsOption("frame_size", "Set frame size (e.g. 320x240)");
supportsOption("frame_rate", "Set frame rate (e.g. 25)");
// WARNING: This option is kept for backwards compatibility only, use out_sample_rate instead!
supportsOption("audio_sample_rate", "Set audio sampling rate (e.g. 44100)");
supportsOption("out_sample_format", "Set the output sample format (e.g. AV_SAMPLE_FMT_S16)");
supportsOption("out_sample_rate", "Set the output sample rate or frequency in Hz (e.g. 48000)");
supportsOption("out_nb_channels", "Set the output number of channels (e.g. 2 for stereo)");
supportsOption("context", "AVIOContext* for custom IO");
supportsOption("mad", "Max analyze duration (seconds)");
supportsOption("rtsp_transport", "RTSP transport (udp, tcp, udp_multicast or http)");
av_log_set_callback(log_to_osg);
#ifdef USE_AV_LOCK_MANAGER
// enable thread locking
av_lockmgr_register(&lockMgr);
#endif
// Register all FFmpeg formats/codecs
av_register_all();
avformat_network_init();
}
virtual ~ReaderWriterFFmpeg()
{
}
virtual const char * className() const
{
return "ReaderWriterFFmpeg";
}
virtual ReadResult readImage(const std::string & filename, const osgDB::ReaderWriter::Options* options) const
{
const std::string ext = osgDB::getLowerCaseFileExtension(filename);
const std::string pro = osgDB::getServerProtocol(filename);
if (!acceptsExtension(ext) && !acceptsProtocol(pro)) return ReadResult::FILE_NOT_HANDLED;
if (ext=="ffmpeg") return readImage(osgDB::getNameLessExtension(filename),options);
osg::ref_ptr<osgFFmpeg::FFmpegParameters> parameters(new osgFFmpeg::FFmpegParameters);
parseOptions(parameters.get(), options);
if (filename.compare(0, 5, "/dev/")==0)
{
return readImageStream(filename, parameters.get());
}
#if 1
// NOTE: The original code checks parameters->isFormatAvailable() which returns
// false when a format is not explicitly specified.
// In these cases, the extension is used, which is a problem for videos served
// from URLs without an extension
{
ReadResult rr = readImageStream(filename, parameters.get());
if ( rr.validImage() )
return rr;
}
#else
if (parameters->isFormatAvailable())
{
return readImageStream(filename, parameters.get());
}
#endif
if (! acceptsExtension(ext))
return ReadResult::FILE_NOT_HANDLED;
const std::string path = osgDB::containsServerAddress(filename) ?
filename :
osgDB::findDataFile(filename, options);
if (path.empty())
return ReadResult::FILE_NOT_FOUND;
return readImageStream(path, parameters.get());
}
ReadResult readImageStream(const std::string& filename, osgFFmpeg::FFmpegParameters* parameters) const
{
OSG_INFO << "ReaderWriterFFmpeg::readImage " << filename << std::endl;
osg::ref_ptr<osgFFmpeg::FFmpegImageStream> image_stream(new osgFFmpeg::FFmpegImageStream);
if (! image_stream->open(filename, parameters))
return ReadResult::FILE_NOT_HANDLED;
return image_stream.release();
}
private:
void parseOptions(osgFFmpeg::FFmpegParameters* parameters, const osgDB::ReaderWriter::Options * options) const
{
if (options && options->getNumPluginStringData()>0)
{
const FormatDescriptionMap& supportedOptList = supportedOptions();
for (FormatDescriptionMap::const_iterator itr = supportedOptList.begin();
itr != supportedOptList.end(); ++itr)
{
const std::string& name = itr->first;
parameters->parse(name, options->getPluginStringData(name));
}
}
if (options && options->getNumPluginData()>0)
{
AVIOContext* context = (AVIOContext*)options->getPluginData("context");
if (context != NULL)
{
parameters->setContext(context);
}
}
}
#ifdef USE_AV_LOCK_MANAGER
static int lockMgr(void **mutex, enum AVLockOp op)
{
// returns are 0 success
OpenThreads::Mutex **m=(OpenThreads::Mutex**)mutex;
if (op==AV_LOCK_CREATE)
{
*m=new OpenThreads::Mutex;
return !*m;
}
else if (op==AV_LOCK_DESTROY)
{
delete *m;
return 0;
}
else if (op==AV_LOCK_OBTAIN)
{
(*m)->lock();
return 0;
}
else if (op==AV_LOCK_RELEASE)
{
(*m)->unlock();
return 0;
}
else
{
return -1;
}
}
#endif
};
REGISTER_OSGPLUGIN(ffmpeg, ReaderWriterFFmpeg)
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "buildmanager.h"
#include "buildprogress.h"
#include "buildstep.h"
#include "compileoutputwindow.h"
#include "projectexplorerconstants.h"
#include "projectexplorer.h"
#include "project.h"
#include "projectexplorersettings.h"
#include "taskwindow.h"
#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/progressmanager/futureprogress.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <QtCore/QDir>
#include <QtCore/QTimer>
#include <qtconcurrent/QtConcurrentTools>
#include <QtGui/QHeaderView>
#include <QtGui/QIcon>
#include <QtGui/QLabel>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
static inline QString msgProgress(int n, int total)
{
return BuildManager::tr("Finished %n of %1 build steps", 0, n).arg(total);
}
BuildManager::BuildManager(ProjectExplorerPlugin *parent)
: QObject(parent)
, m_running(false)
, m_previousBuildStepProject(0)
, m_canceling(false)
, m_maxProgress(0)
, m_progressFutureInterface(0)
{
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
m_projectExplorerPlugin = parent;
connect(&m_watcher, SIGNAL(finished()),
this, SLOT(nextBuildQueue()));
connect(&m_watcher, SIGNAL(progressValueChanged(int)),
this, SLOT(progressChanged()));
connect(&m_watcher, SIGNAL(progressRangeChanged(int, int)),
this, SLOT(progressChanged()));
m_outputWindow = new CompileOutputWindow(this);
pm->addObject(m_outputWindow);
m_taskWindow = new TaskWindow;
pm->addObject(m_taskWindow);
connect(m_taskWindow, SIGNAL(tasksChanged()),
this, SIGNAL(tasksChanged()));
connect(&m_progressWatcher, SIGNAL(canceled()),
this, SLOT(cancel()));
}
BuildManager::~BuildManager()
{
cancel();
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
pm->removeObject(m_taskWindow);
delete m_taskWindow;
pm->removeObject(m_outputWindow);
delete m_outputWindow;
}
bool BuildManager::isBuilding() const
{
// we are building even if we are not running yet
return !m_buildQueue.isEmpty() || m_running;
}
void BuildManager::cancel()
{
if (m_running) {
m_canceling = true;
m_watcher.cancel();
m_watcher.waitForFinished();
// The cancel message is added to the output window via a single shot timer
// since the canceling is likely to have generated new addToOutputWindow signals
// which are waiting in the event queue to be processed
// (And we want those to be before the cancel message.)
QTimer::singleShot(0, this, SLOT(emitCancelMessage()));
disconnect(m_currentBuildStep, SIGNAL(addToTaskWindow(QString, int, int, QString)),
this, SLOT(addToTaskWindow(QString, int, int, QString)));
disconnect(m_currentBuildStep, SIGNAL(addToOutputWindow(QString)),
this, SLOT(addToOutputWindow(QString)));
decrementActiveBuildSteps(m_currentBuildStep->project());
m_progressFutureInterface->setProgressValueAndText(m_progress*100, "Build canceled"); //TODO NBS fix in qtconcurrent
clearBuildQueue();
}
return;
}
void BuildManager::emitCancelMessage()
{
emit addToOutputWindow(tr("<font color=\"#ff0000\">Canceled build.</font>"));
}
void BuildManager::clearBuildQueue()
{
foreach (BuildStep * bs, m_buildQueue)
decrementActiveBuildSteps(bs->project());
m_buildQueue.clear();
m_configurations.clear();
m_running = false;
m_previousBuildStepProject = 0;
m_progressFutureInterface->reportCanceled();
m_progressFutureInterface->reportFinished();
m_progressWatcher.setFuture(QFuture<void>());
delete m_progressFutureInterface;
m_progressFutureInterface = 0;
m_maxProgress = 0;
emit buildQueueFinished(false);
}
void BuildManager::toggleOutputWindow()
{
m_outputWindow->toggle(false);
}
void BuildManager::showTaskWindow()
{
m_taskWindow->popup(false);
}
void BuildManager::toggleTaskWindow()
{
m_taskWindow->toggle(false);
}
bool BuildManager::tasksAvailable() const
{
return m_taskWindow->numberOfTasks() > 0;
}
void BuildManager::gotoTaskWindow()
{
m_taskWindow->popup(true);
}
void BuildManager::startBuildQueue()
{
if (m_buildQueue.isEmpty())
return;
if (!m_running) {
// Progress Reporting
Core::ProgressManager *progressManager = Core::ICore::instance()->progressManager();
m_progressFutureInterface = new QFutureInterface<void>;
m_progressWatcher.setFuture(m_progressFutureInterface->future());
Core::FutureProgress *progress = progressManager->addTask(m_progressFutureInterface->future(),
tr("Build"),
Constants::TASK_BUILD);
connect(progress, SIGNAL(clicked()), this, SLOT(showBuildResults()));
progress->setWidget(new BuildProgress(m_taskWindow));
m_progress = 0;
m_progressFutureInterface->setProgressRange(0, m_maxProgress * 100);
m_running = true;
m_canceling = false;
m_progressFutureInterface->reportStarted();
m_outputWindow->clearContents();
m_taskWindow->clearContents();
nextStep();
} else {
// Already running
m_progressFutureInterface->setProgressRange(0, m_maxProgress * 100);
m_progressFutureInterface->setProgressValueAndText(m_progress*100, msgProgress(m_progress, m_maxProgress));
}
}
void BuildManager::showBuildResults()
{
if (m_taskWindow->numberOfTasks() != 0)
toggleTaskWindow();
else
toggleOutputWindow();
//toggleTaskWindow();
}
void BuildManager::addToTaskWindow(const QString &file, int type, int line, const QString &description)
{
m_taskWindow->addItem(BuildParserInterface::PatternType(type), description, file, line);
}
void BuildManager::addToOutputWindow(const QString &string)
{
m_outputWindow->appendText(string);
}
void BuildManager::nextBuildQueue()
{
if (m_canceling)
return;
disconnect(m_currentBuildStep, SIGNAL(addToTaskWindow(QString, int, int, QString)),
this, SLOT(addToTaskWindow(QString, int, int, QString)));
disconnect(m_currentBuildStep, SIGNAL(addToOutputWindow(QString)),
this, SLOT(addToOutputWindow(QString)));
++m_progress;
m_progressFutureInterface->setProgressValueAndText(m_progress*100, msgProgress(m_progress, m_maxProgress));
bool result = m_watcher.result();
if (!result) {
// Build Failure
addToOutputWindow(tr("<font color=\"#ff0000\">Error while building project %1</font>").arg(m_currentBuildStep->project()->name()));
addToOutputWindow(tr("<font color=\"#ff0000\">When executing build step '%1'</font>").arg(m_currentBuildStep->displayName()));
// NBS TODO fix in qtconcurrent
m_progressFutureInterface->setProgressValueAndText(m_progress*100, tr("Error while building project %1").arg(m_currentBuildStep->project()->name()));
}
decrementActiveBuildSteps(m_currentBuildStep->project());
if (result)
nextStep();
else
clearBuildQueue();
}
void BuildManager::progressChanged()
{
if (!m_progressFutureInterface)
return;
int range = m_watcher.progressMaximum() - m_watcher.progressMinimum();
if (range != 0) {
int percent = (m_watcher.progressValue() - m_watcher.progressMinimum()) * 100 / range;
m_progressFutureInterface->setProgressValue(m_progress * 100 + percent);
}
}
void BuildManager::nextStep()
{
if (!m_buildQueue.empty()) {
m_currentBuildStep = m_buildQueue.front();
m_currentConfiguration = m_configurations.front();
m_buildQueue.pop_front();
m_configurations.pop_front();
connect(m_currentBuildStep, SIGNAL(addToTaskWindow(QString, int, int, QString)),
this, SLOT(addToTaskWindow(QString, int, int, QString)));
connect(m_currentBuildStep, SIGNAL(addToOutputWindow(QString)),
this, SLOT(addToOutputWindow(QString)));
bool init = m_currentBuildStep->init(m_currentConfiguration);
if (!init) {
addToOutputWindow(tr("<font color=\"#ff0000\">Error while building project %1</font>").arg(m_currentBuildStep->project()->name()));
addToOutputWindow(tr("<font color=\"#ff0000\">When executing build step '%1'</font>").arg(m_currentBuildStep->displayName()));
cancel();
return;
}
if (m_currentBuildStep->project() != m_previousBuildStepProject) {
const QString projectName = m_currentBuildStep->project()->name();
addToOutputWindow(tr("<b>Running build steps for project %2...</b>")
.arg(projectName));
m_previousBuildStepProject = m_currentBuildStep->project();
}
m_watcher.setFuture(QtConcurrent::run(&BuildStep::run, m_currentBuildStep));
} else {
m_running = false;
m_previousBuildStepProject = 0;
m_progressFutureInterface->reportFinished();
m_progressWatcher.setFuture(QFuture<void>());
delete m_progressFutureInterface;
m_progressFutureInterface = 0;
m_maxProgress = 0;
emit buildQueueFinished(true);
}
}
void BuildManager::buildQueueAppend(BuildStep * bs, const QString &configuration)
{
m_buildQueue.append(bs);
++m_maxProgress;
incrementActiveBuildSteps(bs->project());
m_configurations.append(configuration);
}
void BuildManager::buildProjects(const QList<Project *> &projects, const QList<QString> &configurations)
{
Q_ASSERT(projects.count() == configurations.count());
QList<QString>::const_iterator cit = configurations.constBegin();
QList<Project *>::const_iterator it, end;
end = projects.constEnd();
for (it = projects.constBegin(); it != end; ++it, ++cit) {
if (*cit != QString::null) {
QList<BuildStep *> buildSteps = (*it)->buildSteps();
foreach (BuildStep *bs, buildSteps) {
buildQueueAppend(bs, *cit);
}
}
}
startBuildQueue();
if (ProjectExplorerPlugin::instance()->projectExplorerSettings().showCompilerOutput)
m_outputWindow->popup(false);
}
void BuildManager::cleanProjects(const QList<Project *> &projects, const QList<QString> &configurations)
{
Q_ASSERT(projects.count() == configurations.count());
QList<QString>::const_iterator cit = configurations.constBegin();
QList<Project *>::const_iterator it, end;
end = projects.constEnd();
for (it = projects.constBegin(); it != end; ++it, ++cit) {
QList<BuildStep *> cleanSteps = (*it)->cleanSteps();
foreach (BuildStep *bs, cleanSteps) {
buildQueueAppend(bs, *cit);
}
}
startBuildQueue();
if (ProjectExplorerPlugin::instance()->projectExplorerSettings().showCompilerOutput)
m_outputWindow->popup(false);
}
void BuildManager::buildProject(Project *p, const QString &configuration)
{
buildProjects(QList<Project *>() << p, QList<QString>() << configuration);
}
void BuildManager::cleanProject(Project *p, const QString &configuration)
{
cleanProjects(QList<Project *>() << p, QList<QString>() << configuration);
}
void BuildManager::appendStep(BuildStep *step, const QString &configuration)
{
buildQueueAppend(step, configuration);
startBuildQueue();
}
bool BuildManager::isBuilding(Project *pro)
{
QHash<Project *, int>::iterator it = m_activeBuildSteps.find(pro);
QHash<Project *, int>::iterator end = m_activeBuildSteps.end();
if (it == end || *it == 0)
return false;
else
return true;
}
void BuildManager::incrementActiveBuildSteps(Project *pro)
{
QHash<Project *, int>::iterator it = m_activeBuildSteps.find(pro);
QHash<Project *, int>::iterator end = m_activeBuildSteps.end();
if (it == end) {
m_activeBuildSteps.insert(pro, 1);
emit buildStateChanged(pro);
} else if (*it == 0) {
++*it;
emit buildStateChanged(pro);
} else {
++*it;
}
}
void BuildManager::decrementActiveBuildSteps(Project *pro)
{
QHash<Project *, int>::iterator it = m_activeBuildSteps.find(pro);
QHash<Project *, int>::iterator end = m_activeBuildSteps.end();
if (it == end) {
Q_ASSERT(false && "BuildManager m_activeBuildSteps says project is not building, but apparently a build step was still in the queue.");
} else if (*it == 1) {
--*it;
emit buildStateChanged(pro);
} else {
--*it;
}
}
<commit_msg>Fix build & run for projects without buildsteps<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "buildmanager.h"
#include "buildprogress.h"
#include "buildstep.h"
#include "compileoutputwindow.h"
#include "projectexplorerconstants.h"
#include "projectexplorer.h"
#include "project.h"
#include "projectexplorersettings.h"
#include "taskwindow.h"
#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/progressmanager/futureprogress.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <QtCore/QDir>
#include <QtCore/QTimer>
#include <qtconcurrent/QtConcurrentTools>
#include <QtGui/QHeaderView>
#include <QtGui/QIcon>
#include <QtGui/QLabel>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
static inline QString msgProgress(int n, int total)
{
return BuildManager::tr("Finished %n of %1 build steps", 0, n).arg(total);
}
BuildManager::BuildManager(ProjectExplorerPlugin *parent)
: QObject(parent)
, m_running(false)
, m_previousBuildStepProject(0)
, m_canceling(false)
, m_maxProgress(0)
, m_progressFutureInterface(0)
{
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
m_projectExplorerPlugin = parent;
connect(&m_watcher, SIGNAL(finished()),
this, SLOT(nextBuildQueue()));
connect(&m_watcher, SIGNAL(progressValueChanged(int)),
this, SLOT(progressChanged()));
connect(&m_watcher, SIGNAL(progressRangeChanged(int, int)),
this, SLOT(progressChanged()));
m_outputWindow = new CompileOutputWindow(this);
pm->addObject(m_outputWindow);
m_taskWindow = new TaskWindow;
pm->addObject(m_taskWindow);
connect(m_taskWindow, SIGNAL(tasksChanged()),
this, SIGNAL(tasksChanged()));
connect(&m_progressWatcher, SIGNAL(canceled()),
this, SLOT(cancel()));
}
BuildManager::~BuildManager()
{
cancel();
ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
pm->removeObject(m_taskWindow);
delete m_taskWindow;
pm->removeObject(m_outputWindow);
delete m_outputWindow;
}
bool BuildManager::isBuilding() const
{
// we are building even if we are not running yet
return !m_buildQueue.isEmpty() || m_running;
}
void BuildManager::cancel()
{
if (m_running) {
m_canceling = true;
m_watcher.cancel();
m_watcher.waitForFinished();
// The cancel message is added to the output window via a single shot timer
// since the canceling is likely to have generated new addToOutputWindow signals
// which are waiting in the event queue to be processed
// (And we want those to be before the cancel message.)
QTimer::singleShot(0, this, SLOT(emitCancelMessage()));
disconnect(m_currentBuildStep, SIGNAL(addToTaskWindow(QString, int, int, QString)),
this, SLOT(addToTaskWindow(QString, int, int, QString)));
disconnect(m_currentBuildStep, SIGNAL(addToOutputWindow(QString)),
this, SLOT(addToOutputWindow(QString)));
decrementActiveBuildSteps(m_currentBuildStep->project());
m_progressFutureInterface->setProgressValueAndText(m_progress*100, "Build canceled"); //TODO NBS fix in qtconcurrent
clearBuildQueue();
}
return;
}
void BuildManager::emitCancelMessage()
{
emit addToOutputWindow(tr("<font color=\"#ff0000\">Canceled build.</font>"));
}
void BuildManager::clearBuildQueue()
{
foreach (BuildStep * bs, m_buildQueue)
decrementActiveBuildSteps(bs->project());
m_buildQueue.clear();
m_configurations.clear();
m_running = false;
m_previousBuildStepProject = 0;
m_progressFutureInterface->reportCanceled();
m_progressFutureInterface->reportFinished();
m_progressWatcher.setFuture(QFuture<void>());
delete m_progressFutureInterface;
m_progressFutureInterface = 0;
m_maxProgress = 0;
emit buildQueueFinished(false);
}
void BuildManager::toggleOutputWindow()
{
m_outputWindow->toggle(false);
}
void BuildManager::showTaskWindow()
{
m_taskWindow->popup(false);
}
void BuildManager::toggleTaskWindow()
{
m_taskWindow->toggle(false);
}
bool BuildManager::tasksAvailable() const
{
return m_taskWindow->numberOfTasks() > 0;
}
void BuildManager::gotoTaskWindow()
{
m_taskWindow->popup(true);
}
void BuildManager::startBuildQueue()
{
if (m_buildQueue.isEmpty()) {
emit buildQueueFinished(true);
return;
}
if (!m_running) {
// Progress Reporting
Core::ProgressManager *progressManager = Core::ICore::instance()->progressManager();
m_progressFutureInterface = new QFutureInterface<void>;
m_progressWatcher.setFuture(m_progressFutureInterface->future());
Core::FutureProgress *progress = progressManager->addTask(m_progressFutureInterface->future(),
tr("Build"),
Constants::TASK_BUILD);
connect(progress, SIGNAL(clicked()), this, SLOT(showBuildResults()));
progress->setWidget(new BuildProgress(m_taskWindow));
m_progress = 0;
m_progressFutureInterface->setProgressRange(0, m_maxProgress * 100);
m_running = true;
m_canceling = false;
m_progressFutureInterface->reportStarted();
m_outputWindow->clearContents();
m_taskWindow->clearContents();
nextStep();
} else {
// Already running
m_progressFutureInterface->setProgressRange(0, m_maxProgress * 100);
m_progressFutureInterface->setProgressValueAndText(m_progress*100, msgProgress(m_progress, m_maxProgress));
}
}
void BuildManager::showBuildResults()
{
if (m_taskWindow->numberOfTasks() != 0)
toggleTaskWindow();
else
toggleOutputWindow();
//toggleTaskWindow();
}
void BuildManager::addToTaskWindow(const QString &file, int type, int line, const QString &description)
{
m_taskWindow->addItem(BuildParserInterface::PatternType(type), description, file, line);
}
void BuildManager::addToOutputWindow(const QString &string)
{
m_outputWindow->appendText(string);
}
void BuildManager::nextBuildQueue()
{
if (m_canceling)
return;
disconnect(m_currentBuildStep, SIGNAL(addToTaskWindow(QString, int, int, QString)),
this, SLOT(addToTaskWindow(QString, int, int, QString)));
disconnect(m_currentBuildStep, SIGNAL(addToOutputWindow(QString)),
this, SLOT(addToOutputWindow(QString)));
++m_progress;
m_progressFutureInterface->setProgressValueAndText(m_progress*100, msgProgress(m_progress, m_maxProgress));
bool result = m_watcher.result();
if (!result) {
// Build Failure
addToOutputWindow(tr("<font color=\"#ff0000\">Error while building project %1</font>").arg(m_currentBuildStep->project()->name()));
addToOutputWindow(tr("<font color=\"#ff0000\">When executing build step '%1'</font>").arg(m_currentBuildStep->displayName()));
// NBS TODO fix in qtconcurrent
m_progressFutureInterface->setProgressValueAndText(m_progress*100, tr("Error while building project %1").arg(m_currentBuildStep->project()->name()));
}
decrementActiveBuildSteps(m_currentBuildStep->project());
if (result)
nextStep();
else
clearBuildQueue();
}
void BuildManager::progressChanged()
{
if (!m_progressFutureInterface)
return;
int range = m_watcher.progressMaximum() - m_watcher.progressMinimum();
if (range != 0) {
int percent = (m_watcher.progressValue() - m_watcher.progressMinimum()) * 100 / range;
m_progressFutureInterface->setProgressValue(m_progress * 100 + percent);
}
}
void BuildManager::nextStep()
{
if (!m_buildQueue.empty()) {
m_currentBuildStep = m_buildQueue.front();
m_currentConfiguration = m_configurations.front();
m_buildQueue.pop_front();
m_configurations.pop_front();
connect(m_currentBuildStep, SIGNAL(addToTaskWindow(QString, int, int, QString)),
this, SLOT(addToTaskWindow(QString, int, int, QString)));
connect(m_currentBuildStep, SIGNAL(addToOutputWindow(QString)),
this, SLOT(addToOutputWindow(QString)));
bool init = m_currentBuildStep->init(m_currentConfiguration);
if (!init) {
addToOutputWindow(tr("<font color=\"#ff0000\">Error while building project %1</font>").arg(m_currentBuildStep->project()->name()));
addToOutputWindow(tr("<font color=\"#ff0000\">When executing build step '%1'</font>").arg(m_currentBuildStep->displayName()));
cancel();
return;
}
if (m_currentBuildStep->project() != m_previousBuildStepProject) {
const QString projectName = m_currentBuildStep->project()->name();
addToOutputWindow(tr("<b>Running build steps for project %2...</b>")
.arg(projectName));
m_previousBuildStepProject = m_currentBuildStep->project();
}
m_watcher.setFuture(QtConcurrent::run(&BuildStep::run, m_currentBuildStep));
} else {
m_running = false;
m_previousBuildStepProject = 0;
m_progressFutureInterface->reportFinished();
m_progressWatcher.setFuture(QFuture<void>());
delete m_progressFutureInterface;
m_progressFutureInterface = 0;
m_maxProgress = 0;
emit buildQueueFinished(true);
}
}
void BuildManager::buildQueueAppend(BuildStep * bs, const QString &configuration)
{
m_buildQueue.append(bs);
++m_maxProgress;
incrementActiveBuildSteps(bs->project());
m_configurations.append(configuration);
}
void BuildManager::buildProjects(const QList<Project *> &projects, const QList<QString> &configurations)
{
Q_ASSERT(projects.count() == configurations.count());
QList<QString>::const_iterator cit = configurations.constBegin();
QList<Project *>::const_iterator it, end;
end = projects.constEnd();
for (it = projects.constBegin(); it != end; ++it, ++cit) {
if (*cit != QString::null) {
QList<BuildStep *> buildSteps = (*it)->buildSteps();
foreach (BuildStep *bs, buildSteps) {
buildQueueAppend(bs, *cit);
}
}
}
startBuildQueue();
if (ProjectExplorerPlugin::instance()->projectExplorerSettings().showCompilerOutput)
m_outputWindow->popup(false);
}
void BuildManager::cleanProjects(const QList<Project *> &projects, const QList<QString> &configurations)
{
Q_ASSERT(projects.count() == configurations.count());
QList<QString>::const_iterator cit = configurations.constBegin();
QList<Project *>::const_iterator it, end;
end = projects.constEnd();
for (it = projects.constBegin(); it != end; ++it, ++cit) {
QList<BuildStep *> cleanSteps = (*it)->cleanSteps();
foreach (BuildStep *bs, cleanSteps) {
buildQueueAppend(bs, *cit);
}
}
startBuildQueue();
if (ProjectExplorerPlugin::instance()->projectExplorerSettings().showCompilerOutput)
m_outputWindow->popup(false);
}
void BuildManager::buildProject(Project *p, const QString &configuration)
{
buildProjects(QList<Project *>() << p, QList<QString>() << configuration);
}
void BuildManager::cleanProject(Project *p, const QString &configuration)
{
cleanProjects(QList<Project *>() << p, QList<QString>() << configuration);
}
void BuildManager::appendStep(BuildStep *step, const QString &configuration)
{
buildQueueAppend(step, configuration);
startBuildQueue();
}
bool BuildManager::isBuilding(Project *pro)
{
QHash<Project *, int>::iterator it = m_activeBuildSteps.find(pro);
QHash<Project *, int>::iterator end = m_activeBuildSteps.end();
if (it == end || *it == 0)
return false;
else
return true;
}
void BuildManager::incrementActiveBuildSteps(Project *pro)
{
QHash<Project *, int>::iterator it = m_activeBuildSteps.find(pro);
QHash<Project *, int>::iterator end = m_activeBuildSteps.end();
if (it == end) {
m_activeBuildSteps.insert(pro, 1);
emit buildStateChanged(pro);
} else if (*it == 0) {
++*it;
emit buildStateChanged(pro);
} else {
++*it;
}
}
void BuildManager::decrementActiveBuildSteps(Project *pro)
{
QHash<Project *, int>::iterator it = m_activeBuildSteps.find(pro);
QHash<Project *, int>::iterator end = m_activeBuildSteps.end();
if (it == end) {
Q_ASSERT(false && "BuildManager m_activeBuildSteps says project is not building, but apparently a build step was still in the queue.");
} else if (*it == 1) {
--*it;
emit buildStateChanged(pro);
} else {
--*it;
}
}
<|endoftext|>
|
<commit_before>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2010 Siddharth Srivastava <akssps011@gmail.com>
//
#include "RoutingPlugin.h"
#include "ui_RoutingItemWidget.h"
#include "MarbleWidget.h"
#include "routing/RoutingManager.h"
#include "routing/RoutingModel.h"
#include "MarbleDirs.h"
#include "MarbleWidget.h"
#include "MarbleModel.h"
#include "MarbleMap.h"
#include "MarbleDataFacade.h"
#include "gps/PositionTracking.h"
#include "GeoPainter.h"
#include "ViewportParams.h"
#include "WidgetGraphicsItem.h"
#include "MarbleGraphicsGridLayout.h"
#include "global.h"
#include <QtGui/QIcon>
#include <QtCore/QRect>
#include <QtGui/QColor>
#include <QtGui/QPixmap>
#include <QtGui/QWidget>
using namespace Marble;
RoutingPlugin::RoutingPlugin( const QPointF &point )
:AbstractFloatItem( point ),
m_routingModel( 0 ),
m_routingManager( 0 ),
m_remainingTime( 0.0 ),
m_remainingDistance( 0.0 ),
m_routingItem( 0 ),
m_widgetItem( 0 )
{
setEnabled( true );
setVisible( false );
}
RoutingPlugin::~RoutingPlugin ()
{
}
QStringList RoutingPlugin::backendTypes() const
{
return QStringList( "routing" );
}
QString RoutingPlugin::name() const
{
return tr( "Routing" );
}
QString RoutingPlugin::guiString() const
{
return tr( "&Routing" );
}
QString RoutingPlugin::nameId() const
{
return QString("routing");
}
QString RoutingPlugin::description() const
{
return tr( "Shows the information about the route" );
}
QIcon RoutingPlugin::icon() const
{
return QIcon();
}
void RoutingPlugin::initialize()
{
QWidget *widget = new QWidget( 0 );
m_routingItem = new Ui::RoutingItemWidget;
m_routingItem->setupUi( widget );
m_widgetItem = new WidgetGraphicsItem( this );
m_widgetItem->setWidget( widget );
MarbleGraphicsGridLayout *gridLayout = new MarbleGraphicsGridLayout( 1, 1 );
gridLayout->addItem( m_widgetItem ,0 ,0 );
setLayout( gridLayout );
}
bool RoutingPlugin::isInitialized() const
{
return m_widgetItem;
}
void RoutingPlugin::setDestinationInformation( qreal remainingTime, qreal remainingDistance )
{
m_remainingTime = remainingTime;
m_remainingDistance = remainingDistance;
}
bool RoutingPlugin::eventFilter(QObject *object, QEvent *e)
{
if( m_routingManager ) {
return AbstractFloatItem::eventFilter( object, e );
}
MarbleWidget *marbleWidget = dynamic_cast<MarbleWidget*> ( object );
m_routingManager = dataFacade()->routingManager();
m_routingModel = m_routingManager->routingModel();
connect( m_routingModel, SIGNAL( nextInstruction( qreal, qreal ) ),
this, SLOT( setDestinationInformation( qreal, qreal ) ) );
PositionTracking *tracking = marbleWidget->map()->model()->positionTracking();
connect( tracking, SIGNAL( gpsLocation( GeoDataCoordinates, qreal ) ),
this, SLOT( setCurrentLocation( GeoDataCoordinates, qreal ) ) );
return AbstractFloatItem::eventFilter( object, e );
}
void RoutingPlugin::setCurrentLocation( GeoDataCoordinates position, qreal speed )
{
m_currentPosition = position;
bool hasRoute = m_routingModel->rowCount() != 0;
setVisible( hasRoute );
if ( hasRoute ) {
showRoutingItem();
}
}
void RoutingPlugin::showRoutingItem()
{
if( m_remainingTime < 60 ) {
m_routingItem->timeUnitLabel->setText( tr( "Minutes" ) );
m_routingItem->remainingTimeLabel->setText( QString::number( m_remainingTime, 'f', 2 ) );
}
else {
m_routingItem->timeUnitLabel->setText( tr( "Hours" ) );
m_routingItem->remainingTimeLabel->setText( QString::number( m_remainingTime * MIN2HOUR, 'f', 2 ) );
}
if( m_remainingDistance < 1000 ) {
m_routingItem->distanceUnitLabel->setText( tr( "Metres" ) );
m_routingItem->remainingDistanceLabel->setText( QString::number( m_remainingDistance, 'f', 3 ) );
}
else {
m_routingItem->distanceUnitLabel->setText( tr( "KM" ) );
m_routingItem->remainingDistanceLabel->setText( QString::number( m_remainingDistance * METER2KM , 'f', 3 ) );
}
qreal totalDistance = ( m_routingManager->routingModel()->totalDistance() ) ;
if( !m_routingModel->deviatedFromRoute() && m_remainingDistance !=0 && m_remainingTime != 0 ) {
m_routingItem->distanceCoveredProgressBar->setRange( 0, qRound( totalDistance ) );
m_routingItem->distanceCoveredProgressBar->setValue( qRound ( totalDistance - m_remainingDistance ) );
}
if ( m_remainingDistance == 0 && m_remainingTime == 0 ) {
m_routingItem->distanceCoveredProgressBar->setValue( qRound( totalDistance ) );
}
}
Q_EXPORT_PLUGIN2( RoutingPlugin, Marble::RoutingPlugin )
#include "RoutingPlugin.moc"
<commit_msg>fix compiler warnings (init order, unused variable)<commit_after>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2010 Siddharth Srivastava <akssps011@gmail.com>
//
#include "RoutingPlugin.h"
#include "ui_RoutingItemWidget.h"
#include "MarbleWidget.h"
#include "routing/RoutingManager.h"
#include "routing/RoutingModel.h"
#include "MarbleDirs.h"
#include "MarbleWidget.h"
#include "MarbleModel.h"
#include "MarbleMap.h"
#include "MarbleDataFacade.h"
#include "gps/PositionTracking.h"
#include "GeoPainter.h"
#include "ViewportParams.h"
#include "WidgetGraphicsItem.h"
#include "MarbleGraphicsGridLayout.h"
#include "global.h"
#include <QtGui/QIcon>
#include <QtCore/QRect>
#include <QtGui/QColor>
#include <QtGui/QPixmap>
#include <QtGui/QWidget>
using namespace Marble;
RoutingPlugin::RoutingPlugin( const QPointF &point )
:AbstractFloatItem( point ),
m_routingManager( 0 ),
m_routingModel( 0 ),
m_remainingTime( 0.0 ),
m_remainingDistance( 0.0 ),
m_widgetItem( 0 ),
m_routingItem( 0 )
{
setEnabled( true );
setVisible( false );
}
RoutingPlugin::~RoutingPlugin ()
{
}
QStringList RoutingPlugin::backendTypes() const
{
return QStringList( "routing" );
}
QString RoutingPlugin::name() const
{
return tr( "Routing" );
}
QString RoutingPlugin::guiString() const
{
return tr( "&Routing" );
}
QString RoutingPlugin::nameId() const
{
return QString("routing");
}
QString RoutingPlugin::description() const
{
return tr( "Shows the information about the route" );
}
QIcon RoutingPlugin::icon() const
{
return QIcon();
}
void RoutingPlugin::initialize()
{
QWidget *widget = new QWidget( 0 );
m_routingItem = new Ui::RoutingItemWidget;
m_routingItem->setupUi( widget );
m_widgetItem = new WidgetGraphicsItem( this );
m_widgetItem->setWidget( widget );
MarbleGraphicsGridLayout *gridLayout = new MarbleGraphicsGridLayout( 1, 1 );
gridLayout->addItem( m_widgetItem ,0 ,0 );
setLayout( gridLayout );
}
bool RoutingPlugin::isInitialized() const
{
return m_widgetItem;
}
void RoutingPlugin::setDestinationInformation( qreal remainingTime, qreal remainingDistance )
{
m_remainingTime = remainingTime;
m_remainingDistance = remainingDistance;
}
bool RoutingPlugin::eventFilter(QObject *object, QEvent *e)
{
if( m_routingManager ) {
return AbstractFloatItem::eventFilter( object, e );
}
MarbleWidget *marbleWidget = dynamic_cast<MarbleWidget*> ( object );
m_routingManager = dataFacade()->routingManager();
m_routingModel = m_routingManager->routingModel();
connect( m_routingModel, SIGNAL( nextInstruction( qreal, qreal ) ),
this, SLOT( setDestinationInformation( qreal, qreal ) ) );
PositionTracking *tracking = marbleWidget->map()->model()->positionTracking();
connect( tracking, SIGNAL( gpsLocation( GeoDataCoordinates, qreal ) ),
this, SLOT( setCurrentLocation( GeoDataCoordinates, qreal ) ) );
return AbstractFloatItem::eventFilter( object, e );
}
void RoutingPlugin::setCurrentLocation( GeoDataCoordinates position, qreal speed )
{
Q_UNUSED(speed);
m_currentPosition = position;
bool hasRoute = m_routingModel->rowCount() != 0;
setVisible( hasRoute );
if ( hasRoute ) {
showRoutingItem();
}
}
void RoutingPlugin::showRoutingItem()
{
if( m_remainingTime < 60 ) {
m_routingItem->timeUnitLabel->setText( tr( "Minutes" ) );
m_routingItem->remainingTimeLabel->setText( QString::number( m_remainingTime, 'f', 2 ) );
}
else {
m_routingItem->timeUnitLabel->setText( tr( "Hours" ) );
m_routingItem->remainingTimeLabel->setText( QString::number( m_remainingTime * MIN2HOUR, 'f', 2 ) );
}
if( m_remainingDistance < 1000 ) {
m_routingItem->distanceUnitLabel->setText( tr( "Metres" ) );
m_routingItem->remainingDistanceLabel->setText( QString::number( m_remainingDistance, 'f', 3 ) );
}
else {
m_routingItem->distanceUnitLabel->setText( tr( "KM" ) );
m_routingItem->remainingDistanceLabel->setText( QString::number( m_remainingDistance * METER2KM , 'f', 3 ) );
}
qreal totalDistance = ( m_routingManager->routingModel()->totalDistance() ) ;
if( !m_routingModel->deviatedFromRoute() && m_remainingDistance !=0 && m_remainingTime != 0 ) {
m_routingItem->distanceCoveredProgressBar->setRange( 0, qRound( totalDistance ) );
m_routingItem->distanceCoveredProgressBar->setValue( qRound ( totalDistance - m_remainingDistance ) );
}
if ( m_remainingDistance == 0 && m_remainingTime == 0 ) {
m_routingItem->distanceCoveredProgressBar->setValue( qRound( totalDistance ) );
}
}
Q_EXPORT_PLUGIN2( RoutingPlugin, Marble::RoutingPlugin )
#include "RoutingPlugin.moc"
<|endoftext|>
|
<commit_before>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2010 Dennis Nienhüser <earthwings@gentoo.org>
//
#include "RoutinoPlugin.h"
#include "RoutinoRunner.h"
#include "ui_RoutinoConfigWidget.h"
namespace Marble
{
RoutinoPlugin::RoutinoPlugin( QObject *parent ) : RunnerPlugin( parent )
{
setCapabilities( Routing );
setSupportedCelestialBodies( QStringList() << "earth" );
setCanWorkOffline( true );
setName( tr( "Routino" ) );
setNameId( "routino" );
setDescription( tr( "Retrieves routes from routino" ) );
setGuiString( tr( "Routino Routing" ) );
}
MarbleAbstractRunner* RoutinoPlugin::newRunner() const
{
return new RoutinoRunner;
}
class RoutinoConfigWidget : public RunnerPlugin::ConfigWidget
{
public:
RoutinoConfigWidget()
: RunnerPlugin::ConfigWidget()
{
ui_configWidget = new Ui::RoutinoConfigWidget;
ui_configWidget->setupUi( this );
QStringList transports;
//TODO: read from profiles.xml
//TODO: translate
transports << "foot" << "horse" << "wheelchair" << "bicycle" << "moped" << "motorbike" << "motorcar" << "goods" << "hgv" << "psv";
foreach ( const QString &transport, transports) {
ui_configWidget->transport->addItem(transport, transport);
}
}
virtual void loadSettings( const QHash<QString, QVariant> &settings_ )
{
QHash<QString, QVariant> settings = settings_;
// Check if all fields are filled and fill them with default values.
if ( !settings.contains( "transport" ) ) {
settings.insert( "transport", "motorcar" );
}
ui_configWidget->transport->setCurrentIndex(
ui_configWidget->transport->findData( settings.value( "transport" ).toString() ) );
if ( settings.value( "method" ).toString() == "shortest" ) {
ui_configWidget->shortest->setChecked( true );
} else {
ui_configWidget->fastest->setChecked( true );
}
}
virtual QHash<QString, QVariant> settings() const
{
QHash<QString,QVariant> settings;
settings.insert( "transport",
ui_configWidget->transport->itemData( ui_configWidget->transport->currentIndex() ) );
if ( ui_configWidget->shortest->isChecked() ) {
settings.insert( "method", "shortest" );
} else {
settings.insert( "method", "fastest" );
}
return settings;
}
private:
Ui::RoutinoConfigWidget *ui_configWidget;
};
RunnerPlugin::ConfigWidget *RoutinoPlugin::configWidget() const
{
return new RoutinoConfigWidget();
}
bool RoutinoPlugin::supportsTemplate(RoutingProfilesModel::ProfileTemplate profileTemplate) const
{
QSet<RoutingProfilesModel::ProfileTemplate> availableTemplates;
availableTemplates.insert( RoutingProfilesModel::CarFastestTemplate );
availableTemplates.insert( RoutingProfilesModel::CarShortestTemplate );
availableTemplates.insert( RoutingProfilesModel::BicycleTemplate );
availableTemplates.insert( RoutingProfilesModel::PedestrianTemplate );
return availableTemplates.contains( profileTemplate );
}
QHash< QString, QVariant > RoutinoPlugin::templateSettings(RoutingProfilesModel::ProfileTemplate profileTemplate) const
{
QHash<QString, QVariant> result;
switch ( profileTemplate ) {
case RoutingProfilesModel::CarFastestTemplate:
result["transport"] = "motorcar";
result["method"] = "fastest";
break;
case RoutingProfilesModel::CarShortestTemplate:
result["transport"] = "motorcar";
result["method"] = "shortest";
break;
case RoutingProfilesModel::CarEcologicalTemplate:
break;
case RoutingProfilesModel::BicycleTemplate:
result["transport"] = "bicycle";
result["method"] = "shortest";
break;
case RoutingProfilesModel::PedestrianTemplate:
result["transport"] = "foot";
result["method"] = "shortest";
break;
case RoutingProfilesModel::LastTemplate:
Q_ASSERT( false );
break;
}
return result;
}
}
Q_EXPORT_PLUGIN2( RoutinoPlugin, Marble::RoutinoPlugin )
#include "RoutinoPlugin.moc"
<commit_msg>Fix mem leak<commit_after>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2010 Dennis Nienhüser <earthwings@gentoo.org>
//
#include "RoutinoPlugin.h"
#include "RoutinoRunner.h"
#include "ui_RoutinoConfigWidget.h"
namespace Marble
{
RoutinoPlugin::RoutinoPlugin( QObject *parent ) : RunnerPlugin( parent )
{
setCapabilities( Routing );
setSupportedCelestialBodies( QStringList() << "earth" );
setCanWorkOffline( true );
setName( tr( "Routino" ) );
setNameId( "routino" );
setDescription( tr( "Retrieves routes from routino" ) );
setGuiString( tr( "Routino Routing" ) );
}
MarbleAbstractRunner* RoutinoPlugin::newRunner() const
{
return new RoutinoRunner;
}
class RoutinoConfigWidget : public RunnerPlugin::ConfigWidget
{
public:
RoutinoConfigWidget()
: RunnerPlugin::ConfigWidget()
{
ui_configWidget = new Ui::RoutinoConfigWidget;
ui_configWidget->setupUi( this );
QStringList transports;
//TODO: read from profiles.xml
//TODO: translate
transports << "foot" << "horse" << "wheelchair" << "bicycle" << "moped" << "motorbike" << "motorcar" << "goods" << "hgv" << "psv";
foreach ( const QString &transport, transports) {
ui_configWidget->transport->addItem(transport, transport);
}
}
virtual ~RoutinoConfigWidget()
{
delete ui_configWidget;
}
virtual void loadSettings( const QHash<QString, QVariant> &settings_ )
{
QHash<QString, QVariant> settings = settings_;
// Check if all fields are filled and fill them with default values.
if ( !settings.contains( "transport" ) ) {
settings.insert( "transport", "motorcar" );
}
ui_configWidget->transport->setCurrentIndex(
ui_configWidget->transport->findData( settings.value( "transport" ).toString() ) );
if ( settings.value( "method" ).toString() == "shortest" ) {
ui_configWidget->shortest->setChecked( true );
} else {
ui_configWidget->fastest->setChecked( true );
}
}
virtual QHash<QString, QVariant> settings() const
{
QHash<QString,QVariant> settings;
settings.insert( "transport",
ui_configWidget->transport->itemData( ui_configWidget->transport->currentIndex() ) );
if ( ui_configWidget->shortest->isChecked() ) {
settings.insert( "method", "shortest" );
} else {
settings.insert( "method", "fastest" );
}
return settings;
}
private:
Ui::RoutinoConfigWidget *ui_configWidget;
};
RunnerPlugin::ConfigWidget *RoutinoPlugin::configWidget() const
{
return new RoutinoConfigWidget();
}
bool RoutinoPlugin::supportsTemplate(RoutingProfilesModel::ProfileTemplate profileTemplate) const
{
QSet<RoutingProfilesModel::ProfileTemplate> availableTemplates;
availableTemplates.insert( RoutingProfilesModel::CarFastestTemplate );
availableTemplates.insert( RoutingProfilesModel::CarShortestTemplate );
availableTemplates.insert( RoutingProfilesModel::BicycleTemplate );
availableTemplates.insert( RoutingProfilesModel::PedestrianTemplate );
return availableTemplates.contains( profileTemplate );
}
QHash< QString, QVariant > RoutinoPlugin::templateSettings(RoutingProfilesModel::ProfileTemplate profileTemplate) const
{
QHash<QString, QVariant> result;
switch ( profileTemplate ) {
case RoutingProfilesModel::CarFastestTemplate:
result["transport"] = "motorcar";
result["method"] = "fastest";
break;
case RoutingProfilesModel::CarShortestTemplate:
result["transport"] = "motorcar";
result["method"] = "shortest";
break;
case RoutingProfilesModel::CarEcologicalTemplate:
break;
case RoutingProfilesModel::BicycleTemplate:
result["transport"] = "bicycle";
result["method"] = "shortest";
break;
case RoutingProfilesModel::PedestrianTemplate:
result["transport"] = "foot";
result["method"] = "shortest";
break;
case RoutingProfilesModel::LastTemplate:
Q_ASSERT( false );
break;
}
return result;
}
}
Q_EXPORT_PLUGIN2( RoutinoPlugin, Marble::RoutinoPlugin )
#include "RoutinoPlugin.moc"
<|endoftext|>
|
<commit_before>//******************************************************************************
//******************************************************************************
#include "xbridgetransactionsview.h"
// #include "../xbridgeapp.h"
// #include "xbridgetransactiondialog.h"
#include "xbridge/xbridgeexchange.h"
#include "xbridge/xuiconnector.h"
#include "xbridge/util/logger.h"
#include <QTableView>
#include <QHeaderView>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QLabel>
#include <QTextEdit>
#include <QFile>
//******************************************************************************
//******************************************************************************
XBridgeTransactionsView::XBridgeTransactionsView(QWidget *parent)
: QWidget(parent)
// , m_walletModel(0)
, m_dlg(m_txModel, this)
{
setupUi();
}
//******************************************************************************
//******************************************************************************
XBridgeTransactionsView::~XBridgeTransactionsView()
{
xuiConnector.NotifyLogMessage.disconnect
(boost::bind(&XBridgeTransactionsView::onLogString, this, _1));
}
//******************************************************************************
//******************************************************************************
void XBridgeTransactionsView::setupUi()
{
QVBoxLayout * vbox = new QVBoxLayout;
QLabel * l = new QLabel(tr("Blocknet Decentralized Exchange"), this);
vbox->addWidget(l);
m_transactionsProxy.setSourceModel(&m_txModel);
m_transactionsProxy.setDynamicSortFilter(true);
QList<XBridgeTransactionDescr::State> transactionsAccetpedStates;
transactionsAccetpedStates << XBridgeTransactionDescr::trNew
<< XBridgeTransactionDescr::trPending
<< XBridgeTransactionDescr::trAccepting
<< XBridgeTransactionDescr::trHold
<< XBridgeTransactionDescr::trCreated
<< XBridgeTransactionDescr::trSigned
<< XBridgeTransactionDescr::trCommited;
m_transactionsProxy.setAcceptedStates(transactionsAccetpedStates);
m_transactionsList = new QTableView(this);
m_transactionsList->setModel(&m_transactionsProxy);
m_transactionsList->setContextMenuPolicy(Qt::CustomContextMenu);
m_transactionsList->setSelectionBehavior(QAbstractItemView::SelectRows);
m_transactionsList->setSortingEnabled(true);
connect(m_transactionsList, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(onContextMenu(QPoint)));
QHeaderView * header = m_transactionsList->horizontalHeader();
#if QT_VERSION <0x050000
header->setResizeMode(XBridgeTransactionsModel::Total, QHeaderView::Stretch);
#else
header->setSectionResizeMode(XBridgeTransactionsModel::Total, QHeaderView::Stretch);
#endif
#if QT_VERSION <0x050000
header->setResizeMode(XBridgeTransactionsModel::Size, QHeaderView::Stretch);
#else
header->setSectionResizeMode(XBridgeTransactionsModel::Size, QHeaderView::Stretch);
#endif
#if QT_VERSION <0x050000
header->setResizeMode(XBridgeTransactionsModel::BID, QHeaderView::Stretch);
#else
header->setSectionResizeMode(XBridgeTransactionsModel::BID, QHeaderView::Stretch);
#endif
header->resizeSection(XBridgeTransactionsModel::Total, 80);
header->resizeSection(XBridgeTransactionsModel::Size, 80);
header->resizeSection(XBridgeTransactionsModel::BID, 80);
header->resizeSection(XBridgeTransactionsModel::State, 128);
vbox->addWidget(m_transactionsList);
QHBoxLayout * hbox = new QHBoxLayout;
XBridgeExchange & e = XBridgeExchange::instance();
if (!e.isEnabled())
{
QPushButton * addTxBtn = new QPushButton(trUtf8("New Transaction"), this);
// addTxBtn->setIcon(QIcon("qrc://"))
connect(addTxBtn, SIGNAL(clicked()), this, SLOT(onNewTransaction()));
hbox->addWidget(addTxBtn);
}
else
{
QPushButton * addTxBtn = new QPushButton(trUtf8("Exchange node"), this);
addTxBtn->setEnabled(false);
hbox->addWidget(addTxBtn);
}
hbox->addStretch();
QPushButton * showHideButton = new QPushButton("Toggle to log", this);
connect(showHideButton, SIGNAL(clicked()), this, SLOT(onToggleHistoricLogs()));
hbox->addWidget(showHideButton);
vbox->addLayout(hbox);
m_historicTransactionsProxy.setSourceModel(&m_txModel);
m_historicTransactionsProxy.setDynamicSortFilter(true);
QList<XBridgeTransactionDescr::State> historicTransactionsAccetpedStates;
historicTransactionsAccetpedStates << XBridgeTransactionDescr::trExpired
<< XBridgeTransactionDescr::trOffline
<< XBridgeTransactionDescr::trFinished
<< XBridgeTransactionDescr::trDropped
<< XBridgeTransactionDescr::trCancelled
<< XBridgeTransactionDescr::trInvalid;
m_historicTransactionsProxy.setAcceptedStates(historicTransactionsAccetpedStates);
m_historicTransactionsList = new QTableView(this);
m_historicTransactionsList->setModel(&m_historicTransactionsProxy);
m_historicTransactionsList->setContextMenuPolicy(Qt::CustomContextMenu);
m_historicTransactionsList->setSelectionBehavior(QAbstractItemView::SelectRows);
m_historicTransactionsList->setSortingEnabled(true);
QHeaderView * historicHeader = m_historicTransactionsList->horizontalHeader();
#if QT_VERSION <0x050000
header->setResizeMode(XBridgeTransactionsModel::Total, QHeaderView::Stretch);
#else
historicHeader->setSectionResizeMode(XBridgeTransactionsModel::Total, QHeaderView::Stretch);
#endif
#if QT_VERSION <0x050000
header->setResizeMode(XBridgeTransactionsModel::Size, QHeaderView::Stretch);
#else
historicHeader->setSectionResizeMode(XBridgeTransactionsModel::Size, QHeaderView::Stretch);
#endif
#if QT_VERSION <0x050000
header->setResizeMode(XBridgeTransactionsModel::BID, QHeaderView::Stretch);
#else
historicHeader->setSectionResizeMode(XBridgeTransactionsModel::BID, QHeaderView::Stretch);
#endif
historicHeader->resizeSection(XBridgeTransactionsModel::Total, 80);
historicHeader->resizeSection(XBridgeTransactionsModel::Size, 80);
historicHeader->resizeSection(XBridgeTransactionsModel::BID, 80);
historicHeader->resizeSection(XBridgeTransactionsModel::State, 128);
vbox->addWidget(m_historicTransactionsList);
m_logStrings = new QTextEdit(this);
m_logStrings->setMinimumHeight(64);
m_logStrings->setReadOnly(true);
m_logStrings->setVisible(false);
vbox->addWidget(m_logStrings);
setLayout(vbox);
xuiConnector.NotifyLogMessage.connect
(boost::bind(&XBridgeTransactionsView::onLogString, this, _1));
}
//******************************************************************************
//******************************************************************************
QMenu * XBridgeTransactionsView::setupContextMenu(QModelIndex & index)
{
QMenu * contextMenu = new QMenu();
if (!m_txModel.isMyTransaction(index.row()))
{
QAction * acceptTransaction = new QAction(tr("&Accept transaction"), this);
contextMenu->addAction(acceptTransaction);
connect(acceptTransaction, SIGNAL(triggered()),
this, SLOT(onAcceptTransaction()));
}
else
{
QAction * cancelTransaction = new QAction(tr("&Cancel transaction"), this);
contextMenu->addAction(cancelTransaction);
connect(cancelTransaction, SIGNAL(triggered()),
this, SLOT(onCancelTransaction()));
}
if (false)
{
QAction * rollbackTransaction = new QAction(tr("&Rollback transaction"), this);
contextMenu->addAction(rollbackTransaction);
connect(rollbackTransaction, SIGNAL(triggered()),
this, SLOT(onRollbackTransaction()));
}
return contextMenu;
}
//******************************************************************************
//******************************************************************************
void XBridgeTransactionsView::onNewTransaction()
{
m_dlg.setPendingId(uint256(), std::vector<unsigned char>());
m_dlg.show();
}
//******************************************************************************
//******************************************************************************
void XBridgeTransactionsView::onAcceptTransaction()
{
if (!m_contextMenuIndex.isValid())
{
return;
}
if (m_txModel.isMyTransaction(m_contextMenuIndex.row()))
{
return;
}
XBridgeTransactionDescr d = m_txModel.item(m_contextMenuIndex.row());
if (d.state != XBridgeTransactionDescr::trPending)
{
return;
}
m_dlg.setPendingId(d.id, d.hubAddress);
m_dlg.setFromAmount((double)d.toAmount / XBridgeTransactionDescr::COIN);
m_dlg.setToAmount((double)d.fromAmount / XBridgeTransactionDescr::COIN);
m_dlg.setFromCurrency(QString::fromStdString(d.toCurrency));
m_dlg.setToCurrency(QString::fromStdString(d.fromCurrency));
m_dlg.show();
}
//******************************************************************************
//******************************************************************************
void XBridgeTransactionsView::onCancelTransaction()
{
if (!m_contextMenuIndex.isValid())
{
return;
}
if (QMessageBox::warning(this,
trUtf8("Cancel transaction"),
trUtf8("Are you sure?"),
QMessageBox::Yes | QMessageBox::Cancel,
QMessageBox::Cancel) != QMessageBox::Yes)
{
return;
}
if (!m_txModel.cancelTransaction(m_txModel.item(m_contextMenuIndex.row()).id))
{
QMessageBox::warning(this,
trUtf8("Cancel transaction"),
trUtf8("Error send cancel request"));
}
}
//******************************************************************************
//******************************************************************************
void XBridgeTransactionsView::onRollbackTransaction()
{
if (!m_contextMenuIndex.isValid())
{
return;
}
if (QMessageBox::warning(this,
trUtf8("Rollback transaction"),
trUtf8("Are you sure?"),
QMessageBox::Yes | QMessageBox::Cancel,
QMessageBox::Cancel) != QMessageBox::Yes)
{
return;
}
if (!m_txModel.cancelTransaction(m_txModel.item(m_contextMenuIndex.row()).id))
{
QMessageBox::warning(this,
trUtf8("Cancel transaction"),
trUtf8("Error send cancel request"));
}
}
//******************************************************************************
//******************************************************************************
void XBridgeTransactionsView::onContextMenu(QPoint /*pt*/)
{
XBridgeExchange & e = XBridgeExchange::instance();
if (e.isEnabled())
{
return;
}
m_contextMenuIndex = m_transactionsList->selectionModel()->currentIndex();
if (!m_contextMenuIndex.isValid())
{
return;
}
m_contextMenuIndex = m_transactionsProxy.mapToSource(m_contextMenuIndex);
if (!m_contextMenuIndex.isValid())
{
return;
}
QMenu * contextMenu = setupContextMenu(m_contextMenuIndex);
contextMenu->exec(QCursor::pos());
contextMenu->deleteLater();
}
//******************************************************************************
//******************************************************************************
void XBridgeTransactionsView::onToggleHistoricLogs()
{
QPushButton * btn = qobject_cast<QPushButton *>(sender());
bool logsVisible = m_logStrings->isVisible();
bool historicTrVisible = m_historicTransactionsList->isVisible();
if(logsVisible)
btn->setText("Toggle to log");
else if(historicTrVisible)
btn->setText("Toggle to history");
m_logStrings->setVisible(!logsVisible);
m_historicTransactionsList->setVisible(!historicTrVisible);
if (!logsVisible)
{
m_logStrings->clear();
// show, load all logs
QFile f(QString::fromStdString(LOG::logFileName()));
if (f.open(QIODevice::ReadOnly))
{
m_logStrings->insertPlainText(f.readAll());
}
}
}
//******************************************************************************
//******************************************************************************
void XBridgeTransactionsView::onLogString(const std::string str)
{
const QString qstr = QString::fromStdString(str);
m_logStrings->insertPlainText(qstr);
// QTextCursor c = m_logStrings->textCursor();
// c.movePosition(QTextCursor::End);
// m_logStrings->setTextCursor(c);
// m_logStrings->ensureCursorVisible();
}
<commit_msg>rollback tx menu item<commit_after>//******************************************************************************
//******************************************************************************
#include "xbridgetransactionsview.h"
// #include "../xbridgeapp.h"
// #include "xbridgetransactiondialog.h"
#include "xbridge/xbridgeexchange.h"
#include "xbridge/xuiconnector.h"
#include "xbridge/util/logger.h"
#include <QTableView>
#include <QHeaderView>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QLabel>
#include <QTextEdit>
#include <QFile>
//******************************************************************************
//******************************************************************************
XBridgeTransactionsView::XBridgeTransactionsView(QWidget *parent)
: QWidget(parent)
// , m_walletModel(0)
, m_dlg(m_txModel, this)
{
setupUi();
}
//******************************************************************************
//******************************************************************************
XBridgeTransactionsView::~XBridgeTransactionsView()
{
xuiConnector.NotifyLogMessage.disconnect
(boost::bind(&XBridgeTransactionsView::onLogString, this, _1));
}
//******************************************************************************
//******************************************************************************
void XBridgeTransactionsView::setupUi()
{
QVBoxLayout * vbox = new QVBoxLayout;
QLabel * l = new QLabel(tr("Blocknet Decentralized Exchange"), this);
vbox->addWidget(l);
m_transactionsProxy.setSourceModel(&m_txModel);
m_transactionsProxy.setDynamicSortFilter(true);
QList<XBridgeTransactionDescr::State> transactionsAccetpedStates;
transactionsAccetpedStates << XBridgeTransactionDescr::trNew
<< XBridgeTransactionDescr::trPending
<< XBridgeTransactionDescr::trAccepting
<< XBridgeTransactionDescr::trHold
<< XBridgeTransactionDescr::trCreated
<< XBridgeTransactionDescr::trSigned
<< XBridgeTransactionDescr::trCommited;
m_transactionsProxy.setAcceptedStates(transactionsAccetpedStates);
m_transactionsList = new QTableView(this);
m_transactionsList->setModel(&m_transactionsProxy);
m_transactionsList->setContextMenuPolicy(Qt::CustomContextMenu);
m_transactionsList->setSelectionBehavior(QAbstractItemView::SelectRows);
m_transactionsList->setSortingEnabled(true);
connect(m_transactionsList, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(onContextMenu(QPoint)));
QHeaderView * header = m_transactionsList->horizontalHeader();
#if QT_VERSION <0x050000
header->setResizeMode(XBridgeTransactionsModel::Total, QHeaderView::Stretch);
#else
header->setSectionResizeMode(XBridgeTransactionsModel::Total, QHeaderView::Stretch);
#endif
#if QT_VERSION <0x050000
header->setResizeMode(XBridgeTransactionsModel::Size, QHeaderView::Stretch);
#else
header->setSectionResizeMode(XBridgeTransactionsModel::Size, QHeaderView::Stretch);
#endif
#if QT_VERSION <0x050000
header->setResizeMode(XBridgeTransactionsModel::BID, QHeaderView::Stretch);
#else
header->setSectionResizeMode(XBridgeTransactionsModel::BID, QHeaderView::Stretch);
#endif
header->resizeSection(XBridgeTransactionsModel::Total, 80);
header->resizeSection(XBridgeTransactionsModel::Size, 80);
header->resizeSection(XBridgeTransactionsModel::BID, 80);
header->resizeSection(XBridgeTransactionsModel::State, 128);
vbox->addWidget(m_transactionsList);
QHBoxLayout * hbox = new QHBoxLayout;
XBridgeExchange & e = XBridgeExchange::instance();
if (!e.isEnabled())
{
QPushButton * addTxBtn = new QPushButton(trUtf8("New Transaction"), this);
// addTxBtn->setIcon(QIcon("qrc://"))
connect(addTxBtn, SIGNAL(clicked()), this, SLOT(onNewTransaction()));
hbox->addWidget(addTxBtn);
}
else
{
QPushButton * addTxBtn = new QPushButton(trUtf8("Exchange node"), this);
addTxBtn->setEnabled(false);
hbox->addWidget(addTxBtn);
}
hbox->addStretch();
QPushButton * showHideButton = new QPushButton("Toggle to log", this);
connect(showHideButton, SIGNAL(clicked()), this, SLOT(onToggleHistoricLogs()));
hbox->addWidget(showHideButton);
vbox->addLayout(hbox);
m_historicTransactionsProxy.setSourceModel(&m_txModel);
m_historicTransactionsProxy.setDynamicSortFilter(true);
QList<XBridgeTransactionDescr::State> historicTransactionsAccetpedStates;
historicTransactionsAccetpedStates << XBridgeTransactionDescr::trExpired
<< XBridgeTransactionDescr::trOffline
<< XBridgeTransactionDescr::trFinished
<< XBridgeTransactionDescr::trDropped
<< XBridgeTransactionDescr::trCancelled
<< XBridgeTransactionDescr::trInvalid;
m_historicTransactionsProxy.setAcceptedStates(historicTransactionsAccetpedStates);
m_historicTransactionsList = new QTableView(this);
m_historicTransactionsList->setModel(&m_historicTransactionsProxy);
m_historicTransactionsList->setContextMenuPolicy(Qt::CustomContextMenu);
m_historicTransactionsList->setSelectionBehavior(QAbstractItemView::SelectRows);
m_historicTransactionsList->setSortingEnabled(true);
QHeaderView * historicHeader = m_historicTransactionsList->horizontalHeader();
#if QT_VERSION <0x050000
header->setResizeMode(XBridgeTransactionsModel::Total, QHeaderView::Stretch);
#else
historicHeader->setSectionResizeMode(XBridgeTransactionsModel::Total, QHeaderView::Stretch);
#endif
#if QT_VERSION <0x050000
header->setResizeMode(XBridgeTransactionsModel::Size, QHeaderView::Stretch);
#else
historicHeader->setSectionResizeMode(XBridgeTransactionsModel::Size, QHeaderView::Stretch);
#endif
#if QT_VERSION <0x050000
header->setResizeMode(XBridgeTransactionsModel::BID, QHeaderView::Stretch);
#else
historicHeader->setSectionResizeMode(XBridgeTransactionsModel::BID, QHeaderView::Stretch);
#endif
historicHeader->resizeSection(XBridgeTransactionsModel::Total, 80);
historicHeader->resizeSection(XBridgeTransactionsModel::Size, 80);
historicHeader->resizeSection(XBridgeTransactionsModel::BID, 80);
historicHeader->resizeSection(XBridgeTransactionsModel::State, 128);
vbox->addWidget(m_historicTransactionsList);
m_logStrings = new QTextEdit(this);
m_logStrings->setMinimumHeight(64);
m_logStrings->setReadOnly(true);
m_logStrings->setVisible(false);
vbox->addWidget(m_logStrings);
setLayout(vbox);
xuiConnector.NotifyLogMessage.connect
(boost::bind(&XBridgeTransactionsView::onLogString, this, _1));
}
//******************************************************************************
//******************************************************************************
QMenu * XBridgeTransactionsView::setupContextMenu(QModelIndex & index)
{
QMenu * contextMenu = new QMenu();
if (!m_txModel.isMyTransaction(index.row()))
{
QAction * acceptTransaction = new QAction(tr("&Accept transaction"), this);
contextMenu->addAction(acceptTransaction);
connect(acceptTransaction, SIGNAL(triggered()),
this, SLOT(onAcceptTransaction()));
}
else
{
QAction * cancelTransaction = new QAction(tr("&Cancel transaction"), this);
contextMenu->addAction(cancelTransaction);
connect(cancelTransaction, SIGNAL(triggered()),
this, SLOT(onCancelTransaction()));
QAction * rollbackTransaction = new QAction(tr("&Rollback transaction"), this);
contextMenu->addAction(rollbackTransaction);
connect(rollbackTransaction, SIGNAL(triggered()),
this, SLOT(onRollbackTransaction()));
}
return contextMenu;
}
//******************************************************************************
//******************************************************************************
void XBridgeTransactionsView::onNewTransaction()
{
m_dlg.setPendingId(uint256(), std::vector<unsigned char>());
m_dlg.show();
}
//******************************************************************************
//******************************************************************************
void XBridgeTransactionsView::onAcceptTransaction()
{
if (!m_contextMenuIndex.isValid())
{
return;
}
if (m_txModel.isMyTransaction(m_contextMenuIndex.row()))
{
return;
}
XBridgeTransactionDescr d = m_txModel.item(m_contextMenuIndex.row());
if (d.state != XBridgeTransactionDescr::trPending)
{
return;
}
m_dlg.setPendingId(d.id, d.hubAddress);
m_dlg.setFromAmount((double)d.toAmount / XBridgeTransactionDescr::COIN);
m_dlg.setToAmount((double)d.fromAmount / XBridgeTransactionDescr::COIN);
m_dlg.setFromCurrency(QString::fromStdString(d.toCurrency));
m_dlg.setToCurrency(QString::fromStdString(d.fromCurrency));
m_dlg.show();
}
//******************************************************************************
//******************************************************************************
void XBridgeTransactionsView::onCancelTransaction()
{
if (!m_contextMenuIndex.isValid())
{
return;
}
if (QMessageBox::warning(this,
trUtf8("Cancel transaction"),
trUtf8("Are you sure?"),
QMessageBox::Yes | QMessageBox::Cancel,
QMessageBox::Cancel) != QMessageBox::Yes)
{
return;
}
if (!m_txModel.cancelTransaction(m_txModel.item(m_contextMenuIndex.row()).id))
{
QMessageBox::warning(this,
trUtf8("Cancel transaction"),
trUtf8("Error send cancel request"));
}
}
//******************************************************************************
//******************************************************************************
void XBridgeTransactionsView::onRollbackTransaction()
{
if (!m_contextMenuIndex.isValid())
{
return;
}
if (QMessageBox::warning(this,
trUtf8("Rollback transaction"),
trUtf8("Are you sure?"),
QMessageBox::Yes | QMessageBox::Cancel,
QMessageBox::Cancel) != QMessageBox::Yes)
{
return;
}
if (!m_txModel.cancelTransaction(m_txModel.item(m_contextMenuIndex.row()).id))
{
QMessageBox::warning(this,
trUtf8("Cancel transaction"),
trUtf8("Error send cancel request"));
}
}
//******************************************************************************
//******************************************************************************
void XBridgeTransactionsView::onContextMenu(QPoint /*pt*/)
{
XBridgeExchange & e = XBridgeExchange::instance();
if (e.isEnabled())
{
return;
}
m_contextMenuIndex = m_transactionsList->selectionModel()->currentIndex();
if (!m_contextMenuIndex.isValid())
{
return;
}
m_contextMenuIndex = m_transactionsProxy.mapToSource(m_contextMenuIndex);
if (!m_contextMenuIndex.isValid())
{
return;
}
QMenu * contextMenu = setupContextMenu(m_contextMenuIndex);
contextMenu->exec(QCursor::pos());
contextMenu->deleteLater();
}
//******************************************************************************
//******************************************************************************
void XBridgeTransactionsView::onToggleHistoricLogs()
{
QPushButton * btn = qobject_cast<QPushButton *>(sender());
bool logsVisible = m_logStrings->isVisible();
bool historicTrVisible = m_historicTransactionsList->isVisible();
if(logsVisible)
btn->setText("Toggle to log");
else if(historicTrVisible)
btn->setText("Toggle to history");
m_logStrings->setVisible(!logsVisible);
m_historicTransactionsList->setVisible(!historicTrVisible);
if (!logsVisible)
{
m_logStrings->clear();
// show, load all logs
QFile f(QString::fromStdString(LOG::logFileName()));
if (f.open(QIODevice::ReadOnly))
{
m_logStrings->insertPlainText(f.readAll());
}
}
}
//******************************************************************************
//******************************************************************************
void XBridgeTransactionsView::onLogString(const std::string str)
{
const QString qstr = QString::fromStdString(str);
m_logStrings->insertPlainText(qstr);
// QTextCursor c = m_logStrings->textCursor();
// c.movePosition(QTextCursor::End);
// m_logStrings->setTextCursor(c);
// m_logStrings->ensureCursorVisible();
}
<|endoftext|>
|
<commit_before>// -*- coding: us-ascii-unix -*-
// Copyright 2012 Lukas Kemmer
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You
// may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
#include <algorithm>
#include <cassert>
#include "geo/geo-func.hh"
#include "geo/points.hh"
#include "geo/scale.hh"
#include "geo/size.hh"
#include "util/iter.hh"
namespace faint{
Tri tri_from_points(const std::vector<PathPt>& points){
if (points.empty()){
return {Point(0,0), Angle::Zero(), Size(0,0)};
}
Point topLeft = points[0].p;
Point bottomRight = topLeft;
for (const PathPt& pt : points){
if (pt.ClosesPath()){
continue;
}
topLeft = min_coords(topLeft, pt.p);
bottomRight = max_coords(bottomRight, pt.p);
pt.IfCubicBezier(
[&topLeft, &bottomRight](const CubicBezier& bezier){
// Fixme: The bezier is always bounded by the end points and control
// points, but this isn't the tightest boundary.
topLeft = min_coords(topLeft, bezier.c, bezier.d);
bottomRight = max_coords(bottomRight, bezier.c, bezier.d);
});
}
return {
topLeft,
{bottomRight.x, topLeft.y},
{topLeft.x, bottomRight.y}};
}
Tri tri_from_points(const std::vector<Point>& points){
if (points.empty()){
return {Point(0,0), Angle::Zero(), Size(0,0)};
}
const Point& p0 = points[0];
coord x_min = p0.x;
coord x_max = p0.x;
coord y_min = p0.y;
coord y_max = p0.y;
for (size_t i = 0; i != points.size(); i++){
const Point& pt = points[i];
x_min = std::min(x_min, pt.x);
x_max = std::max(x_max, pt.x);
y_min = std::min(y_min, pt.y);
y_max = std::max(y_max, pt.y);
}
return {Point(x_min, y_min), Point(x_max, y_min), Point(x_min, y_max)};
}
Points::Points()
: m_tri(Point(0,0), Angle::Zero(), faint::Size(0,0)),
m_cacheTri(m_tri)
{}
Points::Points(const Points& other)
: m_tri(other.m_tri),
m_points(other.m_points),
m_cache(),
m_cacheTri()
{}
Points::Points(const std::vector<PathPt>& points) :
m_tri(tri_from_points(points)),
m_points(points),
m_cache(),
m_cacheTri()
{}
void Points::AdjustBack(const PathPt& pt){
PathPt& back(m_points.back());
back = pt;
m_tri = tri_from_points(m_points);
}
void Points::AdjustBack(const Point& p){
PathPt& back(m_points.back());
back.p = p;
m_tri = tri_from_points(m_points);
}
void Points::Append(const PathPt& p){
m_points.push_back(p);
m_tri = tri_from_points(m_points);
}
void Points::Append(const Point& p){
if (m_points.empty()){
m_points.push_back(PathPt::MoveTo(p));
}
else{
m_points.push_back(PathPt::LineTo(p));
}
m_tri = tri_from_points(m_points);
}
const PathPt& Points::Back() const{
return m_points.back();
}
const PathPt& Points::BaBack() const{
assert(m_points.size() >= 2);
return m_points[m_points.size() - 2];
}
void Points::Clear(){
m_points.clear();
m_tri = Tri(Point(0,0), Angle::Zero(), faint::Size(0,0));
}
bool Points::Empty() const{
return m_points.empty();
}
const PathPt& Points::Front() const{
return m_points.front();
}
std::vector<PathPt> Points::GetPoints(const Tri& tri) const{
if (m_cache.size() == m_points.size() && m_cacheTri == tri){
return m_cache;
}
if (m_cache.size() != m_points.size()){
m_cache = m_points;
}
Adj a = get_adj(m_tri, tri);
coord p2y = m_tri.P2().y;
coord ht = m_tri.Height();
for (size_t i = 0; i != m_points.size(); i++){
PathPt pt = m_points[i];
if (ht != 0){
pt.p.x += a.skew * ((p2y - pt.p.y) / ht) / a.scale_x; // assumes m_tri not rotated
}
pt.p.x += a.tr_x;
pt.p.y += a.tr_y;
if (ht != 0){
pt.c.x += a.skew * ((p2y - pt.c.y) / ht) / a.scale_x; // assumes m_tri not rotated
}
pt.c.x += a.tr_x;
pt.c.y += a.tr_y;
if (ht != 0){
pt.d.x += a.skew * ((p2y - pt.d.y) / ht) / a.scale_x; // assumes m_tri not rotated
}
pt.d.x += a.tr_x;
pt.d.y += a.tr_y;
pt = scale_point(pt, Scale(a.scale_x, a.scale_y), tri.P3());
pt = rotate_point(pt, tri.GetAngle(), tri.P3());
m_cache[i] = pt;
}
return m_cache;
}
std::vector<PathPt> Points::GetPoints() const{
return m_points;
}
std::vector<Point> Points::GetPointsDumb() const{
std::vector<Point> v;
v.reserve(m_points.size());
for (size_t i = 0; i != m_points.size(); i++){
const PathPt& pt(m_points[i]);
v.push_back(pt.p);
}
return v;
}
std::vector<Point> Points::GetPointsDumb(const Tri& tri) const{
std::vector<PathPt> pts(GetPoints(tri));
std::vector<Point> v;
v.reserve(m_points.size());
for (size_t i = 0; i != m_points.size(); i++){
PathPt& pt(pts[i]);
v.push_back(pt.p);
}
return v;
}
Tri Points::GetTri() const {
return m_tri;
}
void Points::InsertPoint(const Tri& tri, const Point& p, int index){
InsertPoint(tri, PathPt::LineTo(p), index);
}
void Points::InsertPoint(const Tri& tri, const PathPt& p, int index){
assert(index >= 0);
m_points = GetPoints(tri);
m_points.insert(begin(m_points) + index, p);
m_tri = tri_from_points(m_points);
}
void Points::InsertPointRaw(const PathPt& p, int index){
assert(index >= 0);
m_points.insert(begin(m_points) + index, p);
}
PathPt Points::PopBack(){
PathPt p = m_points.back();
m_points.pop_back();
m_tri = tri_from_points(m_points);
return p;
}
void Points::RemovePoint(const Tri& tri, int index){
m_points = GetPoints(tri);
m_points.erase(begin(m_points) + index);
m_tri = tri_from_points(m_points);
}
void Points::RemovePointRaw(int index){
m_points.erase(begin(m_points) + index);
}
void Points::SetPoint(const Tri& tri, const Point& p, int index){
m_points = GetPoints(tri);
m_points[to_size_t(index)].p = p;
m_tri = tri_from_points(m_points);
}
void Points::SetPoint(const Tri& tri, const PathPt& p, int index){
m_points = GetPoints(tri);
m_points[to_size_t(index)] = p;
m_tri = tri_from_points(m_points);
}
void Points::SetTri(const Tri& tri){
m_tri = tri;
}
int Points::Size() const{
return resigned(m_points.size());
}
Points points_from_coords(const std::vector<coord>& coords){
const size_t n = coords.size();
assert(n % 2 == 0);
Points points;
for (size_t i = 0; i != n; i+=2){
coord x = coords[i];
coord y = coords[i +1];
points.Append(Point(x,y));
}
return points;
}
std::vector<PathPt> to_line_path(const std::vector<Point>& points){
assert(points.size() > 1);
std::vector<PathPt> path;
path.reserve(points.size());
path.push_back(PathPt::MoveTo(points.front()));
for (const Point& p : but_first(points)){
path.push_back(PathPt::LineTo(p));
}
return path;
}
} // namespace
<commit_msg>Simplified Points.cpp using make_vector.<commit_after>// -*- coding: us-ascii-unix -*-
// Copyright 2012 Lukas Kemmer
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You
// may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
#include <algorithm>
#include <cassert>
#include "geo/geo-func.hh"
#include "geo/points.hh"
#include "geo/scale.hh"
#include "geo/size.hh"
#include "util/iter.hh"
#include "util/make-vector.hh"
namespace faint{
static Point get_end_point(const PathPt& pt){
return pt.p;
}
Tri tri_from_points(const std::vector<PathPt>& points){
if (points.empty()){
return {Point(0,0), Angle::Zero(), Size(0,0)};
}
Point topLeft = points[0].p;
Point bottomRight = topLeft;
for (const PathPt& pt : points){
if (pt.ClosesPath()){
continue;
}
topLeft = min_coords(topLeft, pt.p);
bottomRight = max_coords(bottomRight, pt.p);
pt.IfCubicBezier(
[&topLeft, &bottomRight](const CubicBezier& bezier){
// Fixme: The bezier is always bounded by the end points and control
// points, but this isn't the tightest boundary.
topLeft = min_coords(topLeft, bezier.c, bezier.d);
bottomRight = max_coords(bottomRight, bezier.c, bezier.d);
});
}
return {
topLeft,
{bottomRight.x, topLeft.y},
{topLeft.x, bottomRight.y}};
}
Tri tri_from_points(const std::vector<Point>& points){
if (points.empty()){
return {Point(0,0), Angle::Zero(), Size(0,0)};
}
const Point& p0 = points[0];
coord x_min = p0.x;
coord x_max = p0.x;
coord y_min = p0.y;
coord y_max = p0.y;
for (size_t i = 0; i != points.size(); i++){
const Point& pt = points[i];
x_min = std::min(x_min, pt.x);
x_max = std::max(x_max, pt.x);
y_min = std::min(y_min, pt.y);
y_max = std::max(y_max, pt.y);
}
return {Point(x_min, y_min), Point(x_max, y_min), Point(x_min, y_max)};
}
Points::Points()
: m_tri(Point(0,0), Angle::Zero(), faint::Size(0,0)),
m_cacheTri(m_tri)
{}
Points::Points(const Points& other)
: m_tri(other.m_tri),
m_points(other.m_points),
m_cache(),
m_cacheTri()
{}
Points::Points(const std::vector<PathPt>& points) :
m_tri(tri_from_points(points)),
m_points(points),
m_cache(),
m_cacheTri()
{}
void Points::AdjustBack(const PathPt& pt){
PathPt& back(m_points.back());
back = pt;
m_tri = tri_from_points(m_points);
}
void Points::AdjustBack(const Point& p){
PathPt& back(m_points.back());
back.p = p;
m_tri = tri_from_points(m_points);
}
void Points::Append(const PathPt& p){
m_points.push_back(p);
m_tri = tri_from_points(m_points);
}
void Points::Append(const Point& p){
if (m_points.empty()){
m_points.push_back(PathPt::MoveTo(p));
}
else{
m_points.push_back(PathPt::LineTo(p));
}
m_tri = tri_from_points(m_points);
}
const PathPt& Points::Back() const{
return m_points.back();
}
const PathPt& Points::BaBack() const{
assert(m_points.size() >= 2);
return m_points[m_points.size() - 2];
}
void Points::Clear(){
m_points.clear();
m_tri = Tri(Point(0,0), Angle::Zero(), faint::Size(0,0));
}
bool Points::Empty() const{
return m_points.empty();
}
const PathPt& Points::Front() const{
return m_points.front();
}
std::vector<PathPt> Points::GetPoints(const Tri& tri) const{
if (m_cache.size() == m_points.size() && m_cacheTri == tri){
return m_cache;
}
if (m_cache.size() != m_points.size()){
m_cache = m_points;
}
Adj a = get_adj(m_tri, tri);
coord p2y = m_tri.P2().y;
coord ht = m_tri.Height();
for (size_t i = 0; i != m_points.size(); i++){
PathPt pt = m_points[i];
if (ht != 0){
pt.p.x += a.skew * ((p2y - pt.p.y) / ht) / a.scale_x; // assumes m_tri not rotated
}
pt.p.x += a.tr_x;
pt.p.y += a.tr_y;
if (ht != 0){
pt.c.x += a.skew * ((p2y - pt.c.y) / ht) / a.scale_x; // assumes m_tri not rotated
}
pt.c.x += a.tr_x;
pt.c.y += a.tr_y;
if (ht != 0){
pt.d.x += a.skew * ((p2y - pt.d.y) / ht) / a.scale_x; // assumes m_tri not rotated
}
pt.d.x += a.tr_x;
pt.d.y += a.tr_y;
pt = scale_point(pt, Scale(a.scale_x, a.scale_y), tri.P3());
pt = rotate_point(pt, tri.GetAngle(), tri.P3());
m_cache[i] = pt;
}
return m_cache;
}
std::vector<PathPt> Points::GetPoints() const{
return m_points;
}
std::vector<Point> Points::GetPointsDumb() const{
return make_vector(m_points, get_end_point);
}
std::vector<Point> Points::GetPointsDumb(const Tri& tri) const{
return make_vector(GetPoints(tri), get_end_point);
}
Tri Points::GetTri() const {
return m_tri;
}
void Points::InsertPoint(const Tri& tri, const Point& p, int index){
InsertPoint(tri, PathPt::LineTo(p), index);
}
void Points::InsertPoint(const Tri& tri, const PathPt& p, int index){
assert(index >= 0);
m_points = GetPoints(tri);
m_points.insert(begin(m_points) + index, p);
m_tri = tri_from_points(m_points);
}
void Points::InsertPointRaw(const PathPt& p, int index){
assert(index >= 0);
m_points.insert(begin(m_points) + index, p);
}
PathPt Points::PopBack(){
PathPt p = m_points.back();
m_points.pop_back();
m_tri = tri_from_points(m_points);
return p;
}
void Points::RemovePoint(const Tri& tri, int index){
m_points = GetPoints(tri);
m_points.erase(begin(m_points) + index);
m_tri = tri_from_points(m_points);
}
void Points::RemovePointRaw(int index){
m_points.erase(begin(m_points) + index);
}
void Points::SetPoint(const Tri& tri, const Point& p, int index){
m_points = GetPoints(tri);
m_points[to_size_t(index)].p = p;
m_tri = tri_from_points(m_points);
}
void Points::SetPoint(const Tri& tri, const PathPt& p, int index){
m_points = GetPoints(tri);
m_points[to_size_t(index)] = p;
m_tri = tri_from_points(m_points);
}
void Points::SetTri(const Tri& tri){
m_tri = tri;
}
int Points::Size() const{
return resigned(m_points.size());
}
Points points_from_coords(const std::vector<coord>& coords){
const size_t n = coords.size();
assert(n % 2 == 0);
Points points;
for (size_t i = 0; i != n; i+=2){
coord x = coords[i];
coord y = coords[i +1];
points.Append(Point(x,y));
}
return points;
}
std::vector<PathPt> to_line_path(const std::vector<Point>& points){
assert(points.size() > 1);
std::vector<PathPt> path;
path.reserve(points.size());
path.push_back(PathPt::MoveTo(points.front()));
for (const Point& p : but_first(points)){
path.push_back(PathPt::LineTo(p));
}
return path;
}
} // namespace
<|endoftext|>
|
<commit_before>#include <iostream>
void while_Demo();
void for_Demo();
void notQuantitativeValue();
int main() {
// 1.4.1 while
while_Demo();
// 1.4.2 for
for_Demo();
// 1.4.3 读取数量不定的输入数据
notQuantitativeValue();
std::cout << "Section 1.4 end" << std::endl;
return 0;
}
/**
* 读取数量不定的输入数据,
* 只有输入换行符(比如:\n)或者非法字符(非数字,但直接回车不会停止)的时候才会停止接收数据,输出运算结果
* @EOF EOF 是 end of file 的缩写,windows环境是:ctrl+Z,unix 环境是:ctrl+D,即可模拟(?)EOF
*/
void notQuantitativeValue() {
std::cout << "【notQuantitativeValue】=> 请每次输入一个数据,并回车(想结束输入参数的时候输入 EOF 或者输入非数字字符即可):" << std::endl;
int sum = 0, value = 0;
while (std::cin >> value) { // 使用istream对象作为条件,其效果是检测流的状态
sum += value;
}
std::cout << "Sum is " << sum << std::endl;
}
/**
* for 语句 范例
*/
void for_Demo() {
int sum = 0;
for (int value = 0; value <= 10; ++value) {
sum += value;
}
std::cout << "[for_Demo] => Sum of 1 to 10 inclusive is " << sum << std::endl;
}
/**
* while 语句 范例
*/
void while_Demo() {
int sum = 0, value = 1;
while (value <= 10) {
sum += value;
++value;
} // 上面两句可以合并:sum += value++;
std::cout << "[while_Demo] => Sum of 1 to 10 inclusive is " << sum << std::endl;
}
<commit_msg>Section 1.4 control flow<commit_after>#include <iostream>
void while_Demo();
void for_Demo();
void notQuantitativeValue();
void if_Demo();
int main() {
// 1.4.1 while
while_Demo();
// 1.4.2 for
for_Demo();
// 需要注意点是,1.4.3 和 1.4.4 不能同时运行,因为1.4.3结束输入的时候,1.4.4就不能接收到输入数据了
// 1.4.3 读取数量不定的输入数据
notQuantitativeValue();
// 1.4.4 if语句
if_Demo();
std::cout << "Section 1.4 end" << std::endl;
return 0;
}
/**
* if语句,计算连续的相同数字的个数
*/
void if_Demo() {
int currVal = 0, val = 0;
if (std::__1::cin >> currVal) {
int cnt = 1;
while (std::__1::cin >> val) {
if (val == currVal) {
++cnt;
} else {
std::__1::cout << currVal << " occurs " << cnt << " times." << std::__1::endl;
currVal = val;
cnt = 1;
}
} // while 结束
std::__1::cout << currVal << " occurs " << cnt << " times." << std::__1::endl;
} // if 结束
}
/**
* 读取数量不定的输入数据,
* 只有输入换行符(比如:\n)或者非法字符(非数字,但直接回车不会停止)的时候才会停止接收数据,输出运算结果
* @EOF EOF 是 end of file 的缩写,windows环境是:ctrl+Z,unix 环境是:ctrl+D,即可模拟(?)EOF
*/
void notQuantitativeValue() {
std::cout << "【notQuantitativeValue】=> 请每次输入一个数据,并回车(想结束输入参数的时候输入 EOF 或者输入非数字字符即可):" << std::endl;
int sum = 0, value = 0;
while (std::cin >> value) { // 使用istream对象作为条件,其效果是检测流的状态
sum += value;
}
std::cout << "Sum is " << sum << std::endl;
}
/**
* for 语句 范例
*/
void for_Demo() {
int sum = 0;
for (int value = 0; value <= 10; ++value) {
sum += value;
}
std::cout << "[for_Demo] => Sum of 1 to 10 inclusive is " << sum << std::endl;
}
/**
* while 语句 范例
*/
void while_Demo() {
int sum = 0, value = 1;
while (value <= 10) {
sum += value;
++value;
} // 上面两句可以合并:sum += value++;
std::cout << "[while_Demo] => Sum of 1 to 10 inclusive is " << sum << std::endl;
}
<|endoftext|>
|
<commit_before>/*
* Author(s):
* - Cedric Gestes <gestes@aldebaran-robotics.com>
* - Herve Cuche <hcuche@aldebaran-robotics.com>
*
* Copyright (C) 2012 Aldebaran Robotics
*/
#include <qimessaging/session.hpp>
#include <qimessaging/datastream.hpp>
#include <qimessaging/transport_socket.hpp>
#include <qimessaging/object.hpp>
#include <qimessaging/service_info.hpp>
#include "src/remoteobject_p.hpp"
#include "src/network_thread.hpp"
#include "src/session_p.hpp"
namespace qi {
SessionPrivate::SessionPrivate(qi::Session *session)
: _serviceSocket(new qi::TransportSocket()),
_networkThread(new qi::NetworkThread()),
_self(session)
{
}
SessionPrivate::~SessionPrivate() {
delete _networkThread;
delete _serviceSocket;
}
bool SessionPrivate::connect(const qi::Url &serviceDirectoryURL)
{
return _serviceSocket->connect(_self, serviceDirectoryURL);
}
std::vector<ServiceInfo> SessionPrivate::services()
{
std::vector<ServiceInfo> result;
qi::Message msg;
msg.setType(qi::Message::Type_Call);
msg.setService(qi::Message::Service_ServiceDirectory);
msg.setPath(qi::Message::Path_Main);
msg.setFunction(qi::Message::ServiceDirectoryFunction_Services);
_serviceSocket->send(msg);
if (!_serviceSocket->waitForId(msg.id()))
return result;
qi::Message ans;
_serviceSocket->read(msg.id(), &ans);
qi::DataStream d(ans.buffer());
d >> result;
return result;
}
qi::TransportSocket* SessionPrivate::serviceSocket(const std::string &name,
unsigned int *idx,
qi::Url::Protocol type)
{
qi::Message msg;
qi::Buffer buf;
qi::DataStream dr(buf);
msg.setBuffer(buf);
dr << name;
msg.setType(qi::Message::Type_Call);
msg.setService(qi::Message::Service_ServiceDirectory);
msg.setPath(qi::Message::Path_Main);
msg.setFunction(qi::Message::ServiceDirectoryFunction_Service);
_serviceSocket->send(msg);
if (!_serviceSocket->waitForId(msg.id()))
return 0;
qi::Message ans;
_serviceSocket->read(msg.id(), &ans);
qi::ServiceInfo si;
qi::DataStream d(ans.buffer());
d >> si;
*idx = si.serviceId();
for (std::vector<std::string>::const_iterator it = si.endpoints().begin();
it != si.endpoints().end();
++it)
{
qi::Url url(*it);
if (type == qi::Url::Protocol_Any ||
type == url.protocol())
{
qi::TransportSocket* ts = NULL;
ts = new qi::TransportSocket();
ts->connect(_self, url);
ts->setCallbacks(this);
ts->waitForConnected();
return ts;
}
}
return 0;
}
qi::Object* SessionPrivate::service(const std::string &service,
qi::Url::Protocol type)
{
qi::Object *obj;
unsigned int serviceId = 0;
qi::TransportSocket *ts = serviceSocket(service, &serviceId, type);
if (ts == 0)
{
return 0;
}
qi::Message msg;
msg.setType(qi::Message::Type_Call);
msg.setService(serviceId);
msg.setPath(qi::Message::Path_Main);
msg.setFunction(qi::Message::Function_MetaObject);
ts->send(msg);
ts->waitForId(msg.id());
qi::Message ret;
ts->read(msg.id(), &ret);
qi::MetaObject *mo = new qi::MetaObject;
qi::DataStream ds(ret.buffer());
ds >> *mo;
qi::RemoteObject *robj = new qi::RemoteObject(ts, serviceId, mo);
obj = robj;
return obj;
}
// ###### Session
Session::Session()
: _p(new SessionPrivate(this))
{
}
Session::~Session()
{
delete _p;
}
bool Session::connect(const qi::Url &serviceDirectoryURL)
{
return _p->connect(serviceDirectoryURL);
}
bool Session::disconnect()
{
_p->_serviceSocket->disconnect();
return true;
}
bool Session::waitForConnected(int msecs)
{
return _p->_serviceSocket->waitForConnected(msecs);
}
bool Session::waitForDisconnected(int msecs)
{
return _p->_serviceSocket->waitForDisconnected(msecs);
}
qi::Future< std::vector<ServiceInfo> > Session::services()
{
qi::Promise< std::vector<ServiceInfo> > promise;
promise.setValue(_p->services());
return promise.future();
}
qi::Future< qi::TransportSocket* > Session::serviceSocket(const std::string &name,
unsigned int *idx,
qi::Url::Protocol type)
{
qi::Promise< qi::TransportSocket* > promise;
promise.setValue(_p->serviceSocket(name, idx, type));
return promise.future();
}
qi::Future< qi::Object* > Session::service(const std::string &service,
qi::Url::Protocol type)
{
qi::Promise< qi::Object * > promise;
promise.setValue(_p->service(service, type));
return promise.future();
}
bool Session::join()
{
_p->_networkThread->join();
return true;
}
}
<commit_msg>session: log<commit_after>/*
* Author(s):
* - Cedric Gestes <gestes@aldebaran-robotics.com>
* - Herve Cuche <hcuche@aldebaran-robotics.com>
*
* Copyright (C) 2012 Aldebaran Robotics
*/
#include <qimessaging/session.hpp>
#include <qimessaging/datastream.hpp>
#include <qimessaging/transport_socket.hpp>
#include <qimessaging/object.hpp>
#include <qimessaging/service_info.hpp>
#include "src/remoteobject_p.hpp"
#include "src/network_thread.hpp"
#include "src/session_p.hpp"
namespace qi {
SessionPrivate::SessionPrivate(qi::Session *session)
: _serviceSocket(new qi::TransportSocket()),
_networkThread(new qi::NetworkThread()),
_self(session)
{
}
SessionPrivate::~SessionPrivate() {
delete _networkThread;
delete _serviceSocket;
}
bool SessionPrivate::connect(const qi::Url &serviceDirectoryURL)
{
return _serviceSocket->connect(_self, serviceDirectoryURL);
}
std::vector<ServiceInfo> SessionPrivate::services()
{
std::vector<ServiceInfo> result;
qi::Message msg;
msg.setType(qi::Message::Type_Call);
msg.setService(qi::Message::Service_ServiceDirectory);
msg.setPath(qi::Message::Path_Main);
msg.setFunction(qi::Message::ServiceDirectoryFunction_Services);
_serviceSocket->send(msg);
if (!_serviceSocket->waitForId(msg.id()))
return result;
qi::Message ans;
_serviceSocket->read(msg.id(), &ans);
qi::DataStream d(ans.buffer());
d >> result;
return result;
}
qi::TransportSocket* SessionPrivate::serviceSocket(const std::string &name,
unsigned int *idx,
qi::Url::Protocol type)
{
qi::Message msg;
qi::Buffer buf;
qi::DataStream dr(buf);
msg.setBuffer(buf);
dr << name;
msg.setType(qi::Message::Type_Call);
msg.setService(qi::Message::Service_ServiceDirectory);
msg.setPath(qi::Message::Path_Main);
msg.setFunction(qi::Message::ServiceDirectoryFunction_Service);
_serviceSocket->send(msg);
if (!_serviceSocket->waitForId(msg.id()))
return 0;
qi::Message ans;
_serviceSocket->read(msg.id(), &ans);
qi::ServiceInfo si;
qi::DataStream d(ans.buffer());
d >> si;
*idx = si.serviceId();
for (std::vector<std::string>::const_iterator it = si.endpoints().begin();
it != si.endpoints().end();
++it)
{
qi::Url url(*it);
if (type == qi::Url::Protocol_Any ||
type == url.protocol())
{
qi::TransportSocket* ts = NULL;
ts = new qi::TransportSocket();
ts->connect(_self, url);
ts->setCallbacks(this);
ts->waitForConnected();
return ts;
}
}
return 0;
}
qi::Object* SessionPrivate::service(const std::string &service,
qi::Url::Protocol type)
{
qi::Object *obj;
unsigned int serviceId = 0;
qi::TransportSocket *ts = serviceSocket(service, &serviceId, type);
if (ts == 0)
{
qiLogError("qi::Session") << "service not found: " << service;
return 0;
}
qi::Message msg;
msg.setType(qi::Message::Type_Call);
msg.setService(serviceId);
msg.setPath(qi::Message::Path_Main);
msg.setFunction(qi::Message::Function_MetaObject);
ts->send(msg);
ts->waitForId(msg.id());
qi::Message ret;
ts->read(msg.id(), &ret);
qi::MetaObject *mo = new qi::MetaObject;
qi::DataStream ds(ret.buffer());
ds >> *mo;
qi::RemoteObject *robj = new qi::RemoteObject(ts, serviceId, mo);
obj = robj;
return obj;
}
// ###### Session
Session::Session()
: _p(new SessionPrivate(this))
{
}
Session::~Session()
{
delete _p;
}
bool Session::connect(const qi::Url &serviceDirectoryURL)
{
return _p->connect(serviceDirectoryURL);
}
bool Session::disconnect()
{
_p->_serviceSocket->disconnect();
return true;
}
bool Session::waitForConnected(int msecs)
{
return _p->_serviceSocket->waitForConnected(msecs);
}
bool Session::waitForDisconnected(int msecs)
{
return _p->_serviceSocket->waitForDisconnected(msecs);
}
qi::Future< std::vector<ServiceInfo> > Session::services()
{
qi::Promise< std::vector<ServiceInfo> > promise;
promise.setValue(_p->services());
return promise.future();
}
qi::Future< qi::TransportSocket* > Session::serviceSocket(const std::string &name,
unsigned int *idx,
qi::Url::Protocol type)
{
qi::Promise< qi::TransportSocket* > promise;
promise.setValue(_p->serviceSocket(name, idx, type));
return promise.future();
}
qi::Future< qi::Object* > Session::service(const std::string &service,
qi::Url::Protocol type)
{
qi::Promise< qi::Object * > promise;
promise.setValue(_p->service(service, type));
return promise.future();
}
bool Session::join()
{
_p->_networkThread->join();
return true;
}
}
<|endoftext|>
|
<commit_before>#include <bts/blockchain/asset.hpp>
#include <bts/blockchain/config.hpp>
#include <bts/blockchain/exceptions.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/uint128.hpp>
#include <fc/real128.hpp>
#include <sstream>
namespace bts { namespace blockchain {
price operator *( const price& l, const price& r )
{ try {
FC_ASSERT( l.quote_asset_id == r.quote_asset_id );
FC_ASSERT( l.base_asset_id == r.base_asset_id );
// infinity times zero is undefined / exception
// infinity times anything else is infinity
if( l.is_infinite() )
{
if( r.ratio == fc::uint128_t(0) )
FC_THROW_EXCEPTION( price_multiplication_undefined, "price multiplication undefined (0 * inf)" );
return l;
}
if( r.is_infinite() )
{
if( l.ratio == fc::uint128_t(0) )
FC_THROW_EXCEPTION( price_multiplication_undefined, "price multiplication undefined (inf * 0)" );
return r;
}
// zero times anything is zero (infinity is already handled above)
if( l.ratio == fc::uint128_t(0) )
return l;
if( r.ratio == fc::uint128_t(0) )
return r;
fc::bigint product = l.ratio;
product *= r.ratio;
product /= FC_REAL128_PRECISION;
// if the quotient is zero, it means there was an underflow
// (i.e. the result is nonzero but too small to represent)
if( product == fc::bigint() )
FC_THROW_EXCEPTION( price_multiplication_underflow, "price multiplication underflow" );
static fc::bigint bi_infinity = price::infinite();
// if the quotient is infinity or bigger, then we have a finite
// result that is too big to represent (overflow)
if( product >= bi_infinity )
FC_THROW_EXCEPTION( price_multiplication_overflow, "price multiplication overflow" );
// NB we throw away the low bits, thus this function always rounds down
price result( fc::uint128( product ), l.quote_asset_id, l.base_asset_id );
return result;
} FC_CAPTURE_AND_RETHROW( (l)(r) ) }
asset::operator std::string()const
{
return fc::to_string(amount);
}
asset& asset::operator += ( const asset& o )
{ try {
FC_ASSERT( this->asset_id == o.asset_id, "", ("*this",*this)("o",o) );
if (((o.amount > 0) && (amount > (INT64_MAX - o.amount))) ||
((o.amount < 0) && (amount < (INT64_MIN - o.amount))))
{
FC_THROW_EXCEPTION( addition_overflow, "asset addition overflow ${a} + ${b}",
("a", *this)("b",o) );
}
amount += o.amount;
return *this;
} FC_CAPTURE_AND_RETHROW( (*this)(o) ) }
asset& asset::operator -= ( const asset& o )
{
FC_ASSERT( asset_id == o.asset_id );
if ((o.amount > 0 && amount < INT64_MIN + o.amount) ||
(o.amount < 0 && amount > INT64_MAX + o.amount))
{
FC_THROW_EXCEPTION( subtraction_overflow, "asset subtraction underflow ${a} - ${b}",
("a", *this)("b",o) );
}
amount -= o.amount;
return *this;
}
const fc::uint128& price::one()
{
static fc::uint128_t o = fc::uint128(1,0);
return o;
}
const fc::uint128& price::infinite()
{
static fc::uint128 i(-1);
return i;
}
bool price::is_infinite() const
{
static fc::uint128 infinity = infinite();
return (this->ratio == infinity);
}
price::price( const std::string& s )
{ try {
int pos = set_ratio_from_string( s );
std::stringstream ss( s.substr( pos ) );
char div;
ss >> quote_asset_id.value >> div >> base_asset_id.value;
FC_ASSERT( quote_asset_id > base_asset_id, "${quote} > ${base}", ("quote",quote_asset_id)("base",base_asset_id) );
} FC_RETHROW_EXCEPTIONS( warn, "" ) }
int price::set_ratio_from_string( const std::string& ratio_str )
{
const char* c = ratio_str.c_str();
int digit = *c - '0';
if (digit >= 0 && digit <= 9)
{
uint64_t int_part = digit;
++c;
digit = *c - '0';
while (digit >= 0 && digit <= 9)
{
int_part = int_part * 10 + digit;
++c;
digit = *c - '0';
}
ratio = fc::uint128(int_part) * FC_REAL128_PRECISION;
}
else
{
// if the string doesn't look like "123.45" or ".45", this code isn't designed to parse it correctly
// in particular, we don't try to handle leading whitespace or '+'/'-' indicators at the beginning
FC_ASSERT( (*c) == '.' );
ratio = fc::uint128();
}
if (*c == '.')
{
c++;
digit = *c - '0';
if (digit >= 0 && digit <= 9)
{
int64_t frac_part = digit;
int64_t frac_magnitude = 10;
++c;
digit = *c - '0';
while (digit >= 0 && digit <= 9)
{
frac_part = frac_part * 10 + digit;
frac_magnitude *= 10;
++c;
digit = *c - '0';
}
ratio += fc::uint128(frac_part) * (FC_REAL128_PRECISION / frac_magnitude);
}
}
return c - ratio_str.c_str();
}
std::string price::ratio_string()const
{
std::string full_int = std::string( ratio );
std::stringstream ss;
ss <<std::string( ratio / FC_REAL128_PRECISION );
ss << '.';
ss << std::string( (ratio % FC_REAL128_PRECISION) + FC_REAL128_PRECISION ).substr(1);
auto number = ss.str();
while( number.back() == '0' ) number.pop_back();
return number;
}
price::operator std::string()const
{ try {
auto number = ratio_string();
number += ' ' + fc::to_string(int64_t(quote_asset_id.value));
number += '/' + fc::to_string(int64_t(base_asset_id.value));
return number;
} FC_RETHROW_EXCEPTIONS( warn, "" )}
/**
* A price will reorder the asset types such that the
* asset type with the lower enum value is always the
* denominator. Therefore bts/usd and usd/bts will
* always result in a price measured in usd/bts because
* asset::bts < asset::usd.
*/
price operator / ( const asset& a, const asset& b )
{
try
{
if( a.asset_id == b.asset_id )
FC_CAPTURE_AND_THROW( asset_divide_by_self );
price p;
auto l = a; auto r = b;
if( l.asset_id < r.asset_id ) { std::swap(l,r); }
//ilog( "${a} / ${b}", ("a",l)("b",r) );
if( r.amount == 0 )
FC_CAPTURE_AND_THROW( asset_divide_by_zero, (r) );
p.base_asset_id = r.asset_id;
p.quote_asset_id = l.asset_id;
fc::bigint bl = l.amount;
fc::bigint br = r.amount;
fc::bigint result = (bl * fc::bigint(FC_REAL128_PRECISION)) / br;
p.ratio = result;
return p;
} FC_RETHROW_EXCEPTIONS( warn, "${a} / ${b}", ("a",a)("b",b) );
}
asset operator / ( const asset& a, const price& p )
{
return a * p;
}
/**
* Assuming a.type is either the numerator.type or denominator.type in
* the price equation, return the number of the other asset type that
* could be exchanged at price p.
*
* ie: p = 3 usd/bts & a = 4 bts then result = 12 usd
* ie: p = 3 usd/bts & a = 4 usd then result = 1.333 bts
*/
asset operator * ( const asset& a, const price& p )
{
try {
if( a.asset_id == p.base_asset_id )
{
fc::bigint ba( a.amount ); // 64.64
fc::bigint r( p.ratio ); // 64.64
auto amnt = ba * r; // 128.128
amnt /= FC_REAL128_PRECISION; // 128.64
auto lg2 = amnt.log2();
if( lg2 >= 128 )
{
FC_THROW_EXCEPTION( addition_overflow, "overflow ${a} * ${p}", ("a",a)("p",p) );
}
asset rtn;
rtn.amount = amnt.to_int64();
rtn.asset_id = p.quote_asset_id;
//ilog( "${a} * ${p} => ${rtn}", ("a", a)("p",p )("rtn",rtn) );
return rtn;
}
else if( a.asset_id == p.quote_asset_id )
{
fc::bigint amt( a.amount ); // 64.64
amt *= FC_REAL128_PRECISION; //<<= 64; // 64.128
fc::bigint pri( p.ratio ); // 64.64
auto result = amt / pri; // 64.64
// ilog( "amt: ${amt} / ${pri}", ("amt",string(amt))("pri",string(pri) ) );
// ilog( "${r}", ("r",string(result) ) );
auto lg2 = result.log2();
if( lg2 >= 128 )
{
// wlog( "." );
FC_THROW_EXCEPTION( addition_overflow,
"overflow ${a} / ${p} = ${r} lg2 = ${l}",
("a",a)("p",p)("r", std::string(result) )("l",lg2) );
}
// result += 5000000000; // TODO: evaluate this rounding factor..
asset r;
r.amount = result.to_int64();
r.asset_id = p.base_asset_id;
// ilog( "r.amount = ${r}", ("r",r.amount) );
// ilog( "${a} * ${p} => ${rtn}", ("a", a)("p",p )("rtn",r) );
return r;
}
FC_THROW_EXCEPTION( asset_type_mismatch, "type mismatch multiplying asset ${a} by price ${p}",
("a",a)("p",p) );
} FC_RETHROW_EXCEPTIONS( warn, "type mismatch multiplying asset ${a} by price ${p}",
("a",a)("p",p) );
}
} } // bts::blockchain
namespace fc
{
/*
void to_variant( const bts::blockchain::asset& var, variant& vo )
{
vo = std::string(var);
}
void from_variant( const variant& var, bts::blockchain::asset& vo )
{
vo = bts::blockchain::asset( var.as_string() );
}
*/
void to_variant( const bts::blockchain::price& var, variant& vo )
{
fc::mutable_variant_object obj("ratio",var.ratio_string());
obj( "quote_asset_id", var.quote_asset_id );
obj( "base_asset_id", var.base_asset_id );
vo = std::move(obj);
}
void from_variant( const variant& var, bts::blockchain::price& vo )
{
auto obj = var.get_object();
vo.set_ratio_from_string( obj["ratio"].as_string() );
from_variant( obj["quote_asset_id"], vo.quote_asset_id );
from_variant( obj["base_asset_id"], vo.base_asset_id );
}
} // fc
<commit_msg>Attempt to fix crash when marekt order is submitted with too much precision (not yet tested).<commit_after>#include <bts/blockchain/asset.hpp>
#include <bts/blockchain/config.hpp>
#include <bts/blockchain/exceptions.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/uint128.hpp>
#include <fc/real128.hpp>
#include <sstream>
namespace bts { namespace blockchain {
price operator *( const price& l, const price& r )
{ try {
FC_ASSERT( l.quote_asset_id == r.quote_asset_id );
FC_ASSERT( l.base_asset_id == r.base_asset_id );
// infinity times zero is undefined / exception
// infinity times anything else is infinity
if( l.is_infinite() )
{
if( r.ratio == fc::uint128_t(0) )
FC_THROW_EXCEPTION( price_multiplication_undefined, "price multiplication undefined (0 * inf)" );
return l;
}
if( r.is_infinite() )
{
if( l.ratio == fc::uint128_t(0) )
FC_THROW_EXCEPTION( price_multiplication_undefined, "price multiplication undefined (inf * 0)" );
return r;
}
// zero times anything is zero (infinity is already handled above)
if( l.ratio == fc::uint128_t(0) )
return l;
if( r.ratio == fc::uint128_t(0) )
return r;
fc::bigint product = l.ratio;
product *= r.ratio;
product /= FC_REAL128_PRECISION;
// if the quotient is zero, it means there was an underflow
// (i.e. the result is nonzero but too small to represent)
if( product == fc::bigint() )
FC_THROW_EXCEPTION( price_multiplication_underflow, "price multiplication underflow" );
static fc::bigint bi_infinity = price::infinite();
// if the quotient is infinity or bigger, then we have a finite
// result that is too big to represent (overflow)
if( product >= bi_infinity )
FC_THROW_EXCEPTION( price_multiplication_overflow, "price multiplication overflow" );
// NB we throw away the low bits, thus this function always rounds down
price result( fc::uint128( product ), l.quote_asset_id, l.base_asset_id );
return result;
} FC_CAPTURE_AND_RETHROW( (l)(r) ) }
asset::operator std::string()const
{
return fc::to_string(amount);
}
asset& asset::operator += ( const asset& o )
{ try {
FC_ASSERT( this->asset_id == o.asset_id, "", ("*this",*this)("o",o) );
if (((o.amount > 0) && (amount > (INT64_MAX - o.amount))) ||
((o.amount < 0) && (amount < (INT64_MIN - o.amount))))
{
FC_THROW_EXCEPTION( addition_overflow, "asset addition overflow ${a} + ${b}",
("a", *this)("b",o) );
}
amount += o.amount;
return *this;
} FC_CAPTURE_AND_RETHROW( (*this)(o) ) }
asset& asset::operator -= ( const asset& o )
{
FC_ASSERT( asset_id == o.asset_id );
if ((o.amount > 0 && amount < INT64_MIN + o.amount) ||
(o.amount < 0 && amount > INT64_MAX + o.amount))
{
FC_THROW_EXCEPTION( subtraction_overflow, "asset subtraction underflow ${a} - ${b}",
("a", *this)("b",o) );
}
amount -= o.amount;
return *this;
}
const fc::uint128& price::one()
{
static fc::uint128_t o = fc::uint128(1,0);
return o;
}
const fc::uint128& price::infinite()
{
static fc::uint128 i(-1);
return i;
}
bool price::is_infinite() const
{
static fc::uint128 infinity = infinite();
return (this->ratio == infinity);
}
price::price( const std::string& s )
{ try {
int pos = set_ratio_from_string( s );
std::stringstream ss( s.substr( pos ) );
char div;
ss >> quote_asset_id.value >> div >> base_asset_id.value;
FC_ASSERT( quote_asset_id > base_asset_id, "${quote} > ${base}", ("quote",quote_asset_id)("base",base_asset_id) );
} FC_RETHROW_EXCEPTIONS( warn, "" ) }
int price::set_ratio_from_string( const std::string& ratio_str )
{
const char* c = ratio_str.c_str();
int digit = *c - '0';
if (digit >= 0 && digit <= 9)
{
uint64_t int_part = digit;
++c;
digit = *c - '0';
while (digit >= 0 && digit <= 9)
{
//if number is greater max supported value
FC_ASSERT(int_part <= (UINT64_MAX - digit) / 10, "Number too big to store as price.");
int_part = int_part * 10 + digit;
++c;
digit = *c - '0';
}
ratio = fc::uint128(int_part) * FC_REAL128_PRECISION;
}
else
{
// if the string doesn't look like "123.45" or ".45", this code isn't designed to parse it correctly
// in particular, we don't try to handle leading whitespace or '+'/'-' indicators at the beginning
FC_ASSERT( (*c) == '.' );
ratio = fc::uint128();
}
if (*c == '.')
{
c++;
digit = *c - '0';
if (digit >= 0 && digit <= 9)
{
int64_t frac_part = digit;
int64_t frac_magnitude = 10;
++c;
digit = *c - '0';
while (digit >= 0 && digit <= 9)
{
//if we've reached the limits of precision, ignore remaining digits
if (frac_magnitude > FC_REAL128_PRECISION / 10)
{
do
{
++c;
digit = *c - '0';
}
while (digit >= 0 && digit <= 9);
break;
}
frac_magnitude *= 10;
frac_part = frac_part * 10 + digit;
++c;
digit = *c - '0';
}
ratio += fc::uint128(frac_part) * (FC_REAL128_PRECISION / frac_magnitude);
//skip over remaining digits since they are too precise
}
}
return int(c - ratio_str.c_str()); //return end point of digits
}
std::string price::ratio_string()const
{
std::string full_int = std::string( ratio );
std::stringstream ss;
ss <<std::string( ratio / FC_REAL128_PRECISION );
ss << '.';
ss << std::string( (ratio % FC_REAL128_PRECISION) + FC_REAL128_PRECISION ).substr(1);
auto number = ss.str();
while( number.back() == '0' ) number.pop_back();
return number;
}
price::operator std::string()const
{ try {
auto number = ratio_string();
number += ' ' + fc::to_string(int64_t(quote_asset_id.value));
number += '/' + fc::to_string(int64_t(base_asset_id.value));
return number;
} FC_RETHROW_EXCEPTIONS( warn, "" )}
/**
* A price will reorder the asset types such that the
* asset type with the lower enum value is always the
* denominator. Therefore bts/usd and usd/bts will
* always result in a price measured in usd/bts because
* asset::bts < asset::usd.
*/
price operator / ( const asset& a, const asset& b )
{
try
{
if( a.asset_id == b.asset_id )
FC_CAPTURE_AND_THROW( asset_divide_by_self );
price p;
auto l = a; auto r = b;
if( l.asset_id < r.asset_id ) { std::swap(l,r); }
//ilog( "${a} / ${b}", ("a",l)("b",r) );
if( r.amount == 0 )
FC_CAPTURE_AND_THROW( asset_divide_by_zero, (r) );
p.base_asset_id = r.asset_id;
p.quote_asset_id = l.asset_id;
fc::bigint bl = l.amount;
fc::bigint br = r.amount;
fc::bigint result = (bl * fc::bigint(FC_REAL128_PRECISION)) / br;
p.ratio = result;
return p;
} FC_RETHROW_EXCEPTIONS( warn, "${a} / ${b}", ("a",a)("b",b) );
}
asset operator / ( const asset& a, const price& p )
{
return a * p;
}
/**
* Assuming a.type is either the numerator.type or denominator.type in
* the price equation, return the number of the other asset type that
* could be exchanged at price p.
*
* ie: p = 3 usd/bts & a = 4 bts then result = 12 usd
* ie: p = 3 usd/bts & a = 4 usd then result = 1.333 bts
*/
asset operator * ( const asset& a, const price& p )
{
try {
if( a.asset_id == p.base_asset_id )
{
fc::bigint ba( a.amount ); // 64.64
fc::bigint r( p.ratio ); // 64.64
auto amnt = ba * r; // 128.128
amnt /= FC_REAL128_PRECISION; // 128.64
auto lg2 = amnt.log2();
if( lg2 >= 128 )
{
FC_THROW_EXCEPTION( addition_overflow, "overflow ${a} * ${p}", ("a",a)("p",p) );
}
asset rtn;
rtn.amount = amnt.to_int64();
rtn.asset_id = p.quote_asset_id;
//ilog( "${a} * ${p} => ${rtn}", ("a", a)("p",p )("rtn",rtn) );
return rtn;
}
else if( a.asset_id == p.quote_asset_id )
{
fc::bigint amt( a.amount ); // 64.64
amt *= FC_REAL128_PRECISION; //<<= 64; // 64.128
fc::bigint pri( p.ratio ); // 64.64
auto result = amt / pri; // 64.64
// ilog( "amt: ${amt} / ${pri}", ("amt",string(amt))("pri",string(pri) ) );
// ilog( "${r}", ("r",string(result) ) );
auto lg2 = result.log2();
if( lg2 >= 128 )
{
// wlog( "." );
FC_THROW_EXCEPTION( addition_overflow,
"overflow ${a} / ${p} = ${r} lg2 = ${l}",
("a",a)("p",p)("r", std::string(result) )("l",lg2) );
}
// result += 5000000000; // TODO: evaluate this rounding factor..
asset r;
r.amount = result.to_int64();
r.asset_id = p.base_asset_id;
// ilog( "r.amount = ${r}", ("r",r.amount) );
// ilog( "${a} * ${p} => ${rtn}", ("a", a)("p",p )("rtn",r) );
return r;
}
FC_THROW_EXCEPTION( asset_type_mismatch, "type mismatch multiplying asset ${a} by price ${p}",
("a",a)("p",p) );
} FC_RETHROW_EXCEPTIONS( warn, "type mismatch multiplying asset ${a} by price ${p}",
("a",a)("p",p) );
}
} } // bts::blockchain
namespace fc
{
/*
void to_variant( const bts::blockchain::asset& var, variant& vo )
{
vo = std::string(var);
}
void from_variant( const variant& var, bts::blockchain::asset& vo )
{
vo = bts::blockchain::asset( var.as_string() );
}
*/
void to_variant( const bts::blockchain::price& var, variant& vo )
{
fc::mutable_variant_object obj("ratio",var.ratio_string());
obj( "quote_asset_id", var.quote_asset_id );
obj( "base_asset_id", var.base_asset_id );
vo = std::move(obj);
}
void from_variant( const variant& var, bts::blockchain::price& vo )
{
auto obj = var.get_object();
vo.set_ratio_from_string( obj["ratio"].as_string() );
from_variant( obj["quote_asset_id"], vo.quote_asset_id );
from_variant( obj["base_asset_id"], vo.base_asset_id );
}
} // fc
<|endoftext|>
|
<commit_before>#include "views.h"
using namespace std;
namespace rviews {
void login(JsonValue * message, ServerHandler * handler) {
JsonDict * dictMessage = JDICT(message);
if (dictMessage == NULL) {
throw BadRequest("Malformatted request. Need a JSON dict");
}
bool success = getBool(dictMessage, "success");
if (success) {
emit handler->getWindow()->loginSuccess();
}
else {
emit handler->getWindow()->loginFailure(getInt(dictMessage, "code"));
}
}
void signup(JsonValue * message, ServerHandler * handler) {
JsonDict * dictMessage = JDICT(message);
if (dictMessage == NULL) {
throw BadRequest("Malformatted request. Need a JSON dict");
}
bool success = getBool(dictMessage, "success");
if (success) {
emit handler->getWindow()->registerSuccess();
}
else {
emit handler->getWindow()->registerFailure(getInt(dictMessage, "code"));
}
}
void userlist(JsonValue * message, ServerHandler * handler) {
JsonList * listMessage = JLIST(message);
if (listMessage == NULL) {
throw BadRequest("Malformatted request. Need a JSON list");
}
vector<string> * ulist = new vector<string>;
for (int i = 0; i < listMessage->size(); i++) {
ulist->push_back(getString(listMessage, i));
}
emit handler->getWindow()->userList(ulist);
}
void playerlist(JsonValue * message, ServerHandler * handler) {
JsonList * listMessage = JLIST(message);
if (listMessage == NULL) {
throw BadRequest("Malformatted request. Need a JSON list");
}
vector<NonFieldPlayer *> * plist = new vector<NonFieldPlayer *>;
for (int i = 0; i < listMessage->size(); i++) {
plist->push_back(new NonFieldPlayer((*listMessage)[i]));
}
emit handler->getWindow()->playerList(plist);
}
void startMatch(JsonValue * message, ServerHandler * handler) {
JsonDict * listMessage = JDICT(message);
if (listMessage == NULL) {
throw BadRequest("Malformatted request. Need a JSON list");
}
Match * match = new Match(listMessage);
emit handler->getWindow()->startMatch(match);
}
void updateMatch(JsonValue * message, ServerHandler * handler) {
JsonDict * listMessage = JDICT(message);
if (listMessage == NULL) {
throw BadRequest("Malformatted request. Need a JSON list");
}
Match * match = new Match(listMessage);
emit handler->getWindow()->updateMatch(match);
}
}
<commit_msg>Get isGuest from json in startMatch.<commit_after>#include "views.h"
using namespace std;
namespace rviews {
void login(JsonValue * message, ServerHandler * handler) {
JsonDict * dictMessage = JDICT(message);
if (dictMessage == NULL) {
throw BadRequest("Malformatted request. Need a JSON dict");
}
bool success = getBool(dictMessage, "success");
if (success) {
emit handler->getWindow()->loginSuccess();
}
else {
emit handler->getWindow()->loginFailure(getInt(dictMessage, "code"));
}
}
void signup(JsonValue * message, ServerHandler * handler) {
JsonDict * dictMessage = JDICT(message);
if (dictMessage == NULL) {
throw BadRequest("Malformatted request. Need a JSON dict");
}
bool success = getBool(dictMessage, "success");
if (success) {
emit handler->getWindow()->registerSuccess();
}
else {
emit handler->getWindow()->registerFailure(getInt(dictMessage, "code"));
}
}
void userlist(JsonValue * message, ServerHandler * handler) {
JsonList * listMessage = JLIST(message);
if (listMessage == NULL) {
throw BadRequest("Malformatted request. Need a JSON list");
}
vector<string> * ulist = new vector<string>;
for (int i = 0; i < listMessage->size(); i++) {
ulist->push_back(getString(listMessage, i));
}
emit handler->getWindow()->userList(ulist);
}
void playerlist(JsonValue * message, ServerHandler * handler) {
JsonList * listMessage = JLIST(message);
if (listMessage == NULL) {
throw BadRequest("Malformatted request. Need a JSON list");
}
vector<NonFieldPlayer *> * plist = new vector<NonFieldPlayer *>;
for (int i = 0; i < listMessage->size(); i++) {
plist->push_back(new NonFieldPlayer((*listMessage)[i]));
}
emit handler->getWindow()->playerList(plist);
}
void startMatch(JsonValue * message, ServerHandler * handler) {
JsonDict * listMessage = JDICT(message);
if (listMessage == NULL) {
throw BadRequest("Malformatted request. Need a JSON list");
}
bool isGuest = getBool(listMessage, "guest");
Match * match = new Match(listMessage);
emit handler->getWindow()->startMatch(match, isGuest);
}
void updateMatch(JsonValue * message, ServerHandler * handler) {
JsonDict * listMessage = JDICT(message);
if (listMessage == NULL) {
throw BadRequest("Malformatted request. Need a JSON list");
}
Match * match = new Match(listMessage);
emit handler->getWindow()->updateMatch(match);
}
}
<|endoftext|>
|
<commit_before>/**
* blocked.hpp -
* @author: Jonathan Beard
* @version: Sun Jun 29 14:06:10 2014
*
* Copyright 2014 Jonathan Beard
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef BLOCKED_HPP
#define BLOCKED_HPP 1
#include <cstdint>
#include <cassert>
/**
* FIXME move thos code to the defs.hpp file
* useful for other things, no point in duplicating
* elsewhere
*/
#ifdef _MSC_VER
# if (_MSC_VER >= 1800)
# define __alignas_is_defined 1
# endif
# if (_MSC_VER >= 1900)
# define __alignof_is_defined 1
# endif
#else
# ifndef __APPLE__
# include <cstdalign> // __alignas/of_is_defined directly from the implementation
# endif
#endif
/**
* should be included, but just in case there are some
* compilers with only experimental C++11 support still
* running around, check macro..turns out it's #ifdef out
* on GNU G++ so checking __cplusplus flag as indicated
* by https://goo.gl/JD4Gng
*/
#if ( __alignas_is_defined == 1 ) || ( __cplusplus >= 201103L )
# define ALIGN(X) alignas(X)
#else
# pragma message("C++11 alignas unsupported :( Falling back to compiler attributes")
# ifdef __GNUG__
# define ALIGN(X) __attribute__ ((aligned(X)))
# elif defined(_MSC_VER)
# define ALIGN(X) __declspec(align(X))
# else
# error Unknown compiler, unknown alignment attribute!
# endif
#endif
#if ( __alignas_is_defined == 1 ) || ( __cplusplus >= 201103L )
# define ALIGNOF(X) alignof(x)
#else
# pragma message("C++11 alignof unsupported :( Falling back to compiler attributes")
# ifdef __GNUG__
# define ALIGNOF(X) __alignof__ (X)
# elif defined(_MSC_VER)
# define ALIGNOF(X) __alignof(X)
# else
# error Unknown compiler, unknown alignment attribute!
# endif
#endif
/**
* FIXME...should probably align these to cache line then
* zero extend pad for producer/consumer.
*/
struct ALIGN(64) Blocked
{
using value_type = std::uint32_t;
using whole_type = std::uint64_t;
static_assert( sizeof( value_type ) * 2 == sizeof( whole_type ),
"Error, the whole type must be double the size of the half type" );
Blocked() = default;
Blocked( const Blocked &other ) : all( other.all ){}
Blocked& operator += ( const Blocked &rhs )
{
if( ! rhs.bec.blocked )
{
(this)->bec.count += rhs.bec.count;
}
return( *this );
}
struct blocked_and_counter
{
value_type blocked;
value_type count;
};
union
{
blocked_and_counter bec;
whole_type all = 0;
};
char pad[ L1D_CACHE_LINE_SIZE - sizeof( whole_type ) ];
}
;
#endif /* END BLOCKED_HPP */
<commit_msg>moved aligncode to its own file<commit_after>/**
* blocked.hpp -
* @author: Jonathan Beard
* @version: Sun Jun 29 14:06:10 2014
*
* Copyright 2014 Jonathan Beard
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef BLOCKED_HPP
#define BLOCKED_HPP 1
#include <cstdint>
#include <cassert>
#include "internaldefs.hpp"
/**
* FIXME...should probably align these to cache line then
* zero extend pad for producer/consumer.
*/
struct ALIGN(64) Blocked
{
using value_type = std::uint32_t;
using whole_type = std::uint64_t;
static_assert( sizeof( value_type ) * 2 == sizeof( whole_type ),
"Error, the whole type must be double the size of the half type" );
Blocked() = default;
Blocked( const Blocked &other ) : all( other.all ){}
Blocked& operator += ( const Blocked &rhs )
{
if( ! rhs.bec.blocked )
{
(this)->bec.count += rhs.bec.count;
}
return( *this );
}
struct blocked_and_counter
{
value_type blocked;
value_type count;
};
union
{
blocked_and_counter bec;
whole_type all = 0;
};
char pad[ L1D_CACHE_LINE_SIZE - sizeof( whole_type ) ];
}
;
#endif /* END BLOCKED_HPP */
<|endoftext|>
|
<commit_before>//=============================================================================================================
/**
* @file icp.cpp
* @author Ruben Dörfel <doerfelruben@aol.com>
* @since 0.1.0
* @date July, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Ruben Dörfel. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of MNE-CPP authors nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief ICP class definition.
*
*/
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "icp.h"
#include <iostream>
#include "fiff/fiff_coord_trans.h"
#include "mne/mne_project_to_surface.h"
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QSharedPointer>
#include <QDebug>
//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================
#include <Eigen/Core>
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
#include <Eigen/Geometry>
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace MNELIB;
using namespace RTPROCESSINGLIB;
using namespace Eigen;
using namespace FIFFLIB;
//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
ICP::ICP()
{
}
//=============================================================================================================
bool RTPROCESSINGLIB::icp(const MNEProjectToSurface::SPtr mneSurfacePoints,
const Eigen::MatrixXf& matDstPoint,
FiffCoordTrans& transFromTo,
const int iMaxIter,
const float fTol,
const VectorXf& vecWeitgths)
/**
* Follow notation of P.J. Besl and N.D. McKay, A Method for
* Registration of 3-D Shapes, IEEE Trans. Patt. Anal. Machine Intell., 14,
* 239 - 255, 1992.
*/
{
// Initialization
int iNP = matDstPoint.rows(); // The number of points
float fMSEPrev,fMSE = 0.0; // The mean square error
float fScale = 1.0;
float bScale = true;
MatrixXf matP0 = matDstPoint; // Initial Set of points
MatrixXf matPk = matP0; // Transformed Set of points
MatrixXf matYk(matPk.rows(),matPk.cols()); // Iterative losest points on the surface
MatrixXf matDiff = matYk;
VectorXf vecSE(matDiff.rows());
Matrix4f matTrans; // the transformation matrix
VectorXi vecNearest; // Triangle of the new point
VectorXf vecDist; // The Distance between matX and matP
// Initial transformation - apply inverse because we are computing in Model space
FiffCoordTrans transToFrom = transFromTo;
transToFrom.invert_transform();
matPk = transToFrom.apply_trans(matPk);
// Icp algorithm:
for(int iIter = 0; iIter < iMaxIter; ++iIter) {
// Step a: compute the closest point on the surface; eq 29
if(!mneSurfacePoints->mne_find_closest_on_surface(matPk, iNP, matYk, vecNearest, vecDist)) {
qWarning() << "RTPROCESSINGLIB::icp: mne_find_closest_on_surface was not sucessfull.";
return false;
}
// Step b: compute the registration; eq 30
if(!fitMatched(matP0, matYk, matTrans, fScale, bScale, vecWeitgths)) {
qWarning() << "RTPROCESSINGLIB::icp: point cloud registration not succesfull";
}
// Step c: apply registration
transToFrom.trans = matTrans;
matPk = transToFrom.apply_trans(matP0);
// step d: compute mean-square-error and terminate if below fTol
fMSE = vecDist.sum() / iNP;
if(std::fabs(fMSE - fMSEPrev) < fTol) {
transToFrom.invert_transform();
transFromTo = transToFrom;
qInfo() << "RTPROCESSINGLIB::icp: ICP was succesfull and exceeded after " << iIter << " Iterations with MSE: " << fMSE << ".";
return true;
}
fMSEPrev = fMSE;
qInfo() << "RTPROCESSINGLIB::icp: ICP iteration " << iIter << " with MSE: " << fMSE << ".";
}
qWarning() << "RTPROCESSINGLIB::icp: ICP was not succesfull and exceeded after " << iMaxIter << " Iterations with MSE: " << fMSE << ".";
return false;
}
//=============================================================================================================
bool RTPROCESSINGLIB::fitMatched(const MatrixXf& matSrcPoint,
const MatrixXf& matDstPoint,
Eigen::Matrix4f& matTrans,
float fScale,
const bool bScale,
const VectorXf& vecWeitgths)
/**
* Follow notation of P.J. Besl and N.D. McKay, A Method for
* Registration of 3-D Shapes, IEEE Trans. Patt. Anal. Machine Intell., 14,
* 239 - 255, 1992.
*
* The code is further adapted from MNE Python function _fitMatched_points(...).
*/
{
// init values
MatrixXf matP = matSrcPoint;
MatrixXf matX = matDstPoint;
VectorXf vecW = vecWeitgths;
VectorXf vecMuP; // column wise mean - center of mass
VectorXf vecMuX; // column wise mean - center of mass
MatrixXf matDot;
MatrixXf matSigmaPX; // cross-covariance
MatrixXf matAij; // Anti-Symmetric matrix
Vector3f vecDelta; // column vector, elements of matAij
Matrix4f matQ = Matrix4f::Identity(4,4);
Matrix3f matScale = Matrix3f::Identity(3,3); // scaling matrix
Matrix3f matRot = Matrix3f::Identity(3,3);
Vector3f vecTrans;
float fTrace = 0.0;
fScale = 1.0;
// test size of point clouds
if(matSrcPoint.size() != matDstPoint.size()) {
qWarning() << "RTPROCESSINGLIB::fitMatched: Point clouds do not match.";
return false;
}
// get center of mass
if(vecWeitgths.isZero()) {
vecMuP = matP.colwise().mean(); // eq 23
vecMuX = matX.colwise().mean();
matDot = matP.transpose() * matX;
matDot = matDot / matP.rows();
} else {
vecW = vecWeitgths / vecWeitgths.sum();
vecMuP = vecW.transpose() * matP;
vecMuX = vecW.transpose() * matX;
MatrixXf matXWeighted = matX;
for(int i = 0; i < (vecW.size()); ++i) {
matXWeighted.row(i) = matXWeighted.row(i) * vecW(i);
}
matDot = matP.transpose() * (matXWeighted);
}
// get cross-covariance
matSigmaPX = matDot - (vecMuP * vecMuX.transpose()); // eq 24
matAij = matSigmaPX - matSigmaPX.transpose();
vecDelta(0) = matAij(1,2); vecDelta(1) = matAij(2,0); vecDelta(2) = matAij(0,1);
fTrace = matSigmaPX.trace();
matQ(0,0) = fTrace; // eq 25
matQ.block(0,1,1,3) = vecDelta.transpose();
matQ.block(1,0,3,1) = vecDelta;
matQ.block(1,1,3,3) = matSigmaPX + matSigmaPX.transpose() - fTrace * MatrixXf::Identity(3,3);
// unit eigenvector coresponding to maximum eigenvalue of matQ is selected as optimal rotation quaterions q0,q1,q2,q3
SelfAdjointEigenSolver<MatrixXf> es(matQ);
Vector4f vecEigVec = es.eigenvectors().col(matQ.cols()-1); // only take last Eigen-Vector since this corresponds to the maximum Eigenvalue
// quatRot(w,x,y,z)
Quaternionf quatRot(vecEigVec(0),vecEigVec(1),vecEigVec(2),vecEigVec(3));
quatRot.normalize();
matRot = quatRot.matrix();
// get scaling factor and matrix
if(bScale) {
MatrixXf matDevX = matX.rowwise() - vecMuX.transpose();
MatrixXf matDevP = matP.rowwise() - vecMuP.transpose();
matDevX = matDevX.cwiseProduct(matDevX);
matDevP = matDevP.cwiseProduct(matDevP);
if(!vecWeitgths.isZero()) {
for(int i = 0; i < (vecW.size()); ++i) {
matDevX.row(i) = matDevX.row(i) * vecW(i);
matDevP.row(i) = matDevP.row(i) * vecW(i);
}
}
// get scaling factor and set scaling matrix
fScale = std::sqrt(matDevX.sum() / matDevP.sum());
matScale *= fScale;
}
// get translation and Rotation
vecTrans = vecMuX - fScale * matRot * vecMuP;
matRot *= matScale;
matTrans.block<3,3>(0,0) = matRot;
matTrans.block<3,1>(0,3) = vecTrans;
matTrans(3,3) = 1.0f;
return true;
}
//=========================================================================================================
bool RTPROCESSINGLIB::discardOutliers(const QSharedPointer<MNELIB::MNEProjectToSurface> mneSurfacePoints,
const MatrixXf& matDstPoint,
const FiffCoordTrans& transFromTo,
VectorXi& vecTake,
MatrixXf& matTakePoint,
const float fMaxDist)
{
// Initialization
int iNP = matDstPoint.rows(); // The number of points
MatrixXf matP = matDstPoint; // Initial Set of points
MatrixXf matYk(matDstPoint.rows(),matDstPoint.cols()); // Iterative losest points on the surface
VectorXi vecNearest; // Triangle of the new point
VectorXf vecDist; // The Distance between matX and matP
// Initial transformation - apply inverse because we are computing in Model space
FiffCoordTrans transToFrom = transFromTo;
transToFrom.invert_transform();
matP = transToFrom.apply_trans(matP);
int iDiscarded = 0;
// discard outliers if necessary
if(fMaxDist > 0.0) {
if(!mneSurfacePoints->mne_find_closest_on_surface(matP, iNP, matYk, vecNearest, vecDist)) {
qWarning() << "RTPROCESSINGLIB::icp: mne_find_closest_on_surface was not sucessfull.";
return false;
}
for(int i = 0; i < vecDist.size(); ++i) {
if(std::fabs(vecDist(i)) < fMaxDist) {
vecTake.conservativeResize(vecTake.size()+1);
vecTake(vecTake.size()-1) = i;
matTakePoint.conservativeResize(matTakePoint.rows()+1,3);
matTakePoint.row(matTakePoint.rows()-1) = matDstPoint.row(i);
} else {
iDiscarded++;
}
}
}
qInfo() << "RTPROCESSINGLIB::discardOutliers: " << iDiscarded << "digitizers discarded.";
}
<commit_msg>Maint: use correct implementation of RMSE<commit_after>//=============================================================================================================
/**
* @file icp.cpp
* @author Ruben Dörfel <doerfelruben@aol.com>
* @since 0.1.0
* @date July, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Ruben Dörfel. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of MNE-CPP authors nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief ICP class definition.
*
*/
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "icp.h"
#include <iostream>
#include "fiff/fiff_coord_trans.h"
#include "mne/mne_project_to_surface.h"
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QSharedPointer>
#include <QDebug>
//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================
#include <Eigen/Core>
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
#include <Eigen/Geometry>
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace MNELIB;
using namespace RTPROCESSINGLIB;
using namespace Eigen;
using namespace FIFFLIB;
//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
ICP::ICP()
{
}
//=============================================================================================================
bool RTPROCESSINGLIB::icp(const MNEProjectToSurface::SPtr mneSurfacePoints,
const Eigen::MatrixXf& matDstPoint,
FiffCoordTrans& transFromTo,
const int iMaxIter,
const float fTol,
const VectorXf& vecWeitgths)
/**
* Follow notation of P.J. Besl and N.D. McKay, A Method for
* Registration of 3-D Shapes, IEEE Trans. Patt. Anal. Machine Intell., 14,
* 239 - 255, 1992.
*/
{
// Initialization
int iNP = matDstPoint.rows(); // The number of points
float fMSEPrev,fMSE = 0.0; // The mean square error
float fScale = 1.0;
float bScale = true;
MatrixXf matP0 = matDstPoint; // Initial Set of points
MatrixXf matPk = matP0; // Transformed Set of points
MatrixXf matYk(matPk.rows(),matPk.cols()); // Iterative losest points on the surface
MatrixXf matDiff = matYk;
VectorXf vecSE(matDiff.rows());
Matrix4f matTrans; // the transformation matrix
VectorXi vecNearest; // Triangle of the new point
VectorXf vecDist; // The Distance between matX and matP
// Initial transformation - apply inverse because we are computing in Model space
FiffCoordTrans transToFrom = transFromTo;
transToFrom.invert_transform();
matPk = transToFrom.apply_trans(matPk);
// Icp algorithm:
for(int iIter = 0; iIter < iMaxIter; ++iIter) {
// Step a: compute the closest point on the surface; eq 29
if(!mneSurfacePoints->mne_find_closest_on_surface(matPk, iNP, matYk, vecNearest, vecDist)) {
qWarning() << "RTPROCESSINGLIB::icp: mne_find_closest_on_surface was not sucessfull.";
return false;
}
// Step b: compute the registration; eq 30
if(!fitMatched(matP0, matYk, matTrans, fScale, bScale, vecWeitgths)) {
qWarning() << "RTPROCESSINGLIB::icp: point cloud registration not succesfull";
}
// Step c: apply registration
transToFrom.trans = matTrans;
matPk = transToFrom.apply_trans(matP0);
// step d: compute mean-square-error and terminate if below fTol
vecDist = vecDist.cwiseProduct(vecDist);
fMSE = vecDist.sum() / iNP;
if(std::fabs(fMSE - fMSEPrev) < fTol) {
transToFrom.invert_transform();
transFromTo = transToFrom;
qInfo() << "RTPROCESSINGLIB::icp: ICP was succesfull and exceeded after " << iIter +1 << " Iterations with MSE dist: " << fMSE << " mm.";
return true;
}
fMSEPrev = fMSE;
qInfo() << "RTPROCESSINGLIB::icp: ICP iteration " << iIter + 1 << " with MSE: " << fMSE << ".";
}
qWarning() << "RTPROCESSINGLIB::icp: ICP was not succesfull and exceeded after " << iMaxIter << " Iterations with MSE: " << fMSE << ".";
return false;
}
//=============================================================================================================
bool RTPROCESSINGLIB::fitMatched(const MatrixXf& matSrcPoint,
const MatrixXf& matDstPoint,
Eigen::Matrix4f& matTrans,
float fScale,
const bool bScale,
const VectorXf& vecWeitgths)
/**
* Follow notation of P.J. Besl and N.D. McKay, A Method for
* Registration of 3-D Shapes, IEEE Trans. Patt. Anal. Machine Intell., 14,
* 239 - 255, 1992.
*
* The code is further adapted from MNE Python function _fitMatched_points(...).
*/
{
// init values
MatrixXf matP = matSrcPoint;
MatrixXf matX = matDstPoint;
VectorXf vecW = vecWeitgths;
VectorXf vecMuP; // column wise mean - center of mass
VectorXf vecMuX; // column wise mean - center of mass
MatrixXf matDot;
MatrixXf matSigmaPX; // cross-covariance
MatrixXf matAij; // Anti-Symmetric matrix
Vector3f vecDelta; // column vector, elements of matAij
Matrix4f matQ = Matrix4f::Identity(4,4);
Matrix3f matScale = Matrix3f::Identity(3,3); // scaling matrix
Matrix3f matRot = Matrix3f::Identity(3,3);
Vector3f vecTrans;
float fTrace = 0.0;
fScale = 1.0;
// test size of point clouds
if(matSrcPoint.size() != matDstPoint.size()) {
qWarning() << "RTPROCESSINGLIB::fitMatched: Point clouds do not match.";
return false;
}
// get center of mass
if(vecWeitgths.isZero()) {
vecMuP = matP.colwise().mean(); // eq 23
vecMuX = matX.colwise().mean();
matDot = matP.transpose() * matX;
matDot = matDot / matP.rows();
} else {
vecW = vecWeitgths / vecWeitgths.sum();
vecMuP = vecW.transpose() * matP;
vecMuX = vecW.transpose() * matX;
MatrixXf matXWeighted = matX;
for(int i = 0; i < (vecW.size()); ++i) {
matXWeighted.row(i) = matXWeighted.row(i) * vecW(i);
}
matDot = matP.transpose() * (matXWeighted);
}
// get cross-covariance
matSigmaPX = matDot - (vecMuP * vecMuX.transpose()); // eq 24
matAij = matSigmaPX - matSigmaPX.transpose();
vecDelta(0) = matAij(1,2); vecDelta(1) = matAij(2,0); vecDelta(2) = matAij(0,1);
fTrace = matSigmaPX.trace();
matQ(0,0) = fTrace; // eq 25
matQ.block(0,1,1,3) = vecDelta.transpose();
matQ.block(1,0,3,1) = vecDelta;
matQ.block(1,1,3,3) = matSigmaPX + matSigmaPX.transpose() - fTrace * MatrixXf::Identity(3,3);
// unit eigenvector coresponding to maximum eigenvalue of matQ is selected as optimal rotation quaterions q0,q1,q2,q3
SelfAdjointEigenSolver<MatrixXf> es(matQ);
Vector4f vecEigVec = es.eigenvectors().col(matQ.cols()-1); // only take last Eigen-Vector since this corresponds to the maximum Eigenvalue
// quatRot(w,x,y,z)
Quaternionf quatRot(vecEigVec(0),vecEigVec(1),vecEigVec(2),vecEigVec(3));
quatRot.normalize();
matRot = quatRot.matrix();
// get scaling factor and matrix
if(bScale) {
MatrixXf matDevX = matX.rowwise() - vecMuX.transpose();
MatrixXf matDevP = matP.rowwise() - vecMuP.transpose();
matDevX = matDevX.cwiseProduct(matDevX);
matDevP = matDevP.cwiseProduct(matDevP);
if(!vecWeitgths.isZero()) {
for(int i = 0; i < (vecW.size()); ++i) {
matDevX.row(i) = matDevX.row(i) * vecW(i);
matDevP.row(i) = matDevP.row(i) * vecW(i);
}
}
// get scaling factor and set scaling matrix
fScale = std::sqrt(matDevX.sum() / matDevP.sum());
matScale *= fScale;
}
// get translation and Rotation
vecTrans = vecMuX - fScale * matRot * vecMuP;
matRot *= matScale;
matTrans.block<3,3>(0,0) = matRot;
matTrans.block<3,1>(0,3) = vecTrans;
matTrans(3,3) = 1.0f;
matTrans.block<1,3>(3,0) = MatrixXf::Zero(1,3);
return true;
}
//=========================================================================================================
bool RTPROCESSINGLIB::discardOutliers(const QSharedPointer<MNELIB::MNEProjectToSurface> mneSurfacePoints,
const MatrixXf& matDstPoint,
const FiffCoordTrans& transFromTo,
VectorXi& vecTake,
MatrixXf& matTakePoint,
const float fMaxDist)
{
// Initialization
int iNP = matDstPoint.rows(); // The number of points
MatrixXf matP = matDstPoint; // Initial Set of points
MatrixXf matYk(matDstPoint.rows(),matDstPoint.cols()); // Iterative losest points on the surface
VectorXi vecNearest; // Triangle of the new point
VectorXf vecDist; // The Distance between matX and matP
// Initial transformation - apply inverse because we are computing in Model space
FiffCoordTrans transToFrom = transFromTo;
transToFrom.invert_transform();
matP = transToFrom.apply_trans(matP);
int iDiscarded = 0;
// discard outliers if necessary
if(fMaxDist > 0.0) {
if(!mneSurfacePoints->mne_find_closest_on_surface(matP, iNP, matYk, vecNearest, vecDist)) {
qWarning() << "RTPROCESSINGLIB::icp: mne_find_closest_on_surface was not sucessfull.";
return false;
}
for(int i = 0; i < vecDist.size(); ++i) {
if(std::fabs(vecDist(i)) < fMaxDist) {
vecTake.conservativeResize(vecTake.size()+1);
vecTake(vecTake.size()-1) = i;
matTakePoint.conservativeResize(matTakePoint.rows()+1,3);
matTakePoint.row(matTakePoint.rows()-1) = matDstPoint.row(i);
} else {
iDiscarded++;
}
}
}
qInfo() << "RTPROCESSINGLIB::discardOutliers: " << iDiscarded << "digitizers discarded.";
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2004-2017 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/User.h>
#include <znc/znc.h>
#include <time.h>
using std::map;
using std::pair;
using std::multimap;
class CLastSeenMod : public CModule {
private:
time_t GetTime(const CUser* pUser) {
return GetNV(pUser->GetUserName()).ToULong();
}
void SetTime(const CUser* pUser) {
SetNV(pUser->GetUserName(), CString(time(nullptr)));
}
const CString FormatLastSeen(const CUser* pUser,
const char* sDefault = "") {
time_t last = GetTime(pUser);
if (last < 1) {
return sDefault;
} else {
char buf[1024];
strftime(buf, sizeof(buf) - 1, "%c", localtime(&last));
return buf;
}
}
typedef multimap<time_t, CUser*> MTimeMulti;
typedef map<CString, CUser*> MUsers;
// Shows all users as well as the time they were last seen online
void ShowCommand(const CString& sLine) {
if (!GetUser()->IsAdmin()) {
PutModule("Access denied");
return;
}
const MUsers& mUsers = CZNC::Get().GetUserMap();
MUsers::const_iterator it;
CTable Table;
Table.AddColumn("User");
Table.AddColumn("Last Seen");
for (it = mUsers.begin(); it != mUsers.end(); ++it) {
Table.AddRow();
Table.SetCell("User", it->first);
Table.SetCell("Last Seen", FormatLastSeen(it->second, "never"));
}
PutModule(Table);
}
public:
MODCONSTRUCTOR(CLastSeenMod) {
AddHelpCommand();
AddCommand("Show", static_cast<CModCommand::ModCmdFunc>(
&CLastSeenMod::ShowCommand),
"", "Shows list of users and when they last logged in");
}
~CLastSeenMod() override {}
// Event stuff:
void OnClientLogin() override { SetTime(GetUser()); }
void OnClientDisconnect() override { SetTime(GetUser()); }
EModRet OnDeleteUser(CUser& User) override {
DelNV(User.GetUserName());
return CONTINUE;
}
// Web stuff:
bool WebRequiresAdmin() override { return true; }
CString GetWebMenuTitle() override { return "Last Seen"; }
// Provides GUI to configure this module by adding a widget to user page in webadmin.
bool OnWebRequest(CWebSock& WebSock, const CString& sPageName,
CTemplate& Tmpl) override {
if (sPageName == "index") {
CModules& GModules = CZNC::Get().GetModules();
Tmpl["WebAdminLoaded"] =
CString(GModules.FindModule("webadmin") != nullptr);
MTimeMulti mmSorted;
const MUsers& mUsers = CZNC::Get().GetUserMap();
for (MUsers::const_iterator uit = mUsers.begin();
uit != mUsers.end(); ++uit) {
mmSorted.insert(
pair<time_t, CUser*>(GetTime(uit->second), uit->second));
}
for (MTimeMulti::const_iterator it = mmSorted.begin();
it != mmSorted.end(); ++it) {
CUser* pUser = it->second;
CTemplate& Row = Tmpl.AddRow("UserLoop");
Row["Username"] = pUser->GetUserName();
Row["IsSelf"] =
CString(pUser == WebSock.GetSession()->GetUser());
Row["LastSeen"] = FormatLastSeen(pUser, "never");
}
return true;
}
return false;
}
bool OnEmbeddedWebRequest(CWebSock& WebSock, const CString& sPageName,
CTemplate& Tmpl) override {
if (sPageName == "webadmin/user" && WebSock.GetSession()->IsAdmin()) {
CUser* pUser = CZNC::Get().FindUser(Tmpl["Username"]);
if (pUser) {
Tmpl["LastSeen"] = FormatLastSeen(pUser);
}
return true;
}
return false;
}
};
template <>
void TModInfo<CLastSeenMod>(CModInfo& Info) {
Info.SetWikiPage("lastseen");
}
GLOBALMODULEDEFS(CLastSeenMod,
"Collects data about when a user last logged in.")
<commit_msg>updating comments<commit_after>/*
* Copyright (C) 2004-2017 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/User.h>
#include <znc/znc.h>
#include <time.h>
using std::map;
using std::pair;
using std::multimap;
class CLastSeenMod : public CModule {
private:
time_t GetTime(const CUser* pUser) {
return GetNV(pUser->GetUserName()).ToULong();
}
void SetTime(const CUser* pUser) {
SetNV(pUser->GetUserName(), CString(time(nullptr)));
}
const CString FormatLastSeen(const CUser* pUser,
const char* sDefault = "") {
time_t last = GetTime(pUser);
if (last < 1) {
return sDefault;
} else {
char buf[1024];
strftime(buf, sizeof(buf) - 1, "%c", localtime(&last));
return buf;
}
}
typedef multimap<time_t, CUser*> MTimeMulti;
typedef map<CString, CUser*> MUsers;
// Shows all users as well as the time they were last seen online
void ShowCommand(const CString& sLine) {
if (!GetUser()->IsAdmin()) {
PutModule("Access denied");
return;
}
const MUsers& mUsers = CZNC::Get().GetUserMap();
MUsers::const_iterator it;
CTable Table;
Table.AddColumn("User");
Table.AddColumn("Last Seen");
for (it = mUsers.begin(); it != mUsers.end(); ++it) {
Table.AddRow();
Table.SetCell("User", it->first);
Table.SetCell("Last Seen", FormatLastSeen(it->second, "never"));
}
PutModule(Table);
}
public:
MODCONSTRUCTOR(CLastSeenMod) {
AddHelpCommand();
AddCommand("Show", static_cast<CModCommand::ModCmdFunc>(
&CLastSeenMod::ShowCommand),
"", "Shows list of users and when they last logged in");
}
~CLastSeenMod() override {}
// Event stuff:
void OnClientLogin() override { SetTime(GetUser()); }
void OnClientDisconnect() override { SetTime(GetUser()); }
EModRet OnDeleteUser(CUser& User) override {
DelNV(User.GetUserName());
return CONTINUE;
}
// Web stuff:
bool WebRequiresAdmin() override { return true; }
CString GetWebMenuTitle() override { return "Last Seen"; }
bool OnWebRequest(CWebSock& WebSock, const CString& sPageName,
CTemplate& Tmpl) override {
if (sPageName == "index") {
CModules& GModules = CZNC::Get().GetModules();
Tmpl["WebAdminLoaded"] =
CString(GModules.FindModule("webadmin") != nullptr);
MTimeMulti mmSorted;
const MUsers& mUsers = CZNC::Get().GetUserMap();
for (MUsers::const_iterator uit = mUsers.begin();
uit != mUsers.end(); ++uit) {
mmSorted.insert(
pair<time_t, CUser*>(GetTime(uit->second), uit->second));
}
for (MTimeMulti::const_iterator it = mmSorted.begin();
it != mmSorted.end(); ++it) {
CUser* pUser = it->second;
CTemplate& Row = Tmpl.AddRow("UserLoop");
Row["Username"] = pUser->GetUserName();
Row["IsSelf"] =
CString(pUser == WebSock.GetSession()->GetUser());
Row["LastSeen"] = FormatLastSeen(pUser, "never");
}
return true;
}
return false;
}
bool OnEmbeddedWebRequest(CWebSock& WebSock, const CString& sPageName,
CTemplate& Tmpl) override {
if (sPageName == "webadmin/user" && WebSock.GetSession()->IsAdmin()) {
CUser* pUser = CZNC::Get().FindUser(Tmpl["Username"]);
if (pUser) {
Tmpl["LastSeen"] = FormatLastSeen(pUser);
}
return true;
}
return false;
}
};
template <>
void TModInfo<CLastSeenMod>(CModInfo& Info) {
Info.SetWikiPage("lastseen");
}
GLOBALMODULEDEFS(CLastSeenMod,
"Collects data about when a user last logged in.")
<|endoftext|>
|
<commit_before>#include "mbed.h"
#include "max32630fthr.h"
#include "cmsis.h" // register base address definitions
#include "pwrseq_regs.h" // power sequence register definitions
#include "rtc_regs.h" //RTC register definitions
#include "SDFileSystem.h"
MAX32630FTHR pegasus(MAX32630FTHR::VIO_3V3);
DigitalOut rLed(LED1);
DigitalOut gLed(LED2);
DigitalOut bLed(LED3);
DigitalOut CTS(P0_2);
Serial dap(P2_1, P2_0);
Serial hci(P0_0,P0_1); //BT Tx and Rx (For mcu)
SDFileSystem sd(P0_5, P0_6, P0_4, P0_7, "sd"); // mosi, miso, sclk, cs
int val;
int x = 0;
int y = 0;
int z = 0;
void reg_cfg(){ //Configure registers
dap.printf("Start\r\n");
if ((MXC_PWRSEQ->reg0 |= MXC_F_PWRSEQ_REG0_PWR_RTCEN_RUN) != MXC_PWRSEQ->reg0){ //If the register isn't set, set it
MXC_PWRSEQ->reg0 |= MXC_F_PWRSEQ_REG0_PWR_RTCEN_RUN; //Enable 32k RTC
x = 1;
}
dap.printf("x = %d\r\n", x);
//dap.printf("RTC_En = %d\r\n\r\n", RTC_En);
Thread::wait(100);
if ((MXC_PWRSEQ->reg4 |= MXC_F_PWRSEQ_REG4_PWR_PSEQ_32K_EN) != MXC_PWRSEQ->reg4){
MXC_PWRSEQ->reg4 |= MXC_F_PWRSEQ_REG4_PWR_PSEQ_32K_EN; //Output RTC to P1_7
y = 1;
}
dap.printf("y = %d\r\n",y);
//dap.printf("ClkOut_En = %d\r\n\r\n", ClkOut_En);
Thread::wait(100);
//if ((MXC_UART0->ctrl |= MXC_F_UART_CTRL_CTS_EN) != MXC_UART0->ctrl){
MXC_UART0->ctrl |= MXC_F_UART_CTRL_CTS_EN; //Enable Hardware Output flow control
MXC_UART0->ctrl |= MXC_F_UART_CTRL_CTS_POLARITY;
MXC_UART0->ctrl ^= MXC_F_UART_CTRL_RTS_EN; //Enable Hardware Input flow control (not enabled)
MXC_UART0->ctrl ^= MXC_F_UART_CTRL_RTS_POLARITY;
MXC_IOMAN->uart0_req ^= MXC_F_IOMAN_UART0_REQ_IO_MAP; //Properly map RX & TX
MXC_IOMAN->uart0_req |= MXC_F_IOMAN_UART0_REQ_CTS_MAP; //Properly map CTS
MXC_IOMAN->uart0_req |= MXC_F_IOMAN_UART0_REQ_RTS_MAP; //Properly map RTS
z = 1;
// }
if((x == 1) | (y == 1)){
x = 2;
y = 2;
z = 2;
dap.printf("Z = %d", z);
NVIC_SystemReset();
}
dap.printf("Z = %d", z);
dap.printf("Made it through cfg\r\n");
}
void ServicePack(){
dap.printf("In service pack function\r\n");
unsigned char buff[4];
unsigned char buff2[1];
int num = 0;
FILE *packet;
packet = fopen("/sd/packet.txt", "r");
while(num < 9176 ){ //55054
for(int i = 0; i<3;i++){
buff[i] = getc(packet);
}
buff2 = buff[0]+buff[1]+buff[2]+buff[3];
dap.putc(buff2);
num++;
}
fclose(packet);
gLed = 0;
}
int main()
{
dap.baud(115200);
dap.printf("Literally just starting up.\r\n");
reg_cfg();
//Config Interrupts
//RTS.rise(&flowControl);
//
rLed = 1;
bLed = 1;
gLed = 1;
CTS = 1;
dap.printf("Starting rest\r\n");
//val = RTS.read();
//dap.printf("RTS = %d\r\n\r\n", val);
/*
for(int i = 0; i < 10; i++)
{
rLed = 1;
Thread::wait(500);
rLed = 0;
val = RTS.read();
dap.printf("RTS = %i\r\n", val);
Thread::wait(500); //Something to do/see
}
dap.printf("\r\n");
rLed = 1;
*/ //Test to see RTS value. RTS is low on proper initialization.
//HCI Serial setup
hci.baud(115200);
//hci.format(8,Serial::None,1); //Explicitly define 8n1 serial
//hci.set_flow_control(Serial::RTSCTS,P0_2,P0_3); //Enable RTS,CTS flow control <--- Flow control doesn't work: causes break
//^^ I did it mysyelf. See reg_cfg. RTS control only.
//End setup
bLed = 0;
Thread::wait(250);
bLed = 1;
//Test: Output Service Pack
dap.printf("Sending Service Pack...\r\n");
ServicePack();
dap.printf("Service Pack uploaded\r\n");
//val = RTS.read();
//dap.printf("RTS = %d", val);
/* Test: Transparent Mode
* This will take data from the daplink and output
* it to the BT module and vice versa. Should allow
* use with TI HCI Tool.
*/
dap.printf("Begin Transparent Mode\r\n");
CTS = 0;
while(1) {
//If terminal data available send through hci
if(dap.readable()) {
hci.putc(dap.getc());
}
//If dap gets data send to terminal
if(hci.readable()) {
dap.putc(hci.getc());
}
}
/* Not Yet. Need service pack.
//Write
hci.putc(0x01); //Send command
hci.putc(0x09);//Command LSB, Read_BD_ADDR
hci.putc(0x10);
hci.putc(0x00);//Null parameter length
//Read
CTS = 0;
for(int n = 0; n < 32; n++){ //if there's data
buff[n]=hci.getc();
}
for(int i=0; i< sizeof(buff); i++){
dap.printf("buff[%i] = %c", i, buff[i]);
}
*/
}
<commit_msg>Update main.cpp<commit_after>#include "mbed.h"
#include "max32630fthr.h"
#include "cmsis.h" // register base address definitions
#include "pwrseq_regs.h" // power sequence register definitions
#include "rtc_regs.h" //RTC register definitions
#include "SDFileSystem.h"
MAX32630FTHR pegasus(MAX32630FTHR::VIO_3V3);
DigitalOut rLed(LED1);
DigitalOut gLed(LED2);
DigitalOut bLed(LED3);
DigitalOut CTS(P0_2);
Serial dap(P2_1, P2_0);
Serial hci(P0_0,P0_1); //BT Tx and Rx (For mcu)
SDFileSystem sd(P0_5, P0_6, P0_4, P0_7, "sd"); // mosi, miso, sclk, cs
int val;
int x = 0;
int y = 0;
int z = 0;
void reg_cfg(){ //Configure registers
dap.printf("Start\r\n");
if ((MXC_PWRSEQ->reg0 |= MXC_F_PWRSEQ_REG0_PWR_RTCEN_RUN) != MXC_PWRSEQ->reg0){ //If the register isn't set, set it
MXC_PWRSEQ->reg0 |= MXC_F_PWRSEQ_REG0_PWR_RTCEN_RUN; //Enable 32k RTC
x = 1;
}
dap.printf("x = %d\r\n", x);
//dap.printf("RTC_En = %d\r\n\r\n", RTC_En);
Thread::wait(100);
if ((MXC_PWRSEQ->reg4 |= MXC_F_PWRSEQ_REG4_PWR_PSEQ_32K_EN) != MXC_PWRSEQ->reg4){
MXC_PWRSEQ->reg4 |= MXC_F_PWRSEQ_REG4_PWR_PSEQ_32K_EN; //Output RTC to P1_7
y = 1;
}
dap.printf("y = %d\r\n",y);
//dap.printf("ClkOut_En = %d\r\n\r\n", ClkOut_En);
Thread::wait(100);
//if ((MXC_UART0->ctrl |= MXC_F_UART_CTRL_CTS_EN) != MXC_UART0->ctrl){
//Enable Hardware Output flow control
MXC_UART0->ctrl |= MXC_F_UART_CTRL_CTS_EN;
MXC_UART0->ctrl |= MXC_F_UART_CTRL_CTS_POLARITY;
//Attempts to use RTS causes runtime crash. Don't use.
MXC_UART0->ctrl ^= MXC_F_UART_CTRL_RTS_EN; //Enable Hardware Input flow control (not enabled)
MXC_UART0->ctrl ^= MXC_F_UART_CTRL_RTS_POLARITY;
MXC_IOMAN->uart0_req ^= MXC_F_IOMAN_UART0_REQ_IO_MAP; //Properly map RX & TX
MXC_IOMAN->uart0_req |= MXC_F_IOMAN_UART0_REQ_CTS_MAP; //Properly map CTS
MXC_IOMAN->uart0_req |= MXC_F_IOMAN_UART0_REQ_RTS_MAP; //Properly map RTS
z = 1;
// }
if((x == 1) | (y == 1)){
x = 2;
y = 2;
z = 2;
dap.printf("Z = %d", z);
NVIC_SystemReset();
}
dap.printf("Z = %d", z);
dap.printf("Made it through cfg\r\n");
}
/*
* Attempt to load TI Service Pack for the PAN1326b(CC2564b) from SD card,
* loading from memory causes runtime error.
* This code currently doesn't work.
*/
void ServicePack(){
dap.printf("In service pack function\r\n");
unsigned char buff[4];
unsigned char buff2[1];
int num = 0;
FILE *packet;
packet = fopen("/sd/packet.txt", "r");
while(num < 9176 ){ //55054
for(int i = 0; i<3;i++){
buff[i] = getc(packet);
}
buff2 = buff[0]+buff[1]+buff[2]+buff[3];
dap.putc(buff2);
num++;
}
fclose(packet);
gLed = 0;
}
int main()
{
dap.baud(115200);
dap.printf("Literally just starting up.\r\n");
reg_cfg();
rLed = 1;
bLed = 1;
gLed = 1;
CTS = 1;
dap.printf("Starting rest\r\n");
//HCI Serial setup
hci.baud(115200);
//hci.set_flow_control(Serial::RTSCTS,P0_2,P0_3); //Enable RTS,CTS flow control <--- Flow control doesn't work: causes break
//End setup
bLed = 0;
Thread::wait(250);
bLed = 1;
//Test: Output Service Pack
dap.printf("Sending Service Pack...\r\n");
//Currently doesn't work. Comment out to manually load service pack.
ServicePack();
dap.printf("Service Pack uploaded\r\n");
/* Test: Transparent Mode
* This will take data from the daplink and output
* it to the BT module and vice versa. Should allow
* use with TI HCI Tool.
*/
dap.printf("Begin Transparent Mode\r\n");
CTS = 0;
while(1) {
//If terminal data available send through hci
if(dap.readable()) {
hci.putc(dap.getc());
}
//If dap gets data send to terminal
if(hci.readable()) {
dap.putc(hci.getc());
}
}
}
<|endoftext|>
|
<commit_before>#pragma once
/**
* \file sal/buf_ptr.hpp
*/
#include <sal/config.hpp>
#include <sal/char_array.hpp>
#include <algorithm>
#include <array>
#include <string>
#include <vector>
__sal_begin
/**
* buf_ptr represents contiguous region of raw memory with specified size.
* Internally it is kept as pointer pair to beginning and one byte past
* end of region. Object of this class does not own pointed region. It is
* application responsibility to handle lifecycle of buf_ptr and pointed
* region.
*/
class buf_ptr
{
public:
buf_ptr () = default;
/**
* Construct buf_ptr pointing to \a region with \a size.
*/
buf_ptr (void *region, size_t size) noexcept
: begin_(static_cast<char *>(region))
, end_(begin_ + size)
{}
/**
* Return byte pointer to beginning of region.
*/
uint8_t *begin () const noexcept
{
return reinterpret_cast<uint8_t *>(begin_);
}
/**
* Return byte pointer to end of region.
*/
uint8_t *end () const noexcept
{
return reinterpret_cast<uint8_t *>(end_);
}
/**
* Return raw pointer to beginning of region.
*/
void *data () const noexcept
{
return begin_;
}
/**
* Return raw pointer to beginning of region.
*/
void *get () const noexcept
{
return begin_;
}
/**
* Return size of region
*/
size_t size () const noexcept
{
return end_ - begin_;
}
/**
* Move beginning of pointed region by \a s bytes toward end of region.
*/
buf_ptr &operator+= (size_t s) noexcept
{
begin_ += s;
if (begin_ + s > end_)
{
begin_ = end_;
}
return *this;
}
private:
char *begin_{}, * const end_{};
};
/**
* Create and return new ptr from \a p with beginning of region moved
* toward end by \a n bytes.
*/
inline buf_ptr operator+ (const buf_ptr &p, size_t n) noexcept
{
auto r = p;
r += n;
return r;
}
/**
* Create and return new ptr from \a p with beginning of region moved
* toward end by \a n bytes.
*/
inline buf_ptr operator+ (size_t n, const buf_ptr &p) noexcept
{
auto r = p;
r += n;
return r;
}
/**
* Construct buf_ptr pointing to \a region with \a size.
*/
inline buf_ptr make_buf (void *region, size_t size) noexcept
{
return buf_ptr(region, size);
}
/**
* Construct new buf_ptr as copy of \a ptr.
*/
inline buf_ptr make_buf (const buf_ptr &ptr) noexcept
{
return buf_ptr(ptr.get(), ptr.size());
}
/**
* Construct new buf_ptr as copy of \a ptr with up \a max_bytes.
*/
inline buf_ptr make_buf (const buf_ptr &ptr, size_t max_bytes) noexcept
{
return buf_ptr(ptr.get(), (std::min)(max_bytes, ptr.size()));
}
/**
* Construct buf_ptr using region owned by \a data
*/
template <size_t N>
inline buf_ptr make_buf (char_array_t<N> &data) noexcept
{
// not nice, but ok: returned area is initialized
return buf_ptr(const_cast<char *>(data.data()), data.size());
}
/**
* Construct buf_ptr using region owned by \a data.
*/
template <typename T, size_t N>
inline buf_ptr make_buf (T (&data)[N]) noexcept
{
return buf_ptr(data, N * sizeof(T));
}
/**
* Construct buf_ptr using region owned by \a data.
*/
template <typename T, size_t N>
inline buf_ptr make_buf (std::array<T, N> &data) noexcept
{
return buf_ptr(data.data(), data.size() * sizeof(T));
}
/**
* Construct buf_ptr using region owned by \a data. Returned object is
* invalidated by any vector operation that invalidates all references,
* pointers and iterators referring to the elements in the sequence.
*/
template <typename T, typename Allocator>
inline buf_ptr make_buf (std::vector<T, Allocator> &data) noexcept
{
return buf_ptr(data.data(), data.size() * sizeof(T));
}
/**
* Construct buf_ptr using region owned by \a data. Returned object is
* invalidated by any string operation that invalidates all references,
* pointers and iterators referring to the elements in the sequence.
*/
template <typename T, typename Traits, typename Allocator>
inline buf_ptr make_buf (std::basic_string<T, Traits, Allocator> &data)
noexcept
{
return buf_ptr(&data[0], data.size() * sizeof(T));
}
/**
* Construct buf_ptr using region owned by \a data but not more than
* \a max_bytes
*/
template <size_t N>
inline buf_ptr make_buf (char_array_t<N> &data, size_t max_bytes) noexcept
{
// not nice, but ok: returned area is initialized
return buf_ptr(const_cast<char *>(data.data()),
(std::min)(max_bytes, data.size())
);
}
/**
* Construct buf_ptr using region owned by \a data but not more than
* \a max_bytes.
*/
template <typename T, size_t N>
inline buf_ptr make_buf (T (&data)[N], size_t max_bytes) noexcept
{
return buf_ptr(data, (std::min)(max_bytes, N * sizeof(T)));
}
/**
* Construct buf_ptr using region owned by \a data but not more than
* \a max_bytes.
*/
template <typename T, size_t N>
inline buf_ptr make_buf (std::array<T, N> &data, size_t max_bytes) noexcept
{
return buf_ptr(data.data(), (std::min)(max_bytes, data.size() * sizeof(T)));
}
/**
* Construct buf_ptr using region owned by \a data but not more than
* \a max_bytes.
*/
template <typename T, typename Allocator>
inline buf_ptr make_buf (std::vector<T, Allocator> &data, size_t max_bytes)
noexcept
{
return buf_ptr(data.data(), (std::min)(max_bytes, data.size() * sizeof(T)));
}
/**
* Construct buf_ptr using region owned by \a data but not more than
* \a max_bytes.
*/
template <typename T, typename Traits, typename Allocator>
inline buf_ptr make_buf (std::basic_string<T, Traits, Allocator> &data,
size_t max_bytes) noexcept
{
return buf_ptr(&data[0], (std::min)(max_bytes, data.size() * sizeof(T)));
}
/**
* const_buf_ptr represents contiguous region of raw memory with specified
* size. Internally it is kept as pointer pair to beginning and one byte past
* end of region. Object of this class does not own pointed region. It is
* application responsibility to handle lifecycle of buf_ptr and pointed
* region.
*/
class const_buf_ptr
{
public:
const_buf_ptr () = default;
/**
* Construct const_buf_ptr pointing to \a region with \a size.
*/
const_buf_ptr (const void *region, size_t size) noexcept
: begin_(static_cast<const char *>(region))
, end_(begin_ + size)
{}
/**
* Return byte pointer to beginning of region.
*/
const uint8_t *begin () const noexcept
{
return reinterpret_cast<const uint8_t *>(begin_);
}
/**
* Return byte pointer to end of region.
*/
const uint8_t *end () const noexcept
{
return reinterpret_cast<const uint8_t *>(end_);
}
/**
* Return pointer to beginning of region.
*/
const void *data () const noexcept
{
return begin_;
}
/**
* Return pointer to beginning of region.
*/
const void *get () const noexcept
{
return begin_;
}
/**
* Return size of region
*/
size_t size () const noexcept
{
return end_ - begin_;
}
/**
* Move beginning of pointed region by \a s bytes toward end of region.
*/
const_buf_ptr &operator+= (size_t s) noexcept
{
begin_ += s;
if (begin_ > end_)
{
begin_ = end_;
}
return *this;
}
private:
const char *begin_{}, * const end_{};
};
/**
* Create and return new ptr from \a p with beginning of region moved
* toward end by \a n bytes.
*/
inline const_buf_ptr operator+ (const const_buf_ptr &p, size_t n) noexcept
{
auto r = p;
r += n;
return r;
}
/**
* Create and return new ptr from \a p with beginning of region moved
* toward end by \a n bytes.
*/
inline const_buf_ptr operator+ (size_t n, const const_buf_ptr &p) noexcept
{
auto r = p;
r += n;
return r;
}
/**
* Construct const_buf_ptr pointing to \a region with \a size.
*/
inline const_buf_ptr make_buf (const void *region, size_t size) noexcept
{
return const_buf_ptr(region, size);
}
/**
* Construct new const_buf_ptr as copy of \a ptr.
*/
inline const_buf_ptr make_buf (const const_buf_ptr &ptr) noexcept
{
return const_buf_ptr(ptr.get(), ptr.size());
}
/**
* Construct new const_buf_ptr as copy of \a ptr with up \a max_bytes.
*/
inline const_buf_ptr make_buf (const const_buf_ptr &ptr, size_t max_bytes)
noexcept
{
return const_buf_ptr(ptr.get(), (std::min)(max_bytes, ptr.size()));
}
/**
* Construct const_buf_ptr using region owned by \a data
*/
template <size_t N>
inline const_buf_ptr make_buf (const char_array_t<N> &data) noexcept
{
return const_buf_ptr(data.data(), data.size());
}
/**
* Construct const_buf_ptr using region owned by \a data.
*/
template <typename T, size_t N>
inline const_buf_ptr make_buf (const T (&data)[N]) noexcept
{
return const_buf_ptr(data, N * sizeof(T));
}
/**
* Construct const_buf_ptr using region owned by \a data.
*/
template <typename T, size_t N>
inline const_buf_ptr make_buf (const std::array<T, N> &data) noexcept
{
return const_buf_ptr(data.data(), data.size() * sizeof(T));
}
/**
* Construct const_buf_ptr using region owned by \a data. Returned object is
* invalidated by any vector operation that invalidates all references,
* pointers and iterators referring to the elements in the sequence.
*/
template <typename T, typename Allocator>
inline const_buf_ptr make_buf (const std::vector<T, Allocator> &data) noexcept
{
return const_buf_ptr(data.data(), data.size() * sizeof(T));
}
/**
* Construct const_buf_ptr using region owned by \a data. Returned object is
* invalidated by any string operation that invalidates all references,
* pointers and iterators referring to the elements in the sequence.
*/
template <typename T, typename Traits, typename Allocator>
inline const_buf_ptr make_buf (
const std::basic_string<T, Traits, Allocator> &data) noexcept
{
return const_buf_ptr(&data[0], data.size() * sizeof(T));
}
/**
* Construct const_buf_ptr using region owned by \a data but not more than
* \a max_bytes.
*/
template <size_t N>
inline const_buf_ptr make_buf (const char_array_t<N> &data, size_t max_bytes)
noexcept
{
return const_buf_ptr(data.data(), (std::min)(max_bytes, data.size()));
}
/**
* Construct const_buf_ptr using region owned by \a data but not more than
* \a max_bytes.
*/
template <typename T, size_t N>
inline const_buf_ptr make_buf (const T (&data)[N], size_t max_bytes) noexcept
{
return const_buf_ptr(data, (std::min)(max_bytes, N * sizeof(T)));
}
/**
* Construct const_buf_ptr using region owned by \a data but not more than
* \a max_bytes.
*/
template <typename T, size_t N>
inline const_buf_ptr make_buf (const std::array<T, N> &data, size_t max_bytes)
noexcept
{
return const_buf_ptr(data.data(),
(std::min)(max_bytes, data.size() * sizeof(T))
);
}
/**
* Construct const_buf_ptr using region owned by \a data but not more than
* \a max_bytes.
*/
template <typename T, typename Allocator>
inline const_buf_ptr make_buf (const std::vector<T, Allocator> &data,
size_t max_bytes) noexcept
{
return const_buf_ptr(data.data(),
(std::min)(max_bytes, data.size() * sizeof(T))
);
}
/**
* Construct const_buf_ptr using region owned by \a data but not more than
* \a max_bytes.
*/
template <typename T, typename Traits, typename Allocator>
inline const_buf_ptr make_buf (
const std::basic_string<T, Traits, Allocator> &data,
size_t max_bytes) noexcept
{
return const_buf_ptr(&data[0],
(std::min)(max_bytes, data.size() * sizeof(T))
);
}
__sal_end
<commit_msg>buf_ptr: drop reinterpret_cast as much as possible<commit_after>#pragma once
/**
* \file sal/buf_ptr.hpp
*/
#include <sal/config.hpp>
#include <sal/char_array.hpp>
#include <algorithm>
#include <array>
#include <string>
#include <vector>
__sal_begin
/**
* buf_ptr represents contiguous region of raw memory with specified size.
* Internally it is kept as pointer pair to beginning and one byte past
* end of region. Object of this class does not own pointed region. It is
* application responsibility to handle lifecycle of buf_ptr and pointed
* region.
*/
class buf_ptr
{
public:
buf_ptr () = default;
/**
* Construct buf_ptr pointing to \a region with \a size.
*/
buf_ptr (void *region, size_t size) noexcept
: begin_(static_cast<uint8_t *>(region))
, end_(begin_ + size)
{}
/**
* Return byte pointer to beginning of region.
*/
uint8_t *begin () const noexcept
{
return begin_;
}
/**
* Return byte pointer to end of region.
*/
uint8_t *end () const noexcept
{
return end_;
}
/**
* Return raw pointer to beginning of region.
*/
void *data () const noexcept
{
return begin_;
}
/**
* Return raw pointer to beginning of region.
*/
void *get () const noexcept
{
return begin_;
}
/**
* Return size of region
*/
size_t size () const noexcept
{
return end_ - begin_;
}
/**
* Move beginning of pointed region by \a s bytes toward end of region.
*/
buf_ptr &operator+= (size_t s) noexcept
{
begin_ += s;
if (begin_ + s > end_)
{
begin_ = end_;
}
return *this;
}
private:
uint8_t *begin_{}, * const end_{};
};
/**
* Create and return new ptr from \a p with beginning of region moved
* toward end by \a n bytes.
*/
inline buf_ptr operator+ (const buf_ptr &p, size_t n) noexcept
{
auto r = p;
r += n;
return r;
}
/**
* Create and return new ptr from \a p with beginning of region moved
* toward end by \a n bytes.
*/
inline buf_ptr operator+ (size_t n, const buf_ptr &p) noexcept
{
auto r = p;
r += n;
return r;
}
/**
* Construct buf_ptr pointing to \a region with \a size.
*/
inline buf_ptr make_buf (void *region, size_t size) noexcept
{
return buf_ptr(region, size);
}
/**
* Construct new buf_ptr as copy of \a ptr.
*/
inline buf_ptr make_buf (const buf_ptr &ptr) noexcept
{
return buf_ptr(ptr.get(), ptr.size());
}
/**
* Construct new buf_ptr as copy of \a ptr with up \a max_bytes.
*/
inline buf_ptr make_buf (const buf_ptr &ptr, size_t max_bytes) noexcept
{
return buf_ptr(ptr.get(), (std::min)(max_bytes, ptr.size()));
}
/**
* Construct buf_ptr using region owned by \a data
*/
template <size_t N>
inline buf_ptr make_buf (char_array_t<N> &data) noexcept
{
// not nice, but ok: returned pointer is initialized known size area
return buf_ptr(const_cast<char *>(data.data()), data.size());
}
/**
* Construct buf_ptr using region owned by \a data.
*/
template <typename T, size_t N>
inline buf_ptr make_buf (T (&data)[N]) noexcept
{
return buf_ptr(data, N * sizeof(T));
}
/**
* Construct buf_ptr using region owned by \a data.
*/
template <typename T, size_t N>
inline buf_ptr make_buf (std::array<T, N> &data) noexcept
{
return buf_ptr(data.data(), data.size() * sizeof(T));
}
/**
* Construct buf_ptr using region owned by \a data. Returned object is
* invalidated by any vector operation that invalidates all references,
* pointers and iterators referring to the elements in the sequence.
*/
template <typename T, typename Allocator>
inline buf_ptr make_buf (std::vector<T, Allocator> &data) noexcept
{
return buf_ptr(data.data(), data.size() * sizeof(T));
}
/**
* Construct buf_ptr using region owned by \a data. Returned object is
* invalidated by any string operation that invalidates all references,
* pointers and iterators referring to the elements in the sequence.
*/
template <typename T, typename Traits, typename Allocator>
inline buf_ptr make_buf (std::basic_string<T, Traits, Allocator> &data)
noexcept
{
return buf_ptr(&data[0], data.size() * sizeof(T));
}
/**
* Construct buf_ptr using region owned by \a data but not more than
* \a max_bytes
*/
template <size_t N>
inline buf_ptr make_buf (char_array_t<N> &data, size_t max_bytes) noexcept
{
// not nice, but ok: returned pointer is initialized known size area
return buf_ptr(const_cast<char *>(data.data()),
(std::min)(max_bytes, data.size())
);
}
/**
* Construct buf_ptr using region owned by \a data but not more than
* \a max_bytes.
*/
template <typename T, size_t N>
inline buf_ptr make_buf (T (&data)[N], size_t max_bytes) noexcept
{
return buf_ptr(data, (std::min)(max_bytes, N * sizeof(T)));
}
/**
* Construct buf_ptr using region owned by \a data but not more than
* \a max_bytes.
*/
template <typename T, size_t N>
inline buf_ptr make_buf (std::array<T, N> &data, size_t max_bytes) noexcept
{
return buf_ptr(data.data(), (std::min)(max_bytes, data.size() * sizeof(T)));
}
/**
* Construct buf_ptr using region owned by \a data but not more than
* \a max_bytes.
*/
template <typename T, typename Allocator>
inline buf_ptr make_buf (std::vector<T, Allocator> &data, size_t max_bytes)
noexcept
{
return buf_ptr(data.data(), (std::min)(max_bytes, data.size() * sizeof(T)));
}
/**
* Construct buf_ptr using region owned by \a data but not more than
* \a max_bytes.
*/
template <typename T, typename Traits, typename Allocator>
inline buf_ptr make_buf (std::basic_string<T, Traits, Allocator> &data,
size_t max_bytes) noexcept
{
return buf_ptr(&data[0], (std::min)(max_bytes, data.size() * sizeof(T)));
}
/**
* const_buf_ptr represents contiguous region of raw memory with specified
* size. Internally it is kept as pointer pair to beginning and one byte past
* end of region. Object of this class does not own pointed region. It is
* application responsibility to handle lifecycle of buf_ptr and pointed
* region.
*/
class const_buf_ptr
{
public:
const_buf_ptr () = default;
/**
* Construct const_buf_ptr pointing to \a region with \a size.
*/
const_buf_ptr (const void *region, size_t size) noexcept
: begin_(static_cast<const uint8_t *>(region))
, end_(begin_ + size)
{}
/**
* Return byte pointer to beginning of region.
*/
const uint8_t *begin () const noexcept
{
return begin_;
}
/**
* Return byte pointer to end of region.
*/
const uint8_t *end () const noexcept
{
return end_;
}
/**
* Return pointer to beginning of region.
*/
const void *data () const noexcept
{
return begin_;
}
/**
* Return pointer to beginning of region.
*/
const void *get () const noexcept
{
return begin_;
}
/**
* Return size of region
*/
size_t size () const noexcept
{
return end_ - begin_;
}
/**
* Move beginning of pointed region by \a s bytes toward end of region.
*/
const_buf_ptr &operator+= (size_t s) noexcept
{
begin_ += s;
if (begin_ > end_)
{
begin_ = end_;
}
return *this;
}
private:
const uint8_t *begin_{}, * const end_{};
};
/**
* Create and return new ptr from \a p with beginning of region moved
* toward end by \a n bytes.
*/
inline const_buf_ptr operator+ (const const_buf_ptr &p, size_t n) noexcept
{
auto r = p;
r += n;
return r;
}
/**
* Create and return new ptr from \a p with beginning of region moved
* toward end by \a n bytes.
*/
inline const_buf_ptr operator+ (size_t n, const const_buf_ptr &p) noexcept
{
auto r = p;
r += n;
return r;
}
/**
* Construct const_buf_ptr pointing to \a region with \a size.
*/
inline const_buf_ptr make_buf (const void *region, size_t size) noexcept
{
return const_buf_ptr(region, size);
}
/**
* Construct new const_buf_ptr as copy of \a ptr.
*/
inline const_buf_ptr make_buf (const const_buf_ptr &ptr) noexcept
{
return const_buf_ptr(ptr.get(), ptr.size());
}
/**
* Construct new const_buf_ptr as copy of \a ptr with up \a max_bytes.
*/
inline const_buf_ptr make_buf (const const_buf_ptr &ptr, size_t max_bytes)
noexcept
{
return const_buf_ptr(ptr.get(), (std::min)(max_bytes, ptr.size()));
}
/**
* Construct const_buf_ptr using region owned by \a data
*/
template <size_t N>
inline const_buf_ptr make_buf (const char_array_t<N> &data) noexcept
{
return const_buf_ptr(data.data(), data.size());
}
/**
* Construct const_buf_ptr using region owned by \a data.
*/
template <typename T, size_t N>
inline const_buf_ptr make_buf (const T (&data)[N]) noexcept
{
return const_buf_ptr(data, N * sizeof(T));
}
/**
* Construct const_buf_ptr using region owned by \a data.
*/
template <typename T, size_t N>
inline const_buf_ptr make_buf (const std::array<T, N> &data) noexcept
{
return const_buf_ptr(data.data(), data.size() * sizeof(T));
}
/**
* Construct const_buf_ptr using region owned by \a data. Returned object is
* invalidated by any vector operation that invalidates all references,
* pointers and iterators referring to the elements in the sequence.
*/
template <typename T, typename Allocator>
inline const_buf_ptr make_buf (const std::vector<T, Allocator> &data) noexcept
{
return const_buf_ptr(data.data(), data.size() * sizeof(T));
}
/**
* Construct const_buf_ptr using region owned by \a data. Returned object is
* invalidated by any string operation that invalidates all references,
* pointers and iterators referring to the elements in the sequence.
*/
template <typename T, typename Traits, typename Allocator>
inline const_buf_ptr make_buf (
const std::basic_string<T, Traits, Allocator> &data) noexcept
{
return const_buf_ptr(&data[0], data.size() * sizeof(T));
}
/**
* Construct const_buf_ptr using region owned by \a data but not more than
* \a max_bytes.
*/
template <size_t N>
inline const_buf_ptr make_buf (const char_array_t<N> &data, size_t max_bytes)
noexcept
{
return const_buf_ptr(data.data(), (std::min)(max_bytes, data.size()));
}
/**
* Construct const_buf_ptr using region owned by \a data but not more than
* \a max_bytes.
*/
template <typename T, size_t N>
inline const_buf_ptr make_buf (const T (&data)[N], size_t max_bytes) noexcept
{
return const_buf_ptr(data, (std::min)(max_bytes, N * sizeof(T)));
}
/**
* Construct const_buf_ptr using region owned by \a data but not more than
* \a max_bytes.
*/
template <typename T, size_t N>
inline const_buf_ptr make_buf (const std::array<T, N> &data, size_t max_bytes)
noexcept
{
return const_buf_ptr(data.data(),
(std::min)(max_bytes, data.size() * sizeof(T))
);
}
/**
* Construct const_buf_ptr using region owned by \a data but not more than
* \a max_bytes.
*/
template <typename T, typename Allocator>
inline const_buf_ptr make_buf (const std::vector<T, Allocator> &data,
size_t max_bytes) noexcept
{
return const_buf_ptr(data.data(),
(std::min)(max_bytes, data.size() * sizeof(T))
);
}
/**
* Construct const_buf_ptr using region owned by \a data but not more than
* \a max_bytes.
*/
template <typename T, typename Traits, typename Allocator>
inline const_buf_ptr make_buf (
const std::basic_string<T, Traits, Allocator> &data,
size_t max_bytes) noexcept
{
return const_buf_ptr(&data[0],
(std::min)(max_bytes, data.size() * sizeof(T))
);
}
__sal_end
<|endoftext|>
|
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
int cv::meanShift( InputArray _probImage, Rect& window, TermCriteria criteria )
{
CV_INSTRUMENT_REGION();
Size size;
int cn;
Mat mat;
UMat umat;
bool isUMat = _probImage.isUMat();
if (isUMat)
umat = _probImage.getUMat(), cn = umat.channels(), size = umat.size();
else
mat = _probImage.getMat(), cn = mat.channels(), size = mat.size();
Rect cur_rect = window;
CV_Assert( cn == 1 );
if( window.height <= 0 || window.width <= 0 )
CV_Error( Error::StsBadArg, "Input window has non-positive sizes" );
window = window & Rect(0, 0, size.width, size.height);
double eps = (criteria.type & TermCriteria::EPS) ? std::max(criteria.epsilon, 0.) : 1.;
eps = cvRound(eps*eps);
int i, niters = (criteria.type & TermCriteria::MAX_ITER) ? std::max(criteria.maxCount, 1) : 100;
for( i = 0; i < niters; i++ )
{
cur_rect = cur_rect & Rect(0, 0, size.width, size.height);
if( cur_rect == Rect() )
{
cur_rect.x = size.width/2;
cur_rect.y = size.height/2;
}
cur_rect.width = std::max(cur_rect.width, 1);
cur_rect.height = std::max(cur_rect.height, 1);
Moments m = isUMat ? moments(umat(cur_rect)) : moments(mat(cur_rect));
// Calculating center of mass
if( fabs(m.m00) < DBL_EPSILON )
break;
int dx = cvRound( m.m10/m.m00 - window.width*0.5 );
int dy = cvRound( m.m01/m.m00 - window.height*0.5 );
int nx = std::min(std::max(cur_rect.x + dx, 0), size.width - cur_rect.width);
int ny = std::min(std::max(cur_rect.y + dy, 0), size.height - cur_rect.height);
dx = nx - cur_rect.x;
dy = ny - cur_rect.y;
cur_rect.x = nx;
cur_rect.y = ny;
// Check for coverage centers mass & window
if( dx*dx + dy*dy < eps )
break;
}
window = cur_rect;
return i;
}
cv::RotatedRect cv::CamShift( InputArray _probImage, Rect& window,
TermCriteria criteria )
{
CV_INSTRUMENT_REGION();
const int TOLERANCE = 10;
Size size;
Mat mat;
UMat umat;
bool isUMat = _probImage.isUMat();
if (isUMat)
umat = _probImage.getUMat(), size = umat.size();
else
mat = _probImage.getMat(), size = mat.size();
meanShift( _probImage, window, criteria );
window.x -= TOLERANCE;
if( window.x < 0 )
window.x = 0;
window.y -= TOLERANCE;
if( window.y < 0 )
window.y = 0;
window.width += 2 * TOLERANCE;
if( window.x + window.width > size.width )
window.width = size.width - window.x;
window.height += 2 * TOLERANCE;
if( window.y + window.height > size.height )
window.height = size.height - window.y;
// Calculating moments in new center mass
Moments m = isUMat ? moments(umat(window)) : moments(mat(window));
double m00 = m.m00, m10 = m.m10, m01 = m.m01;
double mu11 = m.mu11, mu20 = m.mu20, mu02 = m.mu02;
if( fabs(m00) < DBL_EPSILON )
return RotatedRect();
double inv_m00 = 1. / m00;
int xc = cvRound( m10 * inv_m00 + window.x );
int yc = cvRound( m01 * inv_m00 + window.y );
double a = mu20 * inv_m00, b = mu11 * inv_m00, c = mu02 * inv_m00;
// Calculating width & height
double square = std::sqrt( 4 * b * b + (a - c) * (a - c) );
// Calculating orientation
double theta = atan2( 2 * b, a - c + square );
// Calculating width & length of figure
double cs = cos( theta );
double sn = sin( theta );
double rotate_a = cs * cs * mu20 + 2 * cs * sn * mu11 + sn * sn * mu02;
double rotate_c = sn * sn * mu20 - 2 * cs * sn * mu11 + cs * cs * mu02;
double length = std::sqrt( rotate_a * inv_m00 ) * 4;
double width = std::sqrt( rotate_c * inv_m00 ) * 4;
// In case, when tetta is 0 or 1.57... the Length & Width may be exchanged
if( length < width )
{
std::swap( length, width );
std::swap( cs, sn );
theta = CV_PI*0.5 - theta;
}
// Saving results
int _xc = cvRound( xc );
int _yc = cvRound( yc );
int t0 = cvRound( fabs( length * cs ));
int t1 = cvRound( fabs( width * sn ));
t0 = MAX( t0, t1 ) + 2;
window.width = MIN( t0, (size.width - _xc) * 2 );
t0 = cvRound( fabs( length * sn ));
t1 = cvRound( fabs( width * cs ));
t0 = MAX( t0, t1 ) + 2;
window.height = MIN( t0, (size.height - _yc) * 2 );
window.x = MAX( 0, _xc - window.width / 2 );
window.y = MAX( 0, _yc - window.height / 2 );
window.width = MIN( size.width - window.x, window.width );
window.height = MIN( size.height - window.y, window.height );
RotatedRect box;
box.size.height = (float)length;
box.size.width = (float)width;
box.angle = (float)((CV_PI*0.5+theta)*180./CV_PI);
while(box.angle < 0)
box.angle += 360;
while(box.angle >= 360)
box.angle -= 360;
if(box.angle >= 180)
box.angle -= 180;
box.center = Point2f( window.x + window.width*0.5f, window.y + window.height*0.5f);
return box;
}
/* End of file. */
<commit_msg> fixed bug: added threshold for variables 'rotate_a', ' rotate_c'<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
int cv::meanShift( InputArray _probImage, Rect& window, TermCriteria criteria )
{
CV_INSTRUMENT_REGION();
Size size;
int cn;
Mat mat;
UMat umat;
bool isUMat = _probImage.isUMat();
if (isUMat)
umat = _probImage.getUMat(), cn = umat.channels(), size = umat.size();
else
mat = _probImage.getMat(), cn = mat.channels(), size = mat.size();
Rect cur_rect = window;
CV_Assert( cn == 1 );
if( window.height <= 0 || window.width <= 0 )
CV_Error( Error::StsBadArg, "Input window has non-positive sizes" );
window = window & Rect(0, 0, size.width, size.height);
double eps = (criteria.type & TermCriteria::EPS) ? std::max(criteria.epsilon, 0.) : 1.;
eps = cvRound(eps*eps);
int i, niters = (criteria.type & TermCriteria::MAX_ITER) ? std::max(criteria.maxCount, 1) : 100;
for( i = 0; i < niters; i++ )
{
cur_rect = cur_rect & Rect(0, 0, size.width, size.height);
if( cur_rect == Rect() )
{
cur_rect.x = size.width/2;
cur_rect.y = size.height/2;
}
cur_rect.width = std::max(cur_rect.width, 1);
cur_rect.height = std::max(cur_rect.height, 1);
Moments m = isUMat ? moments(umat(cur_rect)) : moments(mat(cur_rect));
// Calculating center of mass
if( fabs(m.m00) < DBL_EPSILON )
break;
int dx = cvRound( m.m10/m.m00 - window.width*0.5 );
int dy = cvRound( m.m01/m.m00 - window.height*0.5 );
int nx = std::min(std::max(cur_rect.x + dx, 0), size.width - cur_rect.width);
int ny = std::min(std::max(cur_rect.y + dy, 0), size.height - cur_rect.height);
dx = nx - cur_rect.x;
dy = ny - cur_rect.y;
cur_rect.x = nx;
cur_rect.y = ny;
// Check for coverage centers mass & window
if( dx*dx + dy*dy < eps )
break;
}
window = cur_rect;
return i;
}
cv::RotatedRect cv::CamShift( InputArray _probImage, Rect& window,
TermCriteria criteria )
{
CV_INSTRUMENT_REGION();
const int TOLERANCE = 10;
Size size;
Mat mat;
UMat umat;
bool isUMat = _probImage.isUMat();
if (isUMat)
umat = _probImage.getUMat(), size = umat.size();
else
mat = _probImage.getMat(), size = mat.size();
meanShift( _probImage, window, criteria );
window.x -= TOLERANCE;
if( window.x < 0 )
window.x = 0;
window.y -= TOLERANCE;
if( window.y < 0 )
window.y = 0;
window.width += 2 * TOLERANCE;
if( window.x + window.width > size.width )
window.width = size.width - window.x;
window.height += 2 * TOLERANCE;
if( window.y + window.height > size.height )
window.height = size.height - window.y;
// Calculating moments in new center mass
Moments m = isUMat ? moments(umat(window)) : moments(mat(window));
double m00 = m.m00, m10 = m.m10, m01 = m.m01;
double mu11 = m.mu11, mu20 = m.mu20, mu02 = m.mu02;
if( fabs(m00) < DBL_EPSILON )
return RotatedRect();
double inv_m00 = 1. / m00;
int xc = cvRound( m10 * inv_m00 + window.x );
int yc = cvRound( m01 * inv_m00 + window.y );
double a = mu20 * inv_m00, b = mu11 * inv_m00, c = mu02 * inv_m00;
// Calculating width & height
double square = std::sqrt( 4 * b * b + (a - c) * (a - c) );
// Calculating orientation
double theta = atan2( 2 * b, a - c + square );
// Calculating width & length of figure
double cs = cos( theta );
double sn = sin( theta );
double rotate_a = cs * cs * mu20 + 2 * cs * sn * mu11 + sn * sn * mu02;
double rotate_c = sn * sn * mu20 - 2 * cs * sn * mu11 + cs * cs * mu02;
rotate_a = std::max(0.0, rotate_a); // avoid negative result due calculation numeric errors
rotate_c = std::max(0.0, rotate_c); // avoid negative result due calculation numeric errors
double length = std::sqrt( rotate_a * inv_m00 ) * 4;
double width = std::sqrt( rotate_c * inv_m00 ) * 4;
// In case, when tetta is 0 or 1.57... the Length & Width may be exchanged
if( length < width )
{
std::swap( length, width );
std::swap( cs, sn );
theta = CV_PI*0.5 - theta;
}
// Saving results
int _xc = cvRound( xc );
int _yc = cvRound( yc );
int t0 = cvRound( fabs( length * cs ));
int t1 = cvRound( fabs( width * sn ));
t0 = MAX( t0, t1 ) + 2;
window.width = MIN( t0, (size.width - _xc) * 2 );
t0 = cvRound( fabs( length * sn ));
t1 = cvRound( fabs( width * cs ));
t0 = MAX( t0, t1 ) + 2;
window.height = MIN( t0, (size.height - _yc) * 2 );
window.x = MAX( 0, _xc - window.width / 2 );
window.y = MAX( 0, _yc - window.height / 2 );
window.width = MIN( size.width - window.x, window.width );
window.height = MIN( size.height - window.y, window.height );
RotatedRect box;
box.size.height = (float)length;
box.size.width = (float)width;
box.angle = (float)((CV_PI*0.5+theta)*180./CV_PI);
while(box.angle < 0)
box.angle += 360;
while(box.angle >= 360)
box.angle -= 360;
if(box.angle >= 180)
box.angle -= 180;
box.center = Point2f( window.x + window.width*0.5f, window.y + window.height*0.5f);
return box;
}
/* End of file. */
<|endoftext|>
|
<commit_before>#include "kernel.h"
#include "ilwisdata.h"
#include "domain.h"
#include "range.h"
#include "datadefinition.h"
#include "columndefinition.h"
#include "connectorinterface.h"
#include "domainitem.h"
#include "basetable.h"
#include "flattable.h"
#include "tablemerger.h"
#include "itemrange.h"
#include "logicalexpressionparser.h"
#include "tableselector.h"
using namespace Ilwis;
FlatTable::FlatTable()
{
}
FlatTable::FlatTable(const Resource& resource) : BaseTable(resource){
}
FlatTable::~FlatTable()
{
_datagrid.clear();
}
bool FlatTable::createTable()
{
if(!BaseTable::createTable())
return false;
for(unsigned int i=0; i < recordCount(); ++i)
_datagrid.push_back(std::vector<QVariant>(_columnDefinitionsByIndex.size()));
return true;
}
quint32 FlatTable::newRecord()
{
if (!const_cast<FlatTable *>(this)->initLoad())
return iUNDEF;
std::vector<QVariant> values;
initRecord(values);
record(NEW_RECORD, values);
return recordCount() - 1;
}
void FlatTable::removeRecord(quint32 rec)
{
if ( rec < recordCount()){
_datagrid.erase(_datagrid.begin() + rec);
}
}
bool FlatTable::prepare()
{
return Table::prepare();
}
bool FlatTable::isValid() const
{
return Table::isValid();
}
bool FlatTable::addColumn(const QString &name, const IDomain &domain)
{
bool ok = BaseTable::addColumn(name, domain);
if(!ok)
return false;
if ( isDataLoaded()){
for(Record& row : _datagrid) {
row.addColumn();
row.changed(true);
}
initValuesColumn(name);
}
return true;
}
bool FlatTable::addColumn(const ColumnDefinition &def)
{
bool ok = BaseTable::addColumn(def);
if(!ok)
return false;
if ( isDataLoaded()) {
for(Record& row : _datagrid) {
row.addColumn();
row.changed(true);
}
initValuesColumn(def.name());
}
return true;
}
std::vector<QVariant> FlatTable::column(quint32 index, quint32 start, quint32 stop) const {
if (!const_cast<FlatTable *>(this)->initLoad())
return std::vector<QVariant>();
if ( !isColumnIndexValid(index))
return std::vector<QVariant>();
stop = std::min(stop, recordCount());
start = std::max((quint32)0, start);
std::vector<QVariant> data(stop - start);
for(quint32 i=start; i < stop; ++i) {
data[i - start] = _datagrid[i].cell(index);
}
return data;
}
std::vector<QVariant> FlatTable::column(const QString &nme, quint32 start, quint32 stop) const
{
quint32 index = columnIndex(nme);
return column(index, start, stop);
}
void FlatTable::column(quint32 index, const std::vector<QVariant> &vars, quint32 offset)
{
if (index >= columnCount()) {
ERROR2(ERR_ILLEGAL_VALUE_2,"Column index", name());
return ;
}
column( _columnDefinitionsByIndex[index].name(), vars, offset);
}
void FlatTable::column(const QString &nme, const std::vector<QVariant> &vars, quint32 offset)
{
if (!const_cast<FlatTable *>(this)->initLoad())
return ;
if ( isReadOnly())
return ;
changed(true);
quint32 index = columnIndex(nme);
if ( !isColumnIndexValid(index))
return ;
quint32 rec = offset;
_columnDefinitionsByIndex[index].changed(true);
for(const QVariant& var : vars) {
if ( rec < _datagrid.size()){
_datagrid[rec].changed(true);
_datagrid[rec++].cell(index, var);
}
else {
_datagrid.push_back(std::vector<QVariant>(_columnDefinitionsByIndex.size()));
_datagrid[rec].changed(true);
_datagrid[rec++].cell(index,checkInput(var,index));
recordCount(_datagrid.size());
}
}
}
const Record& FlatTable::record(quint32 rec) const{
if (!const_cast<FlatTable *>(this)->initLoad())
throw ErrorObject(QString(TR("failed load of table %1")).arg(name()));
if ( rec < recordCount() && _datagrid.size() != 0) {
return _datagrid[rec];
}
throw ErrorObject(QString("Requested record number is not in the table").arg(rec));
}
Record& FlatTable::recordRef(quint32 rec)
{
if (!const_cast<FlatTable *>(this)->initLoad())
throw ErrorObject(QString(TR("failed load of table %1")).arg(name()));
if ( rec < recordCount() && _datagrid.size() != 0) {
return _datagrid[rec];
}
throw ErrorObject(QString("Requested record number is not in the table").arg(rec));
}
void FlatTable::record(quint32 rec, const std::vector<QVariant>& vars, quint32 offset)
{
if (!const_cast<FlatTable *>(this)->initLoad())
return ;
if ( isReadOnly())
return ;
changed(true);
if ( rec >=recordCount() ) {
_datagrid.push_back(std::vector<QVariant>(_columnDefinitionsByIndex.size()));
_datagrid.back().changed(true);
recordCount(_datagrid.size());
rec = recordCount() - 1;
}
quint32 col = offset;
int cols = std::min((quint32)vars.size() - offset, columnCount());
for(const QVariant& var : vars) {
if ( col < cols){
_datagrid[rec].changed(true);
_datagrid[rec].cell(col, checkInput(var, col));
++col;
}
}
}
QVariant FlatTable::cell(const QString& col, quint32 rec, bool asRaw) const {
if (!const_cast<FlatTable *>(this)->initLoad())
return QVariant();
quint32 index = columnIndex(col);
return cell(index , rec, asRaw);
}
QVariant FlatTable::cell(const quint32 index, quint32 rec, bool asRaw) const
{
if (!const_cast<FlatTable *>(this)->initLoad())
return QVariant();
if ( !isColumnIndexValid(index))
return QVariant();
if ( rec < recordCount()) {
QVariant var = _datagrid[rec].cell(index);
if ( !asRaw) {
ColumnDefinition coldef = columndefinition(index);
return coldef.datadef().domain<>()->impliedValue(var);
}
return var;
}
kernel()->issues()->log(TR(ERR_INVALID_RECORD_SIZE_IN).arg(name()),IssueObject::itWarning);
return QVariant();
}
void FlatTable::setCell(quint32 index, quint32 rec, const QVariant& var){
if (!const_cast<FlatTable *>(this)->initLoad())
return ;
if ( !isColumnIndexValid(index))
return;
if ( isReadOnly())
return ;
changed(true);
_columnDefinitionsByIndex[index].changed(true);
if ( rec >= recordCount()) {
newRecord();
}
_datagrid[rec].cell(index, checkInput(var, index));
_datagrid[rec].changed(true);
}
void FlatTable::setCell(const QString &col, quint32 rec, const QVariant &var)
{
if (!const_cast<FlatTable *>(this)->initLoad())
return ;
if ( isReadOnly())
return ;
changed(true);
quint32 index = columnIndex(col);
setCell(index, rec, var);
}
IlwisTypes FlatTable::ilwisType() const
{
return itFLATTABLE;
}
IlwisObject *FlatTable::clone()
{
if (initLoad()){
FlatTable *tbl = new FlatTable();
copyTo(tbl);
tbl->_datagrid = _datagrid;
for(auto& record : tbl->_datagrid){
record.changed(false);
}
return tbl;
}
return 0;
}
void FlatTable::copyTo(IlwisObject *obj){
BaseTable::copyTo(obj);
}
std::vector<quint32> FlatTable::select(const QString &conditions) const
{
return TableSelector::select(this, conditions);
}
bool FlatTable::initLoad(){
if ( isDataLoaded())
return true;
bool ok = BaseTable::initLoad();
for(int i=0; ok && i < columnCount() && _datagrid.size() > 0; ++i){
QVariant var = cell(i,0);
if ( !var.isValid()) {
initValuesColumn(columndefinition(i).name());
}
}
return ok;
}
<commit_msg>replaced recordCount() with datagrid.size()<commit_after>#include "kernel.h"
#include "ilwisdata.h"
#include "domain.h"
#include "range.h"
#include "datadefinition.h"
#include "columndefinition.h"
#include "connectorinterface.h"
#include "domainitem.h"
#include "basetable.h"
#include "flattable.h"
#include "tablemerger.h"
#include "itemrange.h"
#include "logicalexpressionparser.h"
#include "tableselector.h"
using namespace Ilwis;
FlatTable::FlatTable()
{
}
FlatTable::FlatTable(const Resource& resource) : BaseTable(resource){
}
FlatTable::~FlatTable()
{
_datagrid.clear();
}
bool FlatTable::createTable()
{
if(!BaseTable::createTable())
return false;
for(unsigned int i=0; i < recordCount(); ++i)
_datagrid.push_back(std::vector<QVariant>(_columnDefinitionsByIndex.size()));
return true;
}
quint32 FlatTable::newRecord()
{
if (!const_cast<FlatTable *>(this)->initLoad())
return iUNDEF;
std::vector<QVariant> values;
initRecord(values);
record(NEW_RECORD, values);
return recordCount() - 1;
}
void FlatTable::removeRecord(quint32 rec)
{
if ( rec < recordCount()){
_datagrid.erase(_datagrid.begin() + rec);
}
}
bool FlatTable::prepare()
{
return Table::prepare();
}
bool FlatTable::isValid() const
{
return Table::isValid();
}
bool FlatTable::addColumn(const QString &name, const IDomain &domain)
{
bool ok = BaseTable::addColumn(name, domain);
if(!ok)
return false;
if ( isDataLoaded()){
for(Record& row : _datagrid) {
row.addColumn();
row.changed(true);
}
initValuesColumn(name);
}
return true;
}
bool FlatTable::addColumn(const ColumnDefinition &def)
{
bool ok = BaseTable::addColumn(def);
if(!ok)
return false;
if ( isDataLoaded()) {
for(Record& row : _datagrid) {
row.addColumn();
row.changed(true);
}
initValuesColumn(def.name());
}
return true;
}
std::vector<QVariant> FlatTable::column(quint32 index, quint32 start, quint32 stop) const {
if (!const_cast<FlatTable *>(this)->initLoad())
return std::vector<QVariant>();
if ( !isColumnIndexValid(index))
return std::vector<QVariant>();
stop = std::min(stop, recordCount());
start = std::max((quint32)0, start);
std::vector<QVariant> data(stop - start);
for(quint32 i=start; i < stop; ++i) {
data[i - start] = _datagrid[i].cell(index);
}
return data;
}
std::vector<QVariant> FlatTable::column(const QString &nme, quint32 start, quint32 stop) const
{
quint32 index = columnIndex(nme);
return column(index, start, stop);
}
void FlatTable::column(quint32 index, const std::vector<QVariant> &vars, quint32 offset)
{
if (index >= columnCount()) {
ERROR2(ERR_ILLEGAL_VALUE_2,"Column index", name());
return ;
}
column( _columnDefinitionsByIndex[index].name(), vars, offset);
}
void FlatTable::column(const QString &nme, const std::vector<QVariant> &vars, quint32 offset)
{
if (!const_cast<FlatTable *>(this)->initLoad())
return ;
if ( isReadOnly())
return ;
changed(true);
quint32 index = columnIndex(nme);
if ( !isColumnIndexValid(index))
return ;
quint32 rec = offset;
_columnDefinitionsByIndex[index].changed(true);
for(const QVariant& var : vars) {
if ( rec < _datagrid.size()){
_datagrid[rec].changed(true);
_datagrid[rec++].cell(index, var);
}
else {
_datagrid.push_back(std::vector<QVariant>(_columnDefinitionsByIndex.size()));
_datagrid[rec].changed(true);
_datagrid[rec++].cell(index,checkInput(var,index));
recordCount(_datagrid.size());
}
}
}
const Record& FlatTable::record(quint32 rec) const{
if (!const_cast<FlatTable *>(this)->initLoad())
throw ErrorObject(QString(TR("failed load of table %1")).arg(name()));
if ( rec < recordCount() && _datagrid.size() != 0) {
return _datagrid[rec];
}
throw ErrorObject(QString("Requested record number is not in the table").arg(rec));
}
Record& FlatTable::recordRef(quint32 rec)
{
if (!const_cast<FlatTable *>(this)->initLoad())
throw ErrorObject(QString(TR("failed load of table %1")).arg(name()));
if ( rec < recordCount() && _datagrid.size() != 0) {
return _datagrid[rec];
}
throw ErrorObject(QString("Requested record number is not in the table").arg(rec));
}
void FlatTable::record(quint32 rec, const std::vector<QVariant>& vars, quint32 offset)
{
if (!const_cast<FlatTable *>(this)->initLoad())
return ;
if ( isReadOnly())
return ;
changed(true);
if ( rec >= _datagrid.size() ) {
_datagrid.push_back(std::vector<QVariant>(_columnDefinitionsByIndex.size()));
_datagrid.back().changed(true);
recordCount(_datagrid.size());
rec = recordCount() - 1;
}
quint32 col = offset;
int cols = std::min((quint32)vars.size() - offset, columnCount());
for(const QVariant& var : vars) {
if ( col < cols){
_datagrid[rec].changed(true);
_datagrid[rec].cell(col, checkInput(var, col));
++col;
}
}
}
QVariant FlatTable::cell(const QString& col, quint32 rec, bool asRaw) const {
if (!const_cast<FlatTable *>(this)->initLoad())
return QVariant();
quint32 index = columnIndex(col);
return cell(index , rec, asRaw);
}
QVariant FlatTable::cell(const quint32 index, quint32 rec, bool asRaw) const
{
if (!const_cast<FlatTable *>(this)->initLoad())
return QVariant();
if ( !isColumnIndexValid(index))
return QVariant();
if ( rec < recordCount()) {
QVariant var = _datagrid[rec].cell(index);
if ( !asRaw) {
ColumnDefinition coldef = columndefinition(index);
return coldef.datadef().domain<>()->impliedValue(var);
}
return var;
}
kernel()->issues()->log(TR(ERR_INVALID_RECORD_SIZE_IN).arg(name()),IssueObject::itWarning);
return QVariant();
}
void FlatTable::setCell(quint32 index, quint32 rec, const QVariant& var){
if (!const_cast<FlatTable *>(this)->initLoad())
return ;
if ( !isColumnIndexValid(index))
return;
if ( isReadOnly())
return ;
changed(true);
_columnDefinitionsByIndex[index].changed(true);
if ( rec >= recordCount()) {
newRecord();
}
_datagrid[rec].cell(index, checkInput(var, index));
_datagrid[rec].changed(true);
}
void FlatTable::setCell(const QString &col, quint32 rec, const QVariant &var)
{
if (!const_cast<FlatTable *>(this)->initLoad())
return ;
if ( isReadOnly())
return ;
changed(true);
quint32 index = columnIndex(col);
setCell(index, rec, var);
}
IlwisTypes FlatTable::ilwisType() const
{
return itFLATTABLE;
}
IlwisObject *FlatTable::clone()
{
if (initLoad()){
FlatTable *tbl = new FlatTable();
copyTo(tbl);
tbl->_datagrid = _datagrid;
for(auto& record : tbl->_datagrid){
record.changed(false);
}
return tbl;
}
return 0;
}
void FlatTable::copyTo(IlwisObject *obj){
BaseTable::copyTo(obj);
}
std::vector<quint32> FlatTable::select(const QString &conditions) const
{
return TableSelector::select(this, conditions);
}
bool FlatTable::initLoad(){
if ( isDataLoaded())
return true;
bool ok = BaseTable::initLoad();
for(int i=0; ok && i < columnCount() && _datagrid.size() > 0; ++i){
QVariant var = cell(i,0);
if ( !var.isValid()) {
initValuesColumn(columndefinition(i).name());
}
}
return ok;
}
<|endoftext|>
|
<commit_before>// Copyright (C) 2019-2020 European Spallation Source, see LICENSE file
//===----------------------------------------------------------------------===//
///
/// \file
///
/// \brief Digital geometry for SUMO (Sub-Modules) - implementation
///
//===----------------------------------------------------------------------===//
#include <jalousie/SumoMappings.h>
#include <fmt/format.h>
#include <jalousie/rapidcsv.h>
namespace Jalousie {
bool SumoCoordinates::is_valid() const {
return ((wire_layer != kInvalidCoord) &&
(wire != kInvalidCoord) &&
(strip != kInvalidCoord));
}
std::string SumoCoordinates::debug() const {
if (!is_valid())
return "INV";
return fmt::format("(wl{},w{},s{})", wire_layer, wire, strip);
}
SumoCoordinates min(const SumoCoordinates &a,
const SumoCoordinates &b) {
SumoCoordinates ret;
ret.wire_layer = std::min(a.wire_layer, b.wire_layer);
ret.wire = std::min(a.wire, b.wire);
ret.strip = std::min(a.strip, b.strip);
return ret;
}
SumoCoordinates max(const SumoCoordinates &a,
const SumoCoordinates &b) {
SumoCoordinates ret;
ret.wire_layer = std::max(a.wire_layer, b.wire_layer);
ret.wire = std::max(a.wire, b.wire);
ret.strip = std::max(a.strip, b.strip);
return ret;
}
SumoMappings::SumoMappings(std::string file_name, uint8_t sumo_id) {
rapidcsv::Document doc(file_name,
rapidcsv::LabelParams(0, -1),
rapidcsv::SeparatorParams(';'));
std::vector<int> line;
SumoCoordinates coord;
int anode;
int cathode;
for (size_t i = 0; i < doc.GetRowCount(); ++i) {
line = doc.GetRow<int>(i);
int sumo_type = line[0];
if (sumo_type != sumo_id)
continue;
coord.wire_layer = line[1];
coord.wire = line[2];
coord.strip = line[3];
anode = line[4];
cathode = line[5];
add_mapping(anode, cathode, coord);
}
}
void SumoMappings::add_mapping(uint8_t anode, uint8_t cathode, SumoCoordinates coord) {
if (!coord.is_valid())
return;
/// Initialize or update max coordinate
if (table_.empty()) {
min_ = coord;
max_ = coord;
}
min_ = Jalousie::min(min_, coord);
max_ = Jalousie::max(max_, coord);
/// Resize table on demand
if (table_.size() <= anode)
table_.resize(anode + 1);
auto &anode_line = table_[anode];
if (anode_line.size() <= cathode)
anode_line.resize(cathode + 1);
/// Finally, assign
anode_line[cathode] = coord;
}
SumoCoordinates SumoMappings::map(uint8_t anode, uint8_t cathode) const {
if (table_.size() <= anode)
return {};
const auto &anode_line = table_[anode];
if (anode_line.size() <= cathode)
return {};
return anode_line[cathode];
}
SumoCoordinates SumoMappings::min() const {
return min_;
}
SumoCoordinates SumoMappings::max() const {
return max_;
}
std::string SumoMappings::debug(bool depict_domain) const {
std::string ret;
ret += " --> [" + min_.debug() + " - " + max_.debug();
if (!depict_domain)
return ret;
ret += "\n";
for (size_t anode = 0; anode < table_.size(); ++anode) {
const auto &anode_line = table_[anode];
ret += fmt::format("{:<5}", anode);
for (size_t cathode = 0; cathode < anode_line.size(); ++cathode) {
ret += anode_line[cathode].is_valid() ? "@" : "-";
}
ret += "\n";
}
return ret;
}
}
<commit_msg>small corrections to doxygen headers<commit_after>// Copyright (C) 2019-2020 European Spallation Source, see LICENSE file
//===----------------------------------------------------------------------===//
///
/// \file
///
/// \brief Digital geometry for SUMO (SUper-MOdules) - implementation
///
//===----------------------------------------------------------------------===//
#include <jalousie/SumoMappings.h>
#include <fmt/format.h>
#include <jalousie/rapidcsv.h>
namespace Jalousie {
bool SumoCoordinates::is_valid() const {
return ((wire_layer != kInvalidCoord) &&
(wire != kInvalidCoord) &&
(strip != kInvalidCoord));
}
std::string SumoCoordinates::debug() const {
if (!is_valid())
return "INV";
return fmt::format("(wl{},w{},s{})", wire_layer, wire, strip);
}
SumoCoordinates min(const SumoCoordinates &a,
const SumoCoordinates &b) {
SumoCoordinates ret;
ret.wire_layer = std::min(a.wire_layer, b.wire_layer);
ret.wire = std::min(a.wire, b.wire);
ret.strip = std::min(a.strip, b.strip);
return ret;
}
SumoCoordinates max(const SumoCoordinates &a,
const SumoCoordinates &b) {
SumoCoordinates ret;
ret.wire_layer = std::max(a.wire_layer, b.wire_layer);
ret.wire = std::max(a.wire, b.wire);
ret.strip = std::max(a.strip, b.strip);
return ret;
}
SumoMappings::SumoMappings(std::string file_name, uint8_t sumo_id) {
rapidcsv::Document doc(file_name,
rapidcsv::LabelParams(0, -1),
rapidcsv::SeparatorParams(';'));
std::vector<int> line;
SumoCoordinates coord;
int anode;
int cathode;
for (size_t i = 0; i < doc.GetRowCount(); ++i) {
line = doc.GetRow<int>(i);
int sumo_type = line[0];
if (sumo_type != sumo_id)
continue;
coord.wire_layer = line[1];
coord.wire = line[2];
coord.strip = line[3];
anode = line[4];
cathode = line[5];
add_mapping(anode, cathode, coord);
}
}
void SumoMappings::add_mapping(uint8_t anode, uint8_t cathode, SumoCoordinates coord) {
if (!coord.is_valid())
return;
/// Initialize or update max coordinate
if (table_.empty()) {
min_ = coord;
max_ = coord;
}
min_ = Jalousie::min(min_, coord);
max_ = Jalousie::max(max_, coord);
/// Resize table on demand
if (table_.size() <= anode)
table_.resize(anode + 1);
auto &anode_line = table_[anode];
if (anode_line.size() <= cathode)
anode_line.resize(cathode + 1);
/// Finally, assign
anode_line[cathode] = coord;
}
SumoCoordinates SumoMappings::map(uint8_t anode, uint8_t cathode) const {
if (table_.size() <= anode)
return {};
const auto &anode_line = table_[anode];
if (anode_line.size() <= cathode)
return {};
return anode_line[cathode];
}
SumoCoordinates SumoMappings::min() const {
return min_;
}
SumoCoordinates SumoMappings::max() const {
return max_;
}
std::string SumoMappings::debug(bool depict_domain) const {
std::string ret;
ret += " --> [" + min_.debug() + " - " + max_.debug();
if (!depict_domain)
return ret;
ret += "\n";
for (size_t anode = 0; anode < table_.size(); ++anode) {
const auto &anode_line = table_[anode];
ret += fmt::format("{:<5}", anode);
for (size_t cathode = 0; cathode < anode_line.size(); ++cathode) {
ret += anode_line[cathode].is_valid() ? "@" : "-";
}
ret += "\n";
}
return ret;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 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 "base/command_line.h"
#if defined(OS_WIN)
#include <windows.h>
#include <shellapi.h>
#elif defined(OS_POSIX)
#include <limits.h>
#include <stdlib.h>
#include <unistd.h>
#endif
#if defined(OS_LINUX)
#include <sys/prctl.h>
#endif
#include <algorithm>
#include "base/file_path.h"
#include "base/logging.h"
#include "base/singleton.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#if defined(OS_LINUX)
// Linux/glibc doesn't natively have setproctitle().
#include "base/setproctitle_linux.h"
#endif
CommandLine* CommandLine::current_process_commandline_ = NULL;
// Since we use a lazy match, make sure that longer versions (like L"--")
// are listed before shorter versions (like L"-") of similar prefixes.
#if defined(OS_WIN)
const wchar_t* const kSwitchPrefixes[] = {L"--", L"-", L"/"};
const wchar_t kSwitchTerminator[] = L"--";
const wchar_t kSwitchValueSeparator[] = L"=";
#elif defined(OS_POSIX)
// Unixes don't use slash as a switch.
const char* const kSwitchPrefixes[] = {"--", "-"};
const char kSwitchTerminator[] = "--";
const char kSwitchValueSeparator[] = "=";
#endif
#if defined(OS_WIN)
// Lowercase a string. This is used to lowercase switch names.
// Is this what we really want? It seems crazy to me. I've left it in
// for backwards compatibility on Windows.
static void Lowercase(std::string* parameter) {
transform(parameter->begin(), parameter->end(), parameter->begin(),
tolower);
}
#endif
#if defined(OS_WIN)
CommandLine::CommandLine(ArgumentsOnly args_only) {
}
void CommandLine::ParseFromString(const std::wstring& command_line) {
TrimWhitespace(command_line, TRIM_ALL, &command_line_string_);
if (command_line_string_.empty())
return;
int num_args = 0;
wchar_t** args = NULL;
args = CommandLineToArgvW(command_line_string_.c_str(), &num_args);
// Populate program_ with the trimmed version of the first arg.
TrimWhitespace(args[0], TRIM_ALL, &program_);
bool parse_switches = true;
for (int i = 1; i < num_args; ++i) {
std::wstring arg;
TrimWhitespace(args[i], TRIM_ALL, &arg);
if (!parse_switches) {
loose_values_.push_back(arg);
continue;
}
if (arg == kSwitchTerminator) {
parse_switches = false;
continue;
}
std::string switch_string;
std::wstring switch_value;
if (IsSwitch(arg, &switch_string, &switch_value)) {
switches_[switch_string] = switch_value;
} else {
loose_values_.push_back(arg);
}
}
if (args)
LocalFree(args);
}
CommandLine::CommandLine(const FilePath& program) {
if (!program.empty()) {
program_ = program.value();
command_line_string_ = L'"' + program.value() + L'"';
}
}
#elif defined(OS_POSIX)
CommandLine::CommandLine(ArgumentsOnly args_only) {
// Push an empty argument, because we always assume argv_[0] is a program.
argv_.push_back("");
}
void CommandLine::InitFromArgv(int argc, const char* const* argv) {
for (int i = 0; i < argc; ++i)
argv_.push_back(argv[i]);
InitFromArgv(argv_);
}
void CommandLine::InitFromArgv(const std::vector<std::string>& argv) {
argv_ = argv;
bool parse_switches = true;
for (size_t i = 1; i < argv_.size(); ++i) {
const std::string& arg = argv_[i];
if (!parse_switches) {
loose_values_.push_back(arg);
continue;
}
if (arg == kSwitchTerminator) {
parse_switches = false;
continue;
}
std::string switch_string;
std::string switch_value;
if (IsSwitch(arg, &switch_string, &switch_value)) {
switches_[switch_string] = switch_value;
} else {
loose_values_.push_back(arg);
}
}
}
CommandLine::CommandLine(const FilePath& program) {
argv_.push_back(program.value());
}
#endif
// static
bool CommandLine::IsSwitch(const StringType& parameter_string,
std::string* switch_string,
StringType* switch_value) {
switch_string->clear();
switch_value->clear();
for (size_t i = 0; i < arraysize(kSwitchPrefixes); ++i) {
StringType prefix(kSwitchPrefixes[i]);
if (parameter_string.find(prefix) != 0)
continue;
const size_t switch_start = prefix.length();
const size_t equals_position = parameter_string.find(
kSwitchValueSeparator, switch_start);
StringType switch_native;
if (equals_position == StringType::npos) {
switch_native = parameter_string.substr(switch_start);
} else {
switch_native = parameter_string.substr(
switch_start, equals_position - switch_start);
*switch_value = parameter_string.substr(equals_position + 1);
}
#if defined(OS_WIN)
*switch_string = WideToASCII(switch_native);
Lowercase(switch_string);
#else
*switch_string = switch_native;
#endif
return true;
}
return false;
}
// static
void CommandLine::Init(int argc, const char* const* argv) {
delete current_process_commandline_;
current_process_commandline_ = new CommandLine;
#if defined(OS_WIN)
current_process_commandline_->ParseFromString(::GetCommandLineW());
#elif defined(OS_POSIX)
current_process_commandline_->InitFromArgv(argc, argv);
#endif
#if defined(OS_LINUX)
if (argv)
setproctitle_init(const_cast<char**>(argv));
#endif
}
#if defined(OS_POSIX) && !defined(OS_MACOSX)
// static
void CommandLine::SetProcTitle() {
// Build a single string which consists of all the arguments separated
// by spaces. We can't actually keep them separate due to the way the
// setproctitle() function works.
std::string title;
bool have_argv0 = false;
#if defined(OS_LINUX)
// In Linux we sometimes exec ourselves from /proc/self/exe, but this makes us
// show up as "exe" in process listings. Read the symlink /proc/self/exe and
// use the path it points at for our process title. Note that this is only for
// display purposes and has no TOCTTOU security implications.
char buffer[PATH_MAX];
// Note: readlink() does not append a null byte to terminate the string.
ssize_t length = readlink("/proc/self/exe", buffer, sizeof(buffer));
DCHECK(length <= static_cast<ssize_t>(sizeof(buffer)));
if (length > 0) {
have_argv0 = true;
title.assign(buffer, length);
// If the binary has since been deleted, Linux appends " (deleted)" to the
// symlink target. Remove it, since this is not really part of our name.
const std::string kDeletedSuffix = " (deleted)";
if (EndsWith(title, kDeletedSuffix, true))
title.resize(title.size() - kDeletedSuffix.size());
#if defined(PR_SET_NAME)
// If PR_SET_NAME is available at compile time, we try using it. We ignore
// any errors if the kernel does not support it at runtime though. When
// available, this lets us set the short process name that shows when the
// full command line is not being displayed in most process listings.
prctl(PR_SET_NAME, FilePath(title).BaseName().value().c_str());
#endif
}
#endif
for (size_t i = 1; i < current_process_commandline_->argv_.size(); ++i) {
if (!title.empty())
title += " ";
title += current_process_commandline_->argv_[i];
}
// Disable prepending argv[0] with '-' if we prepended it ourselves above.
setproctitle(have_argv0 ? "-%s" : "%s", title.c_str());
}
#endif
void CommandLine::Reset() {
DCHECK(current_process_commandline_ != NULL);
delete current_process_commandline_;
current_process_commandline_ = NULL;
}
bool CommandLine::HasSwitch(const std::string& switch_string) const {
std::string lowercased_switch(switch_string);
#if defined(OS_WIN)
Lowercase(&lowercased_switch);
#endif
return switches_.find(lowercased_switch) != switches_.end();
}
std::wstring CommandLine::GetSwitchValue(
const std::string& switch_string) const {
std::string lowercased_switch(switch_string);
#if defined(OS_WIN)
Lowercase(&lowercased_switch);
#endif
std::map<std::string, StringType>::const_iterator result =
switches_.find(lowercased_switch);
if (result == switches_.end()) {
return L"";
} else {
#if defined(OS_WIN)
return result->second;
#else
return base::SysNativeMBToWide(result->second);
#endif
}
}
#if defined(OS_WIN)
std::vector<std::wstring> CommandLine::GetLooseValues() const {
return loose_values_;
}
std::wstring CommandLine::program() const {
return program_;
}
#else
std::vector<std::wstring> CommandLine::GetLooseValues() const {
std::vector<std::wstring> values;
for (size_t i = 0; i < loose_values_.size(); ++i)
values.push_back(base::SysNativeMBToWide(loose_values_[i]));
return values;
}
std::wstring CommandLine::program() const {
DCHECK_GT(argv_.size(), 0U);
return base::SysNativeMBToWide(argv_[0]);
}
#endif
// static
std::wstring CommandLine::PrefixedSwitchString(
const std::string& switch_string) {
#if defined(OS_WIN)
return kSwitchPrefixes[0] + ASCIIToWide(switch_string);
#else
return ASCIIToWide(kSwitchPrefixes[0] + switch_string);
#endif
}
// static
std::wstring CommandLine::PrefixedSwitchStringWithValue(
const std::string& switch_string, const std::wstring& value_string) {
if (value_string.empty()) {
return PrefixedSwitchString(switch_string);
}
return PrefixedSwitchString(switch_string +
#if defined(OS_WIN)
WideToASCII(kSwitchValueSeparator)
#else
kSwitchValueSeparator
#endif
) + value_string;
}
#if defined(OS_WIN)
void CommandLine::AppendSwitch(const std::string& switch_string) {
std::wstring prefixed_switch_string = PrefixedSwitchString(switch_string);
command_line_string_.append(L" ");
command_line_string_.append(prefixed_switch_string);
switches_[switch_string] = L"";
}
void CommandLine::AppendSwitchWithValue(const std::string& switch_string,
const std::wstring& value_string) {
std::wstring value_string_edit;
// NOTE(jhughes): If the value contains a quotation mark at one
// end but not both, you may get unusable output.
if (!value_string.empty() &&
(value_string.find(L" ") != std::wstring::npos) &&
(value_string[0] != L'"') &&
(value_string[value_string.length() - 1] != L'"')) {
// need to provide quotes
value_string_edit = StringPrintf(L"\"%ls\"", value_string.c_str());
} else {
value_string_edit = value_string;
}
std::wstring combined_switch_string =
PrefixedSwitchStringWithValue(switch_string, value_string_edit);
command_line_string_.append(L" ");
command_line_string_.append(combined_switch_string);
switches_[switch_string] = value_string;
}
void CommandLine::AppendLooseValue(const std::wstring& value) {
// TODO(evan): quoting?
command_line_string_.append(L" ");
command_line_string_.append(value);
loose_values_.push_back(value);
}
void CommandLine::AppendArguments(const CommandLine& other,
bool include_program) {
// Verify include_program is used correctly.
// Logic could be shorter but this is clearer.
DCHECK(include_program ? !other.program().empty() : other.program().empty());
command_line_string_ += L" " + other.command_line_string_;
std::map<std::string, StringType>::const_iterator i;
for (i = other.switches_.begin(); i != other.switches_.end(); ++i)
switches_[i->first] = i->second;
}
void CommandLine::PrependWrapper(const std::wstring& wrapper) {
// The wrapper may have embedded arguments (like "gdb --args"). In this case,
// we don't pretend to do anything fancy, we just split on spaces.
std::vector<std::wstring> wrapper_and_args;
SplitString(wrapper, ' ', &wrapper_and_args);
program_ = wrapper_and_args[0];
command_line_string_ = wrapper + L" " + command_line_string_;
}
#elif defined(OS_POSIX)
void CommandLine::AppendSwitch(const std::string& switch_string) {
argv_.push_back(kSwitchPrefixes[0] + switch_string);
switches_[switch_string] = "";
}
void CommandLine::AppendSwitchWithValue(const std::string& switch_string,
const std::wstring& value_string) {
std::string mb_value = base::SysWideToNativeMB(value_string);
argv_.push_back(kSwitchPrefixes[0] + switch_string +
kSwitchValueSeparator + mb_value);
switches_[switch_string] = mb_value;
}
void CommandLine::AppendLooseValue(const std::wstring& value) {
argv_.push_back(base::SysWideToNativeMB(value));
}
void CommandLine::AppendArguments(const CommandLine& other,
bool include_program) {
// Verify include_program is used correctly.
// Logic could be shorter but this is clearer.
DCHECK(include_program ? !other.program().empty() : other.program().empty());
size_t first_arg = include_program ? 0 : 1;
for (size_t i = first_arg; i < other.argv_.size(); ++i)
argv_.push_back(other.argv_[i]);
std::map<std::string, StringType>::const_iterator i;
for (i = other.switches_.begin(); i != other.switches_.end(); ++i)
switches_[i->first] = i->second;
}
void CommandLine::PrependWrapper(const std::wstring& wrapper_wide) {
// The wrapper may have embedded arguments (like "gdb --args"). In this case,
// we don't pretend to do anything fancy, we just split on spaces.
const std::string wrapper = base::SysWideToNativeMB(wrapper_wide);
std::vector<std::string> wrapper_and_args;
SplitString(wrapper, ' ', &wrapper_and_args);
argv_.insert(argv_.begin(), wrapper_and_args.begin(), wrapper_and_args.end());
}
#endif
<commit_msg>Cleanup: Replace deprecated CommandLine::program() with CommandLine::GetProgram(). Simplify a couple DCHECKs with DCHECK_EQ.<commit_after>// Copyright (c) 2010 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 "base/command_line.h"
#if defined(OS_WIN)
#include <windows.h>
#include <shellapi.h>
#elif defined(OS_POSIX)
#include <limits.h>
#include <stdlib.h>
#include <unistd.h>
#endif
#if defined(OS_LINUX)
#include <sys/prctl.h>
#endif
#include <algorithm>
#include "base/file_path.h"
#include "base/logging.h"
#include "base/singleton.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#if defined(OS_LINUX)
// Linux/glibc doesn't natively have setproctitle().
#include "base/setproctitle_linux.h"
#endif
CommandLine* CommandLine::current_process_commandline_ = NULL;
// Since we use a lazy match, make sure that longer versions (like L"--")
// are listed before shorter versions (like L"-") of similar prefixes.
#if defined(OS_WIN)
const wchar_t* const kSwitchPrefixes[] = {L"--", L"-", L"/"};
const wchar_t kSwitchTerminator[] = L"--";
const wchar_t kSwitchValueSeparator[] = L"=";
#elif defined(OS_POSIX)
// Unixes don't use slash as a switch.
const char* const kSwitchPrefixes[] = {"--", "-"};
const char kSwitchTerminator[] = "--";
const char kSwitchValueSeparator[] = "=";
#endif
#if defined(OS_WIN)
// Lowercase a string. This is used to lowercase switch names.
// Is this what we really want? It seems crazy to me. I've left it in
// for backwards compatibility on Windows.
static void Lowercase(std::string* parameter) {
transform(parameter->begin(), parameter->end(), parameter->begin(),
tolower);
}
#endif
#if defined(OS_WIN)
CommandLine::CommandLine(ArgumentsOnly args_only) {
}
void CommandLine::ParseFromString(const std::wstring& command_line) {
TrimWhitespace(command_line, TRIM_ALL, &command_line_string_);
if (command_line_string_.empty())
return;
int num_args = 0;
wchar_t** args = NULL;
args = CommandLineToArgvW(command_line_string_.c_str(), &num_args);
// Populate program_ with the trimmed version of the first arg.
TrimWhitespace(args[0], TRIM_ALL, &program_);
bool parse_switches = true;
for (int i = 1; i < num_args; ++i) {
std::wstring arg;
TrimWhitespace(args[i], TRIM_ALL, &arg);
if (!parse_switches) {
loose_values_.push_back(arg);
continue;
}
if (arg == kSwitchTerminator) {
parse_switches = false;
continue;
}
std::string switch_string;
std::wstring switch_value;
if (IsSwitch(arg, &switch_string, &switch_value)) {
switches_[switch_string] = switch_value;
} else {
loose_values_.push_back(arg);
}
}
if (args)
LocalFree(args);
}
CommandLine::CommandLine(const FilePath& program) {
if (!program.empty()) {
program_ = program.value();
command_line_string_ = L'"' + program.value() + L'"';
}
}
#elif defined(OS_POSIX)
CommandLine::CommandLine(ArgumentsOnly args_only) {
// Push an empty argument, because we always assume argv_[0] is a program.
argv_.push_back("");
}
void CommandLine::InitFromArgv(int argc, const char* const* argv) {
for (int i = 0; i < argc; ++i)
argv_.push_back(argv[i]);
InitFromArgv(argv_);
}
void CommandLine::InitFromArgv(const std::vector<std::string>& argv) {
argv_ = argv;
bool parse_switches = true;
for (size_t i = 1; i < argv_.size(); ++i) {
const std::string& arg = argv_[i];
if (!parse_switches) {
loose_values_.push_back(arg);
continue;
}
if (arg == kSwitchTerminator) {
parse_switches = false;
continue;
}
std::string switch_string;
std::string switch_value;
if (IsSwitch(arg, &switch_string, &switch_value)) {
switches_[switch_string] = switch_value;
} else {
loose_values_.push_back(arg);
}
}
}
CommandLine::CommandLine(const FilePath& program) {
argv_.push_back(program.value());
}
#endif
// static
bool CommandLine::IsSwitch(const StringType& parameter_string,
std::string* switch_string,
StringType* switch_value) {
switch_string->clear();
switch_value->clear();
for (size_t i = 0; i < arraysize(kSwitchPrefixes); ++i) {
StringType prefix(kSwitchPrefixes[i]);
if (parameter_string.find(prefix) != 0)
continue;
const size_t switch_start = prefix.length();
const size_t equals_position = parameter_string.find(
kSwitchValueSeparator, switch_start);
StringType switch_native;
if (equals_position == StringType::npos) {
switch_native = parameter_string.substr(switch_start);
} else {
switch_native = parameter_string.substr(
switch_start, equals_position - switch_start);
*switch_value = parameter_string.substr(equals_position + 1);
}
#if defined(OS_WIN)
*switch_string = WideToASCII(switch_native);
Lowercase(switch_string);
#else
*switch_string = switch_native;
#endif
return true;
}
return false;
}
// static
void CommandLine::Init(int argc, const char* const* argv) {
delete current_process_commandline_;
current_process_commandline_ = new CommandLine;
#if defined(OS_WIN)
current_process_commandline_->ParseFromString(::GetCommandLineW());
#elif defined(OS_POSIX)
current_process_commandline_->InitFromArgv(argc, argv);
#endif
#if defined(OS_LINUX)
if (argv)
setproctitle_init(const_cast<char**>(argv));
#endif
}
#if defined(OS_POSIX) && !defined(OS_MACOSX)
// static
void CommandLine::SetProcTitle() {
// Build a single string which consists of all the arguments separated
// by spaces. We can't actually keep them separate due to the way the
// setproctitle() function works.
std::string title;
bool have_argv0 = false;
#if defined(OS_LINUX)
// In Linux we sometimes exec ourselves from /proc/self/exe, but this makes us
// show up as "exe" in process listings. Read the symlink /proc/self/exe and
// use the path it points at for our process title. Note that this is only for
// display purposes and has no TOCTTOU security implications.
char buffer[PATH_MAX];
// Note: readlink() does not append a null byte to terminate the string.
ssize_t length = readlink("/proc/self/exe", buffer, sizeof(buffer));
DCHECK(length <= static_cast<ssize_t>(sizeof(buffer)));
if (length > 0) {
have_argv0 = true;
title.assign(buffer, length);
// If the binary has since been deleted, Linux appends " (deleted)" to the
// symlink target. Remove it, since this is not really part of our name.
const std::string kDeletedSuffix = " (deleted)";
if (EndsWith(title, kDeletedSuffix, true))
title.resize(title.size() - kDeletedSuffix.size());
#if defined(PR_SET_NAME)
// If PR_SET_NAME is available at compile time, we try using it. We ignore
// any errors if the kernel does not support it at runtime though. When
// available, this lets us set the short process name that shows when the
// full command line is not being displayed in most process listings.
prctl(PR_SET_NAME, FilePath(title).BaseName().value().c_str());
#endif
}
#endif
for (size_t i = 1; i < current_process_commandline_->argv_.size(); ++i) {
if (!title.empty())
title += " ";
title += current_process_commandline_->argv_[i];
}
// Disable prepending argv[0] with '-' if we prepended it ourselves above.
setproctitle(have_argv0 ? "-%s" : "%s", title.c_str());
}
#endif
void CommandLine::Reset() {
DCHECK(current_process_commandline_ != NULL);
delete current_process_commandline_;
current_process_commandline_ = NULL;
}
bool CommandLine::HasSwitch(const std::string& switch_string) const {
std::string lowercased_switch(switch_string);
#if defined(OS_WIN)
Lowercase(&lowercased_switch);
#endif
return switches_.find(lowercased_switch) != switches_.end();
}
std::wstring CommandLine::GetSwitchValue(
const std::string& switch_string) const {
std::string lowercased_switch(switch_string);
#if defined(OS_WIN)
Lowercase(&lowercased_switch);
#endif
std::map<std::string, StringType>::const_iterator result =
switches_.find(lowercased_switch);
if (result == switches_.end()) {
return L"";
} else {
#if defined(OS_WIN)
return result->second;
#else
return base::SysNativeMBToWide(result->second);
#endif
}
}
#if defined(OS_WIN)
std::vector<std::wstring> CommandLine::GetLooseValues() const {
return loose_values_;
}
std::wstring CommandLine::program() const {
return program_;
}
#else
std::vector<std::wstring> CommandLine::GetLooseValues() const {
std::vector<std::wstring> values;
for (size_t i = 0; i < loose_values_.size(); ++i)
values.push_back(base::SysNativeMBToWide(loose_values_[i]));
return values;
}
std::wstring CommandLine::program() const {
DCHECK_GT(argv_.size(), 0U);
return base::SysNativeMBToWide(argv_[0]);
}
#endif
// static
std::wstring CommandLine::PrefixedSwitchString(
const std::string& switch_string) {
#if defined(OS_WIN)
return kSwitchPrefixes[0] + ASCIIToWide(switch_string);
#else
return ASCIIToWide(kSwitchPrefixes[0] + switch_string);
#endif
}
// static
std::wstring CommandLine::PrefixedSwitchStringWithValue(
const std::string& switch_string, const std::wstring& value_string) {
if (value_string.empty()) {
return PrefixedSwitchString(switch_string);
}
return PrefixedSwitchString(switch_string +
#if defined(OS_WIN)
WideToASCII(kSwitchValueSeparator)
#else
kSwitchValueSeparator
#endif
) + value_string;
}
#if defined(OS_WIN)
void CommandLine::AppendSwitch(const std::string& switch_string) {
std::wstring prefixed_switch_string = PrefixedSwitchString(switch_string);
command_line_string_.append(L" ");
command_line_string_.append(prefixed_switch_string);
switches_[switch_string] = L"";
}
void CommandLine::AppendSwitchWithValue(const std::string& switch_string,
const std::wstring& value_string) {
std::wstring value_string_edit;
// NOTE(jhughes): If the value contains a quotation mark at one
// end but not both, you may get unusable output.
if (!value_string.empty() &&
(value_string.find(L" ") != std::wstring::npos) &&
(value_string[0] != L'"') &&
(value_string[value_string.length() - 1] != L'"')) {
// need to provide quotes
value_string_edit = StringPrintf(L"\"%ls\"", value_string.c_str());
} else {
value_string_edit = value_string;
}
std::wstring combined_switch_string =
PrefixedSwitchStringWithValue(switch_string, value_string_edit);
command_line_string_.append(L" ");
command_line_string_.append(combined_switch_string);
switches_[switch_string] = value_string;
}
void CommandLine::AppendLooseValue(const std::wstring& value) {
// TODO(evan): quoting?
command_line_string_.append(L" ");
command_line_string_.append(value);
loose_values_.push_back(value);
}
void CommandLine::AppendArguments(const CommandLine& other,
bool include_program) {
// Verify include_program is used correctly.
// Logic could be shorter but this is clearer.
DCHECK_EQ(include_program, !other.GetProgram().empty());
command_line_string_ += L" " + other.command_line_string_;
std::map<std::string, StringType>::const_iterator i;
for (i = other.switches_.begin(); i != other.switches_.end(); ++i)
switches_[i->first] = i->second;
}
void CommandLine::PrependWrapper(const std::wstring& wrapper) {
// The wrapper may have embedded arguments (like "gdb --args"). In this case,
// we don't pretend to do anything fancy, we just split on spaces.
std::vector<std::wstring> wrapper_and_args;
SplitString(wrapper, ' ', &wrapper_and_args);
program_ = wrapper_and_args[0];
command_line_string_ = wrapper + L" " + command_line_string_;
}
#elif defined(OS_POSIX)
void CommandLine::AppendSwitch(const std::string& switch_string) {
argv_.push_back(kSwitchPrefixes[0] + switch_string);
switches_[switch_string] = "";
}
void CommandLine::AppendSwitchWithValue(const std::string& switch_string,
const std::wstring& value_string) {
std::string mb_value = base::SysWideToNativeMB(value_string);
argv_.push_back(kSwitchPrefixes[0] + switch_string +
kSwitchValueSeparator + mb_value);
switches_[switch_string] = mb_value;
}
void CommandLine::AppendLooseValue(const std::wstring& value) {
argv_.push_back(base::SysWideToNativeMB(value));
}
void CommandLine::AppendArguments(const CommandLine& other,
bool include_program) {
// Verify include_program is used correctly.
// Logic could be shorter but this is clearer.
DCHECK_EQ(include_program, !other.GetProgram().empty());
size_t first_arg = include_program ? 0 : 1;
for (size_t i = first_arg; i < other.argv_.size(); ++i)
argv_.push_back(other.argv_[i]);
std::map<std::string, StringType>::const_iterator i;
for (i = other.switches_.begin(); i != other.switches_.end(); ++i)
switches_[i->first] = i->second;
}
void CommandLine::PrependWrapper(const std::wstring& wrapper_wide) {
// The wrapper may have embedded arguments (like "gdb --args"). In this case,
// we don't pretend to do anything fancy, we just split on spaces.
const std::string wrapper = base::SysWideToNativeMB(wrapper_wide);
std::vector<std::string> wrapper_and_args;
SplitString(wrapper, ' ', &wrapper_and_args);
argv_.insert(argv_.begin(), wrapper_and_args.begin(), wrapper_and_args.end());
}
#endif
<|endoftext|>
|
<commit_before><commit_msg>Revert 35907 - Fixes CommandLine::AppendLooseValue() to append the parameter to the loose_values_ vector.<commit_after><|endoftext|>
|
<commit_before>/*VRP*********************************************************************
*
* vehicle routing problems
* A collection of C++ classes for developing VRP solutions
* and specific solutions developed using these classes.
*
* Copyright 2014 Stephen Woodbridge <woodbri@imaptools.com>
* Copyright 2014 Vicky Vergara <vicky_vergara@hotmail.com>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the MIT License. Please file LICENSE for details.
*
********************************************************************VRP*/
#include <iostream>
#include "move.h"
/*! \fn bool Move::operator==(const Move &rhs) const
* \brief Compare two moves and report if they are equal
*/
bool Move::operator==(const Move &rhs) const {
return nid1==rhs.nid1 and nid2==rhs.nid2 and
vid1==rhs.vid1 and vid2==rhs.vid2 and
pos1==rhs.pos1 and pos2==rhs.pos2;
}
/*! \fn bool Move::less(const Move& m) const
* \brief Compare two moves and report if move \< rhs.move
*
* This less than comparision operator is used by the TabuList map function
* for ordering the moves in the container.
*/
bool Move::less(const Move& m) const {
return nid1<m.nid1 or ( nid1==m.nid1 and
( nid2<m.nid2 or ( nid2==m.nid2 and
( vid1<m.vid1 or ( vid1==m.vid1 and
( pos1<m.pos1 or ( pos1==m.pos1 and pos2<m.pos2 )))))));
}
/*! \fn bool Move::isForbidden(const Move &tabu) const
* \brief Check if a given move is forbidden based on the TabuList
*
* The isForbidden() test is not associative ( ie: A.equiv(B) != B.equiv(A) ).
* This test is used to determine if A would be tabu if B is on the tabu list
*
* - prohibition rules for Ins
* - Rule PR5 - move removing any order from tabu.vid2.
* This rule basically says if we remove a node from vid2
* then we are not allowed to add a node back to vid2 until
* the tabu length expires.
* This rule is to promote the elimiation of vehicles
*
* - prohibition rules for IntraSw
* - This rules says that if we have swapped either the source
* or the destination nodes that they can not be moved again
* until the tabu length expires.
*
* - prohibition rules for InterSw
* - This rules says that if we have swapped either the source
* or the destination nodes that they can not be moved again
* until the tabu length expires.
*/
bool Move::isForbidden(const Move &tabu) const {
if (*this == tabu) return true;
if (mtype == Ins) {
if (vid1 == tabu.vid2) return true;
}
else if (mtype == IntraSw) {
if (nid1==tabu.nid1 or nid2==tabu.nid2 or
nid1==tabu.nid2 or nid2==tabu.nid1 ) return true;
}
else {
if (nid1==tabu.nid1 or nid2==tabu.nid2 or
nid1==tabu.nid2 or nid2==tabu.nid1 ) return true;
}
return false;
}
/*! \fn void Move::dump() const
* \brief Print the move.
*/
void Move::dump() const {
std::cout << "Move: " << mtype
<< ",\t" << nid1
<< ",\t" << nid2
<< ",\t" << vid1
<< ",\t" << vid2
<< ",\t" << pos1
<< ",\t" << pos2
<< ",\t" << savings
<< std::endl;
}
void Move::Dump() const {
switch (mtype){
case Ins:
std::cout << "Move: INS"
<< "\t NodeID:" << nid1
<< "\tFrom Truck:" << vid1
<< "\t From Pos:" << pos1
<< "\t To Truck:" << vid2
<< "\t To Pos:" << pos2
<< "\t savings:" << savings
<< std::endl;
break;
case IntraSw:
std::cout << "Move: IntraSw"
<< "\t NodeID:" << nid1
<< "\t At Truck:" << vid1
<< "\t From Pos:" << pos1
<< "\t To Pos:" << pos2
<< "\t savings:" << savings
<< std::endl;
break;
case InterSw:
std::cout << "Move: InterSw"
<< "\t NodeID:" << nid1
<< "\t (at Truck:" << vid1
<< "\t at Pos:" << pos1
<< ")\t with NodeID:" << nid2
<< "\t (at Truck:" << vid2
<< "\t at Pos:" << pos2
<< ")\t savings:" << savings
<< std::endl;
break;
}
}
<commit_msg>Fix a nasty bug in Move::isForbidden where from and to trucks were reversed.<commit_after>/*VRP*********************************************************************
*
* vehicle routing problems
* A collection of C++ classes for developing VRP solutions
* and specific solutions developed using these classes.
*
* Copyright 2014 Stephen Woodbridge <woodbri@imaptools.com>
* Copyright 2014 Vicky Vergara <vicky_vergara@hotmail.com>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the MIT License. Please file LICENSE for details.
*
********************************************************************VRP*/
#include <iostream>
#include "move.h"
/*! \fn bool Move::operator==(const Move &rhs) const
* \brief Compare two moves and report if they are equal
*/
bool Move::operator==(const Move &rhs) const {
return nid1==rhs.nid1 and nid2==rhs.nid2 and
vid1==rhs.vid1 and vid2==rhs.vid2 and
pos1==rhs.pos1 and pos2==rhs.pos2;
}
/*! \fn bool Move::less(const Move& m) const
* \brief Compare two moves and report if move \< rhs.move
*
* This less than comparision operator is used by the TabuList map function
* for ordering the moves in the container.
*/
bool Move::less(const Move& m) const {
return nid1<m.nid1 or ( nid1==m.nid1 and
( nid2<m.nid2 or ( nid2==m.nid2 and
( vid1<m.vid1 or ( vid1==m.vid1 and
( pos1<m.pos1 or ( pos1==m.pos1 and pos2<m.pos2 )))))));
}
/*! \fn bool Move::isForbidden(const Move &tabu) const
* \brief Check if a given move is forbidden based on the TabuList
*
* The isForbidden() test is not associative ( ie: A.equiv(B) != B.equiv(A) ).
* This test is used to determine if A would be tabu if B is on the tabu list
*
* - prohibition rules for Ins
* - Rule PR5 - move removing any order from tabu.vid1.
* This rule basically says if we remove a node from vid1
* then we are not allowed to add a node back to vid1 until
* the tabu length expires.
* This rule is to promote the elimiation of vehicles
*
* - prohibition rules for IntraSw
* - This rules says that if we have swapped either the source
* or the destination nodes that they can not be moved again
* until the tabu length expires.
*
* - prohibition rules for InterSw
* - This rules says that if we have swapped either the source
* or the destination nodes that they can not be moved again
* until the tabu length expires.
*/
bool Move::isForbidden(const Move &tabu) const {
if (*this == tabu) return true;
if (mtype == Ins) {
if (vid2 == tabu.vid1) return true;
}
else if (mtype == IntraSw) {
if (nid1==tabu.nid1 or nid2==tabu.nid2 or
nid1==tabu.nid2 or nid2==tabu.nid1 ) return true;
}
else {
if (nid1==tabu.nid1 or nid2==tabu.nid2 or
nid1==tabu.nid2 or nid2==tabu.nid1 ) return true;
}
return false;
}
/*! \fn void Move::dump() const
* \brief Print the move.
*/
void Move::dump() const {
std::cout << "Move: " << mtype
<< ",\t" << nid1
<< ",\t" << nid2
<< ",\t" << vid1
<< ",\t" << vid2
<< ",\t" << pos1
<< ",\t" << pos2
<< ",\t" << savings
<< std::endl;
}
void Move::Dump() const {
switch (mtype){
case Ins:
std::cout << "Move: INS"
<< "\t NodeID:" << nid1
<< "\tFrom Truck:" << vid1
<< "\t From Pos:" << pos1
<< "\t To Truck:" << vid2
<< "\t To Pos:" << pos2
<< "\t savings:" << savings
<< std::endl;
break;
case IntraSw:
std::cout << "Move: IntraSw"
<< "\t NodeID:" << nid1
<< "\t At Truck:" << vid1
<< "\t From Pos:" << pos1
<< "\t To Pos:" << pos2
<< "\t savings:" << savings
<< std::endl;
break;
case InterSw:
std::cout << "Move: InterSw"
<< "\t NodeID:" << nid1
<< "\t (at Truck:" << vid1
<< "\t at Pos:" << pos1
<< ")\t with NodeID:" << nid2
<< "\t (at Truck:" << vid2
<< "\t at Pos:" << pos2
<< ")\t savings:" << savings
<< std::endl;
break;
}
}
<|endoftext|>
|
<commit_before>#include "DynamicData.hpp"
#include "ProcessObject.hpp"
namespace fast {
DynamicData::~DynamicData() {
delete fillCount;
delete emptyCount;
#if defined(__APPLE__) || defined(__MACOSX)
std::string name = "FAST_fill_count_" + boost::lexical_cast<std::string>(mSemaphoreNumber);
boost::interprocess::named_semaphore::remove(name.c_str());
name = "FAST_empty_count_" + boost::lexical_cast<std::string>(mSemaphoreNumber);
boost::interprocess::named_semaphore::remove(name.c_str());
#endif
}
void DynamicData::setMaximumNumberOfFrames(uint nrOfFrames) {
mMaximumNrOfFrames = nrOfFrames;
if(mFrames2.size() > 0)
throw Exception("Must call setMaximumNumberOfFrames before streaming is started");
if(mMaximumNrOfFrames > 0) {
delete fillCount;
delete emptyCount;
// Use named semaphore if Mac
#if defined(__APPLE__) || defined(__MACOSX)
std::string name = "FAST_fill_count_" + boost::lexical_cast<std::string>(mSemaphoreNumber);
boost::interprocess::named_semaphore::remove(name.c_str());
std::string name2 = "FAST_empty_count_" + boost::lexical_cast<std::string>(mSemaphoreNumber);
boost::interprocess::named_semaphore::remove(name2.c_str());
fillCount = new boost::interprocess::named_semaphore(boost::interprocess::create_only, name.c_str(), 0);
emptyCount = new boost::interprocess::named_semaphore(boost::interprocess::create_only, name2.c_str(), nrOfFrames);
#else
fillCount = new boost::interprocess::interprocess_semaphore(0);
emptyCount = new boost::interprocess::interprocess_semaphore(nrOfFrames);
#endif
}
}
uint DynamicData::getLowestFrameCount() const {
if(mConsumerFrameCounters.size() == 0)
return 0;
boost::unordered_map<WeakPointer<Object>, uint>::const_iterator it;
uint lowestFrameCount = std::numeric_limits<uint>::max();
for(it = mConsumerFrameCounters.begin(); it != mConsumerFrameCounters.end(); it++) {
if(it->second < lowestFrameCount) {
lowestFrameCount = it->second;
}
}
return lowestFrameCount;
}
void DynamicData::removeOldFrames(uint frameCounter) {
// TODO this could be implemented in a faster way
typename boost::unordered_map<uint, DataObject::pointer>::iterator it = mFrames2.begin();
while(it != mFrames2.end()) {
if(it->first < frameCounter) {
it = mFrames2.erase(it);
} else {
it++;
}
}
}
void DynamicData::registerConsumer(Object::pointer processObject) {
registerConsumer(WeakPointer<Object>(processObject));
}
void DynamicData::registerConsumer(WeakPointer<Object> processObject) {
Streamer::pointer streamer = getStreamer();
mStreamMutex.lock();
if(mConsumerFrameCounters.count(processObject) == 0) {
if(streamer->getStreamingMode() == STREAMING_MODE_NEWEST_FRAME_ONLY) {
mConsumerFrameCounters[processObject] = mCurrentFrameCounter;
} else if(streamer->getStreamingMode() == STREAMING_MODE_STORE_ALL_FRAMES) {
mConsumerFrameCounters[processObject] = 0;
} else {
mConsumerFrameCounters[processObject] = getLowestFrameCount();
}
}
mStreamMutex.unlock();
}
DataObject::pointer DynamicData::getNextFrame(Object::pointer processObject) {
return getNextFrame(WeakPointer<Object>(processObject));
}
void DynamicData::setAllConsumersUpToDate() {
unsigned long timestamp = getTimestamp();
boost::unordered_map<WeakPointer<Object>, uint>::iterator it;
for(it = mConsumerFrameCounters.begin(); it != mConsumerFrameCounters.end(); it++) {
ProcessObject::pointer consumer = ProcessObject::pointer(it->first.lock());
consumer->updateTimestamp(mPtr.lock());
}
}
DataObject::pointer DynamicData::getNextFrame(WeakPointer<Object> processObject) {
Streamer::pointer streamer = getStreamer();
if(!streamer.isValid()) {
// If streamer has been deleted, return the current frame instead
throw Exception("Streamer has been deleted, but someone has called getNextFrame");
//return getCurrentFrame();
}
// Producer consumer model
if(mMaximumNrOfFrames > 0 && streamer->getStreamingMode() == STREAMING_MODE_PROCESS_ALL_FRAMES) {
bool frameShouldBeRemoved = true;
if(mConsumerFrameCounters.count(processObject) > 0) {
uint thisFrameCounter = mConsumerFrameCounters[processObject]; // Current consumer frame counter
// If any other frame counters are less or equal, we do not want to remove frame
boost::unordered_map<WeakPointer<Object>, uint>::const_iterator it;
for(it = mConsumerFrameCounters.begin(); it != mConsumerFrameCounters.end(); it++) {
if(it->second <= thisFrameCounter) {
frameShouldBeRemoved = false;
break;
}
}
}
if(frameShouldBeRemoved)
fillCount->wait(); // decrement
}
mStreamMutex.lock();
if(streamer->getStreamingMode() == STREAMING_MODE_NEWEST_FRAME_ONLY) {
// Always return last frame
if(mCurrentFrameCounter == 0) {
mStreamMutex.unlock();
throw Exception("Trying to get next frame, when no frame has ever been given to dynamic data.");
}
DataObject::pointer returnData = mCurrentFrame2;
mStreamMutex.unlock();
return mCurrentFrame2;
}
// If process object is not registered, register it
if(mConsumerFrameCounters.count(processObject) == 0) {
if(streamer->getStreamingMode() == STREAMING_MODE_NEWEST_FRAME_ONLY) {
mConsumerFrameCounters[processObject] = mCurrentFrameCounter;
} else if(streamer->getStreamingMode() == STREAMING_MODE_STORE_ALL_FRAMES) {
mConsumerFrameCounters[processObject] = 0;
} else {
uint lowestFrameCount = getLowestFrameCount(); // This must be assigned to a variable first to ensure correct result!
mConsumerFrameCounters[processObject] = lowestFrameCount;
}
}
// Return frame
DataObject::pointer returnData;
if(mFrames2.count(mConsumerFrameCounters[processObject]) > 0) {
returnData = mFrames2[mConsumerFrameCounters[processObject]];
} else {
mStreamMutex.unlock();
throw Exception("Frame in dynamic data was not found");
}
// Increment
mConsumerFrameCounters[processObject] = mConsumerFrameCounters[processObject]+1;
// If PROCESS_ALL and this has smallest frame counter, remove old frame
if(streamer->getStreamingMode() == STREAMING_MODE_PROCESS_ALL_FRAMES) {
removeOldFrames(getLowestFrameCount());
if(mFrames2.size() > 0) { // Update timestamp if there are more frames available
updateModifiedTimestamp();
} else {
// All frames are gone, make sure timestamps that all POs have are up to date
setAllConsumersUpToDate();
}
} else if(streamer->getStreamingMode() == STREAMING_MODE_NEWEST_FRAME_ONLY) {
// With newest frame only, always remove?
//mFrames2.erase(removeFrame);
} else {
// Update timestamp if there are more frames available
if(mConsumerFrameCounters[processObject] < mFrames2.size()) {
updateModifiedTimestamp();
}
}
mStreamMutex.unlock();
// Producer consumer
if(mMaximumNrOfFrames > 0 && streamer->getStreamingMode() == STREAMING_MODE_PROCESS_ALL_FRAMES) {
emptyCount->post(); // increment
}
return returnData;
}
DataObject::pointer DynamicData::getCurrentFrame() {
Streamer::pointer streamer = getStreamer();
mStreamMutex.lock();
/*
if(mFrames.size() == 0 || mFrames.size() <= mCurrentFrame) {
if(!streamer.isValid()) {
mStreamMutex.unlock();
throw Exception("Streamer does not exist (anymore), stop.");
} else {
if(streamer->hasReachedEnd()) {
mStreamMutex.unlock();
throw Exception("Streamer has reached the end.");
} else {
mStreamMutex.unlock();
throw Exception("This exception should not have occured. ");
}
}
}
*/
DataObject::pointer ret = mCurrentFrame2;
mStreamMutex.unlock();
return ret;
}
void DynamicData::addFrame(DataObject::pointer frame) {
Streamer::pointer streamer = getStreamer();
if(!streamer.isValid()) {
//throw Exception("A DynamicImage must have a streamer set before it can be used.");
return;
}
if(mMaximumNrOfFrames > 0) {
if(streamer->getStreamingMode() == STREAMING_MODE_PROCESS_ALL_FRAMES) {
// Producer consumer model using semaphores
emptyCount->wait(); // decrement
//down(mutex);
} else if(streamer->getStreamingMode() == STREAMING_MODE_STORE_ALL_FRAMES) {
if(mFrames2.size() >= mMaximumNrOfFrames)
throw NoMoreFramesException("Maximum number of frames reached. You can change the this number using the setMaximumNumberOfFrames method on the streamer/dynamic data objects.");
}
}
mStreamMutex.lock();
updateModifiedTimestamp();
if(getStreamer()->getStreamingMode() == STREAMING_MODE_NEWEST_FRAME_ONLY) {
mFrames2.clear();
}
mFrames2[mCurrentFrameCounter] = frame;
mCurrentFrame2 = frame;
mCurrentFrameCounter++;
mStreamMutex.unlock();
if(mMaximumNrOfFrames > 0 && streamer->getStreamingMode() == STREAMING_MODE_PROCESS_ALL_FRAMES) {
fillCount->post(); // increment
}
}
DynamicData::DynamicData() {
mCurrentFrameCounter = 0;
mMaximumNrOfFrames = 0;
mIsDynamicData = true;
mHasReachedEnd = false;
fillCount = NULL;
emptyCount = NULL;
updateModifiedTimestamp();
#if defined(__APPLE__) || defined(__MACOSX)
static uint namedSemaphoresCount = 0;
mSemaphoreNumber = namedSemaphoresCount;
namedSemaphoresCount++;
#endif
}
unsigned int DynamicData::getSize() const {
return mFrames2.size();
}
bool DynamicData::hasReachedEnd() {
Streamer::pointer streamer = getStreamer();
if(!streamer.isValid()) {
throw Exception("A DynamicData must have a streamer set before it can be used.");
}
mStreamMutex.lock();
// Check if has reached end can be changed to true
if(!mHasReachedEnd) {
// TODO the checks for NEWEST_FRAME AND PROCESS_ALL are not necessarily correct, for a pipeline with several steps
switch(streamer->getStreamingMode()) {
case STREAMING_MODE_NEWEST_FRAME_ONLY:
// Should get frame nr of last to see if we have read the last
if(streamer->hasReachedEnd())
mHasReachedEnd = true;
break;
case STREAMING_MODE_PROCESS_ALL_FRAMES:
if(streamer->hasReachedEnd() && mFrames2.size() == 0)
mHasReachedEnd = true;
break;
case STREAMING_MODE_STORE_ALL_FRAMES:
if(streamer->hasReachedEnd() && streamer->getNrOfFrames() == getLowestFrameCount())
mHasReachedEnd = true;
break;
}
}
mStreamMutex.unlock();
return mHasReachedEnd;
}
}
<commit_msg>fixed a bug in dynamic data getnextframe<commit_after>#include "DynamicData.hpp"
#include "ProcessObject.hpp"
namespace fast {
DynamicData::~DynamicData() {
delete fillCount;
delete emptyCount;
#if defined(__APPLE__) || defined(__MACOSX)
std::string name = "FAST_fill_count_" + boost::lexical_cast<std::string>(mSemaphoreNumber);
boost::interprocess::named_semaphore::remove(name.c_str());
name = "FAST_empty_count_" + boost::lexical_cast<std::string>(mSemaphoreNumber);
boost::interprocess::named_semaphore::remove(name.c_str());
#endif
}
void DynamicData::setMaximumNumberOfFrames(uint nrOfFrames) {
mMaximumNrOfFrames = nrOfFrames;
if(mFrames2.size() > 0)
throw Exception("Must call setMaximumNumberOfFrames before streaming is started");
if(mMaximumNrOfFrames > 0) {
delete fillCount;
delete emptyCount;
// Use named semaphore if Mac
#if defined(__APPLE__) || defined(__MACOSX)
std::string name = "FAST_fill_count_" + boost::lexical_cast<std::string>(mSemaphoreNumber);
boost::interprocess::named_semaphore::remove(name.c_str());
std::string name2 = "FAST_empty_count_" + boost::lexical_cast<std::string>(mSemaphoreNumber);
boost::interprocess::named_semaphore::remove(name2.c_str());
fillCount = new boost::interprocess::named_semaphore(boost::interprocess::create_only, name.c_str(), 0);
emptyCount = new boost::interprocess::named_semaphore(boost::interprocess::create_only, name2.c_str(), nrOfFrames);
#else
fillCount = new boost::interprocess::interprocess_semaphore(0);
emptyCount = new boost::interprocess::interprocess_semaphore(nrOfFrames);
#endif
}
}
uint DynamicData::getLowestFrameCount() const {
if(mConsumerFrameCounters.size() == 0)
return 0;
boost::unordered_map<WeakPointer<Object>, uint>::const_iterator it;
uint lowestFrameCount = std::numeric_limits<uint>::max();
for(it = mConsumerFrameCounters.begin(); it != mConsumerFrameCounters.end(); it++) {
if(it->second < lowestFrameCount) {
lowestFrameCount = it->second;
}
}
return lowestFrameCount;
}
void DynamicData::removeOldFrames(uint frameCounter) {
// TODO this could be implemented in a faster way
typename boost::unordered_map<uint, DataObject::pointer>::iterator it = mFrames2.begin();
while(it != mFrames2.end()) {
if(it->first < frameCounter) {
it = mFrames2.erase(it);
} else {
it++;
}
}
}
void DynamicData::registerConsumer(Object::pointer processObject) {
registerConsumer(WeakPointer<Object>(processObject));
}
void DynamicData::registerConsumer(WeakPointer<Object> processObject) {
Streamer::pointer streamer = getStreamer();
mStreamMutex.lock();
if(mConsumerFrameCounters.count(processObject) == 0) {
if(streamer->getStreamingMode() == STREAMING_MODE_NEWEST_FRAME_ONLY) {
mConsumerFrameCounters[processObject] = mCurrentFrameCounter;
} else if(streamer->getStreamingMode() == STREAMING_MODE_STORE_ALL_FRAMES) {
mConsumerFrameCounters[processObject] = 0;
} else {
mConsumerFrameCounters[processObject] = getLowestFrameCount();
}
}
mStreamMutex.unlock();
}
DataObject::pointer DynamicData::getNextFrame(Object::pointer processObject) {
return getNextFrame(WeakPointer<Object>(processObject));
}
void DynamicData::setAllConsumersUpToDate() {
unsigned long timestamp = getTimestamp();
boost::unordered_map<WeakPointer<Object>, uint>::iterator it;
for(it = mConsumerFrameCounters.begin(); it != mConsumerFrameCounters.end(); it++) {
ProcessObject::pointer consumer = ProcessObject::pointer(it->first.lock());
consumer->updateTimestamp(mPtr.lock());
}
}
DataObject::pointer DynamicData::getNextFrame(WeakPointer<Object> processObject) {
Streamer::pointer streamer = getStreamer();
if(!streamer.isValid()) {
// If streamer has been deleted, return the current frame instead
throw Exception("Streamer has been deleted, but someone has called getNextFrame");
//return getCurrentFrame();
}
// Producer consumer model
if(mMaximumNrOfFrames > 0 && streamer->getStreamingMode() == STREAMING_MODE_PROCESS_ALL_FRAMES) {
bool frameShouldBeRemoved = true;
if(mConsumerFrameCounters.count(processObject) > 0) {
uint thisFrameCounter = mConsumerFrameCounters[processObject]; // Current consumer frame counter
// If any other frame counters are less or equal, we do not want to remove frame
boost::unordered_map<WeakPointer<Object>, uint>::const_iterator it;
for(it = mConsumerFrameCounters.begin(); it != mConsumerFrameCounters.end(); it++) {
if(it->second <= thisFrameCounter) {
frameShouldBeRemoved = false;
break;
}
}
}
if(frameShouldBeRemoved)
fillCount->wait(); // decrement
}
mStreamMutex.lock();
if(streamer->getStreamingMode() == STREAMING_MODE_NEWEST_FRAME_ONLY) {
// Always return last frame
if(mCurrentFrameCounter == 0) {
mStreamMutex.unlock();
throw Exception("Trying to get next frame, when no frame has ever been given to dynamic data.");
}
DataObject::pointer returnData = mCurrentFrame2;
mStreamMutex.unlock();
return mCurrentFrame2;
}
// If process object is not registered, register it
if(mConsumerFrameCounters.count(processObject) == 0) {
if(streamer->getStreamingMode() == STREAMING_MODE_NEWEST_FRAME_ONLY) {
mConsumerFrameCounters[processObject] = mCurrentFrameCounter;
} else if(streamer->getStreamingMode() == STREAMING_MODE_STORE_ALL_FRAMES) {
mConsumerFrameCounters[processObject] = 0;
} else {
uint lowestFrameCount = getLowestFrameCount(); // This must be assigned to a variable first to ensure correct result!
mConsumerFrameCounters[processObject] = lowestFrameCount;
}
}
// Return frame
DataObject::pointer returnData;
if(mFrames2.count(mConsumerFrameCounters[processObject]) > 0) {
returnData = mFrames2[mConsumerFrameCounters[processObject]];
} else {
mStreamMutex.unlock();
throw Exception("Frame in dynamic data was not found");
}
// Increment
mConsumerFrameCounters[processObject] = mConsumerFrameCounters[processObject]+1;
// If PROCESS_ALL and this has smallest frame counter, remove old frame
if(streamer->getStreamingMode() == STREAMING_MODE_PROCESS_ALL_FRAMES) {
removeOldFrames(getLowestFrameCount());
if(mFrames2.size() > 0) { // Update timestamp if there are more frames available
updateModifiedTimestamp();
// For each consumer
boost::unordered_map<WeakPointer<Object>, uint>::iterator it;
for(it = mConsumerFrameCounters.begin(); it != mConsumerFrameCounters.end(); it++) {
// Check if next frame is available
if(mFrames2.count(it->second) == 0) {
// Set consumer up to date, so that it will not request data yet
ProcessObject::pointer consumer = it->first.lock();
consumer->updateTimestamp(mPtr.lock());
}
}
} else {
// All frames are gone, make sure timestamps that all POs have are up to date
setAllConsumersUpToDate();
}
} else if(streamer->getStreamingMode() == STREAMING_MODE_NEWEST_FRAME_ONLY) {
// With newest frame only, always remove?
//mFrames2.erase(removeFrame);
} else {
// Update timestamp if there are more frames available
if(mConsumerFrameCounters[processObject] < mFrames2.size()) {
updateModifiedTimestamp();
}
}
mStreamMutex.unlock();
// Producer consumer
if(mMaximumNrOfFrames > 0 && streamer->getStreamingMode() == STREAMING_MODE_PROCESS_ALL_FRAMES) {
emptyCount->post(); // increment
}
return returnData;
}
DataObject::pointer DynamicData::getCurrentFrame() {
Streamer::pointer streamer = getStreamer();
mStreamMutex.lock();
/*
if(mFrames.size() == 0 || mFrames.size() <= mCurrentFrame) {
if(!streamer.isValid()) {
mStreamMutex.unlock();
throw Exception("Streamer does not exist (anymore), stop.");
} else {
if(streamer->hasReachedEnd()) {
mStreamMutex.unlock();
throw Exception("Streamer has reached the end.");
} else {
mStreamMutex.unlock();
throw Exception("This exception should not have occured. ");
}
}
}
*/
DataObject::pointer ret = mCurrentFrame2;
mStreamMutex.unlock();
return ret;
}
void DynamicData::addFrame(DataObject::pointer frame) {
Streamer::pointer streamer = getStreamer();
if(!streamer.isValid()) {
//throw Exception("A DynamicImage must have a streamer set before it can be used.");
return;
}
if(mMaximumNrOfFrames > 0) {
if(streamer->getStreamingMode() == STREAMING_MODE_PROCESS_ALL_FRAMES) {
// Producer consumer model using semaphores
emptyCount->wait(); // decrement
//down(mutex);
} else if(streamer->getStreamingMode() == STREAMING_MODE_STORE_ALL_FRAMES) {
if(mFrames2.size() >= mMaximumNrOfFrames)
throw NoMoreFramesException("Maximum number of frames reached. You can change the this number using the setMaximumNumberOfFrames method on the streamer/dynamic data objects.");
}
}
mStreamMutex.lock();
updateModifiedTimestamp();
if(getStreamer()->getStreamingMode() == STREAMING_MODE_NEWEST_FRAME_ONLY) {
mFrames2.clear();
}
mFrames2[mCurrentFrameCounter] = frame;
mCurrentFrame2 = frame;
mCurrentFrameCounter++;
mStreamMutex.unlock();
if(mMaximumNrOfFrames > 0 && streamer->getStreamingMode() == STREAMING_MODE_PROCESS_ALL_FRAMES) {
fillCount->post(); // increment
}
}
DynamicData::DynamicData() {
mCurrentFrameCounter = 0;
mMaximumNrOfFrames = 0;
mIsDynamicData = true;
mHasReachedEnd = false;
fillCount = NULL;
emptyCount = NULL;
updateModifiedTimestamp();
#if defined(__APPLE__) || defined(__MACOSX)
static uint namedSemaphoresCount = 0;
mSemaphoreNumber = namedSemaphoresCount;
namedSemaphoresCount++;
#endif
}
unsigned int DynamicData::getSize() const {
return mFrames2.size();
}
bool DynamicData::hasReachedEnd() {
Streamer::pointer streamer = getStreamer();
if(!streamer.isValid()) {
throw Exception("A DynamicData must have a streamer set before it can be used.");
}
mStreamMutex.lock();
// Check if has reached end can be changed to true
if(!mHasReachedEnd) {
// TODO the checks for NEWEST_FRAME AND PROCESS_ALL are not necessarily correct, for a pipeline with several steps
switch(streamer->getStreamingMode()) {
case STREAMING_MODE_NEWEST_FRAME_ONLY:
// Should get frame nr of last to see if we have read the last
if(streamer->hasReachedEnd())
mHasReachedEnd = true;
break;
case STREAMING_MODE_PROCESS_ALL_FRAMES:
if(streamer->hasReachedEnd() && mFrames2.size() == 0)
mHasReachedEnd = true;
break;
case STREAMING_MODE_STORE_ALL_FRAMES:
if(streamer->hasReachedEnd() && streamer->getNrOfFrames() == getLowestFrameCount())
mHasReachedEnd = true;
break;
}
}
mStreamMutex.unlock();
return mHasReachedEnd;
}
}
<|endoftext|>
|
<commit_before>// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "shared/shmem.h"
#include <fcntl.h>
#include <linux/memfd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <atomic>
#include <filesystem>
#include <string>
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#ifndef F_LINUX_SPECIFIC_BASE
#define F_LINUX_SPECIFIC_BASE 1024
#endif
#ifndef F_ADD_SEALS
#define F_ADD_SEALS (F_LINUX_SPECIFIC_BASE + 9)
#endif
#ifndef F_SEAL_SEAL
#define F_SEAL_SEAL 0x0001 /* prevent further seals from being set */
#endif
#ifndef F_SEAL_SHRINK
#define F_SEAL_SHRINK 0x0002 /* prevent file from shrinking */
#endif
#ifndef F_SEAL_GROW
#define F_SEAL_GROW 0x0004 /* prevent file from growing */
#endif
namespace fs = std::filesystem;
namespace ghost {
constexpr size_t kHugepageSize = 2 * 1024 * 1024;
static const char* kMemFdPrefix = "ghost-shmem-";
#define MFD_GOOGLE_SPECIFIC_BASE 0x0200U
#define MFD_HUGEPAGE (MFD_GOOGLE_SPECIFIC_BASE << 0)
// Please don't use "0" as a header version, it's not distinguishable from
// an uninitialized header.
static constexpr int64_t kHeaderVersion = 1;
// This currently occupies the first page of every mapping (from offset zero).
struct GhostShmem::InternalHeader {
int64_t header_version;
size_t mapping_size;
size_t header_size;
size_t client_size;
std::atomic<bool> ready, finished;
int owning_pid;
int64_t client_version;
};
GhostShmem::GhostShmem(int64_t client_version, const char* name, size_t size) {
CreateShmem(client_version, name, size);
}
bool GhostShmem::Attach(int64_t client_version, const char* name, pid_t pid) {
return ConnectShmem(client_version, name, pid);
}
GhostShmem::~GhostShmem() {
if (hdr_) {
hdr_->finished.store(true);
}
if (shmem_) {
munmap(shmem_, map_size_);
}
if (memfd_ >= 0) {
close(memfd_);
}
}
void GhostShmem::MarkReady() { hdr_->ready.store(true); }
void GhostShmem::WaitForReady() {
// TODO: Use a shared futex here.
while (!hdr_->ready.load()) {
}
}
size_t GhostShmem::size() {
// We apply internal adjustments, e.g. our header, hugepages, etc.
return hdr_->client_size;
}
void GhostShmem::CreateShmem(int64_t client_version, const char* suffix,
size_t size) {
int MFD_FLAGS = MFD_CLOEXEC | MFD_ALLOW_SEALING;
const int MFD_SEALS = F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL;
std::string name;
// Suffixes must currently be unique for the hosting process.
CHECK_EQ(OpenGhostShmemFd(suffix, Gtid::Current().tid()), -1);
name = kMemFdPrefix;
name.append(suffix);
memfd_ = memfd_create(name.c_str(), MFD_FLAGS);
CHECK_GE(memfd_, 0);
// Prepend our header to the mapping.
map_size_ = roundup2(size + kHeaderReservedBytes, kHugepageSize);
CHECK_LE(map_size_, UINT32_MAX);
CHECK_ZERO(ftruncate(memfd_, map_size_));
CHECK_ZERO(fcntl(memfd_, F_ADD_SEALS, MFD_SEALS));
shmem_ =
mmap(nullptr, map_size_, PROT_READ | PROT_WRITE, MAP_SHARED, memfd_, 0);
CHECK_NE(shmem_, MAP_FAILED);
// At this point the shmem_ is created, our header is initialized, but the
// region is not yet ready. Clients must call MarkReady() before we'll allow
// connections against it to proceed.
hdr_ = static_cast<InternalHeader*>(shmem_);
char* bytes = static_cast<char*>(shmem_);
data_ = bytes + kHeaderReservedBytes;
// We can safely initialize InternalHeader data fields after this point, as
// MarkReady() cannot yet proceed.
hdr_->header_version = kHeaderVersion;
hdr_->mapping_size = map_size_;
hdr_->client_size = map_size_ - kHeaderReservedBytes;
hdr_->header_size = kHeaderReservedBytes;
hdr_->owning_pid = getpid(); // Should probably be process.
}
bool GhostShmem::ConnectShmem(int64_t client_version, const char* suffix,
pid_t pid) {
memfd_ = OpenGhostShmemFd(suffix, pid);
if (memfd_ < 0) {
return false;
}
struct stat sb;
CHECK_ZERO(fstat(memfd_, &sb));
map_size_ = sb.st_size;
shmem_ =
mmap(nullptr, map_size_, PROT_READ | PROT_WRITE, MAP_SHARED, memfd_, 0);
CHECK_NE(shmem_, MAP_FAILED);
// Avoid deadlock between agent and the task it is scheduling. This happens
// if both tasks (agent and non-agent) fault on the same page in shared mem
// concurrently. Subsequently when the page is ready then it is possible that
// the non-agent task is woken up first but doesn't get a chance to run
// because the agent (that is responsible for scheduling it) is also blocked
// on the same page.
//
// See b/173811264 for details.
CHECK_ZERO(mlock(shmem_, map_size_));
// Setup internal fields.
hdr_ = static_cast<InternalHeader*>(shmem_);
char* bytes = static_cast<char*>(shmem_);
data_ = bytes + kHeaderReservedBytes;
// Ensure we synchronize on the remote side marking that content is ready
// before trying to validate.
WaitForReady();
CHECK_EQ(hdr_->header_version, kHeaderVersion);
CHECK_EQ(hdr_->client_version, client_version);
CHECK_EQ(hdr_->mapping_size, map_size_);
CHECK_EQ(hdr_->header_size, kHeaderReservedBytes);
return true;
}
// static
int GhostShmem::OpenGhostShmemFd(const char* suffix, pid_t pid) {
std::string path = "/proc/" + std::to_string(pid) + "/fd";
std::string needle("/memfd:");
needle.append(kMemFdPrefix);
needle.append(suffix);
for (auto& f : fs::directory_iterator(path)) {
CHECK(fs::is_symlink(f));
std::string p = fs::read_symlink(f);
if (absl::StartsWith(p, needle)) {
std::string path = fs::path(f);
int fd = open(path.c_str(), O_RDWR | O_CLOEXEC);
CHECK_GE(fd, 0);
return fd;
}
}
return -1;
}
// static
GhostShmem* GhostShmem::GetShmemBlob(size_t size) {
static std::atomic<int> unique = 0;
std::string blob = absl::StrCat(
"blob-", std::to_string(unique.fetch_add(1, std::memory_order_relaxed)));
// GhostShmem needs a unique name per process for the memfd
ghost::GhostShmem* shmem =
new ghost::GhostShmem(/* client_version = */ 0, blob.data(), size);
shmem->MarkReady();
return shmem;
}
} // namespace ghost
<commit_msg>cl/428811065: ghost: handle race with /proc/PID/fd/<commit_after>// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "shared/shmem.h"
#include <fcntl.h>
#include <linux/memfd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <atomic>
#include <filesystem>
#include <string>
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#ifndef F_LINUX_SPECIFIC_BASE
#define F_LINUX_SPECIFIC_BASE 1024
#endif
#ifndef F_ADD_SEALS
#define F_ADD_SEALS (F_LINUX_SPECIFIC_BASE + 9)
#endif
#ifndef F_SEAL_SEAL
#define F_SEAL_SEAL 0x0001 /* prevent further seals from being set */
#endif
#ifndef F_SEAL_SHRINK
#define F_SEAL_SHRINK 0x0002 /* prevent file from shrinking */
#endif
#ifndef F_SEAL_GROW
#define F_SEAL_GROW 0x0004 /* prevent file from growing */
#endif
namespace fs = std::filesystem;
namespace ghost {
constexpr size_t kHugepageSize = 2 * 1024 * 1024;
static const char* kMemFdPrefix = "ghost-shmem-";
#define MFD_GOOGLE_SPECIFIC_BASE 0x0200U
#define MFD_HUGEPAGE (MFD_GOOGLE_SPECIFIC_BASE << 0)
// Please don't use "0" as a header version, it's not distinguishable from
// an uninitialized header.
static constexpr int64_t kHeaderVersion = 1;
// This currently occupies the first page of every mapping (from offset zero).
struct GhostShmem::InternalHeader {
int64_t header_version;
size_t mapping_size;
size_t header_size;
size_t client_size;
std::atomic<bool> ready, finished;
int owning_pid;
int64_t client_version;
};
GhostShmem::GhostShmem(int64_t client_version, const char* name, size_t size) {
CreateShmem(client_version, name, size);
}
bool GhostShmem::Attach(int64_t client_version, const char* name, pid_t pid) {
return ConnectShmem(client_version, name, pid);
}
GhostShmem::~GhostShmem() {
if (hdr_) {
hdr_->finished.store(true);
}
if (shmem_) {
munmap(shmem_, map_size_);
}
if (memfd_ >= 0) {
close(memfd_);
}
}
void GhostShmem::MarkReady() { hdr_->ready.store(true); }
void GhostShmem::WaitForReady() {
// TODO: Use a shared futex here.
while (!hdr_->ready.load()) {
}
}
size_t GhostShmem::size() {
// We apply internal adjustments, e.g. our header, hugepages, etc.
return hdr_->client_size;
}
void GhostShmem::CreateShmem(int64_t client_version, const char* suffix,
size_t size) {
int MFD_FLAGS = MFD_CLOEXEC | MFD_ALLOW_SEALING;
const int MFD_SEALS = F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL;
std::string name;
// Suffixes must currently be unique for the hosting process.
CHECK_EQ(OpenGhostShmemFd(suffix, Gtid::Current().tid()), -1);
name = kMemFdPrefix;
name.append(suffix);
memfd_ = memfd_create(name.c_str(), MFD_FLAGS);
CHECK_GE(memfd_, 0);
// Prepend our header to the mapping.
map_size_ = roundup2(size + kHeaderReservedBytes, kHugepageSize);
CHECK_LE(map_size_, UINT32_MAX);
CHECK_ZERO(ftruncate(memfd_, map_size_));
CHECK_ZERO(fcntl(memfd_, F_ADD_SEALS, MFD_SEALS));
shmem_ =
mmap(nullptr, map_size_, PROT_READ | PROT_WRITE, MAP_SHARED, memfd_, 0);
CHECK_NE(shmem_, MAP_FAILED);
// At this point the shmem_ is created, our header is initialized, but the
// region is not yet ready. Clients must call MarkReady() before we'll allow
// connections against it to proceed.
hdr_ = static_cast<InternalHeader*>(shmem_);
char* bytes = static_cast<char*>(shmem_);
data_ = bytes + kHeaderReservedBytes;
// We can safely initialize InternalHeader data fields after this point, as
// MarkReady() cannot yet proceed.
hdr_->header_version = kHeaderVersion;
hdr_->mapping_size = map_size_;
hdr_->client_size = map_size_ - kHeaderReservedBytes;
hdr_->header_size = kHeaderReservedBytes;
hdr_->owning_pid = getpid(); // Should probably be process.
}
bool GhostShmem::ConnectShmem(int64_t client_version, const char* suffix,
pid_t pid) {
memfd_ = OpenGhostShmemFd(suffix, pid);
if (memfd_ < 0) {
return false;
}
struct stat sb;
CHECK_ZERO(fstat(memfd_, &sb));
map_size_ = sb.st_size;
shmem_ =
mmap(nullptr, map_size_, PROT_READ | PROT_WRITE, MAP_SHARED, memfd_, 0);
CHECK_NE(shmem_, MAP_FAILED);
// Avoid deadlock between agent and the task it is scheduling. This happens
// if both tasks (agent and non-agent) fault on the same page in shared mem
// concurrently. Subsequently when the page is ready then it is possible that
// the non-agent task is woken up first but doesn't get a chance to run
// because the agent (that is responsible for scheduling it) is also blocked
// on the same page.
//
// See b/173811264 for details.
CHECK_ZERO(mlock(shmem_, map_size_));
// Setup internal fields.
hdr_ = static_cast<InternalHeader*>(shmem_);
char* bytes = static_cast<char*>(shmem_);
data_ = bytes + kHeaderReservedBytes;
// Ensure we synchronize on the remote side marking that content is ready
// before trying to validate.
WaitForReady();
CHECK_EQ(hdr_->header_version, kHeaderVersion);
CHECK_EQ(hdr_->client_version, client_version);
CHECK_EQ(hdr_->mapping_size, map_size_);
CHECK_EQ(hdr_->header_size, kHeaderReservedBytes);
return true;
}
// static
int GhostShmem::OpenGhostShmemFd(const char* suffix, pid_t pid) {
std::string path = "/proc/" + std::to_string(pid) + "/fd";
std::string needle("/memfd:");
needle.append(kMemFdPrefix);
needle.append(suffix);
for (auto& f : fs::directory_iterator(path)) {
// It's possible for f to disappear at any moment if the file is closed.
std::error_code ec;
std::string p = fs::read_symlink(f, ec);
if (ec) {
continue;
}
if (absl::StartsWith(p, needle)) {
std::string path = fs::path(f);
int fd = open(path.c_str(), O_RDWR | O_CLOEXEC);
if (fd < 0) {
continue;
}
return fd;
}
}
return -1;
}
// static
GhostShmem* GhostShmem::GetShmemBlob(size_t size) {
static std::atomic<int> unique = 0;
std::string blob = absl::StrCat(
"blob-", std::to_string(unique.fetch_add(1, std::memory_order_relaxed)));
// GhostShmem needs a unique name per process for the memfd
ghost::GhostShmem* shmem =
new ghost::GhostShmem(/* client_version = */ 0, blob.data(), size);
shmem->MarkReady();
return shmem;
}
} // namespace ghost
<|endoftext|>
|
<commit_before>/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Author: sligocki@google.com (Shawn Ligocki)
#include "net/instaweb/http/public/content_type.h"
#include "net/instaweb/util/public/basictypes.h"
#include "net/instaweb/util/public/string_util.h"
namespace net_instaweb {
namespace {
const ContentType kTypes[] = {
// Canonical types:
{"text/html", ".html", ContentType::kHtml}, // RFC 2854
{"application/xhtml+xml", ".xhtml", ContentType::kXhtml}, // RFC 3236
{"application/ce-html+xml", ".xhtml", ContentType::kCeHtml},
{"text/javascript", ".js", ContentType::kJavascript},
{"text/css", ".css", ContentType::kCss},
{"text/plain", ".txt", ContentType::kText},
{"text/xml", ".xml", ContentType::kXml}, // RFC 3023
{"image/png", ".png", ContentType::kPng},
{"image/gif", ".gif", ContentType::kGif},
{"image/jpeg", ".jpg", ContentType::kJpeg},
{"application/x-shockwave-flash", ".swf", ContentType::kSwf},
{"image/webp", ".webp", ContentType::kWebp},
{"application/json", ".json", ContentType::kJson},
{"application/pdf", ".pdf", ContentType::kPdf}, // RFC 3778
// Synonyms; Note that the canonical types are referenced by index
// in the named references declared below.
{"application/x-javascript", ".js", ContentType::kJavascript},
{"application/javascript", ".js", ContentType::kJavascript},
{"text/ecmascript", ".js", ContentType::kJavascript},
{"text/x-js", ".js", ContentType::kJavascript},
{"application/ecmascript", ".js", ContentType::kJavascript},
{"image/jpeg", ".jpeg", ContentType::kJpeg},
{"text/html", ".htm", ContentType::kHtml},
{"application/xml", ".xml", ContentType::kXml}, // RFC 3023
};
const int kNumTypes = arraysize(kTypes);
} // namespace
const ContentType& kContentTypeHtml = kTypes[0];
const ContentType& kContentTypeXhtml = kTypes[1];
const ContentType& kContentTypeCeHtml = kTypes[2];
const ContentType& kContentTypeJavascript = kTypes[3];
const ContentType& kContentTypeCss = kTypes[4];
const ContentType& kContentTypeText = kTypes[5];
const ContentType& kContentTypeXml = kTypes[6];
const ContentType& kContentTypePng = kTypes[7];
const ContentType& kContentTypeGif = kTypes[8];
const ContentType& kContentTypeJpeg = kTypes[9];
const ContentType& kContentTypeSwf = kTypes[10];
const ContentType& kContentTypeWebp = kTypes[11];
const ContentType& kContentTypeJson = kTypes[12];
const ContentType& kContentTypePdf = kTypes[13];
int ContentType::MaxProducedExtensionLength() {
return 4; // .jpeg or .webp
}
bool ContentType::IsHtmlLike() const {
switch (type_) {
case kHtml:
case kXhtml:
case kCeHtml:
return true;
default:
return false;
}
}
bool ContentType::IsXmlLike() const {
switch (type_) {
case kXhtml:
case kXml:
return true;
default:
return false;
}
}
bool ContentType::IsFlash() const {
switch (type_) {
case kSwf:
return true;
default:
return false;
}
}
bool ContentType::IsImage() const {
switch (type_) {
case kPng:
case kGif:
case kJpeg:
case kWebp:
return true;
default:
return false;
}
}
const ContentType* NameExtensionToContentType(const StringPiece& name) {
// Get the name from the extension.
StringPiece::size_type ext_pos = name.rfind('.');
const ContentType* res = NULL;
if (ext_pos != StringPiece::npos) {
StringPiece ext = name.substr(ext_pos);
// TODO(jmarantz): convert to a map if the list gets large.
for (int i = 0; i < kNumTypes; ++i) {
if (StringCaseEqual(ext, kTypes[i].file_extension())) {
res = &kTypes[i];
break;
}
}
}
return res;
}
const ContentType* MimeTypeToContentType(const StringPiece& mime_type) {
// TODO(jmarantz): convert to a map if the list gets large.
const ContentType* res = NULL;
// The content-type can have a "; charset=...". We are not interested
// in that, for the purpose of our ContentType object.
//
// TODO(jmarantz): we should be grabbing the encoding, however, and
// saving it so that when we emit content-type headers for resources,
// they include the proper encoding.
StringPiece stripped_mime_type;
StringPiece::size_type semi_colon = mime_type.find(';');
if (semi_colon == StringPiece::npos) {
stripped_mime_type = mime_type;
} else {
stripped_mime_type = mime_type.substr(0, semi_colon);
}
for (int i = 0; i < kNumTypes; ++i) {
if (StringCaseEqual(stripped_mime_type, kTypes[i].mime_type())) {
res = &kTypes[i];
break;
}
}
return res;
}
// TODO(nforman): Have some further indication of whether
// content_type_str was just empty or invalid.
bool ParseContentType(const StringPiece& content_type_str,
GoogleString* mime_type,
GoogleString* charset) {
StringPiece content_type = content_type_str;
// Set default values
mime_type->clear();
charset->clear();
if (content_type.empty()) {
return false;
}
// Mime type is in the form: "\w+/\w+ *;(.*;)* *charset *= *\w+"
StringPieceVector semi_split;
SplitStringPieceToVector(content_type, ";", &semi_split, false);
if (semi_split.size() == 0) {
return false;
}
semi_split[0].CopyToString(mime_type);
for (int i = 1, n = semi_split.size(); i < n; ++i) {
StringPieceVector eq_split;
SplitStringPieceToVector(semi_split[i], "=", &eq_split, false);
if (eq_split.size() == 2) {
TrimWhitespace(&eq_split[0]);
if (StringCaseEqual(eq_split[0], "charset")) {
TrimWhitespace(&eq_split[1]);
eq_split[1].CopyToString(charset);
break;
}
}
}
return !mime_type->empty() || !charset->empty();
}
} // namespace net_instaweb
<commit_msg>Change default content type of javascript to application/javascript rather than text/javascript to avoid confusing certain firewalls.<commit_after>/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Author: sligocki@google.com (Shawn Ligocki)
#include "net/instaweb/http/public/content_type.h"
#include "net/instaweb/util/public/basictypes.h"
#include "net/instaweb/util/public/string_util.h"
namespace net_instaweb {
namespace {
const ContentType kTypes[] = {
// Canonical types:
{"text/html", ".html", ContentType::kHtml}, // RFC 2854
{"application/xhtml+xml", ".xhtml", ContentType::kXhtml}, // RFC 3236
{"application/ce-html+xml", ".xhtml", ContentType::kCeHtml},
{"application/javascript", ".js", ContentType::kJavascript},
// RFC 4329 makes this canonical; text/... can break firewall gzipping
{"text/css", ".css", ContentType::kCss},
{"text/plain", ".txt", ContentType::kText},
{"text/xml", ".xml", ContentType::kXml}, // RFC 3023
{"image/png", ".png", ContentType::kPng},
{"image/gif", ".gif", ContentType::kGif},
{"image/jpeg", ".jpg", ContentType::kJpeg},
{"application/x-shockwave-flash", ".swf", ContentType::kSwf},
{"image/webp", ".webp", ContentType::kWebp},
{"application/json", ".json", ContentType::kJson},
{"application/pdf", ".pdf", ContentType::kPdf}, // RFC 3778
// Synonyms; Note that the canonical types are referenced by index
// in the named references declared below.
{"application/x-javascript", ".js", ContentType::kJavascript},
{"text/javascript", ".js", ContentType::kJavascript},
{"text/ecmascript", ".js", ContentType::kJavascript},
{"text/x-js", ".js", ContentType::kJavascript},
{"application/ecmascript", ".js", ContentType::kJavascript},
{"image/jpeg", ".jpeg", ContentType::kJpeg},
{"text/html", ".htm", ContentType::kHtml},
{"application/xml", ".xml", ContentType::kXml}, // RFC 3023
};
const int kNumTypes = arraysize(kTypes);
} // namespace
const ContentType& kContentTypeHtml = kTypes[0];
const ContentType& kContentTypeXhtml = kTypes[1];
const ContentType& kContentTypeCeHtml = kTypes[2];
const ContentType& kContentTypeJavascript = kTypes[3];
const ContentType& kContentTypeCss = kTypes[4];
const ContentType& kContentTypeText = kTypes[5];
const ContentType& kContentTypeXml = kTypes[6];
const ContentType& kContentTypePng = kTypes[7];
const ContentType& kContentTypeGif = kTypes[8];
const ContentType& kContentTypeJpeg = kTypes[9];
const ContentType& kContentTypeSwf = kTypes[10];
const ContentType& kContentTypeWebp = kTypes[11];
const ContentType& kContentTypeJson = kTypes[12];
const ContentType& kContentTypePdf = kTypes[13];
int ContentType::MaxProducedExtensionLength() {
return 4; // .jpeg or .webp
}
bool ContentType::IsHtmlLike() const {
switch (type_) {
case kHtml:
case kXhtml:
case kCeHtml:
return true;
default:
return false;
}
}
bool ContentType::IsXmlLike() const {
switch (type_) {
case kXhtml:
case kXml:
return true;
default:
return false;
}
}
bool ContentType::IsFlash() const {
switch (type_) {
case kSwf:
return true;
default:
return false;
}
}
bool ContentType::IsImage() const {
switch (type_) {
case kPng:
case kGif:
case kJpeg:
case kWebp:
return true;
default:
return false;
}
}
const ContentType* NameExtensionToContentType(const StringPiece& name) {
// Get the name from the extension.
StringPiece::size_type ext_pos = name.rfind('.');
const ContentType* res = NULL;
if (ext_pos != StringPiece::npos) {
StringPiece ext = name.substr(ext_pos);
// TODO(jmarantz): convert to a map if the list gets large.
for (int i = 0; i < kNumTypes; ++i) {
if (StringCaseEqual(ext, kTypes[i].file_extension())) {
res = &kTypes[i];
break;
}
}
}
return res;
}
const ContentType* MimeTypeToContentType(const StringPiece& mime_type) {
// TODO(jmarantz): convert to a map if the list gets large.
const ContentType* res = NULL;
// The content-type can have a "; charset=...". We are not interested
// in that, for the purpose of our ContentType object.
//
// TODO(jmarantz): we should be grabbing the encoding, however, and
// saving it so that when we emit content-type headers for resources,
// they include the proper encoding.
StringPiece stripped_mime_type;
StringPiece::size_type semi_colon = mime_type.find(';');
if (semi_colon == StringPiece::npos) {
stripped_mime_type = mime_type;
} else {
stripped_mime_type = mime_type.substr(0, semi_colon);
}
for (int i = 0; i < kNumTypes; ++i) {
if (StringCaseEqual(stripped_mime_type, kTypes[i].mime_type())) {
res = &kTypes[i];
break;
}
}
return res;
}
// TODO(nforman): Have some further indication of whether
// content_type_str was just empty or invalid.
bool ParseContentType(const StringPiece& content_type_str,
GoogleString* mime_type,
GoogleString* charset) {
StringPiece content_type = content_type_str;
// Set default values
mime_type->clear();
charset->clear();
if (content_type.empty()) {
return false;
}
// Mime type is in the form: "\w+/\w+ *;(.*;)* *charset *= *\w+"
StringPieceVector semi_split;
SplitStringPieceToVector(content_type, ";", &semi_split, false);
if (semi_split.size() == 0) {
return false;
}
semi_split[0].CopyToString(mime_type);
for (int i = 1, n = semi_split.size(); i < n; ++i) {
StringPieceVector eq_split;
SplitStringPieceToVector(semi_split[i], "=", &eq_split, false);
if (eq_split.size() == 2) {
TrimWhitespace(&eq_split[0]);
if (StringCaseEqual(eq_split[0], "charset")) {
TrimWhitespace(&eq_split[1]);
eq_split[1].CopyToString(charset);
break;
}
}
}
return !mime_type->empty() || !charset->empty();
}
} // namespace net_instaweb
<|endoftext|>
|
<commit_before>//===-- tsan_clock.cc -----------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of ThreadSanitizer (TSan), a race detector.
//
//===----------------------------------------------------------------------===//
#include "tsan_clock.h"
#include "tsan_rtl.h"
// It's possible to optimize clock operations for some important cases
// so that they are O(1). The cases include singletons, once's, local mutexes.
// First, SyncClock must be re-implemented to allow indexing by tid.
// It must not necessarily be a full vector clock, though. For example it may
// be a multi-level table.
// Then, each slot in SyncClock must contain a dirty bit (it's united with
// the clock value, so no space increase). The acquire algorithm looks
// as follows:
// void acquire(thr, tid, thr_clock, sync_clock) {
// if (!sync_clock[tid].dirty)
// return; // No new info to acquire.
// // This handles constant reads of singleton pointers and
// // stop-flags.
// acquire_impl(thr_clock, sync_clock); // As usual, O(N).
// sync_clock[tid].dirty = false;
// sync_clock.dirty_count--;
// }
// The release operation looks as follows:
// void release(thr, tid, thr_clock, sync_clock) {
// // thr->sync_cache is a simple fixed-size hash-based cache that holds
// // several previous sync_clock's.
// if (thr->sync_cache[sync_clock] >= thr->last_acquire_epoch) {
// // The thread did no acquire operations since last release on this clock.
// // So update only the thread's slot (other slots can't possibly change).
// sync_clock[tid].clock = thr->epoch;
// if (sync_clock.dirty_count == sync_clock.cnt
// || (sync_clock.dirty_count == sync_clock.cnt - 1
// && sync_clock[tid].dirty == false))
// // All dirty flags are set, bail out.
// return;
// set all dirty bits, but preserve the thread's bit. // O(N)
// update sync_clock.dirty_count;
// return;
// }
// release_impl(thr_clock, sync_clock); // As usual, O(N).
// set all dirty bits, but preserve the thread's bit.
// // The previous step is combined with release_impl(), so that
// // we scan the arrays only once.
// update sync_clock.dirty_count;
// }
namespace __tsan {
ThreadClock::ThreadClock() {
nclk_ = 0;
for (uptr i = 0; i < (uptr)kMaxTidInClock; i++)
clk_[i] = 0;
}
void ThreadClock::acquire(const SyncClock *src) {
DCHECK(nclk_ <= kMaxTid);
DCHECK(src->clk_.Size() <= kMaxTid);
const uptr nclk = src->clk_.Size();
if (nclk == 0)
return;
nclk_ = max(nclk_, nclk);
for (uptr i = 0; i < nclk; i++) {
if (clk_[i] < src->clk_[i])
clk_[i] = src->clk_[i];
}
}
void ThreadClock::release(SyncClock *dst) const {
DCHECK(nclk_ <= kMaxTid);
DCHECK(dst->clk_.Size() <= kMaxTid);
if (dst->clk_.Size() < nclk_)
dst->clk_.Resize(nclk_);
for (uptr i = 0; i < nclk_; i++) {
if (dst->clk_[i] < clk_[i])
dst->clk_[i] = clk_[i];
}
}
void ThreadClock::ReleaseStore(SyncClock *dst) const {
DCHECK(nclk_ <= kMaxTid);
DCHECK(dst->clk_.Size() <= kMaxTid);
if (dst->clk_.Size() < nclk_)
dst->clk_.Resize(nclk_);
for (uptr i = 0; i < nclk_; i++)
dst->clk_[i] = clk_[i];
for (uptr i = nclk_; i < dst->clk_.Size(); i++)
dst->clk_[i] = 0;
}
void ThreadClock::acq_rel(SyncClock *dst) {
acquire(dst);
release(dst);
}
void ThreadClock::Disable(unsigned tid) {
u64 c0 = clk_[tid];
for (uptr i = 0; i < kMaxTidInClock; i++)
clk_[i] = (u64)-1;
clk_[tid] = c0;
}
SyncClock::SyncClock()
: clk_(MBlockClock) {
}
} // namespace __tsan
<commit_msg>[TSan] delete trailing spaces<commit_after>//===-- tsan_clock.cc -----------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of ThreadSanitizer (TSan), a race detector.
//
//===----------------------------------------------------------------------===//
#include "tsan_clock.h"
#include "tsan_rtl.h"
// It's possible to optimize clock operations for some important cases
// so that they are O(1). The cases include singletons, once's, local mutexes.
// First, SyncClock must be re-implemented to allow indexing by tid.
// It must not necessarily be a full vector clock, though. For example it may
// be a multi-level table.
// Then, each slot in SyncClock must contain a dirty bit (it's united with
// the clock value, so no space increase). The acquire algorithm looks
// as follows:
// void acquire(thr, tid, thr_clock, sync_clock) {
// if (!sync_clock[tid].dirty)
// return; // No new info to acquire.
// // This handles constant reads of singleton pointers and
// // stop-flags.
// acquire_impl(thr_clock, sync_clock); // As usual, O(N).
// sync_clock[tid].dirty = false;
// sync_clock.dirty_count--;
// }
// The release operation looks as follows:
// void release(thr, tid, thr_clock, sync_clock) {
// // thr->sync_cache is a simple fixed-size hash-based cache that holds
// // several previous sync_clock's.
// if (thr->sync_cache[sync_clock] >= thr->last_acquire_epoch) {
// // The thread did no acquire operations since last release on this clock.
// // So update only the thread's slot (other slots can't possibly change).
// sync_clock[tid].clock = thr->epoch;
// if (sync_clock.dirty_count == sync_clock.cnt
// || (sync_clock.dirty_count == sync_clock.cnt - 1
// && sync_clock[tid].dirty == false))
// // All dirty flags are set, bail out.
// return;
// set all dirty bits, but preserve the thread's bit. // O(N)
// update sync_clock.dirty_count;
// return;
// }
// release_impl(thr_clock, sync_clock); // As usual, O(N).
// set all dirty bits, but preserve the thread's bit.
// // The previous step is combined with release_impl(), so that
// // we scan the arrays only once.
// update sync_clock.dirty_count;
// }
namespace __tsan {
ThreadClock::ThreadClock() {
nclk_ = 0;
for (uptr i = 0; i < (uptr)kMaxTidInClock; i++)
clk_[i] = 0;
}
void ThreadClock::acquire(const SyncClock *src) {
DCHECK(nclk_ <= kMaxTid);
DCHECK(src->clk_.Size() <= kMaxTid);
const uptr nclk = src->clk_.Size();
if (nclk == 0)
return;
nclk_ = max(nclk_, nclk);
for (uptr i = 0; i < nclk; i++) {
if (clk_[i] < src->clk_[i])
clk_[i] = src->clk_[i];
}
}
void ThreadClock::release(SyncClock *dst) const {
DCHECK(nclk_ <= kMaxTid);
DCHECK(dst->clk_.Size() <= kMaxTid);
if (dst->clk_.Size() < nclk_)
dst->clk_.Resize(nclk_);
for (uptr i = 0; i < nclk_; i++) {
if (dst->clk_[i] < clk_[i])
dst->clk_[i] = clk_[i];
}
}
void ThreadClock::ReleaseStore(SyncClock *dst) const {
DCHECK(nclk_ <= kMaxTid);
DCHECK(dst->clk_.Size() <= kMaxTid);
if (dst->clk_.Size() < nclk_)
dst->clk_.Resize(nclk_);
for (uptr i = 0; i < nclk_; i++)
dst->clk_[i] = clk_[i];
for (uptr i = nclk_; i < dst->clk_.Size(); i++)
dst->clk_[i] = 0;
}
void ThreadClock::acq_rel(SyncClock *dst) {
acquire(dst);
release(dst);
}
void ThreadClock::Disable(unsigned tid) {
u64 c0 = clk_[tid];
for (uptr i = 0; i < kMaxTidInClock; i++)
clk_[i] = (u64)-1;
clk_[tid] = c0;
}
SyncClock::SyncClock()
: clk_(MBlockClock) {
}
} // namespace __tsan
<|endoftext|>
|
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2014 n@zgul <naazgull@dfz.pt>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <zapata/mongodb/Client.h>
zpt::mongodb::ClientPtr::ClientPtr(zpt::mongodb::Client * _target) : std::shared_ptr<zpt::mongodb::Client>(_target) {
}
zpt::mongodb::ClientPtr::ClientPtr(zpt::json _options, std::string _conf_path) : std::shared_ptr<zpt::mongodb::Client>(new zpt::mongodb::Client(_options, _conf_path)) {
}
zpt::mongodb::ClientPtr::~ClientPtr() {
}
zpt::mongodb::Client::Client(zpt::json _options, std::string _conf_path) : __options( _options), __mongodb_conf(_options->getPath(_conf_path)), __conf_path(_conf_path), __conn((string) __mongodb_conf["bind"]), __broadcast(true), __addons(new zpt::Addons(_options)) {
if (this->__mongodb_conf["user"]->ok()) {
this->__conn->auth(BSON("mechanism" << "MONGODB-CR" << "user" << (string) this->__mongodb_conf["user"] << "pwd" << (string) this->__mongodb_conf["passwd"] << "db" << (string) this->__mongodb_conf["db"]));
}
this->__conn->setWriteConcern((mongo::WriteConcern) 2);
}
zpt::mongodb::Client::~Client() {
this->__conn.done();
}
zpt::json zpt::mongodb::Client::options() {
return this->__options;
}
std::string zpt::mongodb::Client::name() {
return string("mongodb://") + ((string) this->__mongodb_conf["bind"]) + string(":") + ((string) this->__mongodb_conf["port"]) + string("/") + ((string) this->__mongodb_conf["db"]);
}
bool& zpt::mongodb::Client::broadcast() {
return this->__broadcast;
}
zpt::ev::emitter zpt::mongodb::Client::addons() {
return this->__addons;
}
std::string zpt::mongodb::Client::insert(std::string _collection, std::string _id_prefix, zpt::json _document) {
assertz(_document->ok() && _document->type() == zpt::JSObject, "'_document' must be of type JSObject", 412, 0);
std::string _full_collection(_collection);
_full_collection.insert(0, ".");
_full_collection.insert(0, (string) this->__mongodb_conf["db"]);
if (!_document["id"]->ok()) {
uuid _uuid;
_uuid.make(UUID_MAKE_V1);
_document << "id" << _uuid.string();
}
if (!_document["_id"]->ok() && _id_prefix.length() != 0) {
_document << "_id" << (_id_prefix + (_id_prefix.back() != '/' ? string("/") : string("")) + _document["id"]->str());
}
_document << "href" << _document["_id"];
mongo::BSONObjBuilder _mongo_document;
zpt::mongodb::tomongo(_document, _mongo_document);
this->__conn->insert(_full_collection, _mongo_document.obj());
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
if (this->__broadcast && this->addons().get() != nullptr) {
this->addons()->trigger(zpt::ev::Post, string("INSERT ") + _collection, _document);
}
return _document["id"]->str();
}
int zpt::mongodb::Client::save(std::string _collection, zpt::json _pattern, zpt::json _document) {
assertz(_document->ok() && _document->type() == zpt::JSObject, "'_document' must be of type JSObject", 412, 0);
if (!_pattern->ok()) {
_pattern = zpt::mkobj();
}
std::string _full_collection(_collection);
_full_collection.insert(0, ".");
_full_collection.insert(0, (string) this->__mongodb_conf["db"]);
size_t _page_size = 0;
size_t _page_start_index = 0;
mongo::BSONObjBuilder _query_b;
mongo::BSONObjBuilder _order_b;
zpt::mongodb::get_query(_pattern, _query_b, _order_b, _page_size, _page_start_index);
mongo::Query _filter(_query_b.done());
unsigned long _size = this->__conn->count(_full_collection, _filter.obj, (int) mongo::QueryOption_SlaveOk);
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
mongo::BSONObjBuilder _mongo_document;
zpt::mongodb::tomongo(_document, _mongo_document);
this->__conn->update(_full_collection, _filter, _mongo_document.obj(), false, false);
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
if (this->__broadcast) {
this->addons()->trigger(zpt::ev::Post, string("UPDATE ") + _collection, _pattern);
}
return _size;
}
int zpt::mongodb::Client::set(std::string _collection, zpt::json _pattern, zpt::json _document) {
assertz(_document->ok() && _document->type() == zpt::JSObject, "'_document' must be of type JSObject", 412, 0);
if (!_pattern->ok()) {
_pattern = zpt::mkobj();
}
std::string _full_collection(_collection);
_full_collection.insert(0, ".");
_full_collection.insert(0, (string) this->__mongodb_conf["db"]);
size_t _page_size = 0;
size_t _page_start_index = 0;
mongo::BSONObjBuilder _query_b;
mongo::BSONObjBuilder _order_b;
zpt::mongodb::get_query(_pattern, _query_b, _order_b, _page_size, _page_start_index);
mongo::Query _filter(_query_b.done());
unsigned long _size = this->__conn->count(_full_collection, _filter.obj, (int) mongo::QueryOption_SlaveOk);
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
_document = { "$set", _document };
mongo::BSONObjBuilder _mongo_document;
zpt::mongodb::tomongo(_document, _mongo_document);
this->__conn->update(_full_collection, _filter, _mongo_document.obj(), false, true);
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
if (this->__broadcast) {
this->addons()->trigger(zpt::ev::Post, string("UPDATE ") + _collection, _pattern);
}
return _size;
}
int zpt::mongodb::Client::unset(std::string _collection, zpt::json _pattern, zpt::json _document) {
assertz(_document->ok() && _document->type() == zpt::JSObject, "'_document' must be of type JSObject", 412, 0);
if (!_pattern->ok()) {
_pattern = zpt::mkobj();
}
std::string _full_collection(_collection);
_full_collection.insert(0, ".");
_full_collection.insert(0, (string) this->__mongodb_conf["db"]);
size_t _page_size = 0;
size_t _page_start_index = 0;
mongo::BSONObjBuilder _query_b;
mongo::BSONObjBuilder _order_b;
zpt::mongodb::get_query(_pattern, _query_b, _order_b, _page_size, _page_start_index);
mongo::Query _filter(_query_b.done());
unsigned long _size = this->__conn->count(_full_collection, _filter.obj, (int) mongo::QueryOption_SlaveOk);
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
_document = { "$unset", _document };
mongo::BSONObjBuilder _mongo_document;
zpt::mongodb::tomongo(_document, _mongo_document);
this->__conn->update(_full_collection, _filter, _mongo_document.obj(), false, true);
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
if (this->__broadcast) {
this->addons()->trigger(zpt::ev::Post, string("UPDATE ") + _collection, _pattern);
}
return _size;
}
int zpt::mongodb::Client::remove(std::string _collection, zpt::json _pattern) {
if (!_pattern->ok()) {
_pattern = zpt::mkobj();
}
std::string _full_collection(_collection);
_full_collection.insert(0, ".");
_full_collection.insert(0, (string) this->__mongodb_conf["db"]);
size_t _page_size = 0;
size_t _page_start_index = 0;
mongo::BSONObjBuilder _query_b;
mongo::BSONObjBuilder _order_b;
zpt::mongodb::get_query(_pattern, _query_b, _order_b, _page_size, _page_start_index);
mongo::Query _filter(_query_b.done());
unsigned long _size = this->__conn->count(_full_collection, _filter.obj, (int) mongo::QueryOption_SlaveOk);
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
this->__conn->remove(_full_collection, _filter);
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
if (this->__broadcast) {
this->addons()->trigger(zpt::ev::Post, string("DELETE ") + _collection, _pattern);
}
return _size;
}
zpt::json zpt::mongodb::Client::query(std::string _collection, zpt::json _pattern) {
if (!_pattern->ok()) {
_pattern = zpt::mkobj();
}
zpt::JSONArr _elements;
std::string _full_collection(_collection);
_full_collection.insert(0, ".");
_full_collection.insert(0, (string) this->__mongodb_conf["db"]);
size_t _page_size = 0;
size_t _page_start_index = 0;
mongo::BSONObjBuilder _query_b;
mongo::BSONObjBuilder _order_b;
zpt::mongodb::get_query(_pattern, _query_b, _order_b, _page_size, _page_start_index);
mongo::Query _query(_query_b.done());
cout << _query.obj.jsonString(mongo::JS) << endl << flush;
unsigned long _size = this->__conn->count(_full_collection, _query.obj, (int) mongo::QueryOption_SlaveOk);
mongo::BSONObj _order = _order_b.done();
if (!_order.isEmpty()) {
_query.sort(_order);
}
std::unique_ptr<mongo::DBClientCursor> _result = this->__conn->query(_full_collection, _query, _page_size, _page_start_index, nullptr, (int) mongo::QueryOption_SlaveOk);
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
while(_result->more()) {
mongo::BSONObj _record = _result->next();
zpt::JSONObj _obj;
zpt::mongodb::frommongo(_record, _obj);
_elements << _obj;
}
if (_elements->size() == 0) {
return zpt::undefined;
}
zpt::json _return = {
"size", _size,
"elements", _elements
};
if (_page_size != 0) {
_return << "links" << zpt::json(
{
"next", (std::string("?page-size=") + std::to_string(_page_size) + std::string("&page-start-index=") + std::to_string(_page_start_index + _page_size)),
"prev", (std::string("?page-size=") + std::to_string(_page_size) + std::string("&page-start-index=") + std::to_string(_page_size < _page_start_index ? _page_start_index - _page_size : 0))
}
);
}
return _return;
}
<commit_msg>added support for object and array types in query<commit_after>/*
The MIT License (MIT)
Copyright (c) 2014 n@zgul <naazgull@dfz.pt>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <zapata/mongodb/Client.h>
zpt::mongodb::ClientPtr::ClientPtr(zpt::mongodb::Client * _target) : std::shared_ptr<zpt::mongodb::Client>(_target) {
}
zpt::mongodb::ClientPtr::ClientPtr(zpt::json _options, std::string _conf_path) : std::shared_ptr<zpt::mongodb::Client>(new zpt::mongodb::Client(_options, _conf_path)) {
}
zpt::mongodb::ClientPtr::~ClientPtr() {
}
zpt::mongodb::Client::Client(zpt::json _options, std::string _conf_path) : __options( _options), __mongodb_conf(_options->getPath(_conf_path)), __conf_path(_conf_path), __conn((string) __mongodb_conf["bind"]), __broadcast(true), __addons(new zpt::Addons(_options)) {
if (this->__mongodb_conf["user"]->ok()) {
this->__conn->auth(BSON("mechanism" << "MONGODB-CR" << "user" << (string) this->__mongodb_conf["user"] << "pwd" << (string) this->__mongodb_conf["passwd"] << "db" << (string) this->__mongodb_conf["db"]));
}
this->__conn->setWriteConcern((mongo::WriteConcern) 2);
}
zpt::mongodb::Client::~Client() {
this->__conn.done();
}
zpt::json zpt::mongodb::Client::options() {
return this->__options;
}
std::string zpt::mongodb::Client::name() {
return string("mongodb://") + ((string) this->__mongodb_conf["bind"]) + string(":") + ((string) this->__mongodb_conf["port"]) + string("/") + ((string) this->__mongodb_conf["db"]);
}
bool& zpt::mongodb::Client::broadcast() {
return this->__broadcast;
}
zpt::ev::emitter zpt::mongodb::Client::addons() {
return this->__addons;
}
std::string zpt::mongodb::Client::insert(std::string _collection, std::string _id_prefix, zpt::json _document) {
assertz(_document->ok() && _document->type() == zpt::JSObject, "'_document' must be of type JSObject", 412, 0);
std::string _full_collection(_collection);
_full_collection.insert(0, ".");
_full_collection.insert(0, (string) this->__mongodb_conf["db"]);
if (!_document["id"]->ok()) {
uuid _uuid;
_uuid.make(UUID_MAKE_V1);
_document << "id" << _uuid.string();
}
if (!_document["_id"]->ok() && _id_prefix.length() != 0) {
_document << "_id" << (_id_prefix + (_id_prefix.back() != '/' ? string("/") : string("")) + _document["id"]->str());
}
_document << "href" << _document["_id"];
mongo::BSONObjBuilder _mongo_document;
zpt::mongodb::tomongo(_document, _mongo_document);
this->__conn->insert(_full_collection, _mongo_document.obj());
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
if (this->__broadcast && this->addons().get() != nullptr) {
this->addons()->trigger(zpt::ev::Post, string("INSERT ") + _collection, _document);
}
return _document["id"]->str();
}
int zpt::mongodb::Client::save(std::string _collection, zpt::json _pattern, zpt::json _document) {
assertz(_document->ok() && _document->type() == zpt::JSObject, "'_document' must be of type JSObject", 412, 0);
if (!_pattern->ok()) {
_pattern = zpt::mkobj();
}
std::string _full_collection(_collection);
_full_collection.insert(0, ".");
_full_collection.insert(0, (string) this->__mongodb_conf["db"]);
size_t _page_size = 0;
size_t _page_start_index = 0;
mongo::BSONObjBuilder _query_b;
mongo::BSONObjBuilder _order_b;
zpt::mongodb::get_query(_pattern, _query_b, _order_b, _page_size, _page_start_index);
mongo::Query _filter(_query_b.done());
unsigned long _size = this->__conn->count(_full_collection, _filter.obj, (int) mongo::QueryOption_SlaveOk);
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
mongo::BSONObjBuilder _mongo_document;
zpt::mongodb::tomongo(_document, _mongo_document);
this->__conn->update(_full_collection, _filter, _mongo_document.obj(), false, false);
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
if (this->__broadcast) {
this->addons()->trigger(zpt::ev::Post, string("UPDATE ") + _collection, _pattern);
}
return _size;
}
int zpt::mongodb::Client::set(std::string _collection, zpt::json _pattern, zpt::json _document) {
assertz(_document->ok() && _document->type() == zpt::JSObject, "'_document' must be of type JSObject", 412, 0);
if (!_pattern->ok()) {
_pattern = zpt::mkobj();
}
std::string _full_collection(_collection);
_full_collection.insert(0, ".");
_full_collection.insert(0, (string) this->__mongodb_conf["db"]);
size_t _page_size = 0;
size_t _page_start_index = 0;
mongo::BSONObjBuilder _query_b;
mongo::BSONObjBuilder _order_b;
zpt::mongodb::get_query(_pattern, _query_b, _order_b, _page_size, _page_start_index);
mongo::Query _filter(_query_b.done());
unsigned long _size = this->__conn->count(_full_collection, _filter.obj, (int) mongo::QueryOption_SlaveOk);
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
_document = { "$set", _document };
mongo::BSONObjBuilder _mongo_document;
zpt::mongodb::tomongo(_document, _mongo_document);
this->__conn->update(_full_collection, _filter, _mongo_document.obj(), false, true);
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
if (this->__broadcast) {
this->addons()->trigger(zpt::ev::Post, string("UPDATE ") + _collection, _pattern);
}
return _size;
}
int zpt::mongodb::Client::unset(std::string _collection, zpt::json _pattern, zpt::json _document) {
assertz(_document->ok() && _document->type() == zpt::JSObject, "'_document' must be of type JSObject", 412, 0);
if (!_pattern->ok()) {
_pattern = zpt::mkobj();
}
std::string _full_collection(_collection);
_full_collection.insert(0, ".");
_full_collection.insert(0, (string) this->__mongodb_conf["db"]);
size_t _page_size = 0;
size_t _page_start_index = 0;
mongo::BSONObjBuilder _query_b;
mongo::BSONObjBuilder _order_b;
zpt::mongodb::get_query(_pattern, _query_b, _order_b, _page_size, _page_start_index);
mongo::Query _filter(_query_b.done());
unsigned long _size = this->__conn->count(_full_collection, _filter.obj, (int) mongo::QueryOption_SlaveOk);
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
_document = { "$unset", _document };
mongo::BSONObjBuilder _mongo_document;
zpt::mongodb::tomongo(_document, _mongo_document);
this->__conn->update(_full_collection, _filter, _mongo_document.obj(), false, true);
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
if (this->__broadcast) {
this->addons()->trigger(zpt::ev::Post, string("UPDATE ") + _collection, _pattern);
}
return _size;
}
int zpt::mongodb::Client::remove(std::string _collection, zpt::json _pattern) {
if (!_pattern->ok()) {
_pattern = zpt::mkobj();
}
std::string _full_collection(_collection);
_full_collection.insert(0, ".");
_full_collection.insert(0, (string) this->__mongodb_conf["db"]);
size_t _page_size = 0;
size_t _page_start_index = 0;
mongo::BSONObjBuilder _query_b;
mongo::BSONObjBuilder _order_b;
zpt::mongodb::get_query(_pattern, _query_b, _order_b, _page_size, _page_start_index);
mongo::Query _filter(_query_b.done());
unsigned long _size = this->__conn->count(_full_collection, _filter.obj, (int) mongo::QueryOption_SlaveOk);
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
this->__conn->remove(_full_collection, _filter);
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
if (this->__broadcast) {
this->addons()->trigger(zpt::ev::Post, string("DELETE ") + _collection, _pattern);
}
return _size;
}
zpt::json zpt::mongodb::Client::query(std::string _collection, zpt::json _pattern) {
if (!_pattern->ok()) {
_pattern = zpt::mkobj();
}
zpt::JSONArr _elements;
std::string _full_collection(_collection);
_full_collection.insert(0, ".");
_full_collection.insert(0, (string) this->__mongodb_conf["db"]);
size_t _page_size = 0;
size_t _page_start_index = 0;
mongo::BSONObjBuilder _query_b;
mongo::BSONObjBuilder _order_b;
zpt::mongodb::get_query(_pattern, _query_b, _order_b, _page_size, _page_start_index);
mongo::Query _query(_query_b.done());
unsigned long _size = this->__conn->count(_full_collection, _query.obj, (int) mongo::QueryOption_SlaveOk);
mongo::BSONObj _order = _order_b.done();
if (!_order.isEmpty()) {
_query.sort(_order);
}
std::unique_ptr<mongo::DBClientCursor> _result = this->__conn->query(_full_collection, _query, _page_size, _page_start_index, nullptr, (int) mongo::QueryOption_SlaveOk);
assertz(this->__conn->getLastError().length() == 0, string("mongodb operation returned an error: ") + this->__conn->getLastError(), 500, 0);
while(_result->more()) {
mongo::BSONObj _record = _result->next();
zpt::JSONObj _obj;
zpt::mongodb::frommongo(_record, _obj);
_elements << _obj;
}
if (_elements->size() == 0) {
return zpt::undefined;
}
zpt::json _return = {
"size", _size,
"elements", _elements
};
if (_page_size != 0) {
_return << "links" << zpt::json(
{
"next", (std::string("?page-size=") + std::to_string(_page_size) + std::string("&page-start-index=") + std::to_string(_page_start_index + _page_size)),
"prev", (std::string("?page-size=") + std::to_string(_page_size) + std::string("&page-start-index=") + std::to_string(_page_size < _page_start_index ? _page_start_index - _page_size : 0))
}
);
}
return _return;
}
<|endoftext|>
|
<commit_before>/*
* gnd_linalg.hpp
*
* Created on: 2012/01/22
* Author: tyamada
*/
#include "gnd-vector-base.hpp"
#include "gnd-matrix-base.hpp"
/**
* @ifnot GNDLinAlg
* @defgroup GNDLinAlg linear-algebras
* @endif GNDLinAlg
*/
namespace gnd {
/**
* @ingroup GNDLinAlg
* @namespace linalg
* supply linear-algebras
*/
namespace linalg {
/**
* @ingroup GNDLinAlg
* @brief cholesky matrix decomposition
*/
template < typename MTRX >
inline int cholesky_decomposition(MTRX *v, const size_t n)
{
gnd_assert(_gnd_matrix_row_(v) < n, -1, "invalid matrix property");
gnd_assert(_gnd_matrix_column_(v) < n, -1, "invalid matrix property");
gnd_error(n == 0, 0, "this argument have no effect");
{ // ---> operation
size_t i, j;
double l00;
gnd_error(_gnd_matrix_ref_(v, 0, 0) <= 0, -1, "general failure.");
l00 = ::sqrt(_gnd_matrix_ref_(v, 0, 0));
_gnd_matrix_ref_(v, 0, 0) = l00;
if(n > 1){
double l10 = _gnd_matrix_ref_(v, 1, 0) / l00;
double diag = _gnd_matrix_ref_(v, 1, 1) - l10 * l10;
double l11;
gnd_error(diag < 0, -1, "general failure.");
l11 = ::sqrt(diag);
_gnd_matrix_ref_(v, 1, 0) = l10;
_gnd_matrix_ref_(v, 1, 1) = l11;
}
// cholesky decomposition
for(j = 2; j < n; j++){
for(i = 0; i < j; i++){
double sum = 0;
double aji = _gnd_matrix_ref_(v, j, i);
double aii = _gnd_matrix_ref_(v, i, i);
double lji;
if(i != 0){
gnd::vector::flex di;
gnd::vector::flex dj;
gnd::vector::init(&di);
gnd::vector::init(&dj);
gnd::matrix::assign_to_as_vector(&di, v, i, 0, i);
gnd::matrix::assign_to_as_vector(&dj, v, j, 0, i);
gnd::matrix::inner_prod(&di, &dj, &sum);
}
gnd_error(aii == 0, -1, "general failure.");
lji = (aji - sum) / aii;
_gnd_matrix_ref_(v, j, i) = lji;
} // for(i)
{ // ---> diagonal
gnd::matrix::flex dj;
double sum;
double diag;
double ljj;
gnd::vector::init(&dj);
gnd::matrix::assign_to_as_vector(&dj, v, j, 0, j);
gnd::vector::sqnorm(&dj, &sum);
diag = _gnd_matrix_ref_(v, j, j) - sum;
gnd_error(diag < 0, -1, "general failure.");
ljj = ::sqrt(diag);
_gnd_matrix_ref_(v, j, j) = ljj;
} // <--- diagonal
}// for(j)
for(i = 0; i < n; i++) {
for(j = i + 1; j < n; j++) {
_gnd_matrix_ref_(v, i, j) = 0;
}
}
} // <--- operation
return 0;
}
} // <--- namespace linalg
} // <--- namespace gnd
<commit_msg>update bug fix<commit_after>/*
* gnd_linalg.hpp
*
* Created on: 2012/01/22
* Author: tyamada
*/
#include "gnd-vector-base.hpp"
#include "gnd-matrix-base.hpp"
#ifndef GND_LINALG
#define GND_LINALG
/**
* @ifnot GNDLinAlg
* @defgroup GNDLinAlg linear-algebras
* @endif GNDLinAlg
*/
namespace gnd {
/**
* @ingroup GNDLinAlg
* @namespace linalg
* supply linear-algebras
*/
namespace linalg {
/**
* @ingroup GNDLinAlg
* @brief cholesky matrix decomposition
*/
template < typename MTRX >
inline int cholesky_decomposition(MTRX *v, const size_t n)
{
gnd_assert(_gnd_matrix_row_(v) < n, -1, "invalid matrix property");
gnd_assert(_gnd_matrix_column_(v) < n, -1, "invalid matrix property");
gnd_error(n == 0, 0, "this argument have no effect");
{ // ---> operation
size_t i, j;
double l00;
gnd_error(_gnd_matrix_ref_(v, 0, 0) <= 0, -1, "general failure.");
l00 = ::sqrt(_gnd_matrix_ref_(v, 0, 0));
_gnd_matrix_ref_(v, 0, 0) = l00;
if(n > 1){
double l10 = _gnd_matrix_ref_(v, 1, 0) / l00;
double diag = _gnd_matrix_ref_(v, 1, 1) - l10 * l10;
double l11;
gnd_error(diag < 0, -1, "general failure.");
l11 = ::sqrt(diag);
_gnd_matrix_ref_(v, 1, 0) = l10;
_gnd_matrix_ref_(v, 1, 1) = l11;
}
// cholesky decomposition
for(j = 2; j < n; j++){
for(i = 0; i < j; i++){
double sum = 0;
double aji = _gnd_matrix_ref_(v, j, i);
double aii = _gnd_matrix_ref_(v, i, i);
double lji;
if(i != 0){
gnd::vector::flex di;
gnd::vector::flex dj;
gnd::vector::init(&di);
gnd::vector::init(&dj);
gnd::matrix::assign_to_as_vector(&di, v, i, 0, i);
gnd::matrix::assign_to_as_vector(&dj, v, j, 0, i);
gnd::matrix::inner_prod(&di, &dj, &sum);
}
gnd_error(aii == 0, -1, "general failure.");
lji = (aji - sum) / aii;
_gnd_matrix_ref_(v, j, i) = lji;
} // for(i)
{ // ---> diagonal
gnd::matrix::flex dj;
double sum;
double diag;
double ljj;
gnd::vector::init(&dj);
gnd::matrix::assign_to_as_vector(&dj, v, j, 0, j);
gnd::vector::sqnorm(&dj, &sum);
diag = _gnd_matrix_ref_(v, j, j) - sum;
gnd_error(diag < 0, -1, "general failure.");
ljj = ::sqrt(diag);
_gnd_matrix_ref_(v, j, j) = ljj;
} // <--- diagonal
}// for(j)
for(i = 0; i < n; i++) {
for(j = i + 1; j < n; j++) {
_gnd_matrix_ref_(v, i, j) = 0;
}
}
} // <--- operation
return 0;
}
} // <--- namespace linalg
} // <--- namespace gnd
#endif
<|endoftext|>
|
<commit_before>/*
* ComponentManager.cpp
*
* Created on: Dec 17, 2013
* Author: Dawid Drozd
*/
#include "component/ComponentManager.h"
#include "component/Component.h"
#define UNUSED_TAG -1
namespace KoalaComponent
{
ComponentManager::ComponentManager ( CCNode* pWorkingNode ,
Notifier& pNotifierNode ) :
m_pWorkingNode ( pWorkingNode )
, m_nodeNotifier ( pNotifierNode )
, m_pOwner ( nullptr )
{
m_componentTags.reserve ( 16 );
m_components.reserve ( 16 );
}
ComponentManager::~ComponentManager()
{
removeAllComponents();
m_pWorkingNode = nullptr;
}
void ComponentManager::addComponent ( Component* const pComponent )
{
addComponent ( pComponent, UNUSED_TAG );
}
void ComponentManager::addComponent ( Component* const pComponent ,
const int tag )
{
#ifdef DEBUG
for ( auto && tagAdded : m_componentTags )
{
if ( tagAdded == tag && tag != UNUSED_TAG )
{
CCAssert ( false, "You can't add component with the same tag again." );
}
}
for ( auto pElement : m_components )
{
if ( pElement == pComponent )
{
CCAssert ( false, "This component was already added" );
}
}
#endif
m_componentTags.push_back ( tag );
m_components.push_back ( pComponent );
pComponent->retain();
pComponent->setOwner ( this );
}
void ComponentManager::removeAllComponents()
{
m_componentTags.clear();
Component* pComponent = nullptr;
while ( m_components.empty() == false )
{
pComponent = m_components.back();
m_nodeNotifier.notify ( getNotificationOnBeforeRemoveFromComponentNode(), pComponent );
//We must remove all potential listeners because when we are using notifier from
//ComponentNode so we don't have to unregister in their destructors
m_nodeNotifier.removeAllForObject ( pComponent );
m_components.pop_back();
pComponent->removeOwner();
pComponent->release();
}
}
void ComponentManager::removeComponent ( const int tag )
{
CCAssert ( tag != UNUSED_TAG,
"can't delete component with this kind of tag" );
int i = 0;
for ( auto && componentTag : m_componentTags )
{
if ( componentTag == tag )
{
removeComponentAtPosition ( i );
return;
}
++i;
}
}
void ComponentManager::removeComponent ( Component* const pComponent )
{
CCAssert ( pComponent != nullptr,
"pComponent can't be null" );
int i = 0;
for ( Component* const pElement : m_components )
{
if ( pElement == pComponent )
{
removeComponentAtPosition ( i );
return;
}
++i;
}
}
Component* ComponentManager::getComponent ( int tag )
{
CCAssert ( tag != UNUSED_TAG,
"can't find component with this kind of tag" );
int i = 0;
for ( int componentTag : m_componentTags )
{
if ( componentTag == tag )
{
return m_components[i];
}
++i;
}
return nullptr;
}
void ComponentManager::removeComponentAtPosition ( const int index )
{
assert ( index < ( int ) m_components.size() );
Component* pComponent = m_components[index];
m_nodeNotifier.notify ( getNotificationOnBeforeRemoveFromComponentNode(), pComponent );
//We must remove all potential listeners because when we are using notifier from
//ComponentNode so we don't have to unregister in destructors
m_nodeNotifier.removeAllForObject ( pComponent );
std::swap ( m_components[index], m_components.back() );
std::swap ( m_componentTags[index], m_componentTags.back() );
m_components.pop_back();
m_componentTags.pop_back();
m_nodeNotifier.removeAllForObject ( pComponent );
pComponent->release();
}
void ComponentManager::setOwner ( Component* pComponentOwner )
{
assert ( m_pOwner == nullptr );
m_pOwner = pComponentOwner;
}
} /* namespace KoalaComponent */
<commit_msg>Fix for special case<commit_after>/*
* ComponentManager.cpp
*
* Created on: Dec 17, 2013
* Author: Dawid Drozd
*/
#include "component/ComponentManager.h"
#include "component/Component.h"
#define UNUSED_TAG -1
namespace KoalaComponent
{
ComponentManager::ComponentManager ( CCNode* pWorkingNode ,
Notifier& pNotifierNode ) :
m_pWorkingNode ( pWorkingNode )
, m_nodeNotifier ( pNotifierNode )
, m_pOwner ( nullptr )
{
m_componentTags.reserve ( 16 );
m_components.reserve ( 16 );
}
ComponentManager::~ComponentManager()
{
removeAllComponents();
m_pWorkingNode = nullptr;
}
void ComponentManager::addComponent ( Component* const pComponent )
{
addComponent ( pComponent, UNUSED_TAG );
}
void ComponentManager::addComponent ( Component* const pComponent ,
const int tag )
{
#ifdef DEBUG
for ( auto && tagAdded : m_componentTags )
{
if ( tagAdded == tag && tag != UNUSED_TAG )
{
CCAssert ( false, "You can't add component with the same tag again." );
}
}
for ( auto pElement : m_components )
{
if ( pElement == pComponent )
{
CCAssert ( false, "This component was already added" );
}
}
#endif
m_componentTags.push_back ( tag );
m_components.push_back ( pComponent );
pComponent->retain();
//Extra retain for case when in init we remove self
pComponent->retain();
{
pComponent->setOwner ( this );
}
pComponent->release();//Remove extra retain
}
void ComponentManager::removeAllComponents()
{
m_componentTags.clear();
Component* pComponent = nullptr;
while ( m_components.empty() == false )
{
pComponent = m_components.back();
m_nodeNotifier.notify ( getNotificationOnBeforeRemoveFromComponentNode(), pComponent );
//We must remove all potential listeners because when we are using notifier from
//ComponentNode so we don't have to unregister in their destructors
m_nodeNotifier.removeAllForObject ( pComponent );
m_components.pop_back();
pComponent->removeOwner();
pComponent->release();
}
}
void ComponentManager::removeComponent ( const int tag )
{
CCAssert ( tag != UNUSED_TAG,
"can't delete component with this kind of tag" );
int i = 0;
for ( auto && componentTag : m_componentTags )
{
if ( componentTag == tag )
{
removeComponentAtPosition ( i );
return;
}
++i;
}
}
void ComponentManager::removeComponent ( Component* const pComponent )
{
CCAssert ( pComponent != nullptr,
"pComponent can't be null" );
int i = 0;
for ( Component* const pElement : m_components )
{
if ( pElement == pComponent )
{
removeComponentAtPosition ( i );
return;
}
++i;
}
}
Component* ComponentManager::getComponent ( int tag )
{
CCAssert ( tag != UNUSED_TAG,
"can't find component with this kind of tag" );
int i = 0;
for ( int componentTag : m_componentTags )
{
if ( componentTag == tag )
{
return m_components[i];
}
++i;
}
return nullptr;
}
void ComponentManager::removeComponentAtPosition ( const int index )
{
assert ( index < ( int ) m_components.size() );
Component* pComponent = m_components[index];
m_nodeNotifier.notify ( getNotificationOnBeforeRemoveFromComponentNode(), pComponent );
//We must remove all potential listeners because when we are using notifier from
//ComponentNode so we don't have to unregister in destructors
m_nodeNotifier.removeAllForObject ( pComponent );
std::swap ( m_components[index], m_components.back() );
std::swap ( m_componentTags[index], m_componentTags.back() );
m_components.pop_back();
m_componentTags.pop_back();
m_nodeNotifier.removeAllForObject ( pComponent );
pComponent->release();
}
void ComponentManager::setOwner ( Component* pComponentOwner )
{
assert ( m_pOwner == nullptr );
m_pOwner = pComponentOwner;
}
} /* namespace KoalaComponent */
<|endoftext|>
|
<commit_before>/*
* Copyright 2004 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/base/latebindingsymboltable.h"
#if defined(WEBRTC_POSIX)
#include <dlfcn.h>
#endif
#include "webrtc/base/logging.h"
namespace rtc {
#if defined(WEBRTC_POSIX)
static const DllHandle kInvalidDllHandle = NULL;
#else
#error Not implemented
#endif
static const char *GetDllError() {
#if defined(WEBRTC_POSIX)
const char *err = dlerror();
if (err) {
return err;
} else {
return "No error";
}
#else
#error Not implemented
#endif
}
static bool LoadSymbol(DllHandle handle,
const char *symbol_name,
void **symbol) {
#if defined(WEBRTC_POSIX)
*symbol = dlsym(handle, symbol_name);
const char *err = dlerror();
if (err) {
LOG(LS_ERROR) << "Error loading symbol " << symbol_name << ": " << err;
return false;
} else if (!*symbol) {
// ELF allows for symbols to be NULL, but that should never happen for our
// usage.
LOG(LS_ERROR) << "Symbol " << symbol_name << " is NULL";
return false;
}
return true;
#else
#error Not implemented
#endif
}
LateBindingSymbolTable::LateBindingSymbolTable(const TableInfo *info,
void **table)
: info_(info),
table_(table),
handle_(kInvalidDllHandle),
undefined_symbols_(false) {
ClearSymbols();
}
LateBindingSymbolTable::~LateBindingSymbolTable() {
Unload();
}
bool LateBindingSymbolTable::IsLoaded() const {
return handle_ != kInvalidDllHandle;
}
bool LateBindingSymbolTable::Load() {
ASSERT(info_->dll_name != NULL);
return LoadFromPath(info_->dll_name);
}
bool LateBindingSymbolTable::LoadFromPath(const char *dll_path) {
if (IsLoaded()) {
return true;
}
if (undefined_symbols_) {
// We do not attempt to load again because repeated attempts are not
// likely to succeed and DLL loading is costly.
LOG(LS_ERROR) << "We know there are undefined symbols";
return false;
}
#if defined(WEBRTC_POSIX)
handle_ = dlopen(dll_path,
// RTLD_NOW front-loads symbol resolution so that errors are
// caught early instead of causing a process abort later.
// RTLD_LOCAL prevents other modules from automatically
// seeing symbol definitions in the newly-loaded tree. This
// is necessary for same-named symbols in different ABI
// versions of the same library to not explode.
RTLD_NOW|RTLD_LOCAL
#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
// RTLD_DEEPBIND makes symbol dependencies in the
// newly-loaded tree prefer to resolve to definitions within
// that tree (the default on OS X). This is necessary for
// same-named symbols in different ABI versions of the same
// library to not explode.
|RTLD_DEEPBIND
#endif
); // NOLINT
#else
#error Not implemented
#endif
if (handle_ == kInvalidDllHandle) {
LOG(LS_WARNING) << "Can't load " << dll_path << ": "
<< GetDllError();
return false;
}
#if defined(WEBRTC_POSIX)
// Clear any old errors.
dlerror();
#endif
for (int i = 0; i < info_->num_symbols; ++i) {
if (!LoadSymbol(handle_, info_->symbol_names[i], &table_[i])) {
undefined_symbols_ = true;
Unload();
return false;
}
}
return true;
}
void LateBindingSymbolTable::Unload() {
if (!IsLoaded()) {
return;
}
#if defined(WEBRTC_POSIX)
if (dlclose(handle_) != 0) {
LOG(LS_ERROR) << GetDllError();
}
#else
#error Not implemented
#endif
handle_ = kInvalidDllHandle;
ClearSymbols();
}
void LateBindingSymbolTable::ClearSymbols() {
memset(table_, 0, sizeof(void *) * info_->num_symbols);
}
} // namespace rtc
<commit_msg>Landing issue 15189004<commit_after>/*
* Copyright 2004 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/base/latebindingsymboltable.h"
#if defined(WEBRTC_POSIX)
#include <dlfcn.h>
#endif
#include "webrtc/base/logging.h"
namespace rtc {
#if defined(WEBRTC_POSIX)
static const DllHandle kInvalidDllHandle = NULL;
#else
#error Not implemented
#endif
static const char *GetDllError() {
#if defined(WEBRTC_POSIX)
const char *err = dlerror();
if (err) {
return err;
} else {
return "No error";
}
#else
#error Not implemented
#endif
}
static bool LoadSymbol(DllHandle handle,
const char *symbol_name,
void **symbol) {
#if defined(WEBRTC_POSIX)
*symbol = dlsym(handle, symbol_name);
const char *err = dlerror();
if (err) {
LOG(LS_ERROR) << "Error loading symbol " << symbol_name << ": " << err;
return false;
} else if (!*symbol) {
// ELF allows for symbols to be NULL, but that should never happen for our
// usage.
LOG(LS_ERROR) << "Symbol " << symbol_name << " is NULL";
return false;
}
return true;
#else
#error Not implemented
#endif
}
LateBindingSymbolTable::LateBindingSymbolTable(const TableInfo *info,
void **table)
: info_(info),
table_(table),
handle_(kInvalidDllHandle),
undefined_symbols_(false) {
ClearSymbols();
}
LateBindingSymbolTable::~LateBindingSymbolTable() {
Unload();
}
bool LateBindingSymbolTable::IsLoaded() const {
return handle_ != kInvalidDllHandle;
}
bool LateBindingSymbolTable::Load() {
ASSERT(info_->dll_name != NULL);
return LoadFromPath(info_->dll_name);
}
bool LateBindingSymbolTable::LoadFromPath(const char *dll_path) {
if (IsLoaded()) {
return true;
}
if (undefined_symbols_) {
// We do not attempt to load again because repeated attempts are not
// likely to succeed and DLL loading is costly.
LOG(LS_ERROR) << "We know there are undefined symbols";
return false;
}
#if defined(WEBRTC_POSIX)
handle_ = dlopen(dll_path,
// RTLD_NOW front-loads symbol resolution so that errors are
// caught early instead of causing a process abort later.
// RTLD_LOCAL prevents other modules from automatically
// seeing symbol definitions in the newly-loaded tree. This
// is necessary for same-named symbols in different ABI
// versions of the same library to not explode.
RTLD_NOW|RTLD_LOCAL
#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID) && defined(RTLD_DEEPBIND)
// RTLD_DEEPBIND makes symbol dependencies in the
// newly-loaded tree prefer to resolve to definitions within
// that tree (the default on OS X). This is necessary for
// same-named symbols in different ABI versions of the same
// library to not explode.
|RTLD_DEEPBIND
#endif
); // NOLINT
#else
#error Not implemented
#endif
if (handle_ == kInvalidDllHandle) {
LOG(LS_WARNING) << "Can't load " << dll_path << ": "
<< GetDllError();
return false;
}
#if defined(WEBRTC_POSIX)
// Clear any old errors.
dlerror();
#endif
for (int i = 0; i < info_->num_symbols; ++i) {
if (!LoadSymbol(handle_, info_->symbol_names[i], &table_[i])) {
undefined_symbols_ = true;
Unload();
return false;
}
}
return true;
}
void LateBindingSymbolTable::Unload() {
if (!IsLoaded()) {
return;
}
#if defined(WEBRTC_POSIX)
if (dlclose(handle_) != 0) {
LOG(LS_ERROR) << GetDllError();
}
#else
#error Not implemented
#endif
handle_ = kInvalidDllHandle;
ClearSymbols();
}
void LateBindingSymbolTable::ClearSymbols() {
memset(table_, 0, sizeof(void *) * info_->num_symbols);
}
} // namespace rtc
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: FmtFilter.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: tra $ $Date: 2001-03-20 09:26:01 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _FMTFILTER_HXX_
#include "FmtFilter.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
//------------------------------------------------------------------------
// namespace directives
//------------------------------------------------------------------------
using namespace com::sun::star::uno;
using rtl::OString;
//------------------------------------------------------------------------
// implementation
//------------------------------------------------------------------------
#pragma pack(2)
struct METAFILEHEADER
{
DWORD key;
short hmf;
SMALL_RECT bbox;
WORD inch;
DWORD reserved;
WORD checksum;
};
#pragma pack()
//------------------------------------------------------------------------
// convert a windows metafile picture to a openoffice metafile picture
//------------------------------------------------------------------------
Sequence< sal_Int8 > SAL_CALL WinMFPictToOOMFPict( Sequence< sal_Int8 >& aMetaFilePict )
{
OSL_ASSERT( aMetaFilePict.getLength( ) == sizeof( METAFILEPICT ) );
Sequence< sal_Int8 > mfpictStream;
METAFILEPICT* pMFPict = reinterpret_cast< METAFILEPICT* >( aMetaFilePict.getArray( ) );
HMETAFILE hMf = pMFPict->hMF;
sal_uInt32 nCount = GetMetaFileBitsEx( hMf, 0, NULL );
if ( nCount > 0 )
{
mfpictStream.realloc( nCount + sizeof( METAFILEHEADER ) );
METAFILEHEADER* pMFHeader = reinterpret_cast< METAFILEHEADER* >( mfpictStream.getArray( ) );
SMALL_RECT aRect = { 0,
0,
static_cast< short >( pMFPict->xExt ),
static_cast< short >( pMFPict->yExt ) };
USHORT nInch;
switch( pMFPict->mm )
{
case MM_TEXT:
nInch = 72;
break;
case MM_LOMETRIC:
nInch = 100;
break;
case MM_HIMETRIC:
nInch = 1000;
break;
case MM_LOENGLISH:
nInch = 254;
break;
case MM_HIENGLISH:
case MM_ISOTROPIC:
case MM_ANISOTROPIC:
nInch = 2540;
break;
case MM_TWIPS:
nInch = 1440;
break;
default:
nInch = 576;
}
pMFHeader->key = 0x9AC6CDD7L;
pMFHeader->hmf = 0;
pMFHeader->bbox = aRect;
pMFHeader->inch = nInch;
pMFHeader->reserved = 0;
pMFHeader->checksum = 0;
char* pMFBuff = reinterpret_cast< char* >( mfpictStream.getArray( ) );
nCount = GetMetaFileBitsEx( pMFPict->hMF, nCount, pMFBuff + sizeof( METAFILEHEADER ) );
OSL_ASSERT( nCount > 0 );
}
return mfpictStream;
}
//------------------------------------------------------------------------
// convert a openoffice metafile picture to a windows metafile picture
//------------------------------------------------------------------------
HMETAFILEPICT SAL_CALL OOMFPictToWinMFPict( Sequence< sal_Int8 >& aOOMetaFilePict )
{
OSL_ASSERT( aOOMetaFilePict.getLength() > 22 );
HMETAFILEPICT hPict = NULL;
HMETAFILE hMtf = SetMetaFileBitsEx( aOOMetaFilePict.getLength() - 22, (sal_uChar*) aOOMetaFilePict.getConstArray() + 22 );
if( hMtf )
{
METAFILEPICT* pPict = (METAFILEPICT*) GlobalLock( hPict = GlobalAlloc( GHND, sizeof( METAFILEPICT ) ) );
pPict->mm = 8;
pPict->xExt = 0;
pPict->yExt = 0;
pPict->hMF = hMtf;
GlobalUnlock( hPict );
}
return hPict;
}
//------------------------------------------------------------------------
// convert a windows device independent bitmap into a openoffice bitmap
//------------------------------------------------------------------------
Sequence< sal_Int8 > SAL_CALL WinDIBToOOBMP( const Sequence< sal_Int8 >& aWinDIB )
{
OSL_ASSERT( aWinDIB.getLength( ) > sizeof( BITMAPINFOHEADER ) );
Sequence< sal_Int8 > ooBmpStream;
ooBmpStream.realloc( aWinDIB.getLength( ) + sizeof(BITMAPFILEHEADER) );
const BITMAPINFOHEADER *pBmpInfoHdr = (const BITMAPINFOHEADER*)aWinDIB.getConstArray();
BITMAPFILEHEADER *pBmpFileHdr = reinterpret_cast< BITMAPFILEHEADER* >( ooBmpStream.getArray() );
DWORD nOffset = sizeof( BITMAPFILEHEADER ) + sizeof( BITMAPINFOHEADER );
rtl_copyMemory( pBmpFileHdr + 1, pBmpInfoHdr, aWinDIB.getLength( ) );
if( pBmpInfoHdr->biBitCount <= 8 )
nOffset += ( pBmpInfoHdr->biClrUsed ? pBmpInfoHdr->biClrUsed : ( 1 << pBmpInfoHdr->biBitCount ) ) << 2;
pBmpFileHdr->bfType = 'MB';
pBmpFileHdr->bfSize = 0; // maybe: nMemSize + sizeof(BITMAPFILEHEADER)
pBmpFileHdr->bfReserved1 = 0;
pBmpFileHdr->bfReserved2 = 0;
pBmpFileHdr->bfOffBits = nOffset;
return ooBmpStream;
}
//------------------------------------------------------------------------
// convert a openoffice bitmap into a windows device independent bitmap
//------------------------------------------------------------------------
Sequence< sal_Int8 > SAL_CALL OOBmpToWinDIB( Sequence< sal_Int8 >& aOOBmp )
{
OSL_ASSERT( aOOBmp.getLength( ) >
( sizeof( BITMAPFILEHEADER ) + sizeof( BITMAPINFOHEADER ) ) );
Sequence< sal_Int8 > winDIBStream( aOOBmp.getLength( ) - sizeof( BITMAPFILEHEADER ) );
rtl_copyMemory( winDIBStream.getArray( ),
aOOBmp.getArray( ) + sizeof( BITMAPFILEHEADER ),
aOOBmp.getLength( ) - sizeof( BITMAPFILEHEADER ) );
return winDIBStream;
}
//------------------------------------------------------------------------------
// converts the openoffice text/html clipboard format to the HTML Format
// well known under MS Windows
// the MS HTML Format has a header before the real html data
//
// Version:1.0 Version number of the clipboard. Staring is 0.9
// StartHTML: Byte count from the beginning of the clipboard to the start
// of the context, or -1 if no context
// EndHTML: Byte count from the beginning of the clipboard to the end
// of the context, or -1 if no context
// StartFragment: Byte count from the beginning of the clipboard to the
// start of the fragment
// EndFragment: Byte count from the beginning of the clipboard to the
// end of the fragment
// StartSelection: Byte count from the beginning of the clipboard to the
// start of the selection
// EndSelection: Byte count from the beginning of the clipboard to the
// end of the selection
//
// StartSelection and EndSelection are optional
// The fragment should be preceded and followed by the HTML comments
// <!--StartFragment--> and <!--EndFragment--> (no space between !-- and the
// text
//------------------------------------------------------------------------------
Sequence< sal_Int8 > SAL_CALL TextHtmlToHTMLFormat( Sequence< sal_Int8 >& aTextHtml )
{
OSL_ASSERT( aTextHtml.getLength( ) > 0 );
// check parameter
if ( !(aTextHtml.getLength( ) > 0) )
return Sequence< sal_Int8 >( );
// we create a buffer with the approximated size of
// the HTML Format header
char aHTMLFmtHdr[120];
rtl_zeroMemory( aHTMLFmtHdr, sizeof( aHTMLFmtHdr ) );
// fill the buffer with dummy values to calc the
// exact length
wsprintf(
aHTMLFmtHdr,
"Version:1.0\nStartHTML:%010d\nEndHTML:%010d\nStartFragment:%010d\nEndFragment:%010d\n", 0, 0, 0, 0 );
sal_uInt32 lHTMLFmtHdr = rtl_str_getLength( aHTMLFmtHdr );
OString startHtmlTag( "<HTML>" );
OString endHtmlTag( "</HTML>" );
OString startBodyTag( "<BODY>" );
OString endBodyTag( "</BODY" );
OString textHtml(
reinterpret_cast< const sal_Char* >( aTextHtml.getConstArray( ) ),
aTextHtml.getLength( ) );
sal_Int32 nStartHtml = textHtml.search( startHtmlTag );
sal_Int32 nEndHtml = textHtml.search( endHtmlTag );
sal_Int32 nStartFrgmt = textHtml.search( startBodyTag );
sal_Int32 nEndFrgmt = textHtml.search( endBodyTag );
Sequence< sal_Int8 > aHTMLFmtSequence;
if ( (nStartHtml > -1) && (nEndHtml > -1) && (nStartFrgmt > -1) && (nEndFrgmt > -1) )
{
nStartHtml = nStartHtml + lHTMLFmtHdr - 1; // we start one before <HTML> Word 2000 does also so
nEndHtml = nEndHtml + lHTMLFmtHdr + endHtmlTag.getLength( ) + 1; // our SOffice 5.2 wants 2 behind </HTML>?
nStartFrgmt = nStartFrgmt + startBodyTag.getLength( ) + lHTMLFmtHdr; // after the <BODY> tag
nEndFrgmt = nEndFrgmt + lHTMLFmtHdr;
// fill the html header
rtl_zeroMemory( aHTMLFmtHdr, sizeof( aHTMLFmtHdr ) );
wsprintf(
aHTMLFmtHdr,
"Version:1.0\nStartHTML:%010d\nEndHTML:%010d\nStartFragment:%010d\nEndFragment:%010d\n",
nStartHtml, nEndHtml, nStartFrgmt, nEndFrgmt );
// we add space for a trailing \0
aHTMLFmtSequence.realloc( lHTMLFmtHdr + aTextHtml.getLength( ) + 1 );
rtl_zeroMemory( aHTMLFmtSequence.getArray( ), aHTMLFmtSequence.getLength( ) );
// copy the HTML Format header
rtl_copyMemory(
static_cast< LPVOID >( aHTMLFmtSequence.getArray( ) ),
static_cast< LPVOID >( aHTMLFmtHdr ), lHTMLFmtHdr );
// concat the text/html
rtl_copyMemory(
static_cast< LPVOID >( aHTMLFmtSequence.getArray( ) + lHTMLFmtHdr ),
static_cast< LPVOID >( aTextHtml.getArray( ) ),
aTextHtml.getLength( ) );
}
return aHTMLFmtSequence;
}
<commit_msg>*** empty log message ***<commit_after>/*************************************************************************
*
* $RCSfile: FmtFilter.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: tra $ $Date: 2001-05-15 13:37:45 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _FMTFILTER_HXX_
#include "FmtFilter.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
//------------------------------------------------------------------------
// namespace directives
//------------------------------------------------------------------------
using namespace com::sun::star::uno;
using rtl::OString;
//------------------------------------------------------------------------
// implementation
//------------------------------------------------------------------------
#pragma pack(2)
struct METAFILEHEADER
{
DWORD key;
short hmf;
SMALL_RECT bbox;
WORD inch;
DWORD reserved;
WORD checksum;
};
#pragma pack()
//------------------------------------------------------------------------
// convert a windows metafile picture to a openoffice metafile picture
//------------------------------------------------------------------------
Sequence< sal_Int8 > SAL_CALL WinMFPictToOOMFPict( Sequence< sal_Int8 >& aMetaFilePict )
{
OSL_ASSERT( aMetaFilePict.getLength( ) == sizeof( METAFILEPICT ) );
Sequence< sal_Int8 > mfpictStream;
METAFILEPICT* pMFPict = reinterpret_cast< METAFILEPICT* >( aMetaFilePict.getArray( ) );
HMETAFILE hMf = pMFPict->hMF;
sal_uInt32 nCount = GetMetaFileBitsEx( hMf, 0, NULL );
if ( nCount > 0 )
{
mfpictStream.realloc( nCount + sizeof( METAFILEHEADER ) );
METAFILEHEADER* pMFHeader = reinterpret_cast< METAFILEHEADER* >( mfpictStream.getArray( ) );
SMALL_RECT aRect = { 0,
0,
static_cast< short >( pMFPict->xExt ),
static_cast< short >( pMFPict->yExt ) };
USHORT nInch;
switch( pMFPict->mm )
{
case MM_TEXT:
nInch = 72;
break;
case MM_LOMETRIC:
nInch = 100;
break;
case MM_HIMETRIC:
nInch = 1000;
break;
case MM_LOENGLISH:
nInch = 254;
break;
case MM_HIENGLISH:
case MM_ISOTROPIC:
case MM_ANISOTROPIC:
nInch = 2540;
break;
case MM_TWIPS:
nInch = 1440;
break;
default:
nInch = 576;
}
pMFHeader->key = 0x9AC6CDD7L;
pMFHeader->hmf = 0;
pMFHeader->bbox = aRect;
pMFHeader->inch = nInch;
pMFHeader->reserved = 0;
pMFHeader->checksum = 0;
char* pMFBuff = reinterpret_cast< char* >( mfpictStream.getArray( ) );
nCount = GetMetaFileBitsEx( pMFPict->hMF, nCount, pMFBuff + sizeof( METAFILEHEADER ) );
OSL_ASSERT( nCount > 0 );
}
return mfpictStream;
}
//------------------------------------------------------------------------
// convert a openoffice metafile picture to a windows metafile picture
//------------------------------------------------------------------------
HMETAFILEPICT SAL_CALL OOMFPictToWinMFPict( Sequence< sal_Int8 >& aOOMetaFilePict )
{
OSL_ASSERT( aOOMetaFilePict.getLength() > 22 );
HMETAFILEPICT hPict = NULL;
HMETAFILE hMtf = SetMetaFileBitsEx( aOOMetaFilePict.getLength() - 22, (sal_uChar*) aOOMetaFilePict.getConstArray() + 22 );
if( hMtf )
{
METAFILEPICT* pPict = (METAFILEPICT*) GlobalLock( hPict = GlobalAlloc( GHND, sizeof( METAFILEPICT ) ) );
pPict->mm = 8;
pPict->xExt = 0;
pPict->yExt = 0;
pPict->hMF = hMtf;
GlobalUnlock( hPict );
}
return hPict;
}
//------------------------------------------------------------------------
// convert a windows device independent bitmap into a openoffice bitmap
//------------------------------------------------------------------------
Sequence< sal_Int8 > SAL_CALL WinDIBToOOBMP( const Sequence< sal_Int8 >& aWinDIB )
{
OSL_ASSERT( aWinDIB.getLength( ) > sizeof( BITMAPINFOHEADER ) );
Sequence< sal_Int8 > ooBmpStream;
ooBmpStream.realloc( aWinDIB.getLength( ) + sizeof(BITMAPFILEHEADER) );
const BITMAPINFOHEADER *pBmpInfoHdr = (const BITMAPINFOHEADER*)aWinDIB.getConstArray();
BITMAPFILEHEADER *pBmpFileHdr = reinterpret_cast< BITMAPFILEHEADER* >( ooBmpStream.getArray() );
DWORD nOffset = sizeof( BITMAPFILEHEADER ) + sizeof( BITMAPINFOHEADER );
rtl_copyMemory( pBmpFileHdr + 1, pBmpInfoHdr, aWinDIB.getLength( ) );
if( pBmpInfoHdr->biBitCount <= 8 )
nOffset += ( pBmpInfoHdr->biClrUsed ? pBmpInfoHdr->biClrUsed : ( 1 << pBmpInfoHdr->biBitCount ) ) << 2;
pBmpFileHdr->bfType = 'MB';
pBmpFileHdr->bfSize = 0; // maybe: nMemSize + sizeof(BITMAPFILEHEADER)
pBmpFileHdr->bfReserved1 = 0;
pBmpFileHdr->bfReserved2 = 0;
pBmpFileHdr->bfOffBits = nOffset;
return ooBmpStream;
}
//------------------------------------------------------------------------
// convert a openoffice bitmap into a windows device independent bitmap
//------------------------------------------------------------------------
Sequence< sal_Int8 > SAL_CALL OOBmpToWinDIB( Sequence< sal_Int8 >& aOOBmp )
{
OSL_ASSERT( aOOBmp.getLength( ) >
( sizeof( BITMAPFILEHEADER ) + sizeof( BITMAPINFOHEADER ) ) );
Sequence< sal_Int8 > winDIBStream( aOOBmp.getLength( ) - sizeof( BITMAPFILEHEADER ) );
rtl_copyMemory( winDIBStream.getArray( ),
aOOBmp.getArray( ) + sizeof( BITMAPFILEHEADER ),
aOOBmp.getLength( ) - sizeof( BITMAPFILEHEADER ) );
return winDIBStream;
}
//------------------------------------------------------------------------------
// converts the openoffice text/html clipboard format to the HTML Format
// well known under MS Windows
// the MS HTML Format has a header before the real html data
//
// Version:1.0 Version number of the clipboard. Staring is 0.9
// StartHTML: Byte count from the beginning of the clipboard to the start
// of the context, or -1 if no context
// EndHTML: Byte count from the beginning of the clipboard to the end
// of the context, or -1 if no context
// StartFragment: Byte count from the beginning of the clipboard to the
// start of the fragment
// EndFragment: Byte count from the beginning of the clipboard to the
// end of the fragment
// StartSelection: Byte count from the beginning of the clipboard to the
// start of the selection
// EndSelection: Byte count from the beginning of the clipboard to the
// end of the selection
//
// StartSelection and EndSelection are optional
// The fragment should be preceded and followed by the HTML comments
// <!--StartFragment--> and <!--EndFragment--> (no space between !-- and the
// text
//------------------------------------------------------------------------------
Sequence< sal_Int8 > SAL_CALL TextHtmlToHTMLFormat( Sequence< sal_Int8 >& aTextHtml )
{
OSL_ASSERT( aTextHtml.getLength( ) > 0 );
// check parameter
if ( !(aTextHtml.getLength( ) > 0) )
return Sequence< sal_Int8 >( );
// we create a buffer with the approximated size of
// the HTML Format header
char aHTMLFmtHdr[120];
rtl_zeroMemory( aHTMLFmtHdr, sizeof( aHTMLFmtHdr ) );
// fill the buffer with dummy values to calc the
// exact length
wsprintf(
aHTMLFmtHdr,
"Version:1.0\nStartHTML:%010d\nEndHTML:%010d\nStartFragment:%010d\nEndFragment:%010d\n", 0, 0, 0, 0 );
sal_uInt32 lHTMLFmtHdr = rtl_str_getLength( aHTMLFmtHdr );
OString startHtmlTag( "<HTML>" );
OString endHtmlTag( "</HTML>" );
OString startBodyTag( "<BODY>" );
OString endBodyTag( "</BODY" );
OString textHtml(
reinterpret_cast< const sal_Char* >( aTextHtml.getConstArray( ) ),
aTextHtml.getLength( ) );
sal_Int32 nStartHtml = textHtml.indexOf( startHtmlTag );
sal_Int32 nEndHtml = textHtml.indexOf( endHtmlTag );
sal_Int32 nStartFrgmt = textHtml.indexOf( startBodyTag );
sal_Int32 nEndFrgmt = textHtml.indexOf( endBodyTag );
Sequence< sal_Int8 > aHTMLFmtSequence;
if ( (nStartHtml > -1) && (nEndHtml > -1) && (nStartFrgmt > -1) && (nEndFrgmt > -1) )
{
nStartHtml = nStartHtml + lHTMLFmtHdr - 1; // we start one before <HTML> Word 2000 does also so
nEndHtml = nEndHtml + lHTMLFmtHdr + endHtmlTag.getLength( ) + 1; // our SOffice 5.2 wants 2 behind </HTML>?
nStartFrgmt = nStartFrgmt + startBodyTag.getLength( ) + lHTMLFmtHdr; // after the <BODY> tag
nEndFrgmt = nEndFrgmt + lHTMLFmtHdr;
// fill the html header
rtl_zeroMemory( aHTMLFmtHdr, sizeof( aHTMLFmtHdr ) );
wsprintf(
aHTMLFmtHdr,
"Version:1.0\nStartHTML:%010d\nEndHTML:%010d\nStartFragment:%010d\nEndFragment:%010d\n",
nStartHtml, nEndHtml, nStartFrgmt, nEndFrgmt );
// we add space for a trailing \0
aHTMLFmtSequence.realloc( lHTMLFmtHdr + aTextHtml.getLength( ) + 1 );
rtl_zeroMemory( aHTMLFmtSequence.getArray( ), aHTMLFmtSequence.getLength( ) );
// copy the HTML Format header
rtl_copyMemory(
static_cast< LPVOID >( aHTMLFmtSequence.getArray( ) ),
static_cast< LPVOID >( aHTMLFmtHdr ), lHTMLFmtHdr );
// concat the text/html
rtl_copyMemory(
static_cast< LPVOID >( aHTMLFmtSequence.getArray( ) + lHTMLFmtHdr ),
static_cast< LPVOID >( aTextHtml.getArray( ) ),
aTextHtml.getLength( ) );
}
return aHTMLFmtSequence;
}
<|endoftext|>
|
<commit_before>#pragma once
/**
* The 'TimingGraph' class represents a timing graph.
*
* Logically the timing graph is a directed graph connecting Primary Inputs (nodes with no
* fan-in, e.g. circuit inputs Flip-Flop Q pins) to Primary Outputs (nodes with no fan-out,
* e.g. circuit outputs, Flip-Flop D pins), connecting through intermediate nodes (nodes with
* both fan-in and fan-out, e.g. combinational logic).
*
* To make performing the forward/backward traversals through the timing graph easier, we actually
* store all edges as bi-directional edges.
*
* NOTE: We store only the static connectivity and node information in the 'TimingGraph' class.
* Other dynamic information (edge delays, node arrival/required times) is stored seperately.
* This means that most actions opearting on the timing graph (e.g. TimingAnalyzers) only
* require read-only access to the timing graph.
*
* Accessing Graph Data
* ======================
* For performance reasons (see Implementation section for details) we store all graph data
* in the 'TimingGraph' class, and do not use separate edge/node objects. To facilitate this,
* each node and edge in the graph is given a unique identifier (e.g. NodeId, EdgeId). These
* ID's can then be used to access the required data through the appropriate member function.
*
* Implementation
* ================
* The 'TimingGraph' class represents the timing graph in a "Struct of Arrays (SoA)" manner,
* rather than the more typical "Array of Structs (AoS)" data layout.
*
* By using a SoA layout we keep all data for a particular field (e.g. node types) in contiguous
* memory. Using an AoS layout the various fields accross nodes would *not* be contiguous
* (although the different fields within each object (e.g. a TimingNode class) would be contiguous.
* Since we typically perform operations on particular fields accross nodes the SoA layout performs
* better (and enables memory ordering optimizations). The edges are also stored in a SOA format.
*
* The SoA layout also motivates the ID based approach, which allows direct indexing into the required
* vector to retrieve data.
*
* Memory Ordering Optimizations
* ===============================
* SoA also allows several additional memory layout optimizations. In particular, we know the
* order that a (serial) timing analyzer will walk the timing graph (i.e. level-by-level, from the
* start to end node in each level).
*
* Using this information we can re-arrange the node and edge data to match this traversal order.
* This greatly improves caching behaviour, since pulling in data for one node immediately pulls
* in data for the next node/edge to be processed. This exploits both spatial and temporal locality,
* and ensures that each cache line pulled into the cache will (likely) be accessed multiple times
* before being evicted.
*
* Note that performing these optimizations is currently done explicity by calling the optimize_edge_layout()
* and optimize_node_layout() member functions. In the future (particularily if incremental modification
* support is added), it may be a good idea apply these modifications automatically as needed.
*
*/
#include <vector>
#include <iosfwd>
#include "tatum_range.hpp"
#include "tatum_linear_map.hpp"
#include "timing_graph_fwd.hpp"
namespace tatum {
struct GraphIdMaps {
GraphIdMaps(tatum::util::linear_map<NodeId,NodeId> node_map,
tatum::util::linear_map<EdgeId,EdgeId> edge_map)
: node_id_map(node_map), edge_id_map(edge_map) {}
tatum::util::linear_map<NodeId,NodeId> node_id_map;
tatum::util::linear_map<EdgeId,EdgeId> edge_id_map;
};
class TimingGraph {
public: //Public types
//Iterators
typedef tatum::util::linear_map<EdgeId,EdgeId>::const_iterator edge_iterator;
typedef tatum::util::linear_map<NodeId,NodeId>::const_iterator node_iterator;
typedef tatum::util::linear_map<LevelId,LevelId>::const_iterator level_iterator;
typedef tatum::util::linear_map<LevelId,LevelId>::const_reverse_iterator reverse_level_iterator;
//Ranges
typedef tatum::util::Range<node_iterator> node_range;
typedef tatum::util::Range<edge_iterator> edge_range;
typedef tatum::util::Range<level_iterator> level_range;
typedef tatum::util::Range<reverse_level_iterator> reverse_level_range;
public: //Public accessors
/*
* Node data accessors
*/
///\param id The id of a node
///\returns The type of the node
NodeType node_type(const NodeId id) const { return node_types_[id]; }
///\param id The node id
///\returns A range of all out-going edges the node drives
edge_range node_out_edges(const NodeId id) const { return tatum::util::make_range(node_out_edges_[id].begin(), node_out_edges_[id].end()); }
///\param id The node id
///\returns A range of all in-coming edges the node drives
edge_range node_in_edges(const NodeId id) const { return tatum::util::make_range(node_in_edges_[id].begin(), node_in_edges_[id].end()); }
/*
* Edge accessors
*/
///\param id The id of an edge
///\returns The node id of the edge's sink
NodeId edge_sink_node(const EdgeId id) const { return edge_sink_nodes_[id]; }
///\param id The id of an edge
///\returns The node id of the edge's source (driver)
NodeId edge_src_node(const EdgeId id) const { return edge_src_nodes_[id]; }
/*
* Level accessors
*/
///\param level_id The level index in the graph
///\pre The graph must be levelized.
///\returns A range containing the nodes in the level
///\see levelize()
node_range level_nodes(const LevelId level_id) const { return tatum::util::make_range(level_nodes_[level_id].begin(),
level_nodes_[level_id].end()); }
///\pre The graph must be levelized.
///\returns A range containing the nodes which are primary inputs
///\see levelize()
node_range primary_inputs() const { return tatum::util::make_range(level_nodes_[LevelId(0)].begin(), level_nodes_[LevelId(0)].end()); } //After levelizing PIs will be 1st level
///\pre The graph must be levelized.
///\returns A range containing the nodes which are primary outputs
///\warning The primary outputs may be on different levels of the graph
///\see levelize()
node_range primary_outputs() const { return tatum::util::make_range(primary_outputs_.begin(), primary_outputs_.end()); }
/*
* Graph aggregate accessors
*/
//\returns A range containing all nodes in the graph
node_range nodes() const { return tatum::util::make_range(node_ids_.begin(), node_ids_.end()); }
//\returns A range containing all edges in the graph
edge_range edges() const { return tatum::util::make_range(edge_ids_.begin(), edge_ids_.end()); }
//\returns A range containing all levels in the graph
level_range levels() const { return tatum::util::make_range(level_ids_.begin(), level_ids_.end()); }
//\returns A range containing all levels in the graph in *reverse* order
reverse_level_range reversed_levels() const { return tatum::util::make_range(level_ids_.rbegin(), level_ids_.rend()); }
public: //Mutators
/*
* Graph modifiers
*/
///Adds a node to the timing graph
///\param type The type of the node to be added
///\warning Graph will likely need to be re-levelized after modification
NodeId add_node(const NodeType type);
///Adds an edge to the timing graph
///\param src_node The node id of the edge's driving node
///\param sink_node The node id of the edge's sink node
///\pre The src_node and sink_node must have been already added to the graph
///\warning Graph will likely need to be re-levelized after modification
EdgeId add_edge(const NodeId src_node, const NodeId sink_node);
void remove_node(const NodeId node_id);
void remove_edge(const EdgeId edge_id);
GraphIdMaps compress();
bool validate();
/*
* Graph-level modification operations
*/
///Levelizes the graph.
///\post The graph topologically ordered (i.e. the level of each node is known)
///\post The primary outputs have been identified
void levelize();
/*
* Memory layout optimization operations
*/
///Optimizes the memory layout of edges in the graph by re-ordering them
///for improved spatial/temporal cache locality.
///\pre The graph must be levelized
///\warning Old edge ids are invalidated
///\returns A mapping from old to new edge ids
///\see levelize()
tatum::util::linear_map<EdgeId,EdgeId> optimize_edge_layout();
///Optimizes the memory layout of nodes in the graph by re-ordering them
///for improved spatial/temporal cache locality.
///\pre The graph must be levelized
///\warning Old node ids are invalidated
///\returns A mapping from old to new node ids
///\see levelize()
tatum::util::linear_map<NodeId,NodeId> optimize_node_layout();
private: //Internal helper functions
bool valid_node_id(const NodeId node_id);
bool valid_edge_id(const EdgeId edge_id);
bool valid_level_id(const LevelId level_id);
bool validate_sizes();
bool validate_values();
private: //Data
/*
* For improved memory locality, we use a Struct of Arrays (SoA)
* data layout, rather than Array of Structs (AoS)
*/
//Node data
tatum::util::linear_map<NodeId,NodeId> node_ids_; //The node IDs in the graph
tatum::util::linear_map<NodeId,NodeType> node_types_; //Type of node [0..num_nodes()-1]
tatum::util::linear_map<NodeId,DomainId> node_clock_domains_; //Clock domain of node [0..num_nodes()-1]
tatum::util::linear_map<NodeId,std::vector<EdgeId>> node_in_edges_; //Incomiing edge IDs for node 'node_id' [0..num_nodes()-1][0..num_node_in_edges(node_id)-1]
tatum::util::linear_map<NodeId,std::vector<EdgeId>> node_out_edges_; //Out going edge IDs for node 'node_id' [0..num_nodes()-1][0..num_node_out_edges(node_id)-1]
tatum::util::linear_map<NodeId,bool> node_is_clock_source_; //Indicates if a node is the start of clock [0..num_nodes()-1]
//Edge data
tatum::util::linear_map<EdgeId,EdgeId> edge_ids_; //The edge IDs in the graph
tatum::util::linear_map<EdgeId,NodeId> edge_sink_nodes_; //Sink node for each edge [0..num_edges()-1]
tatum::util::linear_map<EdgeId,NodeId> edge_src_nodes_; //Source node for each edge [0..num_edges()-1]
//Auxilary graph-level info, filled in by levelize()
tatum::util::linear_map<LevelId,LevelId> level_ids_; //The level IDs in the graph
tatum::util::linear_map<LevelId,std::vector<NodeId>> level_nodes_; //Nodes in each level [0..num_levels()-1]
std::vector<NodeId> primary_outputs_; //Primary output nodes of the timing graph.
//NOTE: we track this separetely (unlike Primary Inputs) since these are
// scattered through the graph and do not exist on a single level
};
} //namepsace
<commit_msg>Remove unused data members<commit_after>#pragma once
/**
* The 'TimingGraph' class represents a timing graph.
*
* Logically the timing graph is a directed graph connecting Primary Inputs (nodes with no
* fan-in, e.g. circuit inputs Flip-Flop Q pins) to Primary Outputs (nodes with no fan-out,
* e.g. circuit outputs, Flip-Flop D pins), connecting through intermediate nodes (nodes with
* both fan-in and fan-out, e.g. combinational logic).
*
* To make performing the forward/backward traversals through the timing graph easier, we actually
* store all edges as bi-directional edges.
*
* NOTE: We store only the static connectivity and node information in the 'TimingGraph' class.
* Other dynamic information (edge delays, node arrival/required times) is stored seperately.
* This means that most actions opearting on the timing graph (e.g. TimingAnalyzers) only
* require read-only access to the timing graph.
*
* Accessing Graph Data
* ======================
* For performance reasons (see Implementation section for details) we store all graph data
* in the 'TimingGraph' class, and do not use separate edge/node objects. To facilitate this,
* each node and edge in the graph is given a unique identifier (e.g. NodeId, EdgeId). These
* ID's can then be used to access the required data through the appropriate member function.
*
* Implementation
* ================
* The 'TimingGraph' class represents the timing graph in a "Struct of Arrays (SoA)" manner,
* rather than the more typical "Array of Structs (AoS)" data layout.
*
* By using a SoA layout we keep all data for a particular field (e.g. node types) in contiguous
* memory. Using an AoS layout the various fields accross nodes would *not* be contiguous
* (although the different fields within each object (e.g. a TimingNode class) would be contiguous.
* Since we typically perform operations on particular fields accross nodes the SoA layout performs
* better (and enables memory ordering optimizations). The edges are also stored in a SOA format.
*
* The SoA layout also motivates the ID based approach, which allows direct indexing into the required
* vector to retrieve data.
*
* Memory Ordering Optimizations
* ===============================
* SoA also allows several additional memory layout optimizations. In particular, we know the
* order that a (serial) timing analyzer will walk the timing graph (i.e. level-by-level, from the
* start to end node in each level).
*
* Using this information we can re-arrange the node and edge data to match this traversal order.
* This greatly improves caching behaviour, since pulling in data for one node immediately pulls
* in data for the next node/edge to be processed. This exploits both spatial and temporal locality,
* and ensures that each cache line pulled into the cache will (likely) be accessed multiple times
* before being evicted.
*
* Note that performing these optimizations is currently done explicity by calling the optimize_edge_layout()
* and optimize_node_layout() member functions. In the future (particularily if incremental modification
* support is added), it may be a good idea apply these modifications automatically as needed.
*
*/
#include <vector>
#include <iosfwd>
#include "tatum_range.hpp"
#include "tatum_linear_map.hpp"
#include "timing_graph_fwd.hpp"
namespace tatum {
struct GraphIdMaps {
GraphIdMaps(tatum::util::linear_map<NodeId,NodeId> node_map,
tatum::util::linear_map<EdgeId,EdgeId> edge_map)
: node_id_map(node_map), edge_id_map(edge_map) {}
tatum::util::linear_map<NodeId,NodeId> node_id_map;
tatum::util::linear_map<EdgeId,EdgeId> edge_id_map;
};
class TimingGraph {
public: //Public types
//Iterators
typedef tatum::util::linear_map<EdgeId,EdgeId>::const_iterator edge_iterator;
typedef tatum::util::linear_map<NodeId,NodeId>::const_iterator node_iterator;
typedef tatum::util::linear_map<LevelId,LevelId>::const_iterator level_iterator;
typedef tatum::util::linear_map<LevelId,LevelId>::const_reverse_iterator reverse_level_iterator;
//Ranges
typedef tatum::util::Range<node_iterator> node_range;
typedef tatum::util::Range<edge_iterator> edge_range;
typedef tatum::util::Range<level_iterator> level_range;
typedef tatum::util::Range<reverse_level_iterator> reverse_level_range;
public: //Public accessors
/*
* Node data accessors
*/
///\param id The id of a node
///\returns The type of the node
NodeType node_type(const NodeId id) const { return node_types_[id]; }
///\param id The node id
///\returns A range of all out-going edges the node drives
edge_range node_out_edges(const NodeId id) const { return tatum::util::make_range(node_out_edges_[id].begin(), node_out_edges_[id].end()); }
///\param id The node id
///\returns A range of all in-coming edges the node drives
edge_range node_in_edges(const NodeId id) const { return tatum::util::make_range(node_in_edges_[id].begin(), node_in_edges_[id].end()); }
/*
* Edge accessors
*/
///\param id The id of an edge
///\returns The node id of the edge's sink
NodeId edge_sink_node(const EdgeId id) const { return edge_sink_nodes_[id]; }
///\param id The id of an edge
///\returns The node id of the edge's source (driver)
NodeId edge_src_node(const EdgeId id) const { return edge_src_nodes_[id]; }
/*
* Level accessors
*/
///\param level_id The level index in the graph
///\pre The graph must be levelized.
///\returns A range containing the nodes in the level
///\see levelize()
node_range level_nodes(const LevelId level_id) const { return tatum::util::make_range(level_nodes_[level_id].begin(),
level_nodes_[level_id].end()); }
///\pre The graph must be levelized.
///\returns A range containing the nodes which are primary inputs
///\see levelize()
node_range primary_inputs() const { return tatum::util::make_range(level_nodes_[LevelId(0)].begin(), level_nodes_[LevelId(0)].end()); } //After levelizing PIs will be 1st level
///\pre The graph must be levelized.
///\returns A range containing the nodes which are primary outputs
///\warning The primary outputs may be on different levels of the graph
///\see levelize()
node_range primary_outputs() const { return tatum::util::make_range(primary_outputs_.begin(), primary_outputs_.end()); }
/*
* Graph aggregate accessors
*/
//\returns A range containing all nodes in the graph
node_range nodes() const { return tatum::util::make_range(node_ids_.begin(), node_ids_.end()); }
//\returns A range containing all edges in the graph
edge_range edges() const { return tatum::util::make_range(edge_ids_.begin(), edge_ids_.end()); }
//\returns A range containing all levels in the graph
level_range levels() const { return tatum::util::make_range(level_ids_.begin(), level_ids_.end()); }
//\returns A range containing all levels in the graph in *reverse* order
reverse_level_range reversed_levels() const { return tatum::util::make_range(level_ids_.rbegin(), level_ids_.rend()); }
public: //Mutators
/*
* Graph modifiers
*/
///Adds a node to the timing graph
///\param type The type of the node to be added
///\warning Graph will likely need to be re-levelized after modification
NodeId add_node(const NodeType type);
///Adds an edge to the timing graph
///\param src_node The node id of the edge's driving node
///\param sink_node The node id of the edge's sink node
///\pre The src_node and sink_node must have been already added to the graph
///\warning Graph will likely need to be re-levelized after modification
EdgeId add_edge(const NodeId src_node, const NodeId sink_node);
void remove_node(const NodeId node_id);
void remove_edge(const EdgeId edge_id);
GraphIdMaps compress();
bool validate();
/*
* Graph-level modification operations
*/
///Levelizes the graph.
///\post The graph topologically ordered (i.e. the level of each node is known)
///\post The primary outputs have been identified
void levelize();
/*
* Memory layout optimization operations
*/
///Optimizes the memory layout of edges in the graph by re-ordering them
///for improved spatial/temporal cache locality.
///\pre The graph must be levelized
///\warning Old edge ids are invalidated
///\returns A mapping from old to new edge ids
///\see levelize()
tatum::util::linear_map<EdgeId,EdgeId> optimize_edge_layout();
///Optimizes the memory layout of nodes in the graph by re-ordering them
///for improved spatial/temporal cache locality.
///\pre The graph must be levelized
///\warning Old node ids are invalidated
///\returns A mapping from old to new node ids
///\see levelize()
tatum::util::linear_map<NodeId,NodeId> optimize_node_layout();
private: //Internal helper functions
bool valid_node_id(const NodeId node_id);
bool valid_edge_id(const EdgeId edge_id);
bool valid_level_id(const LevelId level_id);
bool validate_sizes();
bool validate_values();
private: //Data
/*
* For improved memory locality, we use a Struct of Arrays (SoA)
* data layout, rather than Array of Structs (AoS)
*/
//Node data
tatum::util::linear_map<NodeId,NodeId> node_ids_; //The node IDs in the graph
tatum::util::linear_map<NodeId,NodeType> node_types_; //Type of node [0..num_nodes()-1]
tatum::util::linear_map<NodeId,std::vector<EdgeId>> node_in_edges_; //Incomiing edge IDs for node 'node_id' [0..num_nodes()-1][0..num_node_in_edges(node_id)-1]
tatum::util::linear_map<NodeId,std::vector<EdgeId>> node_out_edges_; //Out going edge IDs for node 'node_id' [0..num_nodes()-1][0..num_node_out_edges(node_id)-1]
//Edge data
tatum::util::linear_map<EdgeId,EdgeId> edge_ids_; //The edge IDs in the graph
tatum::util::linear_map<EdgeId,NodeId> edge_sink_nodes_; //Sink node for each edge [0..num_edges()-1]
tatum::util::linear_map<EdgeId,NodeId> edge_src_nodes_; //Source node for each edge [0..num_edges()-1]
//Auxilary graph-level info, filled in by levelize()
tatum::util::linear_map<LevelId,LevelId> level_ids_; //The level IDs in the graph
tatum::util::linear_map<LevelId,std::vector<NodeId>> level_nodes_; //Nodes in each level [0..num_levels()-1]
std::vector<NodeId> primary_outputs_; //Primary output nodes of the timing graph.
//NOTE: we track this separetely (unlike Primary Inputs) since these are
// scattered through the graph and do not exist on a single level
};
} //namepsace
<|endoftext|>
|
<commit_before>/**
* @file heisenberg.cpp
* @brief The main c++ file for the DMRG
*
*
* @author Roger Melko
* @author Ivan Gonzalez
* @date $Date$
*
* $Revision$
*
* Elementary DMRG simulation for the Heisenberg chain;
* \f$H= \sum_{ij} (S^x_i S^x_j + S^y_i S^y_j + S^z_i S^z_j ) \f$
*
* <ul>
* <li> Begins with the "symmetric" infinite system algorithm to build
* up the chain
* <li> After this, a number of finite system algorithm sweeps are performed
* <li> The exact diagonalization performed with Lanczos
* <li> The output is the energy as a function of sweep
* <li> The code uses Blitz++ to handle tensors and matrices: see http://www.oonumerics.org/blitz/
* </ul>
*/
#include "blitz/array.h"
#include "block.h"
#include "matrixManipulation.h"
#include "lanczosDMRG.h"
#include "densityMatrix.h"
#include "main_helpers.h"
int main()
{
// Read some input from user
int numberOfHalfSweeps;
int numberOfSites;
int m;
std::cout<<"Enter the number states to keep: ";
std::cin>>m;
std::cout<<"Enter the number of sites in the chain: ";
std::cin>>numberOfSites;
std::cout<<"Enter the number of FSA sweeps : ";
std::cin>>numberOfHalfSweeps;
Block system; //create the system block
Block environ; //create the environment block
//Below we declare the Blitz++ matrices used by the program
blitz::Array<double,4> TSR(2,2,2,2); //tensor product for Hab hamiltonian
blitz::Array<double,4> Habcd(4,4,4,4); // superblock hamiltonian
blitz::Array<double,2> Psi(4,4); // ground state wavefunction
blitz::Array<double,2> reducedDM(4,4); // reduced density matrix
blitz::Array<double,2> OO(m,4); // the truncation matrix
blitz::Array<double,2> OT(4,m); // transposed truncation matrix
blitz::Array<double,2> HAp; //A' block hamiltonian
blitz::Array<double,2> SzB; //Sz(left) operator
blitz::Array<double,2> SmB; //Sm(left) operator
blitz::Array<double,2> SpB; //Sp(left) operator
// create the pauli matrices and the 2x2 identity matrix
blitz::Array<double,2> sigma_z(2,2), sigma_p(2,2), sigma_m(2,2);
sigma_z = 0.5, 0,
0, -0.5;
sigma_p = 0, 1.0,
0, 0;
sigma_m = 0, 0,
1.0, 0;
blitz::Array<double,2> I2=createIdentityMatrix(2);
// declare tensor indices according to Blitz++ convention
blitz::firstIndex i; blitz::secondIndex j;
blitz::thirdIndex k; blitz::fourthIndex l;
// build the Hamiltonian for two-sites only
TSR = sigma_z(i,k)*sigma_z(j,l)+ 0.5*sigma_p(i,k)*sigma_m(j,l) +
0.5*sigma_m(i,k)*sigma_p(j,l);
system.blockH.resize(4,4);
system.blockH = reduceM2M2(TSR);
TSR = sigma_z(i,k)*I2(j,l);
blitz::Array<double,2> SzAB = reduceM2M2(TSR);
TSR = sigma_m(i,k)*I2(j,l);
blitz::Array<double,2> SmAB = reduceM2M2(TSR);
TSR = sigma_p(i,k)*I2(j,l);
blitz::Array<double,2> SpAB = reduceM2M2(TSR);
// done building the Hamiltonian
/**
* Infinite system algorithm: build the Hamiltonian from 2 to N-sites
*/
int statesToKeep=2; //start with a 2^2=4 state system
int sitesInSystem=2; //# sites (SYSTEM)
blitz::Array<double,2> I2st=createIdentityMatrix(4);
while (sitesInSystem <= (numberOfSites)/2 )
{
Habcd = system.blockH(i,k)*I2st(j,l)+
I2st(i,k)*system.blockH(j,l)+
SzAB(i,k)*SzAB(j,l)+0.5*SpAB(i,k)*SmAB(j,l)+0.5*SmAB(i,k)*SpAB(j,l);
double groundStateEnergy=calculateGroundState(Habcd, Psi);
printGroundStateEnergy(sitesInSystem, sitesInSystem, groundStateEnergy);
statesToKeep= (2*statesToKeep<=m)? 2*statesToKeep : m;
// calculate the reduced density matrix and truncate
reducedDM=calculateReducedDensityMatrix(Psi);
OO.resize(statesToKeep,reducedDM.rows()); //resize transf. matrix
OT.resize(reducedDM.rows(),statesToKeep); // and its inverse
OO=truncateReducedDM(reducedDM, statesToKeep); //get transf. matrix
OT=OO.transpose(blitz::secondDim, blitz::firstDim); //and its inverse
//transform the operators to new basis
HAp.resize(statesToKeep, statesToKeep);
SzB.resize(statesToKeep, statesToKeep);
SpB.resize(statesToKeep, statesToKeep);
SmB.resize(statesToKeep, statesToKeep);
HAp=transformOperator(system.blockH, OT, OO);
SzB=transformOperator(SzAB, OT, OO);
SpB=transformOperator(SpAB, OT, OO);
SmB=transformOperator(SmAB, OT, OO);
//Hamiltonian for next iteration
TSR.resize(statesToKeep,2,statesToKeep,2);
TSR = HAp(i,k)*I2(j,l) + SzB(i,k)*sigma_z(j,l)+
0.5*SpB(i,k)*sigma_m(j,l) + 0.5*SmB(i,k)*sigma_p(j,l) ;
system.blockH.resize(2*statesToKeep,2*statesToKeep);
system.blockH = reduceM2M2(TSR);
int statesToKeepNext= (2*statesToKeep<=m)? 4*statesToKeep : 2*m;
//redefine identity matrix
I2st.resize(statesToKeepNext, statesToKeepNext);
I2st = createIdentityMatrix(statesToKeepNext);
//Operators for next iteration
SzAB.resize(2*statesToKeep,2*statesToKeep);
TSR = I2st(i,k)*sigma_z(j,l);
SzAB = reduceM2M2(TSR);
SpAB.resize(2*statesToKeep,2*statesToKeep);
TSR = I2st(i,k)*sigma_p(j,l);
SpAB = reduceM2M2(TSR);
SmAB.resize(2*statesToKeep,2*statesToKeep);
TSR = I2st(i,k)*sigma_m(j,l);
SmAB = reduceM2M2(TSR);
Habcd.resize(2*statesToKeep,2*statesToKeep,2*statesToKeep,2*statesToKeep); //re-prepare superblock matrix
Psi.resize(2*statesToKeep,2*statesToKeep); //GS wavefunction
reducedDM.resize(2*statesToKeep,2*statesToKeep);
sitesInSystem++;
system.size = sitesInSystem; //this is the size of the system block
system.ISAwrite(sitesInSystem);
}//end INFINITE SYSTEM ALGORITHM
std::cout<<"End of the infinite system algorithm\n";
/**
* Finite size algorithm
*/
{
// find minimum size of the enviroment
int minEnviromentSize=calculateMinEnviromentSize(m,numberOfSites);
// start in the middle of the chain
int sitesInSystem = numberOfSites/2;
system.FSAread(sitesInSystem,1);
for (int halfSweep=0; halfSweep<numberOfHalfSweeps; halfSweep++)
{
while (sitesInSystem <= numberOfSites-minEnviromentSize)
{
int sitesInEnviroment = numberOfSites - sitesInSystem;
// read the environment block from disk
environ.FSAread(sitesInEnviroment,halfSweep);
// build the hamiltonian as a four-index tensor
Habcd = environ.blockH(i,k)*I2st(j,l)+
I2st(i,k)*system.blockH(j,l)+
SzAB(i,k)*SzAB(j,l)+
0.5*SpAB(i,k)*SmAB(j,l)+0.5*SmAB(i,k)*SpAB(j,l);
// calculate the ground state energy
double groundStateEnergy=calculateGroundState(Habcd, Psi);
if (halfSweep%2 == 0)
printGroundStateEnergy(sitesInSystem, sitesInEnviroment,
groundStateEnergy);
else
printGroundStateEnergy(sitesInEnviroment, sitesInSystem,
groundStateEnergy);
// calculate the reduced density matrix and truncate
reducedDM=calculateReducedDensityMatrix(Psi);
blitz::Array<double,2> OO=truncateReducedDM(reducedDM, m);
OT=OO.transpose(blitz::secondDim, blitz::firstDim);
// transform the operators to new basis
HAp=transformOperator(system.blockH, OT, OO);
SzB=transformOperator(SzAB, OT, OO);
SpB=transformOperator(SpAB, OT, OO);
SmB=transformOperator(SmAB, OT, OO);
// add spin to the system block only
TSR = HAp(i,k)*I2(j,l) + SzB(i,k)*sigma_z(j,l)+
0.5*SpB(i,k)*sigma_m(j,l) + 0.5*SmB(i,k)*sigma_p(j,l);
system.blockH = reduceM2M2(TSR);
sitesInSystem++;
system.size = sitesInSystem;
system.FSAwrite(sitesInSystem,halfSweep);
}// while
sitesInSystem = minEnviromentSize;
system.FSAread(sitesInSystem,halfSweep);
}// for
} // end of the finite size algorithm
return 0;
} // end main
<commit_msg>More cleaning.<commit_after>/**
* @file heisenberg.cpp
* @brief The main c++ file for the DMRG
*
*
* @author Roger Melko
* @author Ivan Gonzalez
* @date $Date$
*
* $Revision$
*
* Elementary DMRG simulation for the Heisenberg chain;
* \f$H= \sum_{ij} (S^x_i S^x_j + S^y_i S^y_j + S^z_i S^z_j ) \f$
*
* <ul>
* <li> Begins with the "symmetric" infinite system algorithm to build
* up the chain
* <li> After this, a number of finite system algorithm sweeps are performed
* <li> The exact diagonalization performed with Lanczos
* <li> The output is the energy as a function of sweep
* <li> The code uses Blitz++ to handle tensors and matrices: see http://www.oonumerics.org/blitz/
* </ul>
*/
#include "blitz/array.h"
#include "block.h"
#include "matrixManipulation.h"
#include "lanczosDMRG.h"
#include "densityMatrix.h"
#include "main_helpers.h"
int main()
{
// Read some input from user
int numberOfHalfSweeps;
int numberOfSites;
int m;
std::cout<<"Enter the number states to keep: ";
std::cin>>m;
std::cout<<"Enter the number of sites in the chain: ";
std::cin>>numberOfSites;
std::cout<<"Enter the number of FSA sweeps : ";
std::cin>>numberOfHalfSweeps;
Block system; //create the system block
Block environ; //create the environment block
//Below we declare the Blitz++ matrices used by the program
blitz::Array<double,4> TSR(2,2,2,2); //tensor product for Hab hamiltonian
blitz::Array<double,4> Habcd(4,4,4,4); // superblock hamiltonian
blitz::Array<double,2> Psi(4,4); // ground state wavefunction
blitz::Array<double,2> reducedDM(4,4); // reduced density matrix
blitz::Array<double,2> OO(m,4); // the truncation matrix
blitz::Array<double,2> OT(4,m); // transposed truncation matrix
blitz::Array<double,2> HAp; //A' block hamiltonian
blitz::Array<double,2> SzB; //Sz(left) operator
blitz::Array<double,2> SmB; //Sm(left) operator
blitz::Array<double,2> SpB; //Sp(left) operator
// create the pauli matrices and the 2x2 identity matrix
blitz::Array<double,2> sigma_z(2,2), sigma_p(2,2), sigma_m(2,2);
sigma_z = 0.5, 0,
0, -0.5;
sigma_p = 0, 1.0,
0, 0;
sigma_m = 0, 0,
1.0, 0;
blitz::Array<double,2> I2=createIdentityMatrix(2);
// declare tensor indices according to Blitz++ convention
blitz::firstIndex i; blitz::secondIndex j;
blitz::thirdIndex k; blitz::fourthIndex l;
// build the Hamiltonian for two-sites only
TSR = sigma_z(i,k)*sigma_z(j,l)+ 0.5*sigma_p(i,k)*sigma_m(j,l) +
0.5*sigma_m(i,k)*sigma_p(j,l);
system.blockH.resize(4,4);
system.blockH = reduceM2M2(TSR);
TSR = sigma_z(i,k)*I2(j,l);
blitz::Array<double,2> S_z = reduceM2M2(TSR);
TSR = sigma_m(i,k)*I2(j,l);
blitz::Array<double,2> S_m = reduceM2M2(TSR);
TSR = sigma_p(i,k)*I2(j,l);
blitz::Array<double,2> S_p = reduceM2M2(TSR);
// done building the Hamiltonian
/**
* Infinite system algorithm: build the Hamiltonian from 2 to N-sites
*/
int statesToKeep=2; //start with a 2^2=4 state system
int sitesInSystem=2; //# sites in the system block
blitz::Array<double,2> I2st=createIdentityMatrix(4);
while (sitesInSystem <= (numberOfSites)/2 )
{
// build the hamiltonian as a four-index tensor
Habcd = system.blockH(i,k)*I2st(j,l)+
I2st(i,k)*system.blockH(j,l)+
S_z(i,k)*S_z(j,l)+0.5*S_p(i,k)*S_m(j,l)+0.5*S_m(i,k)*S_p(j,l);
// calculate the ground state energy
double groundStateEnergy=calculateGroundState(Habcd, Psi);
printGroundStateEnergy(sitesInSystem, sitesInSystem, groundStateEnergy);
// increase the number of states if you are not at m yet
statesToKeep= (2*statesToKeep<=m)? 2*statesToKeep : m;
// calculate the reduced density matrix and truncate
reducedDM=calculateReducedDensityMatrix(Psi);
OO.resize(statesToKeep,reducedDM.rows()); //resize transf. matrix
OT.resize(reducedDM.rows(),statesToKeep); // and its inverse
OO=truncateReducedDM(reducedDM, statesToKeep); //get transf. matrix
OT=OO.transpose(blitz::secondDim, blitz::firstDim); //and its inverse
//transform the operators to new basis
HAp.resize(statesToKeep, statesToKeep);
SzB.resize(statesToKeep, statesToKeep);
SpB.resize(statesToKeep, statesToKeep);
SmB.resize(statesToKeep, statesToKeep);
HAp=transformOperator(system.blockH, OT, OO);
SzB=transformOperator(S_z, OT, OO);
SpB=transformOperator(S_p, OT, OO);
SmB=transformOperator(S_m, OT, OO);
//Hamiltonian for next iteration
TSR.resize(statesToKeep,2,statesToKeep,2);
TSR = HAp(i,k)*I2(j,l) + SzB(i,k)*sigma_z(j,l)+
0.5*SpB(i,k)*sigma_m(j,l) + 0.5*SmB(i,k)*sigma_p(j,l) ;
system.blockH.resize(2*statesToKeep,2*statesToKeep);
system.blockH = reduceM2M2(TSR);
//redefine identity matrix
int statesToKeepNext= (2*statesToKeep<=m)? 4*statesToKeep : 2*m;
I2st.resize(statesToKeepNext, statesToKeepNext);
I2st = createIdentityMatrix(statesToKeepNext);
//redefine the operators for next iteration
S_z.resize(2*statesToKeep,2*statesToKeep);
TSR = I2st(i,k)*sigma_z(j,l);
S_z = reduceM2M2(TSR);
S_p.resize(2*statesToKeep,2*statesToKeep);
TSR = I2st(i,k)*sigma_p(j,l);
S_p = reduceM2M2(TSR);
S_m.resize(2*statesToKeep,2*statesToKeep);
TSR = I2st(i,k)*sigma_m(j,l);
S_m = reduceM2M2(TSR);
// re-prepare superblock matrix, wavefunction and reduced DM
Habcd.resize(2*statesToKeep,2*statesToKeep,2*statesToKeep,2*statesToKeep);
Psi.resize(2*statesToKeep,2*statesToKeep);
reducedDM.resize(2*statesToKeep,2*statesToKeep);
// make the system one site larger and save it
system.size = ++sitesInSystem;
system.ISAwrite(sitesInSystem);
}//end INFINITE SYSTEM ALGORITHM
std::cout<<"End of the infinite system algorithm\n";
/**
* Finite size algorithm
*/
{
// find minimum size of the enviroment
int minEnviromentSize=calculateMinEnviromentSize(m,numberOfSites);
// start in the middle of the chain
int sitesInSystem = numberOfSites/2;
system.FSAread(sitesInSystem,1);
for (int halfSweep=0; halfSweep<numberOfHalfSweeps; halfSweep++)
{
while (sitesInSystem <= numberOfSites-minEnviromentSize)
{
int sitesInEnviroment = numberOfSites - sitesInSystem;
// read the environment block from disk
environ.FSAread(sitesInEnviroment,halfSweep);
// build the hamiltonian as a four-index tensor
Habcd = environ.blockH(i,k)*I2st(j,l)+
I2st(i,k)*system.blockH(j,l)+
S_z(i,k)*S_z(j,l)+
0.5*S_p(i,k)*S_m(j,l)+0.5*S_m(i,k)*S_p(j,l);
// calculate the ground state energy
double groundStateEnergy=calculateGroundState(Habcd, Psi);
if (halfSweep%2 == 0)
printGroundStateEnergy(sitesInSystem, sitesInEnviroment,
groundStateEnergy);
else
printGroundStateEnergy(sitesInEnviroment, sitesInSystem,
groundStateEnergy);
// calculate the reduced density matrix and truncate
reducedDM=calculateReducedDensityMatrix(Psi);
blitz::Array<double,2> OO=truncateReducedDM(reducedDM, m);
OT=OO.transpose(blitz::secondDim, blitz::firstDim);
// transform the operators to new basis
HAp=transformOperator(system.blockH, OT, OO);
SzB=transformOperator(S_z, OT, OO);
SpB=transformOperator(S_p, OT, OO);
SmB=transformOperator(S_m, OT, OO);
// add spin to the system block only
TSR = HAp(i,k)*I2(j,l) + SzB(i,k)*sigma_z(j,l)+
0.5*SpB(i,k)*sigma_m(j,l) + 0.5*SmB(i,k)*sigma_p(j,l);
system.blockH = reduceM2M2(TSR);
sitesInSystem++;
system.size = sitesInSystem;
system.FSAwrite(sitesInSystem,halfSweep);
}// while
sitesInSystem = minEnviromentSize;
system.FSAread(sitesInSystem,halfSweep);
}// for
} // end of the finite size algorithm
return 0;
} // end main
<|endoftext|>
|
<commit_before>/* -*-c++-*- Present3D - Copyright (C) 1999-2006 Robert Osfield
*
* This software is open source and may be redistributed and/or modified under
* the terms of the GNU General Public License (GPL) version 2.0.
* The full license is in LICENSE.txt file included with this distribution,.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* include LICENSE.txt for more details.
*/
#include <osgViewer/Viewer>
#include "JoystickDevice.h"
#include <SDL.h>
#include <SDL_events.h>
#include <SDL_joystick.h>
#include <iostream>
JoystickDevice::JoystickDevice()
{
_verbose = false;
// init SDL
if ( SDL_Init(SDL_INIT_JOYSTICK) < 0 )
{
fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
exit(1);
}
atexit(SDL_Quit);
int numJoysticks = SDL_NumJoysticks();
if (_verbose)
{
std::cout<<"number of joysticks "<<numJoysticks<<std::endl;
for(int i=0; i<numJoysticks; ++i)
{
std::cout<<"Joystick name '"<<SDL_JoystickName(i)<<"'"<<std::endl;
}
}
_joystick = numJoysticks>0 ? SDL_JoystickOpen(0) : 0;
_numAxes = _joystick ? SDL_JoystickNumAxes(_joystick) : 0;
_numBalls = _joystick ? SDL_JoystickNumBalls(_joystick) : 0;
_numHats = _joystick ? SDL_JoystickNumHats(_joystick) : 0;
_numButtons = _joystick ? SDL_JoystickNumButtons(_joystick) : 0;
if (_verbose)
{
std::cout<<"numAxes = "<<_numAxes<<std::endl;
std::cout<<"numBalls = "<<_numBalls<<std::endl;
std::cout<<"numHats = "<<_numHats<<std::endl;
std::cout<<"numButtons = "<<_numButtons<<std::endl;
}
addMouseButtonMapping(4, 1); // left
addMouseButtonMapping(5, 3); // right
addMouseButtonMapping(6, 2); // middle
addKeyMapping(10, ' '); // R2
addKeyMapping(0, '1'); // 1
addKeyMapping(1, '2'); // 2
addKeyMapping(2, '3'); // 3
addKeyMapping(4, '4'); // 4
addKeyMapping(7, ' '); // home
addKeyMapping(8, osgGA::GUIEventAdapter::KEY_Page_Up); // Start
addKeyMapping(9, osgGA::GUIEventAdapter::KEY_Page_Down); // Start
addKeyMapping(10, osgGA::GUIEventAdapter::KEY_Home); // Start
capture(_axisValues, _buttonValues);
}
JoystickDevice::~JoystickDevice()
{
}
void JoystickDevice::capture(ValueList& axisValues, ValueList& buttonValues) const
{
if (_joystick)
{
SDL_JoystickUpdate();
axisValues.resize(_numAxes);
for(int ai=0; ai<_numAxes; ++ai)
{
axisValues[ai] = SDL_JoystickGetAxis(_joystick, ai);
}
buttonValues.resize(_numButtons);
for(int bi=0; bi<_numButtons; ++bi)
{
buttonValues[bi] = SDL_JoystickGetButton(_joystick, bi);
}
}
}
bool JoystickDevice::checkEvents()
{
if (_joystick)
{
OSG_NOTICE<<"JoystickDevice::checkEvents()"<<std::endl;
ValueList newAxisValues;
ValueList newButtonValues;
capture(newAxisValues, newButtonValues);
unsigned int mouseXaxis = 0;
unsigned int mouseYaxis = 1;
float prev_mx = (float)_axisValues[mouseXaxis]/32767.0f;
float prev_my = -(float)_axisValues[mouseYaxis]/32767.0f;
float mx = (float)newAxisValues[mouseXaxis]/32767.0f;
float my = -(float)newAxisValues[mouseYaxis]/32767.0f;
osgGA::EventQueue* eq = getEventQueue();
double time = eq ? eq->getTime() : 0.0;
osgGA::GUIEventAdapter* previous_event = eq->getCurrentEventState();
float projected_mx = previous_event->getXmin() + (mx+1.0)*0.5*(previous_event->getXmax()-previous_event->getXmin());
float projected_my = previous_event->getYmin() + (my+1.0)*0.5*(previous_event->getYmax()-previous_event->getYmin());
if (mx!=prev_mx || my!=prev_my)
{
eq->mouseMotion(projected_mx, projected_my, time);
}
OSG_NOTICE<<"mx="<<mx<<", my="<<my<<", projected_mx="<<projected_mx<<", projected_my="<<projected_my<<std::endl;
if (_verbose)
{
for(int ai=0; ai<_numAxes; ++ai)
{
if (newAxisValues[ai]!=_axisValues[ai])
{
std::cout<<"axis "<<ai<<" moved to "<<newAxisValues[ai]<<std::endl;
}
}
}
for(int bi=0; bi<_numButtons; ++bi)
{
if (newButtonValues[bi]!=_buttonValues[bi])
{
if (_verbose)
{
std::cout<<"button "<<bi<<" changed to "<<newButtonValues[bi]<<std::endl;
}
int key = getKeyMapping(bi);
int mouseButton = getMouseButtonMapping(bi);
if (mouseButton>0)
{
if (newButtonValues[bi]==0) eq->mouseButtonRelease(projected_mx,projected_my,mouseButton,time);
else eq->mouseButtonPress(projected_mx,projected_my,mouseButton,time);
}
else if (key>0)
{
if (newButtonValues[bi]==0) eq->keyRelease(key,time);
else eq->keyPress(key,time);
}
}
}
_axisValues.swap(newAxisValues);
_buttonValues.swap(newButtonValues);
}
return !(getEventQueue()->empty());
}
<commit_msg>From Laurens Voerman, "The current version will not compile with SDL version 2, error OpenSceneGraph\src\osgPlugins\sdl\JoystickDevice.cpp(42): error C2664: 'const char *SDL_JoystickName(SDL_Joystick *)' : cannot convert argument 1 from 'int' to 'SDL_Joystick *' due to changes in the SDL api.<commit_after>/* -*-c++-*- Present3D - Copyright (C) 1999-2006 Robert Osfield
*
* This software is open source and may be redistributed and/or modified under
* the terms of the GNU General Public License (GPL) version 2.0.
* The full license is in LICENSE.txt file included with this distribution,.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* include LICENSE.txt for more details.
*/
#include <osgViewer/Viewer>
#include "JoystickDevice.h"
#include <SDL.h>
#include <SDL_events.h>
#include <SDL_joystick.h>
#include <iostream>
JoystickDevice::JoystickDevice()
{
_verbose = false;
// init SDL
if ( SDL_Init(SDL_INIT_JOYSTICK) < 0 )
{
fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
exit(1);
}
atexit(SDL_Quit);
int numJoysticks = SDL_NumJoysticks();
if (_verbose)
{
std::cout<<"number of joysticks "<<numJoysticks<<std::endl;
for(int i=0; i<numJoysticks; ++i)
{
#if SDL_VERSION_ATLEAST(2, 0, 0)
std::cout << "Joystick name '" << SDL_JoystickNameForIndex(i) << "'" << std::endl;
#else
std::cout << "Joystick name '" << SDL_JoystickName(i) << "'" << std::endl;
#endif
}
}
_joystick = numJoysticks>0 ? SDL_JoystickOpen(0) : 0;
_numAxes = _joystick ? SDL_JoystickNumAxes(_joystick) : 0;
_numBalls = _joystick ? SDL_JoystickNumBalls(_joystick) : 0;
_numHats = _joystick ? SDL_JoystickNumHats(_joystick) : 0;
_numButtons = _joystick ? SDL_JoystickNumButtons(_joystick) : 0;
if (_verbose)
{
std::cout<<"numAxes = "<<_numAxes<<std::endl;
std::cout<<"numBalls = "<<_numBalls<<std::endl;
std::cout<<"numHats = "<<_numHats<<std::endl;
std::cout<<"numButtons = "<<_numButtons<<std::endl;
}
addMouseButtonMapping(4, 1); // left
addMouseButtonMapping(5, 3); // right
addMouseButtonMapping(6, 2); // middle
addKeyMapping(10, ' '); // R2
addKeyMapping(0, '1'); // 1
addKeyMapping(1, '2'); // 2
addKeyMapping(2, '3'); // 3
addKeyMapping(4, '4'); // 4
addKeyMapping(7, ' '); // home
addKeyMapping(8, osgGA::GUIEventAdapter::KEY_Page_Up); // Start
addKeyMapping(9, osgGA::GUIEventAdapter::KEY_Page_Down); // Start
addKeyMapping(10, osgGA::GUIEventAdapter::KEY_Home); // Start
capture(_axisValues, _buttonValues);
}
JoystickDevice::~JoystickDevice()
{
}
void JoystickDevice::capture(ValueList& axisValues, ValueList& buttonValues) const
{
if (_joystick)
{
SDL_JoystickUpdate();
axisValues.resize(_numAxes);
for(int ai=0; ai<_numAxes; ++ai)
{
axisValues[ai] = SDL_JoystickGetAxis(_joystick, ai);
}
buttonValues.resize(_numButtons);
for(int bi=0; bi<_numButtons; ++bi)
{
buttonValues[bi] = SDL_JoystickGetButton(_joystick, bi);
}
}
}
bool JoystickDevice::checkEvents()
{
if (_joystick)
{
OSG_NOTICE<<"JoystickDevice::checkEvents()"<<std::endl;
ValueList newAxisValues;
ValueList newButtonValues;
capture(newAxisValues, newButtonValues);
unsigned int mouseXaxis = 0;
unsigned int mouseYaxis = 1;
float prev_mx = (float)_axisValues[mouseXaxis]/32767.0f;
float prev_my = -(float)_axisValues[mouseYaxis]/32767.0f;
float mx = (float)newAxisValues[mouseXaxis]/32767.0f;
float my = -(float)newAxisValues[mouseYaxis]/32767.0f;
osgGA::EventQueue* eq = getEventQueue();
double time = eq ? eq->getTime() : 0.0;
osgGA::GUIEventAdapter* previous_event = eq->getCurrentEventState();
float projected_mx = previous_event->getXmin() + (mx+1.0)*0.5*(previous_event->getXmax()-previous_event->getXmin());
float projected_my = previous_event->getYmin() + (my+1.0)*0.5*(previous_event->getYmax()-previous_event->getYmin());
if (mx!=prev_mx || my!=prev_my)
{
eq->mouseMotion(projected_mx, projected_my, time);
}
OSG_NOTICE<<"mx="<<mx<<", my="<<my<<", projected_mx="<<projected_mx<<", projected_my="<<projected_my<<std::endl;
if (_verbose)
{
for(int ai=0; ai<_numAxes; ++ai)
{
if (newAxisValues[ai]!=_axisValues[ai])
{
std::cout<<"axis "<<ai<<" moved to "<<newAxisValues[ai]<<std::endl;
}
}
}
for(int bi=0; bi<_numButtons; ++bi)
{
if (newButtonValues[bi]!=_buttonValues[bi])
{
if (_verbose)
{
std::cout<<"button "<<bi<<" changed to "<<newButtonValues[bi]<<std::endl;
}
int key = getKeyMapping(bi);
int mouseButton = getMouseButtonMapping(bi);
if (mouseButton>0)
{
if (newButtonValues[bi]==0) eq->mouseButtonRelease(projected_mx,projected_my,mouseButton,time);
else eq->mouseButtonPress(projected_mx,projected_my,mouseButton,time);
}
else if (key>0)
{
if (newButtonValues[bi]==0) eq->keyRelease(key,time);
else eq->keyPress(key,time);
}
}
}
_axisValues.swap(newAxisValues);
_buttonValues.swap(newButtonValues);
}
return !(getEventQueue()->empty());
}
<|endoftext|>
|
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
*
* Condor Software Copyright Notice
* Copyright (C) 1990-2006, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* This source code is covered by the Condor Public License, which can
* be found in the accompanying LICENSE.TXT file, or online at
* www.condorproject.org.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS
* FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT
* HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON
* MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS,
* ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY
* PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY
* RIGHT.
*
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "condor_distribution.h"
// Constructor
Distribution::Distribution()
{
// Are we 'Condor' or 'Hawkeye'?
SetDistribution( "condor" );
}
int Distribution::Init( int argc, char **argv )
{
char *argv0 = argv[0];
// Are we 'Condor' or 'Hawkeye'?
if ( ( strstr ( argv0, "hawkeye" ) ) ||
( strstr ( argv0, "Hawkeye" ) ) ||
( strstr ( argv0, "HAWKEYE" ) ) ) {
SetDistribution( "hawkeye" );
} else {
SetDistribution( "condor" );
}
return 1;
}
// Destructor (does nothing for now)
Distribution::~Distribution( )
{
}
// Set my actual distro name
void Distribution :: SetDistribution( const char *name )
{
// Make my own private copies of the name
strncpy( distribution, name, MAX_DISTRIBUTION_NAME );
distribution[MAX_DISTRIBUTION_NAME] = '\0';
strcpy( distribution_uc, distribution );
strcpy( distribution_cap, distribution );
// Make the 'uc' version upper case
char *cp = distribution_uc;
while ( *cp )
{
char c = *cp;
*cp = toupper( c );
cp++;
}
// Capitalize the first char of the Cap version
char c = distribution_cap[0];
distribution_cap[0] = toupper( c );
// Cache away it's length
distribution_length = strlen( distribution );
}
<commit_msg>remove warnings<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
*
* Condor Software Copyright Notice
* Copyright (C) 1990-2006, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* This source code is covered by the Condor Public License, which can
* be found in the accompanying LICENSE.TXT file, or online at
* www.condorproject.org.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS
* FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT
* HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON
* MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS,
* ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY
* PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY
* RIGHT.
*
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "condor_distribution.h"
// Constructor
Distribution::Distribution()
{
// Are we 'Condor' or 'Hawkeye'?
SetDistribution( "condor" );
}
int Distribution::Init( int /*argc*/, char **argv )
{
char *argv0 = argv[0];
// Are we 'Condor' or 'Hawkeye'?
if ( ( strstr ( argv0, "hawkeye" ) ) ||
( strstr ( argv0, "Hawkeye" ) ) ||
( strstr ( argv0, "HAWKEYE" ) ) ) {
SetDistribution( "hawkeye" );
} else {
SetDistribution( "condor" );
}
return 1;
}
// Destructor (does nothing for now)
Distribution::~Distribution( )
{
}
// Set my actual distro name
void Distribution :: SetDistribution( const char *name )
{
// Make my own private copies of the name
strncpy( distribution, name, MAX_DISTRIBUTION_NAME );
distribution[MAX_DISTRIBUTION_NAME] = '\0';
strcpy( distribution_uc, distribution );
strcpy( distribution_cap, distribution );
// Make the 'uc' version upper case
char *cp = distribution_uc;
while ( *cp )
{
char c = *cp;
*cp = toupper( c );
cp++;
}
// Capitalize the first char of the Cap version
char c = distribution_cap[0];
distribution_cap[0] = toupper( c );
// Cache away it's length
distribution_length = strlen( distribution );
}
<|endoftext|>
|
<commit_before>// Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// This file contains the main() function for the impala daemon process,
// which exports the Thrift services ImpalaService and ImpalaInternalService.
#include <unistd.h>
#include <jni.h>
#include "common/logging.h"
#include "common/init.h"
#include "exec/hbase-table-scanner.h"
#include "exec/hbase-table-writer.h"
#include "exprs/hive-udf-call.h"
#include "runtime/hbase-table.h"
#include "codegen/llvm-codegen.h"
#include "common/status.h"
#include "runtime/coordinator.h"
#include "runtime/exec-env.h"
#include "util/jni-util.h"
#include "util/network-util.h"
#include "rpc/thrift-util.h"
#include "rpc/thrift-server.h"
#include "rpc/rpc-trace.h"
#include "service/impala-server.h"
#include "service/fe-support.h"
#include "gen-cpp/ImpalaService.h"
#include "gen-cpp/ImpalaInternalService.h"
#include "util/impalad-metrics.h"
#include "util/thread.h"
#include "common/names.h"
using namespace impala;
DECLARE_string(classpath);
DECLARE_bool(use_statestore);
DECLARE_int32(beeswax_port);
DECLARE_int32(hs2_port);
DECLARE_int32(be_port);
DECLARE_string(principal);
int ImpaladMain(int argc, char** argv) {
InitCommonRuntime(argc, argv, true);
LlvmCodeGen::InitializeLlvm();
JniUtil::InitLibhdfs();
ABORT_IF_ERROR(HBaseTableScanner::Init());
ABORT_IF_ERROR(HBaseTable::InitJNI());
ABORT_IF_ERROR(HBaseTableWriter::InitJNI());
ABORT_IF_ERROR(HiveUdfCall::Init());
InitFeSupport();
// start backend service for the coordinator on be_port
ExecEnv exec_env;
StartThreadInstrumentation(exec_env.metrics(), exec_env.webserver());
InitRpcEventTracing(exec_env.webserver());
ThriftServer* beeswax_server = NULL;
ThriftServer* hs2_server = NULL;
ThriftServer* be_server = NULL;
ImpalaServer* server = NULL;
ABORT_IF_ERROR(CreateImpalaServer(&exec_env, FLAGS_beeswax_port, FLAGS_hs2_port,
FLAGS_be_port, &beeswax_server, &hs2_server, &be_server, &server));
ABORT_IF_ERROR(be_server->Start());
Status status = exec_env.StartServices();
if (!status.ok()) {
LOG(ERROR) << "Impalad services did not start correctly, exiting. Error: "
<< status.GetDetail();
ShutdownLogging();
exit(1);
}
// this blocks until the beeswax and hs2 servers terminate
ABORT_IF_ERROR(beeswax_server->Start());
ABORT_IF_ERROR(hs2_server->Start());
ImpaladMetrics::IMPALA_SERVER_READY->set_value(true);
LOG(INFO) << "Impala has started.";
beeswax_server->Join();
hs2_server->Join();
delete be_server;
delete beeswax_server;
delete hs2_server;
return 0;
}
<commit_msg>IMPALA-3521: Impalad should communicate with the statestore after binding to the hs2 and besswax ports<commit_after>// Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// This file contains the main() function for the impala daemon process,
// which exports the Thrift services ImpalaService and ImpalaInternalService.
#include <unistd.h>
#include <jni.h>
#include "common/logging.h"
#include "common/init.h"
#include "exec/hbase-table-scanner.h"
#include "exec/hbase-table-writer.h"
#include "exprs/hive-udf-call.h"
#include "runtime/hbase-table.h"
#include "codegen/llvm-codegen.h"
#include "common/status.h"
#include "runtime/coordinator.h"
#include "runtime/exec-env.h"
#include "util/jni-util.h"
#include "util/network-util.h"
#include "rpc/thrift-util.h"
#include "rpc/thrift-server.h"
#include "rpc/rpc-trace.h"
#include "service/impala-server.h"
#include "service/fe-support.h"
#include "gen-cpp/ImpalaService.h"
#include "gen-cpp/ImpalaInternalService.h"
#include "util/impalad-metrics.h"
#include "util/thread.h"
#include "common/names.h"
using namespace impala;
DECLARE_string(classpath);
DECLARE_bool(use_statestore);
DECLARE_int32(beeswax_port);
DECLARE_int32(hs2_port);
DECLARE_int32(be_port);
DECLARE_string(principal);
int ImpaladMain(int argc, char** argv) {
InitCommonRuntime(argc, argv, true);
LlvmCodeGen::InitializeLlvm();
JniUtil::InitLibhdfs();
ABORT_IF_ERROR(HBaseTableScanner::Init());
ABORT_IF_ERROR(HBaseTable::InitJNI());
ABORT_IF_ERROR(HBaseTableWriter::InitJNI());
ABORT_IF_ERROR(HiveUdfCall::Init());
InitFeSupport();
// start backend service for the coordinator on be_port
ExecEnv exec_env;
StartThreadInstrumentation(exec_env.metrics(), exec_env.webserver());
InitRpcEventTracing(exec_env.webserver());
ThriftServer* beeswax_server = NULL;
ThriftServer* hs2_server = NULL;
ThriftServer* be_server = NULL;
ImpalaServer* server = NULL;
ABORT_IF_ERROR(CreateImpalaServer(&exec_env, FLAGS_beeswax_port, FLAGS_hs2_port,
FLAGS_be_port, &beeswax_server, &hs2_server, &be_server, &server));
ABORT_IF_ERROR(be_server->Start());
ABORT_IF_ERROR(beeswax_server->Start());
ABORT_IF_ERROR(hs2_server->Start());
Status status = exec_env.StartServices();
if (!status.ok()) {
LOG(ERROR) << "Impalad services did not start correctly, exiting. Error: "
<< status.GetDetail();
ShutdownLogging();
exit(1);
}
ImpaladMetrics::IMPALA_SERVER_READY->set_value(true);
LOG(INFO) << "Impala has started.";
// this blocks until the beeswax and hs2 servers terminate
beeswax_server->Join();
hs2_server->Join();
delete be_server;
delete beeswax_server;
delete hs2_server;
return 0;
}
<|endoftext|>
|
<commit_before>//===--------------------------- new.cpp ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <stdlib.h>
#include "new"
#include "include/atomic_support.h"
#if defined(_LIBCPP_ABI_MICROSOFT)
# if !defined(_LIBCPP_ABI_VCRUNTIME)
# include "support/runtime/new_handler_fallback.ipp"
# endif
#elif defined(LIBCXX_BUILDING_LIBCXXABI)
# include <cxxabi.h>
#elif defined(LIBCXXRT)
# include <cxxabi.h>
# include "support/runtime/new_handler_fallback.ipp"
#elif defined(__GLIBCXX__)
// nothing to do
#elif !defined(_LIBCPP_DISABLE_NEW_DELETE_DEFINITIONS)
# include "support/runtime/new_handler_fallback.ipp"
#endif
namespace std
{
#ifndef __GLIBCXX__
const nothrow_t nothrow{};
#endif
#ifndef LIBSTDCXX
void
__throw_bad_alloc()
{
#ifndef _LIBCPP_NO_EXCEPTIONS
throw bad_alloc();
#else
_VSTD::abort();
#endif
}
#endif // !LIBSTDCXX
} // std
#if !defined(__GLIBCXX__) && \
!defined(_LIBCPP_ABI_VCRUNTIME) && \
!defined(_LIBCPP_DISABLE_NEW_DELETE_DEFINITIONS)
// Implement all new and delete operators as weak definitions
// in this shared library, so that they can be overridden by programs
// that define non-weak copies of the functions.
_LIBCPP_WEAK
void *
operator new(std::size_t size) _THROW_BAD_ALLOC
{
if (size == 0)
size = 1;
void* p;
while ((p = ::malloc(size)) == 0)
{
// If malloc fails and there is a new_handler,
// call it to try free up memory.
std::new_handler nh = std::get_new_handler();
if (nh)
nh();
else
#ifndef _LIBCPP_NO_EXCEPTIONS
throw std::bad_alloc();
#else
break;
#endif
}
return p;
}
_LIBCPP_WEAK
void*
operator new(size_t size, const std::nothrow_t&) _NOEXCEPT
{
void* p = 0;
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
p = ::operator new(size);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
}
#endif // _LIBCPP_NO_EXCEPTIONS
return p;
}
_LIBCPP_WEAK
void*
operator new[](size_t size) _THROW_BAD_ALLOC
{
return ::operator new(size);
}
_LIBCPP_WEAK
void*
operator new[](size_t size, const std::nothrow_t&) _NOEXCEPT
{
void* p = 0;
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
p = ::operator new[](size);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
}
#endif // _LIBCPP_NO_EXCEPTIONS
return p;
}
_LIBCPP_WEAK
void
operator delete(void* ptr) _NOEXCEPT
{
::free(ptr);
}
_LIBCPP_WEAK
void
operator delete(void* ptr, const std::nothrow_t&) _NOEXCEPT
{
::operator delete(ptr);
}
_LIBCPP_WEAK
void
operator delete(void* ptr, size_t) _NOEXCEPT
{
::operator delete(ptr);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr) _NOEXCEPT
{
::operator delete(ptr);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, const std::nothrow_t&) _NOEXCEPT
{
::operator delete[](ptr);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, size_t) _NOEXCEPT
{
::operator delete[](ptr);
}
#if !defined(_LIBCPP_HAS_NO_LIBRARY_ALIGNED_ALLOCATION)
_LIBCPP_WEAK
void *
operator new(std::size_t size, std::align_val_t alignment) _THROW_BAD_ALLOC
{
if (size == 0)
size = 1;
if (static_cast<size_t>(alignment) < sizeof(void*))
alignment = std::align_val_t(sizeof(void*));
void* p;
#if defined(_LIBCPP_MSVCRT_LIKE)
while ((p = _aligned_malloc(size, static_cast<size_t>(alignment))) == nullptr)
#else
while (::posix_memalign(&p, static_cast<size_t>(alignment), size) != 0)
#endif
{
// If posix_memalign fails and there is a new_handler,
// call it to try free up memory.
std::new_handler nh = std::get_new_handler();
if (nh)
nh();
else {
#ifndef _LIBCPP_NO_EXCEPTIONS
throw std::bad_alloc();
#else
p = nullptr; // posix_memalign doesn't initialize 'p' on failure
break;
#endif
}
}
return p;
}
_LIBCPP_WEAK
void*
operator new(size_t size, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
{
void* p = 0;
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
p = ::operator new(size, alignment);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
}
#endif // _LIBCPP_NO_EXCEPTIONS
return p;
}
_LIBCPP_WEAK
void*
operator new[](size_t size, std::align_val_t alignment) _THROW_BAD_ALLOC
{
return ::operator new(size, alignment);
}
_LIBCPP_WEAK
void*
operator new[](size_t size, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
{
void* p = 0;
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
p = ::operator new[](size, alignment);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
}
#endif // _LIBCPP_NO_EXCEPTIONS
return p;
}
_LIBCPP_WEAK
void
operator delete(void* ptr, std::align_val_t) _NOEXCEPT
{
#if defined(_LIBCPP_MSVCRT_LIKE)
::_aligned_free(ptr);
#else
::free(ptr);
#endif
}
_LIBCPP_WEAK
void
operator delete(void* ptr, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
{
::operator delete(ptr, alignment);
}
_LIBCPP_WEAK
void
operator delete(void* ptr, size_t, std::align_val_t alignment) _NOEXCEPT
{
::operator delete(ptr, alignment);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, std::align_val_t alignment) _NOEXCEPT
{
::operator delete(ptr, alignment);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
{
::operator delete[](ptr, alignment);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, size_t, std::align_val_t alignment) _NOEXCEPT
{
::operator delete[](ptr, alignment);
}
#endif // !_LIBCPP_HAS_NO_LIBRARY_ALIGNED_ALLOCATION
#endif // !__GLIBCXX__ && !_LIBCPP_ABI_VCRUNTIME && !_LIBCPP_DISABLE_NEW_DELETE_DEFINITIONS
<commit_msg>[libc++][CMake] Remove unnecessary conditional for defining new handlers<commit_after>//===--------------------------- new.cpp ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <stdlib.h>
#include "new"
#include "include/atomic_support.h"
#if defined(_LIBCPP_ABI_MICROSOFT)
# if !defined(_LIBCPP_ABI_VCRUNTIME)
# include "support/runtime/new_handler_fallback.ipp"
# endif
#elif defined(LIBCXX_BUILDING_LIBCXXABI)
# include <cxxabi.h>
#elif defined(LIBCXXRT)
# include <cxxabi.h>
# include "support/runtime/new_handler_fallback.ipp"
#elif defined(__GLIBCXX__)
// nothing to do
#else
# include "support/runtime/new_handler_fallback.ipp"
#endif
namespace std
{
#ifndef __GLIBCXX__
const nothrow_t nothrow{};
#endif
#ifndef LIBSTDCXX
void
__throw_bad_alloc()
{
#ifndef _LIBCPP_NO_EXCEPTIONS
throw bad_alloc();
#else
_VSTD::abort();
#endif
}
#endif // !LIBSTDCXX
} // std
#if !defined(__GLIBCXX__) && \
!defined(_LIBCPP_ABI_VCRUNTIME) && \
!defined(_LIBCPP_DISABLE_NEW_DELETE_DEFINITIONS)
// Implement all new and delete operators as weak definitions
// in this shared library, so that they can be overridden by programs
// that define non-weak copies of the functions.
_LIBCPP_WEAK
void *
operator new(std::size_t size) _THROW_BAD_ALLOC
{
if (size == 0)
size = 1;
void* p;
while ((p = ::malloc(size)) == 0)
{
// If malloc fails and there is a new_handler,
// call it to try free up memory.
std::new_handler nh = std::get_new_handler();
if (nh)
nh();
else
#ifndef _LIBCPP_NO_EXCEPTIONS
throw std::bad_alloc();
#else
break;
#endif
}
return p;
}
_LIBCPP_WEAK
void*
operator new(size_t size, const std::nothrow_t&) _NOEXCEPT
{
void* p = 0;
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
p = ::operator new(size);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
}
#endif // _LIBCPP_NO_EXCEPTIONS
return p;
}
_LIBCPP_WEAK
void*
operator new[](size_t size) _THROW_BAD_ALLOC
{
return ::operator new(size);
}
_LIBCPP_WEAK
void*
operator new[](size_t size, const std::nothrow_t&) _NOEXCEPT
{
void* p = 0;
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
p = ::operator new[](size);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
}
#endif // _LIBCPP_NO_EXCEPTIONS
return p;
}
_LIBCPP_WEAK
void
operator delete(void* ptr) _NOEXCEPT
{
::free(ptr);
}
_LIBCPP_WEAK
void
operator delete(void* ptr, const std::nothrow_t&) _NOEXCEPT
{
::operator delete(ptr);
}
_LIBCPP_WEAK
void
operator delete(void* ptr, size_t) _NOEXCEPT
{
::operator delete(ptr);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr) _NOEXCEPT
{
::operator delete(ptr);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, const std::nothrow_t&) _NOEXCEPT
{
::operator delete[](ptr);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, size_t) _NOEXCEPT
{
::operator delete[](ptr);
}
#if !defined(_LIBCPP_HAS_NO_LIBRARY_ALIGNED_ALLOCATION)
_LIBCPP_WEAK
void *
operator new(std::size_t size, std::align_val_t alignment) _THROW_BAD_ALLOC
{
if (size == 0)
size = 1;
if (static_cast<size_t>(alignment) < sizeof(void*))
alignment = std::align_val_t(sizeof(void*));
void* p;
#if defined(_LIBCPP_MSVCRT_LIKE)
while ((p = _aligned_malloc(size, static_cast<size_t>(alignment))) == nullptr)
#else
while (::posix_memalign(&p, static_cast<size_t>(alignment), size) != 0)
#endif
{
// If posix_memalign fails and there is a new_handler,
// call it to try free up memory.
std::new_handler nh = std::get_new_handler();
if (nh)
nh();
else {
#ifndef _LIBCPP_NO_EXCEPTIONS
throw std::bad_alloc();
#else
p = nullptr; // posix_memalign doesn't initialize 'p' on failure
break;
#endif
}
}
return p;
}
_LIBCPP_WEAK
void*
operator new(size_t size, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
{
void* p = 0;
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
p = ::operator new(size, alignment);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
}
#endif // _LIBCPP_NO_EXCEPTIONS
return p;
}
_LIBCPP_WEAK
void*
operator new[](size_t size, std::align_val_t alignment) _THROW_BAD_ALLOC
{
return ::operator new(size, alignment);
}
_LIBCPP_WEAK
void*
operator new[](size_t size, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
{
void* p = 0;
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
p = ::operator new[](size, alignment);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
}
#endif // _LIBCPP_NO_EXCEPTIONS
return p;
}
_LIBCPP_WEAK
void
operator delete(void* ptr, std::align_val_t) _NOEXCEPT
{
#if defined(_LIBCPP_MSVCRT_LIKE)
::_aligned_free(ptr);
#else
::free(ptr);
#endif
}
_LIBCPP_WEAK
void
operator delete(void* ptr, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
{
::operator delete(ptr, alignment);
}
_LIBCPP_WEAK
void
operator delete(void* ptr, size_t, std::align_val_t alignment) _NOEXCEPT
{
::operator delete(ptr, alignment);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, std::align_val_t alignment) _NOEXCEPT
{
::operator delete(ptr, alignment);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
{
::operator delete[](ptr, alignment);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, size_t, std::align_val_t alignment) _NOEXCEPT
{
::operator delete[](ptr, alignment);
}
#endif // !_LIBCPP_HAS_NO_LIBRARY_ALIGNED_ALLOCATION
#endif // !__GLIBCXX__ && !_LIBCPP_ABI_VCRUNTIME && !_LIBCPP_DISABLE_NEW_DELETE_DEFINITIONS
<|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 "ash/system/ime/tray_ime.h"
#include <vector>
#include "ash/shell.h"
#include "ash/system/tray/system_tray.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_item_more.h"
#include "ash/system/tray/tray_views.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "grit/ash_strings.h"
#include "grit/ui_resources.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/font.h"
#include "ui/gfx/image/image.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
namespace ash {
namespace internal {
namespace tray {
class IMEDefaultView : public TrayItemMore {
public:
explicit IMEDefaultView(SystemTrayItem* owner)
: TrayItemMore(owner) {
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
SetImage(bundle.GetImageNamed(
IDR_AURA_UBER_TRAY_IME).ToSkBitmap());
IMEInfo info;
Shell::GetInstance()->tray_delegate()->GetCurrentIME(&info);
UpdateLabel(info);
}
virtual ~IMEDefaultView() {}
void UpdateLabel(const IMEInfo& info) {
SetLabel(info.name);
SetAccessibleName(info.name);
}
private:
DISALLOW_COPY_AND_ASSIGN(IMEDefaultView);
};
class IMEDetailedView : public views::View,
public ViewClickListener {
public:
IMEDetailedView(SystemTrayItem* owner, user::LoginStatus login)
: login_(login),
header_(NULL) {
SetLayoutManager(new views::BoxLayout(
views::BoxLayout::kVertical, 0, 0, 0));
set_background(views::Background::CreateSolidBackground(kBackgroundColor));
SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
IMEInfoList list;
delegate->GetAvailableIMEList(&list);
IMEPropertyInfoList property_list;
delegate->GetCurrentIMEProperties(&property_list);
Update(list, property_list);
}
virtual ~IMEDetailedView() {}
void Update(const IMEInfoList& list,
const IMEPropertyInfoList& property_list) {
RemoveAllChildViews(true);
header_ = NULL;
AppendHeaderEntry();
AppendIMEList(list);
if (!property_list.empty())
AppendIMEProperties(property_list);
if (login_ != user::LOGGED_IN_NONE && login_ != user::LOGGED_IN_LOCKED)
AppendSettings();
Layout();
SchedulePaint();
}
private:
void AppendHeaderEntry() {
header_ = CreateDetailedHeaderEntry(IDS_ASH_STATUS_TRAY_IME, this);
AddChildView(header_);
}
void AppendIMEList(const IMEInfoList& list) {
ime_map_.clear();
views::View* imes = new views::View;
imes->SetLayoutManager(new views::BoxLayout(
views::BoxLayout::kVertical, 0, 0, 1));
for (size_t i = 0; i < list.size(); i++) {
HoverHighlightView* container = new HoverHighlightView(this);
container->set_fixed_height(kTrayPopupItemHeight);
container->AddLabel(list[i].name,
list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
imes->AddChildView(container);
ime_map_[container] = list[i].id;
}
imes->set_border(views::Border::CreateSolidSidedBorder(1, 0, 1, 0,
kBorderLightColor));
AddChildView(imes);
}
void AppendIMEProperties(const IMEPropertyInfoList& property_list) {
property_map_.clear();
views::View* properties = new views::View;
properties->SetLayoutManager(new views::BoxLayout(
views::BoxLayout::kVertical, 0, 0, 1));
for (size_t i = 0; i < property_list.size(); i++) {
HoverHighlightView* container = new HoverHighlightView(this);
container->set_fixed_height(kTrayPopupItemHeight);
container->AddLabel(
property_list[i].name,
property_list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
properties->AddChildView(container);
property_map_[container] = property_list[i].key;
}
properties->set_border(views::Border::CreateSolidSidedBorder(
0, 0, 1, 0, kBorderLightColor));
AddChildView(properties);
}
void AppendSettings() {
HoverHighlightView* container = new HoverHighlightView(this);
container->set_fixed_height(kTrayPopupItemHeight);
container->AddLabel(ui::ResourceBundle::GetSharedInstance().
GetLocalizedString(IDS_ASH_STATUS_TRAY_IME_SETTINGS),
gfx::Font::NORMAL);
AddChildView(container);
settings_ = container;
}
// Overridden from ViewClickListener.
virtual void ClickedOn(views::View* sender) OVERRIDE {
SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
if (sender == header_) {
Shell::GetInstance()->tray()->ShowDefaultView();
} else if (sender == settings_) {
delegate->ShowIMESettings();
} else {
std::map<views::View*, std::string>::const_iterator ime_find;
ime_find = ime_map_.find(sender);
if (ime_find != ime_map_.end()) {
std::string ime_id = ime_find->second;
delegate->SwitchIME(ime_id);
GetWidget()->Close();
} else {
std::map<views::View*, std::string>::const_iterator prop_find;
prop_find = property_map_.find(sender);
if (prop_find != property_map_.end()) {
const std::string key = prop_find->second;
delegate->ActivateIMEProperty(key);
GetWidget()->Close();
}
}
}
}
user::LoginStatus login_;
std::map<views::View*, std::string> ime_map_;
std::map<views::View*, std::string> property_map_;
views::View* header_;
views::View* settings_;
DISALLOW_COPY_AND_ASSIGN(IMEDetailedView);
};
} // namespace tray
TrayIME::TrayIME() {
}
TrayIME::~TrayIME() {
}
void TrayIME::UpdateTrayLabel(const IMEInfo& current, size_t count) {
tray_label_->SetText(current.short_name);
tray_label_->SetVisible(count > 1);
}
views::View* TrayIME::CreateTrayView(user::LoginStatus status) {
tray_label_.reset(new views::Label);
SetupLabelForTray(tray_label_.get());
tray_label_->set_border(
views::Border::CreateEmptyBorder(0, 2, 0, 2));
return tray_label_.get();
}
views::View* TrayIME::CreateDefaultView(user::LoginStatus status) {
default_.reset(new tray::IMEDefaultView(this));
return default_.get();
}
views::View* TrayIME::CreateDetailedView(user::LoginStatus status) {
detailed_.reset(new tray::IMEDetailedView(this, status));
return detailed_.get();
}
void TrayIME::DestroyTrayView() {
tray_label_.reset();
}
void TrayIME::DestroyDefaultView() {
default_.reset();
}
void TrayIME::DestroyDetailedView() {
detailed_.reset();
}
void TrayIME::OnIMERefresh() {
SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
IMEInfoList list;
IMEInfo current;
IMEPropertyInfoList property_list;
delegate->GetCurrentIME(¤t);
delegate->GetAvailableIMEList(&list);
delegate->GetCurrentIMEProperties(&property_list);
UpdateTrayLabel(current, list.size());
if (default_.get())
default_->UpdateLabel(current);
if (detailed_.get())
detailed_->Update(list, property_list);
}
} // namespace internal
} // namespace ash
<commit_msg>Popup detailed view for IME switch when the tray icon is not visible.<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 "ash/system/ime/tray_ime.h"
#include <vector>
#include "ash/shell.h"
#include "ash/system/tray/system_tray.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_item_more.h"
#include "ash/system/tray/tray_views.h"
#include "ash/wm/shelf_layout_manager.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "grit/ash_strings.h"
#include "grit/ui_resources.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/font.h"
#include "ui/gfx/image/image.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
namespace ash {
namespace internal {
namespace tray {
class IMEDefaultView : public TrayItemMore {
public:
explicit IMEDefaultView(SystemTrayItem* owner)
: TrayItemMore(owner) {
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
SetImage(bundle.GetImageNamed(
IDR_AURA_UBER_TRAY_IME).ToSkBitmap());
IMEInfo info;
Shell::GetInstance()->tray_delegate()->GetCurrentIME(&info);
UpdateLabel(info);
}
virtual ~IMEDefaultView() {}
void UpdateLabel(const IMEInfo& info) {
SetLabel(info.name);
SetAccessibleName(info.name);
}
private:
DISALLOW_COPY_AND_ASSIGN(IMEDefaultView);
};
class IMEDetailedView : public views::View,
public ViewClickListener {
public:
IMEDetailedView(SystemTrayItem* owner, user::LoginStatus login)
: login_(login),
header_(NULL) {
SetLayoutManager(new views::BoxLayout(
views::BoxLayout::kVertical, 0, 0, 0));
set_background(views::Background::CreateSolidBackground(kBackgroundColor));
SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
IMEInfoList list;
delegate->GetAvailableIMEList(&list);
IMEPropertyInfoList property_list;
delegate->GetCurrentIMEProperties(&property_list);
Update(list, property_list);
}
virtual ~IMEDetailedView() {}
void Update(const IMEInfoList& list,
const IMEPropertyInfoList& property_list) {
RemoveAllChildViews(true);
header_ = NULL;
AppendHeaderEntry();
AppendIMEList(list);
if (!property_list.empty())
AppendIMEProperties(property_list);
if (login_ != user::LOGGED_IN_NONE && login_ != user::LOGGED_IN_LOCKED)
AppendSettings();
Layout();
SchedulePaint();
}
private:
void AppendHeaderEntry() {
header_ = CreateDetailedHeaderEntry(IDS_ASH_STATUS_TRAY_IME, this);
AddChildView(header_);
}
void AppendIMEList(const IMEInfoList& list) {
ime_map_.clear();
views::View* imes = new views::View;
imes->SetLayoutManager(new views::BoxLayout(
views::BoxLayout::kVertical, 0, 0, 1));
for (size_t i = 0; i < list.size(); i++) {
HoverHighlightView* container = new HoverHighlightView(this);
container->set_fixed_height(kTrayPopupItemHeight);
container->AddLabel(list[i].name,
list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
imes->AddChildView(container);
ime_map_[container] = list[i].id;
}
imes->set_border(views::Border::CreateSolidSidedBorder(1, 0, 1, 0,
kBorderLightColor));
AddChildView(imes);
}
void AppendIMEProperties(const IMEPropertyInfoList& property_list) {
property_map_.clear();
views::View* properties = new views::View;
properties->SetLayoutManager(new views::BoxLayout(
views::BoxLayout::kVertical, 0, 0, 1));
for (size_t i = 0; i < property_list.size(); i++) {
HoverHighlightView* container = new HoverHighlightView(this);
container->set_fixed_height(kTrayPopupItemHeight);
container->AddLabel(
property_list[i].name,
property_list[i].selected ? gfx::Font::BOLD : gfx::Font::NORMAL);
properties->AddChildView(container);
property_map_[container] = property_list[i].key;
}
properties->set_border(views::Border::CreateSolidSidedBorder(
0, 0, 1, 0, kBorderLightColor));
AddChildView(properties);
}
void AppendSettings() {
HoverHighlightView* container = new HoverHighlightView(this);
container->set_fixed_height(kTrayPopupItemHeight);
container->AddLabel(ui::ResourceBundle::GetSharedInstance().
GetLocalizedString(IDS_ASH_STATUS_TRAY_IME_SETTINGS),
gfx::Font::NORMAL);
AddChildView(container);
settings_ = container;
}
// Overridden from ViewClickListener.
virtual void ClickedOn(views::View* sender) OVERRIDE {
SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
if (sender == header_) {
Shell::GetInstance()->tray()->ShowDefaultView();
} else if (sender == settings_) {
delegate->ShowIMESettings();
} else {
std::map<views::View*, std::string>::const_iterator ime_find;
ime_find = ime_map_.find(sender);
if (ime_find != ime_map_.end()) {
std::string ime_id = ime_find->second;
delegate->SwitchIME(ime_id);
GetWidget()->Close();
} else {
std::map<views::View*, std::string>::const_iterator prop_find;
prop_find = property_map_.find(sender);
if (prop_find != property_map_.end()) {
const std::string key = prop_find->second;
delegate->ActivateIMEProperty(key);
GetWidget()->Close();
}
}
}
}
user::LoginStatus login_;
std::map<views::View*, std::string> ime_map_;
std::map<views::View*, std::string> property_map_;
views::View* header_;
views::View* settings_;
DISALLOW_COPY_AND_ASSIGN(IMEDetailedView);
};
} // namespace tray
TrayIME::TrayIME() {
}
TrayIME::~TrayIME() {
}
void TrayIME::UpdateTrayLabel(const IMEInfo& current, size_t count) {
tray_label_->SetText(current.short_name);
tray_label_->SetVisible(count > 1);
}
views::View* TrayIME::CreateTrayView(user::LoginStatus status) {
tray_label_.reset(new views::Label);
SetupLabelForTray(tray_label_.get());
tray_label_->set_border(
views::Border::CreateEmptyBorder(0, 2, 0, 2));
return tray_label_.get();
}
views::View* TrayIME::CreateDefaultView(user::LoginStatus status) {
default_.reset(new tray::IMEDefaultView(this));
return default_.get();
}
views::View* TrayIME::CreateDetailedView(user::LoginStatus status) {
detailed_.reset(new tray::IMEDetailedView(this, status));
return detailed_.get();
}
void TrayIME::DestroyTrayView() {
tray_label_.reset();
}
void TrayIME::DestroyDefaultView() {
default_.reset();
}
void TrayIME::DestroyDetailedView() {
detailed_.reset();
}
void TrayIME::OnIMERefresh() {
SystemTrayDelegate* delegate = Shell::GetInstance()->tray_delegate();
IMEInfoList list;
IMEInfo current;
IMEPropertyInfoList property_list;
delegate->GetCurrentIME(¤t);
delegate->GetAvailableIMEList(&list);
delegate->GetCurrentIMEProperties(&property_list);
UpdateTrayLabel(current, list.size());
if (default_.get())
default_->UpdateLabel(current);
if (detailed_.get())
detailed_->Update(list, property_list);
else if (!Shell::GetInstance()->shelf()->IsVisible())
PopupDetailedView(kTrayPopupAutoCloseDelayInSeconds, false);
}
} // namespace internal
} // namespace ash
<|endoftext|>
|
<commit_before>#include "model_common_functions.hpp"
#include "species.hpp"
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <cmath> // NAN
#include <vector> // std::vector
namespace model
{
void set_child_pointer(GLuint childID, void* child_pointer, std::vector<void*> &child_pointer_vector, std::queue<GLuint> &free_childID_queue)
{
child_pointer_vector[childID] = child_pointer;
if (child_pointer == NULL)
{
if (childID == child_pointer_vector.size() - 1)
{
// OK, this is the biggest childID of all childID's of this 'object'.
// We can reduce the size of the child pointer vector at least by 1.
while ((!child_pointer_vector.empty()) && (child_pointer_vector.back() == NULL))
{
// Reduce the size of child pointer vector by 1.
child_pointer_vector.pop_back();
}
}
}
}
GLuint get_childID(std::vector<void*> &child_pointer_vector, std::queue<GLuint> &free_childID_queue)
{
GLuint childID;
while (!free_childID_queue.empty())
{
// return the first (oldest) free childID.
childID = free_childID_queue.front();
free_childID_queue.pop();
// check that the child index does not exceed current child pointer vector.
if (childID < child_pointer_vector.size())
{
// OK, it does not exceed current child pointer vector.
return childID;
}
}
// OK, the queue is empty.
// A new child index must be created.
childID = child_pointer_vector.size();
// child pointer vector must also be extended with an appropriate NULL pointer.
child_pointer_vector.push_back(NULL);
return childID;
}
}
<commit_msg>Poistettu tyhjä rivi.<commit_after>#include "model_common_functions.hpp"
#include "species.hpp"
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <cmath> // NAN
#include <vector> // std::vector
namespace model
{
void set_child_pointer(GLuint childID, void* child_pointer, std::vector<void*> &child_pointer_vector, std::queue<GLuint> &free_childID_queue)
{
child_pointer_vector[childID] = child_pointer;
if (child_pointer == NULL)
{
if (childID == child_pointer_vector.size() - 1)
{
// OK, this is the biggest childID of all childID's of this 'object'.
// We can reduce the size of the child pointer vector at least by 1.
while ((!child_pointer_vector.empty()) && (child_pointer_vector.back() == NULL))
{
// Reduce the size of child pointer vector by 1.
child_pointer_vector.pop_back();
}
}
}
}
GLuint get_childID(std::vector<void*> &child_pointer_vector, std::queue<GLuint> &free_childID_queue)
{
GLuint childID;
while (!free_childID_queue.empty())
{
// return the first (oldest) free childID.
childID = free_childID_queue.front();
free_childID_queue.pop();
// check that the child index does not exceed current child pointer vector.
if (childID < child_pointer_vector.size())
{
// OK, it does not exceed current child pointer vector.
return childID;
}
}
// OK, the queue is empty.
// A new child index must be created.
childID = child_pointer_vector.size();
// child pointer vector must also be extended with an appropriate NULL pointer.
child_pointer_vector.push_back(NULL);
return childID;
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: implfont.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 08:28:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CPPCANVAS_IMPLFONT_HXX
#define _CPPCANVAS_IMPLFONT_HXX
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#endif
#ifndef _COM_SUN_STAR_RENDERING_XCANVAS_HPP__
#include <com/sun/star/rendering/XCanvas.hpp>
#endif
#ifndef _CPPCANVAS_FONT_HXX
#include <cppcanvas/font.hxx>
#endif
namespace rtl
{
class OUString;
}
namespace com { namespace sun { namespace star { namespace rendering
{
class XCanvasFont;
} } } }
/* Definition of Font class */
namespace cppcanvas
{
namespace internal
{
class ImplFont : public Font
{
public:
ImplFont( const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XCanvas >& rCanvas,
const ::rtl::OUString& rFontName,
const double& rCellSize );
virtual ~ImplFont();
virtual ::rtl::OUString getName() const;
virtual double getCellSize() const;
virtual ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XCanvasFont > getUNOFont() const;
private:
::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCanvas > mxCanvas;
::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCanvasFont > mxFont;
};
}
}
#endif /* _CPPCANVAS_IMPLFONT_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.5.80); FILE MERGED 2008/04/01 15:10:07 thb 1.5.80.3: #i85898# Stripping all external header guards 2008/04/01 12:27:51 thb 1.5.80.2: #i85898# Stripping all external header guards 2008/03/31 13:07:09 rt 1.5.80.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: implfont.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _CPPCANVAS_IMPLFONT_HXX
#define _CPPCANVAS_IMPLFONT_HXX
#include <com/sun/star/uno/Reference.hxx>
#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#endif
#ifndef _COM_SUN_STAR_RENDERING_XCANVAS_HPP__
#include <com/sun/star/rendering/XCanvas.hpp>
#endif
#include <cppcanvas/font.hxx>
namespace rtl
{
class OUString;
}
namespace com { namespace sun { namespace star { namespace rendering
{
class XCanvasFont;
} } } }
/* Definition of Font class */
namespace cppcanvas
{
namespace internal
{
class ImplFont : public Font
{
public:
ImplFont( const ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XCanvas >& rCanvas,
const ::rtl::OUString& rFontName,
const double& rCellSize );
virtual ~ImplFont();
virtual ::rtl::OUString getName() const;
virtual double getCellSize() const;
virtual ::com::sun::star::uno::Reference<
::com::sun::star::rendering::XCanvasFont > getUNOFont() const;
private:
::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCanvas > mxCanvas;
::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCanvasFont > mxFont;
};
}
}
#endif /* _CPPCANVAS_IMPLFONT_HXX */
<|endoftext|>
|
<commit_before>/* This file is part of the Vc library.
Copyright (C) 2009 Matthias Kretz <kretz@kde.org>
Vc is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Vc is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Vc/Vc>
#include "benchmark.h"
#include "random.h"
#include "../cpuid.h"
#include <cstdio>
#include <cstdlib>
using namespace Vc;
template<typename T, int S> struct KeepResultsHelper {
static inline void keep(const T &tmp0) { asm volatile(""::"r"(tmp0)); }
static inline void keep(const T &tmp0, const T &tmp1, const T &tmp2, const T &tmp3) {
#ifdef __x86_64__
asm volatile(""::"r"(tmp0), "r"(tmp1), "r"(tmp2), "r"(tmp3));
#else
asm volatile(""::"r"(tmp0), "r"(tmp1));
asm volatile(""::"r"(tmp2), "r"(tmp3));
#endif
}
};
#if defined(VC_IMPL_AVX)
template<typename T> struct KeepResultsHelper<T, 16> {
static inline void keep(const T &tmp0) { asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0))); }
static inline void keep(const T &tmp0, const T &tmp1, const T &tmp2, const T &tmp3) {
asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0)), "x"(reinterpret_cast<const __m128 &>(tmp1)), "x"(reinterpret_cast<const __m128 &>(tmp2)), "x"(reinterpret_cast<const __m128 &>(tmp3)));
}
};
template<typename T> struct KeepResultsHelper<T, 32> {
static inline void keep(const T &tmp0) {
asm volatile(""::"x"(reinterpret_cast<const __m256 &>(tmp0)));
}
static inline void keep(const T &tmp0, const T &tmp1, const T &tmp2, const T &tmp3) {
asm volatile(""::"x"(reinterpret_cast<const __m256 &>(tmp0)), "x"(reinterpret_cast<const __m256 &>(tmp1)),
"x"(reinterpret_cast<const __m256 &>(tmp2)), "x"(reinterpret_cast<const __m256 &>(tmp3)));
}
};
#elif defined(VC_IMPL_SSE)
template<typename T> struct KeepResultsHelper<T, 16> {
static inline void keep(const T &tmp0) { asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0))); }
static inline void keep(const T &tmp0, const T &tmp1, const T &tmp2, const T &tmp3) {
asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0)), "x"(reinterpret_cast<const __m128 &>(tmp1)), "x"(reinterpret_cast<const __m128 &>(tmp2)), "x"(reinterpret_cast<const __m128 &>(tmp3)));
}
};
template<typename T> struct KeepResultsHelper<T, 32> {
static inline void keep(const T &tmp0) {
asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0)), "x"(reinterpret_cast<const __m128 *>(&tmp0)[1]));
}
static inline void keep(const T &tmp0, const T &tmp1, const T &tmp2, const T &tmp3) {
asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0)), "x"(reinterpret_cast<const __m128 *>(&tmp0)[1]),
"x"(reinterpret_cast<const __m128 &>(tmp1)), "x"(reinterpret_cast<const __m128 *>(&tmp1)[1]),
"x"(reinterpret_cast<const __m128 &>(tmp2)), "x"(reinterpret_cast<const __m128 *>(&tmp2)[1]),
"x"(reinterpret_cast<const __m128 &>(tmp3)), "x"(reinterpret_cast<const __m128 *>(&tmp3)[1]));
}
};
#elif defined(VC_IMPL_LRBni)
template<typename T> struct KeepResultsHelper<T, 64> {
static inline void keep(const T &tmp0) {
asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0)), "x"(reinterpret_cast<const __m128 *>(&tmp0)[1]), "x"(reinterpret_cast<const __m128 *>(&tmp0)[2]), "x"(reinterpret_cast<const __m128 *>(&tmp0)[3]));
}
static inline void keep(const T &tmp0, const T &tmp1, const T &tmp2, const T &tmp3) {
asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0)), "x"(reinterpret_cast<const __m128 *>(&tmp0)[1]), "x"(reinterpret_cast<const __m128 *>(&tmp0)[2]), "x"(reinterpret_cast<const __m128 *>(&tmp0)[3]),
"x"(reinterpret_cast<const __m128 &>(tmp1)), "x"(reinterpret_cast<const __m128 *>(&tmp1)[1]), "x"(reinterpret_cast<const __m128 *>(&tmp1)[2]), "x"(reinterpret_cast<const __m128 *>(&tmp1)[3]));
asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp2)), "x"(reinterpret_cast<const __m128 *>(&tmp2)[1]), "x"(reinterpret_cast<const __m128 *>(&tmp2)[2]), "x"(reinterpret_cast<const __m128 *>(&tmp2)[3]),
"x"(reinterpret_cast<const __m128 &>(tmp3)), "x"(reinterpret_cast<const __m128 *>(&tmp3)[1]), "x"(reinterpret_cast<const __m128 *>(&tmp3)[2]), "x"(reinterpret_cast<const __m128 *>(&tmp3)[3]));
}
};
#endif
template<typename T> static inline void keepResults(const T &tmp0)
{
KeepResultsHelper<T, sizeof(T)>::keep(tmp0);
}
template<typename T> static inline void keepResults(const T &tmp0, const T &tmp1, const T &tmp2, const T &tmp3)
{
KeepResultsHelper<T, sizeof(T)>::keep(tmp0, tmp1, tmp2, tmp3);
}
template<typename Vector> class DoMemIos
{
public:
static void run()
{
Benchmark::setColumnData("MemorySize", "half L1");
run(CpuId::L1Data() / (sizeof(Vector) * 2), 128);
Benchmark::setColumnData("MemorySize", "L1");
run(CpuId::L1Data() / (sizeof(Vector) * 1), 128);
Benchmark::setColumnData("MemorySize", "half L2");
run(CpuId::L2Data() / (sizeof(Vector) * 2), 32);
Benchmark::setColumnData("MemorySize", "L2");
run(CpuId::L2Data() / (sizeof(Vector) * 1), 16);
if (CpuId::L3Data() > 0) {
Benchmark::setColumnData("MemorySize", "half L3");
run(CpuId::L3Data() / (sizeof(Vector) * 2), 2);
Benchmark::setColumnData("MemorySize", "L3");
run(CpuId::L3Data() / (sizeof(Vector) * 1), 2);
Benchmark::setColumnData("MemorySize", "4x L3");
run(CpuId::L3Data() / sizeof(Vector) * 4, 1);
} else {
Benchmark::setColumnData("MemorySize", "4x L2");
run(CpuId::L2Data() / sizeof(Vector) * 4, 1);
}
}
private:
static void run(const int Factor, const int Factor2)
{
Vector *a = new Vector[Factor];
#ifndef VC_BENCHMARK_NO_MLOCK
mlock(a, Factor * sizeof(Vector));
#endif
{
Benchmark bm("write", sizeof(Vector) * Factor * Factor2, "Byte");
const Vector foo = PseudoRandom<Vector>::next();
keepResults(foo);
for (int i = 0; i < Factor; i += 4) {
a[i + 0] = foo;
a[i + 1] = foo;
a[i + 2] = foo;
a[i + 3] = foo;
}
while (bm.wantsMoreDataPoints()) {
bm.Start();
for (int j = 0; j < Factor2; ++j) {
keepResults(foo);
for (int i = 0; i < Factor; i += 4) {
a[i + 0] = foo;
a[i + 1] = foo;
a[i + 2] = foo;
a[i + 3] = foo;
}
}
bm.Stop();
}
bm.Print();
}
{
Benchmark timer("r/w", sizeof(Vector) * Factor * Factor2, "Byte");
const Vector foo = PseudoRandom<Vector>::next();
while (timer.wantsMoreDataPoints()) {
timer.Start();
for (int j = 0; j < Factor2; ++j) {
keepResults(foo);
for (int i = 0; i < Factor; i += 4) {
const Vector &tmp0 = a[i + 0];
const Vector &tmp1 = a[i + 1];
const Vector &tmp2 = a[i + 2];
const Vector &tmp3 = a[i + 3];
keepResults(tmp0, tmp1, tmp2, tmp3);
a[i + 0] = foo;
a[i + 1] = foo;
a[i + 2] = foo;
a[i + 3] = foo;
}
}
timer.Stop();
}
timer.Print();
}
{
Benchmark timer("read", sizeof(Vector) * Factor * Factor2, "Byte");
while (timer.wantsMoreDataPoints()) {
timer.Start();
for (int j = 0; j < Factor2; ++j) {
for (int i = 0; i < Factor; i += 4) {
const Vector &tmp0 = a[i + 0];
const Vector &tmp1 = a[i + 1];
const Vector &tmp2 = a[i + 2];
const Vector &tmp3 = a[i + 3];
keepResults(tmp0, tmp1, tmp2, tmp3);
}
}
timer.Stop();
}
timer.Print();
}
delete[] a;
}
};
int bmain()
{
Benchmark::addColumn("MemorySize");
Benchmark::addColumn("datatype");
Benchmark::setColumnData("datatype", "double_v");
DoMemIos<double_v>::run();
Benchmark::setColumnData("datatype", "float_v");
DoMemIos<float_v>::run();
Benchmark::setColumnData("datatype", "short_v");
DoMemIos<short_v>::run();
return 0;
}
<commit_msg>do a first round of touching all values; then start with read so that the cachelines are not marked as dirty there<commit_after>/* This file is part of the Vc library.
Copyright (C) 2009 Matthias Kretz <kretz@kde.org>
Vc is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Vc is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Vc/Vc>
#include "benchmark.h"
#include "random.h"
#include "../cpuid.h"
#include <cstdio>
#include <cstdlib>
using namespace Vc;
template<typename T, int S> struct KeepResultsHelper {
static inline void keep(const T &tmp0) { asm volatile(""::"r"(tmp0)); }
static inline void keep(const T &tmp0, const T &tmp1, const T &tmp2, const T &tmp3) {
#ifdef __x86_64__
asm volatile(""::"r"(tmp0), "r"(tmp1), "r"(tmp2), "r"(tmp3));
#else
asm volatile(""::"r"(tmp0), "r"(tmp1));
asm volatile(""::"r"(tmp2), "r"(tmp3));
#endif
}
};
#if defined(VC_IMPL_AVX)
template<typename T> struct KeepResultsHelper<T, 16> {
static inline void keep(const T &tmp0) { asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0))); }
static inline void keep(const T &tmp0, const T &tmp1, const T &tmp2, const T &tmp3) {
asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0)), "x"(reinterpret_cast<const __m128 &>(tmp1)), "x"(reinterpret_cast<const __m128 &>(tmp2)), "x"(reinterpret_cast<const __m128 &>(tmp3)));
}
};
template<typename T> struct KeepResultsHelper<T, 32> {
static inline void keep(const T &tmp0) {
asm volatile(""::"x"(reinterpret_cast<const __m256 &>(tmp0)));
}
static inline void keep(const T &tmp0, const T &tmp1, const T &tmp2, const T &tmp3) {
asm volatile(""::"x"(reinterpret_cast<const __m256 &>(tmp0)), "x"(reinterpret_cast<const __m256 &>(tmp1)),
"x"(reinterpret_cast<const __m256 &>(tmp2)), "x"(reinterpret_cast<const __m256 &>(tmp3)));
}
};
#elif defined(VC_IMPL_SSE)
template<typename T> struct KeepResultsHelper<T, 16> {
static inline void keep(const T &tmp0) { asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0))); }
static inline void keep(const T &tmp0, const T &tmp1, const T &tmp2, const T &tmp3) {
asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0)), "x"(reinterpret_cast<const __m128 &>(tmp1)), "x"(reinterpret_cast<const __m128 &>(tmp2)), "x"(reinterpret_cast<const __m128 &>(tmp3)));
}
};
template<typename T> struct KeepResultsHelper<T, 32> {
static inline void keep(const T &tmp0) {
asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0)), "x"(reinterpret_cast<const __m128 *>(&tmp0)[1]));
}
static inline void keep(const T &tmp0, const T &tmp1, const T &tmp2, const T &tmp3) {
asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0)), "x"(reinterpret_cast<const __m128 *>(&tmp0)[1]),
"x"(reinterpret_cast<const __m128 &>(tmp1)), "x"(reinterpret_cast<const __m128 *>(&tmp1)[1]),
"x"(reinterpret_cast<const __m128 &>(tmp2)), "x"(reinterpret_cast<const __m128 *>(&tmp2)[1]),
"x"(reinterpret_cast<const __m128 &>(tmp3)), "x"(reinterpret_cast<const __m128 *>(&tmp3)[1]));
}
};
#elif defined(VC_IMPL_LRBni)
template<typename T> struct KeepResultsHelper<T, 64> {
static inline void keep(const T &tmp0) {
asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0)), "x"(reinterpret_cast<const __m128 *>(&tmp0)[1]), "x"(reinterpret_cast<const __m128 *>(&tmp0)[2]), "x"(reinterpret_cast<const __m128 *>(&tmp0)[3]));
}
static inline void keep(const T &tmp0, const T &tmp1, const T &tmp2, const T &tmp3) {
asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp0)), "x"(reinterpret_cast<const __m128 *>(&tmp0)[1]), "x"(reinterpret_cast<const __m128 *>(&tmp0)[2]), "x"(reinterpret_cast<const __m128 *>(&tmp0)[3]),
"x"(reinterpret_cast<const __m128 &>(tmp1)), "x"(reinterpret_cast<const __m128 *>(&tmp1)[1]), "x"(reinterpret_cast<const __m128 *>(&tmp1)[2]), "x"(reinterpret_cast<const __m128 *>(&tmp1)[3]));
asm volatile(""::"x"(reinterpret_cast<const __m128 &>(tmp2)), "x"(reinterpret_cast<const __m128 *>(&tmp2)[1]), "x"(reinterpret_cast<const __m128 *>(&tmp2)[2]), "x"(reinterpret_cast<const __m128 *>(&tmp2)[3]),
"x"(reinterpret_cast<const __m128 &>(tmp3)), "x"(reinterpret_cast<const __m128 *>(&tmp3)[1]), "x"(reinterpret_cast<const __m128 *>(&tmp3)[2]), "x"(reinterpret_cast<const __m128 *>(&tmp3)[3]));
}
};
#endif
template<typename T> static inline void keepResults(const T &tmp0)
{
KeepResultsHelper<T, sizeof(T)>::keep(tmp0);
}
template<typename T> static inline void keepResults(const T &tmp0, const T &tmp1, const T &tmp2, const T &tmp3)
{
KeepResultsHelper<T, sizeof(T)>::keep(tmp0, tmp1, tmp2, tmp3);
}
template<typename Vector> class DoMemIos
{
public:
static void run()
{
Benchmark::setColumnData("MemorySize", "half L1");
run(CpuId::L1Data() / (sizeof(Vector) * 2), 128);
Benchmark::setColumnData("MemorySize", "L1");
run(CpuId::L1Data() / (sizeof(Vector) * 1), 128);
Benchmark::setColumnData("MemorySize", "half L2");
run(CpuId::L2Data() / (sizeof(Vector) * 2), 32);
Benchmark::setColumnData("MemorySize", "L2");
run(CpuId::L2Data() / (sizeof(Vector) * 1), 16);
if (CpuId::L3Data() > 0) {
Benchmark::setColumnData("MemorySize", "half L3");
run(CpuId::L3Data() / (sizeof(Vector) * 2), 2);
Benchmark::setColumnData("MemorySize", "L3");
run(CpuId::L3Data() / (sizeof(Vector) * 1), 2);
Benchmark::setColumnData("MemorySize", "4x L3");
run(CpuId::L3Data() / sizeof(Vector) * 4, 1);
} else {
Benchmark::setColumnData("MemorySize", "4x L2");
run(CpuId::L2Data() / sizeof(Vector) * 4, 1);
}
}
private:
static void run(const int Factor, const int Factor2)
{
Vector *a = new Vector[Factor];
#ifndef VC_BENCHMARK_NO_MLOCK
mlock(a, Factor * sizeof(Vector));
#endif
// initial loop so that the first iteration in the benchmark loop
// has the same cache history as subsequent runs
for (int i = 0; i < Factor; ++i) {
Vector tmp = a[i];
keepResults(tmp);
}
{ // start with reads so that the cache lines are not marked as dirty yet
Benchmark timer("read", sizeof(Vector) * Factor * Factor2, "Byte");
benchmark_loop(timer) {
for (int j = 0; j < Factor2; ++j) {
for (int i = 0; i < Factor; i += 4) {
const Vector &tmp0 = a[i + 0];
const Vector &tmp1 = a[i + 1];
const Vector &tmp2 = a[i + 2];
const Vector &tmp3 = a[i + 3];
keepResults(tmp0, tmp1, tmp2, tmp3);
}
}
}
}
{
Benchmark bm("write", sizeof(Vector) * Factor * Factor2, "Byte");
const Vector foo = PseudoRandom<Vector>::next();
keepResults(foo);
for (int i = 0; i < Factor; i += 4) {
a[i + 0] = foo;
a[i + 1] = foo;
a[i + 2] = foo;
a[i + 3] = foo;
}
while (bm.wantsMoreDataPoints()) {
bm.Start();
for (int j = 0; j < Factor2; ++j) {
keepResults(foo);
for (int i = 0; i < Factor; i += 4) {
a[i + 0] = foo;
a[i + 1] = foo;
a[i + 2] = foo;
a[i + 3] = foo;
}
}
bm.Stop();
}
bm.Print();
}
{
Benchmark timer("r/w", sizeof(Vector) * Factor * Factor2, "Byte");
const Vector foo = PseudoRandom<Vector>::next();
while (timer.wantsMoreDataPoints()) {
timer.Start();
for (int j = 0; j < Factor2; ++j) {
keepResults(foo);
for (int i = 0; i < Factor; i += 4) {
const Vector &tmp0 = a[i + 0];
const Vector &tmp1 = a[i + 1];
const Vector &tmp2 = a[i + 2];
const Vector &tmp3 = a[i + 3];
keepResults(tmp0, tmp1, tmp2, tmp3);
a[i + 0] = foo;
a[i + 1] = foo;
a[i + 2] = foo;
a[i + 3] = foo;
}
}
timer.Stop();
}
timer.Print();
}
delete[] a;
}
};
int bmain()
{
Benchmark::addColumn("MemorySize");
Benchmark::addColumn("datatype");
Benchmark::setColumnData("datatype", "double_v");
DoMemIos<double_v>::run();
Benchmark::setColumnData("datatype", "float_v");
DoMemIos<float_v>::run();
Benchmark::setColumnData("datatype", "short_v");
DoMemIos<short_v>::run();
return 0;
}
<|endoftext|>
|
<commit_before>/*
TidyEngine
Copyright (C) 2016 Jakob Sinclair
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 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
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Contact the author at: jakob.sinclair99@gmail.com
*/
#include "camera2d.hpp"
#include <glm/gtc/matrix_transform.hpp>
Camera2D::~Camera2D()
{
;
}
/*
* Always set the scale of the y axis
* to (-m_Scale) because that makes the positive
* y direction to go down the screen
*/
void Camera2D::Initialise(uint16_t width, uint16_t height)
{
m_Width = width;
m_Height = height;
m_Position.x = 640.0f;
m_Position.y = 360.0f;
m_Position.z = 0.0f;
m_OrthoMatrix = glm::ortho(0.0f, (float)m_Width, 0.0f, (float)m_Height,
0.0f, 100.0f);
glm::vec3 translate = glm::vec3(-m_Position.x + m_Width / 2,
m_Position.y + m_Height / 2, m_Position.z);
m_View = glm::translate(m_View, translate);
glm::vec3 scale = glm::vec3(m_Scale, -m_Scale, m_Scale);
m_Model = glm::scale(glm::mat4(1.0f), scale);
m_Update = false;
}
void Camera2D::Update()
{
if (m_Update == true) {
glm::vec3 translate = glm::vec3(-m_Position.x + m_Width / 2,
m_Position.y + m_Height / 2, 0.0f);
m_View = glm::translate(m_View, translate);
glm::vec3 scale = glm::vec3(m_Scale, -m_Scale, 0.0f);
m_Model = glm::scale(glm::mat4(1.0f), scale);
m_Update = false;
}
}
void Camera2D::SetScale(float scale)
{
m_Scale = scale;
m_Update = true;
}
void Camera2D::SetPosition(glm::vec3 position)
{
m_Position = position;
m_Update = true;
}
const float &Camera2D::GetScale() const
{
return m_Scale;
}
const glm::vec3 &Camera2D::GetPos() const
{
return m_Position;
}
const glm::mat4 &Camera2D::GetProj() const
{
return m_OrthoMatrix;
}
const glm::mat4 &Camera2D::GetView() const
{
return m_View;
}
const glm::mat4 &Camera2D::GetModel() const
{
return m_Model;
}<commit_msg>libTidyEngine: added comment to Camera2D<commit_after>/*
TidyEngine
Copyright (C) 2016 Jakob Sinclair
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 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
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Contact the author at: jakob.sinclair99@gmail.com
*/
#include "camera2d.hpp"
#include <glm/gtc/matrix_transform.hpp>
Camera2D::~Camera2D()
{
;
}
/*
* Always set the scale of the y axis
* to (-m_Scale) because that makes the positive
* y direction to go down the screen
*/
void Camera2D::Initialise(uint16_t width, uint16_t height)
{
m_Width = width;
m_Height = height;
m_Position.x = 640.0f;
m_Position.y = 360.0f;
m_Position.z = 0.0f;
m_OrthoMatrix = glm::ortho(0.0f, (float)m_Width, 0.0f, (float)m_Height,
0.0f, 100.0f);
glm::vec3 translate = glm::vec3(-m_Position.x + m_Width / 2,
m_Position.y + m_Height / 2, m_Position.z);
m_View = glm::translate(m_View, translate);
glm::vec3 scale = glm::vec3(m_Scale, -m_Scale, m_Scale);
m_Model = glm::scale(glm::mat4(1.0f), scale);
m_Update = false;
}
void Camera2D::Update()
{
/* Only update the camera if it has moved, scaled or rotated */
if (m_Update == true) {
glm::vec3 translate = glm::vec3(-m_Position.x + m_Width / 2,
m_Position.y + m_Height / 2, 0.0f);
m_View = glm::translate(m_View, translate);
glm::vec3 scale = glm::vec3(m_Scale, -m_Scale, 0.0f);
m_Model = glm::scale(glm::mat4(1.0f), scale);
m_Update = false;
}
}
void Camera2D::SetScale(float scale)
{
m_Scale = scale;
m_Update = true;
}
void Camera2D::SetPosition(glm::vec3 position)
{
m_Position = position;
m_Update = true;
}
const float &Camera2D::GetScale() const
{
return m_Scale;
}
const glm::vec3 &Camera2D::GetPos() const
{
return m_Position;
}
const glm::mat4 &Camera2D::GetProj() const
{
return m_OrthoMatrix;
}
const glm::mat4 &Camera2D::GetView() const
{
return m_View;
}
const glm::mat4 &Camera2D::GetModel() const
{
return m_Model;
}
<|endoftext|>
|
<commit_before>/***************************************************************************
**
** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <MTheme>
#include "mcontainer.h"
#include "mcontainer_p.h"
#include "mwidgetcreator.h"
M_REGISTER_WIDGET(MContainer)
MContainerPrivate::MContainerPrivate()
{
}
MContainerPrivate::~MContainerPrivate()
{
}
void MContainerPrivate::_q_onCentralWidgetDestroyed()
{
Q_Q(MContainer);
q->model()->setCentralWidget(0);
}
void MContainerPrivate::init(const QString &newTitle)
{
Q_Q(MContainer);
q->model()->setCentralWidget(new MWidget(q));
q->setTitle(newTitle);
q->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}
MContainer::MContainer(QGraphicsItem *parent)
: MWidgetController(new MContainerPrivate(), new MContainerModel(), parent)
{
Q_D(MContainer);
d->init();
}
MContainer::MContainer(const QString &title, QGraphicsItem *parent)
: MWidgetController(new MContainerPrivate(), new MContainerModel(), parent)
{
Q_D(MContainer);
d->init(title);
}
MContainer::~MContainer()
{
}
QGraphicsWidget *MContainer::centralWidget()
{
return model()->centralWidget();
}
void MContainer::setCentralWidget(QGraphicsWidget *centralWidget, bool destroy)
{
QGraphicsWidget *oldCentralWidget = model()->centralWidget();
// Set the new central widget
model()->setCentralWidget(centralWidget);
// Destroy the old central widget if requested
if (destroy) {
delete oldCentralWidget;
if (centralWidget)
connect(centralWidget, SIGNAL(destroyed()), SLOT(_q_onCentralWidgetDestroyed()));
} else {
// pass the ownership back to the caller.
oldCentralWidget->setParentItem(0);
oldCentralWidget->setParent(0);
if (scene())
scene()->removeItem(oldCentralWidget);
if (oldCentralWidget)
disconnect(oldCentralWidget, SIGNAL(destroyed()), this, SLOT(_q_onCentralWidgetDestroyed()));
}
}
QString MContainer::title() const
{
return model()->title();
}
void MContainer::setTitle(const QString &newTitle)
{
model()->setTitle(newTitle);
}
QString MContainer::text() const
{
return model()->text();
}
void MContainer::setText(const QString &text)
{
model()->setText(text);
}
QString MContainer::iconID() const
{
return model()->icon();
}
void MContainer::setIconID(const QString &iconID)
{
model()->setIcon(iconID);
}
bool MContainer::headerVisible() const
{
return model()->headerVisible();
}
void MContainer::setHeaderVisible(const bool visibility)
{
model()->setHeaderVisible(visibility);
}
void MContainer::toggleHeaderVisible()
{
setHeaderVisible(!model()->headerVisible());
}
bool MContainer::isProgressIndicatorVisible() const
{
return model()->progressIndicatorVisible();
}
void MContainer::setProgressIndicatorVisible(bool visibility)
{
model()->setProgressIndicatorVisible(visibility);
}
void MContainer::toggleProgressIndicatorVisible()
{
setProgressIndicatorVisible(!isProgressIndicatorVisible());
}
#include "moc_mcontainer.cpp"
<commit_msg>Changes: MContainer should set only one size policy.<commit_after>/***************************************************************************
**
** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <MTheme>
#include "mcontainer.h"
#include "mcontainer_p.h"
#include "mwidgetcreator.h"
M_REGISTER_WIDGET(MContainer)
MContainerPrivate::MContainerPrivate()
{
}
MContainerPrivate::~MContainerPrivate()
{
}
void MContainerPrivate::_q_onCentralWidgetDestroyed()
{
Q_Q(MContainer);
q->model()->setCentralWidget(0);
}
void MContainerPrivate::init(const QString &newTitle)
{
Q_Q(MContainer);
q->model()->setCentralWidget(new MWidget(q));
q->setTitle(newTitle);
}
MContainer::MContainer(QGraphicsItem *parent)
: MWidgetController(new MContainerPrivate(), new MContainerModel(), parent)
{
Q_D(MContainer);
d->init();
}
MContainer::MContainer(const QString &title, QGraphicsItem *parent)
: MWidgetController(new MContainerPrivate(), new MContainerModel(), parent)
{
Q_D(MContainer);
d->init(title);
}
MContainer::~MContainer()
{
}
QGraphicsWidget *MContainer::centralWidget()
{
return model()->centralWidget();
}
void MContainer::setCentralWidget(QGraphicsWidget *centralWidget, bool destroy)
{
QGraphicsWidget *oldCentralWidget = model()->centralWidget();
// Set the new central widget
model()->setCentralWidget(centralWidget);
// Destroy the old central widget if requested
if (destroy) {
delete oldCentralWidget;
if (centralWidget)
connect(centralWidget, SIGNAL(destroyed()), SLOT(_q_onCentralWidgetDestroyed()));
} else {
// pass the ownership back to the caller.
oldCentralWidget->setParentItem(0);
oldCentralWidget->setParent(0);
if (scene())
scene()->removeItem(oldCentralWidget);
if (oldCentralWidget)
disconnect(oldCentralWidget, SIGNAL(destroyed()), this, SLOT(_q_onCentralWidgetDestroyed()));
}
}
QString MContainer::title() const
{
return model()->title();
}
void MContainer::setTitle(const QString &newTitle)
{
model()->setTitle(newTitle);
}
QString MContainer::text() const
{
return model()->text();
}
void MContainer::setText(const QString &text)
{
model()->setText(text);
}
QString MContainer::iconID() const
{
return model()->icon();
}
void MContainer::setIconID(const QString &iconID)
{
model()->setIcon(iconID);
}
bool MContainer::headerVisible() const
{
return model()->headerVisible();
}
void MContainer::setHeaderVisible(const bool visibility)
{
model()->setHeaderVisible(visibility);
}
void MContainer::toggleHeaderVisible()
{
setHeaderVisible(!model()->headerVisible());
}
bool MContainer::isProgressIndicatorVisible() const
{
return model()->progressIndicatorVisible();
}
void MContainer::setProgressIndicatorVisible(bool visibility)
{
model()->setProgressIndicatorVisible(visibility);
}
void MContainer::toggleProgressIndicatorVisible()
{
setProgressIndicatorVisible(!isProgressIndicatorVisible());
}
#include "moc_mcontainer.cpp"
<|endoftext|>
|
<commit_before>#include "collision-map.h"
#include "platformer/object/object.h"
#include "platformer/game/camera.h"
#include "util/debug.h"
#include "util/token.h"
#include "util/graphics/bitmap.h"
#include "util/exceptions/load_exception.h"
#include <math.h>
namespace Platformer{
static bool within(const Area & area1, const Area & area2){
return !((area1.x > area2.getX2()) ||
(area1.y > area2.getY2()) ||
(area2.x > area1.getX2()) ||
(area2.y > area1.getY2()));
}
CollisionBody::CollisionBody():
velocityX(0),
velocityY(0){
}
CollisionBody::~CollisionBody(){
}
CollisionMap::CollisionMap(const Token * token){
if (*token != "collision-map"){
throw LoadException(__FILE__, __LINE__, "Not a collision map.");
}
TokenView view = token->view();
while (view.hasMore()){
try{
const Token * tok;
view >> tok;
if (*tok == "area"){
// get the name
Area area;
tok->view() >> area.x >> area.y >> area.width >> area.height;
regions.push_back(area);
} else {
Global::debug( 3 ) << "Unhandled Collision attribute: " << tok->getName() << std::endl;
}
} catch ( const TokenException & ex ) {
throw LoadException(__FILE__, __LINE__, ex, "Collision parse error");
} catch ( const LoadException & ex ) {
throw ex;
}
}
}
CollisionMap::~CollisionMap(){
}
void CollisionMap::collides(const CollisionBody & body) const{
Area nextMovement = body.getArea();
// Scan ahead
nextMovement.x += body.getVelocityX();
nextMovement.y += body.getVelocityY();
bool collides = false;
for (std::vector<Area>::const_iterator i = regions.begin(); i != regions.end(); i++){
const Area & area = *i;
if (within(nextMovement, area)){
CollisionInfo info;
info.top = info.bottom = info.left = info.right = false;
// FIXME need to figure out where the collision occurs
if (nextMovement.getX2() >= area.x && body.getArea().getX2() <= area.x){
// Collision is happening at the top
info.left = true;
}
if (nextMovement.getY2() >= area.y && body.getArea().getY2() <= area.y){
// Collision is happening at the left
info.top = true;
}
if (nextMovement.x <= area.getX2() && body.getArea().x >= area.getX2()){
// Collision is happening at the bottom
info.right = true;
}
if (nextMovement.getY2() >= area.y && body.getArea().y >= area.getY2()){
// Collision is happening at the right
info.bottom = true;
}
body.response(info);
collides = true;
}
}
if (!collides){
body.noCollision();
}
}
void CollisionMap::act(){
// Check if they collide with bodies
for (std::vector<Area>::iterator i = regions.begin(); i != regions.end(); i++){
const Area & area = *i;
// Nothing for now
}
}
void CollisionMap::render(const Camera & camera){
Area cameraWindow = { camera.getX(), camera.getY(), camera.getWidth(), camera.getHeight() };
for (std::vector<Area>::iterator i = regions.begin(); i != regions.end(); i++){
const Area & area = *i;
if (within(area, cameraWindow)){
const int x1 = (area.x <= camera.getX() ? 0 : area.x - camera.getX());
const int y1 = (area.y <= camera.getY() ? 0 : area.y - camera.getY());
const int x2 = ((area.x + area.width) >= (camera.getX() + camera.getWidth()) ?
0 : (camera.getX() + camera.getWidth()) - (area.x + area.width));
const int y2 = ((area.y + area.height) >= (camera.getY() + camera.getHeight()) ?
0 : (camera.getY() + camera.getHeight()) - (area.y + area.height));
// Draw to current screen
camera.getWindow().rectangle(x1, y1, (camera.getWidth() - x2), (camera.getHeight() - y2), Graphics::makeColor(0,255,0));
}
}
}
}
<commit_msg>[platformer] Use double for collision rect draw placement.<commit_after>#include "collision-map.h"
#include "platformer/object/object.h"
#include "platformer/game/camera.h"
#include "util/debug.h"
#include "util/token.h"
#include "util/graphics/bitmap.h"
#include "util/exceptions/load_exception.h"
#include <math.h>
namespace Platformer{
static bool within(const Area & area1, const Area & area2){
return !((area1.x > area2.getX2()) ||
(area1.y > area2.getY2()) ||
(area2.x > area1.getX2()) ||
(area2.y > area1.getY2()));
}
CollisionBody::CollisionBody():
velocityX(0),
velocityY(0){
}
CollisionBody::~CollisionBody(){
}
CollisionMap::CollisionMap(const Token * token){
if (*token != "collision-map"){
throw LoadException(__FILE__, __LINE__, "Not a collision map.");
}
TokenView view = token->view();
while (view.hasMore()){
try{
const Token * tok;
view >> tok;
if (*tok == "area"){
// get the name
Area area;
tok->view() >> area.x >> area.y >> area.width >> area.height;
regions.push_back(area);
} else {
Global::debug( 3 ) << "Unhandled Collision attribute: " << tok->getName() << std::endl;
}
} catch ( const TokenException & ex ) {
throw LoadException(__FILE__, __LINE__, ex, "Collision parse error");
} catch ( const LoadException & ex ) {
throw ex;
}
}
}
CollisionMap::~CollisionMap(){
}
void CollisionMap::collides(const CollisionBody & body) const{
Area nextMovement = body.getArea();
// Scan ahead
nextMovement.x += body.getVelocityX();
nextMovement.y += body.getVelocityY();
bool collides = false;
for (std::vector<Area>::const_iterator i = regions.begin(); i != regions.end(); i++){
const Area & area = *i;
if (within(nextMovement, area)){
CollisionInfo info;
info.top = info.bottom = info.left = info.right = false;
// FIXME need to figure out where the collision occurs
if (nextMovement.getX2() >= area.x && body.getArea().getX2() <= area.x){
// Collision is happening at the top
info.left = true;
}
if (nextMovement.getY2() >= area.y && body.getArea().getY2() <= area.y){
// Collision is happening at the left
info.top = true;
}
if (nextMovement.x <= area.getX2() && body.getArea().x >= area.getX2()){
// Collision is happening at the bottom
info.right = true;
}
if (nextMovement.getY2() >= area.y && body.getArea().y >= area.getY2()){
// Collision is happening at the right
info.bottom = true;
}
body.response(info);
collides = true;
}
}
if (!collides){
body.noCollision();
}
}
void CollisionMap::act(){
// Check if they collide with bodies
for (std::vector<Area>::iterator i = regions.begin(); i != regions.end(); i++){
const Area & area = *i;
// Nothing for now
}
}
void CollisionMap::render(const Camera & camera){
Area cameraWindow = { camera.getX(), camera.getY(), camera.getWidth(), camera.getHeight() };
for (std::vector<Area>::iterator i = regions.begin(); i != regions.end(); i++){
const Area & area = *i;
if (within(area, cameraWindow)){
const double x1 = (area.x <= camera.getX() ? 0 : area.x - camera.getX());
const double y1 = (area.y <= camera.getY() ? 0 : area.y - camera.getY());
const double x2 = ((area.x + area.width) >= (camera.getX() + camera.getWidth()) ?
0 : (camera.getX() + camera.getWidth()) - (area.x + area.width));
const double y2 = ((area.y + area.height) >= (camera.getY() + camera.getHeight()) ?
0 : (camera.getY() + camera.getHeight()) - (area.y + area.height));
// Draw to current screen
camera.getWindow().rectangle(x1, y1, (camera.getWidth() - x2), (camera.getHeight() - y2), Graphics::makeColor(0,255,0));
}
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu)
*
* Released under the MIT license, see LICENSE.txt
*/
#include <sstream>
#include <deque>
#include <iostream>
#include "halValidate.h"
#include "hal.h"
using namespace std;
using namespace hal;
// current implementation is poor and hacky. should fix up to
// use iterators to properly scan the segments.
void hal::validateBottomSegment(const BottomSegment* bottomSegment)
{
const Genome* genome = bottomSegment->getGenome();
hal_index_t index = bottomSegment->getArrayIndex();
if (index < 0 || index >= (hal_index_t)genome->getSequenceLength())
{
stringstream ss;
ss << "Bottom segment out of range " << index << " in genome "
<< genome->getName();
throw hal_exception(ss.str());
}
if (bottomSegment->getLength() < 1)
{
stringstream ss;
ss << "Bottom segment " << index << " in genome " << genome->getName()
<< " has length 0 which is not currently supported";
throw hal_exception(ss.str());
}
hal_size_t numChildren = bottomSegment->getNumChildren();
for (hal_size_t child = 0; child < numChildren; ++child)
{
const Genome* childGenome = genome->getChild(child);
const hal_index_t childIndex = bottomSegment->getChildIndex(child);
if (childGenome != NULL && childIndex != NULL_INDEX)
{
if (childIndex >= (hal_index_t)childGenome->getNumTopSegments())
{
stringstream ss;
ss << "Child " << child << " index " <<childIndex << " of segment "
<< bottomSegment->getArrayIndex() << " out of range in genome "
<< childGenome->getName();
throw hal_exception(ss.str());
}
TopSegmentIteratorConstPtr topSegmentIteratr =
childGenome->getTopSegmentIterator(childIndex);
const TopSegment* childSegment = topSegmentIteratr->getTopSegment();
if (childSegment->getLength() != bottomSegment->getLength())
{
stringstream ss;
ss << "Child " << child << " length of segment "
<< bottomSegment->getArrayIndex()
<< " in genome " << genome->getName() << " has length "
<< childSegment->getLength() << " which does not match "
<< bottomSegment->getLength();
throw hal_exception(ss.str());
}
if (childSegment->getNextParalogyIndex() == NULL_INDEX &&
childSegment->getParentIndex() != bottomSegment->getArrayIndex())
{
throw hal_exception("parent / child index mismatch (parent=" +
genome->getName() + " child=" +
childGenome->getName());
}
}
}
const hal_index_t parseIndex = bottomSegment->getTopParseIndex();
if (parseIndex == NULL_INDEX)
{
if (genome->getParent() != NULL)
{
stringstream ss;
ss << "Bottom segment " << bottomSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has null parse index";
throw hal_exception(ss.str());
}
}
else
{
if (parseIndex >= (hal_index_t)genome->getNumTopSegments())
{
stringstream ss;
ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has parse index " << parseIndex
<< " greater than the number of top segments, "
<< (hal_index_t)genome->getNumTopSegments();
throw hal_exception(ss.str());
}
TopSegmentIteratorConstPtr parseIterator =
genome->getTopSegmentIterator(parseIndex);
const TopSegment* parseSegment = parseIterator->getTopSegment();
hal_offset_t parseOffset = bottomSegment->getTopParseOffset();
if (parseOffset >= parseSegment->getLength())
{
stringstream ss;
ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has parse offset, " << parseOffset
<< ", greater than the length of the segment, "
<< parseSegment->getLength();
throw hal_exception(ss.str());
}
if ((hal_index_t)parseOffset + parseSegment->getStartPosition() !=
bottomSegment->getStartPosition())
{
throw hal_exception("parse index broken in bottom segment in genome " +
genome->getName());
}
}
}
void hal::validateTopSegment(const TopSegment* topSegment)
{
const Genome* genome = topSegment->getGenome();
hal_index_t index = topSegment->getArrayIndex();
if (index < 0 || index >= (hal_index_t)genome->getSequenceLength())
{
stringstream ss;
ss << "Segment out of range " << index << " in genome "
<< genome->getName();
throw hal_exception(ss.str());
}
if (topSegment->getLength() < 1)
{
stringstream ss;
ss << "Top segment " << index << " in genome " << genome->getName()
<< " has length 0 which is not currently supported";
throw hal_exception(ss.str());
}
const Genome* parentGenome = genome->getParent();
const hal_index_t parentIndex = topSegment->getParentIndex();
if (parentGenome != NULL && parentIndex != NULL_INDEX)
{
if (parentIndex >= (hal_index_t)parentGenome->getNumBottomSegments())
{
stringstream ss;
ss << "Parent index " << parentIndex << " of segment "
<< topSegment->getArrayIndex() << " out of range in genome "
<< parentGenome->getName();
throw hal_exception(ss.str());
}
BottomSegmentIteratorConstPtr bottomSegmentIterator =
parentGenome->getBottomSegmentIterator(parentIndex);
const BottomSegment* parentSegment =
bottomSegmentIterator->getBottomSegment();
if (topSegment->getLength() != parentSegment->getLength())
{
stringstream ss;
ss << "Parent length of segment " << topSegment->getArrayIndex()
<< " in genome " << genome->getName() << " has length "
<< parentSegment->getLength() << " which does not match "
<< topSegment->getLength();
throw hal_exception(ss.str());
}
}
const hal_index_t parseIndex = topSegment->getBottomParseIndex();
if (parseIndex == NULL_INDEX)
{
if (genome->getNumChildren() != 0)
{
stringstream ss;
ss << "Segment " << topSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has null parse index";
throw hal_exception(ss.str());
}
}
else
{
if (parseIndex >= (hal_index_t)genome->getNumBottomSegments())
{
stringstream ss;
ss << "Top Segment " << topSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has parse index out of range";
throw hal_exception(ss.str());
}
hal_offset_t parseOffset = topSegment->getBottomParseOffset();
BottomSegmentIteratorConstPtr bottomSegmentIterator =
genome->getBottomSegmentIterator(parseIndex);
const BottomSegment* parseSegment =
bottomSegmentIterator->getBottomSegment();
if (parseOffset >= parseSegment->getLength())
{
stringstream ss;
ss << "Top Segment " << topSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has parse offset out of range";
throw hal_exception(ss.str());
}
if ((hal_index_t)parseOffset + parseSegment->getStartPosition() !=
topSegment->getStartPosition())
{
throw hal_exception("parse index broken in top segment in genome " +
genome->getName());
}
}
const hal_index_t paralogyIndex = topSegment->getNextParalogyIndex();
if (paralogyIndex != NULL_INDEX)
{
TopSegmentIteratorConstPtr pti =
genome->getTopSegmentIterator(paralogyIndex);
if (pti->getTopSegment()->getParentIndex() != topSegment->getParentIndex())
{
stringstream ss;
ss << "Top segment " << topSegment->getArrayIndex() << " has parent index "
<< topSegment->getParentIndex() << ", but next paraglog "
<< topSegment->getNextParalogyIndex() << " has parent Index "
<< pti->getTopSegment()->getParentIndex()
<< ". Paralogous top segments must share same parent.";
throw hal_exception(ss.str());
}
}
}
void hal::validateSequence(const Sequence* sequence)
{
// Verify that the DNA sequence doesn't contain funny characters
DNAIteratorConstPtr dnaIt = sequence->getDNAIterator();
hal_size_t length = sequence->getSequenceLength();
for (hal_size_t i = 0; i < length; ++i)
{
hal_dna_t c = dnaIt->getChar();
if (isNucleotide(c) == false)
{
stringstream ss;
ss << "Non-nucleotide character discoverd at position "
<< i << " of sequence " << sequence->getName() << ": " << c;
throw hal_exception(ss.str());
}
}
// Check the top segments
if (sequence->getGenome()->getParent() != NULL)
{
hal_size_t totalTopLength = 0;
TopSegmentIteratorConstPtr topIt = sequence->getTopSegmentIterator();
hal_size_t numTopSegments = sequence->getNumTopSegments();
for (hal_size_t i = 0; i < numTopSegments; ++i)
{
const TopSegment* topSegment = topIt->getTopSegment();
validateTopSegment(topSegment);
totalTopLength += topSegment->getLength();
topIt->toRight();
}
if (totalTopLength != length)
{
stringstream ss;
ss << "Sequence " << sequence->getName() << " has length " << length
<< " but its top segments add up to " << totalTopLength;
throw hal_exception(ss.str());
}
}
// Check the bottom segments
if (sequence->getGenome()->getNumChildren() > 0)
{
hal_size_t totalBottomLength = 0;
BottomSegmentIteratorConstPtr bottomIt =
sequence->getBottomSegmentIterator();
hal_size_t numBottomSegments = sequence->getNumBottomSegments();
for (hal_size_t i = 0; i < numBottomSegments; ++i)
{
const BottomSegment* bottomSegment = bottomIt->getBottomSegment();
validateBottomSegment(bottomSegment);
totalBottomLength += bottomSegment->getLength();
bottomIt->toRight();
}
if (totalBottomLength != length)
{
stringstream ss;
ss << "Sequence " << sequence->getName() << " has length " << length
<< " but its bottom segments add up to " << totalBottomLength;
throw hal_exception(ss.str());
}
}
}
void hal::validateGenome(const Genome* genome)
{
// first we check the sequence coverage
hal_size_t totalTop = 0;
hal_size_t totalBottom = 0;
hal_size_t totalLength = 0;
SequenceIteratorConstPtr seqIt = genome->getSequenceIterator();
hal_size_t numSequences = genome->getNumSequences();
for (hal_size_t i = 0; i < numSequences; ++i)
{
const Sequence* sequence = seqIt->getSequence();
validateSequence(sequence);
totalTop += sequence->getNumTopSegments();
totalBottom += sequence->getNumBottomSegments();
totalLength += sequence->getSequenceLength();
// make sure it doesn't overlap any other sequences;
const Sequence* s1 =
genome->getSequenceBySite(sequence->getStartPosition());
if (s1 == NULL || s1->getName() != sequence->getName())
{
stringstream ss;
ss << "Sequence " << sequence->getName() << " has a bad overlap in "
<< genome->getName();
throw hal_exception(ss.str());
}
const Sequence* s2 =
genome->getSequenceBySite(sequence->getStartPosition() +
sequence->getSequenceLength() - 1);
if (s2 == NULL || s2->getName() != sequence->getName())
{
stringstream ss;
ss << "Sequence " << sequence->getName() << " has a bad overlap in "
<< genome->getName();
throw hal_exception(ss.str());
}
}
hal_size_t genomeLength = genome->getSequenceLength();
hal_size_t genomeTop = genome->getNumTopSegments();
hal_size_t genomeBottom = genome->getNumBottomSegments();
if (genomeLength != totalLength)
{
stringstream ss;
ss << "Problem: genome has length " << genomeLength
<< "But sequences total " << totalLength;
throw hal_exception(ss.str());
}
if (genomeTop != totalTop)
{
stringstream ss;
ss << "Problem: genome has " << genomeTop << " top segments but "
<< "sequences have " << totalTop << " top segments";
throw ss.str();
}
if (genomeBottom != totalBottom)
{
stringstream ss;
ss << "Problem: genome has " << genomeBottom << " bottom segments but "
<< "sequences have " << totalBottom << " bottom segments";
throw hal_exception(ss.str());
}
}
void hal::validateAlignment(AlignmentConstPtr alignment)
{
deque<string> bfQueue;
bfQueue.push_back(alignment->getRootName());
while (bfQueue.empty() == false)
{
string name = bfQueue.back();
bfQueue.pop_back();
if (name.empty() == false)
{
const Genome* genome = alignment->openGenome(name);
if (genome == NULL)
{
throw hal_exception("Failure to open genome " + name);
}
validateGenome(genome);
vector<string> childNames = alignment->getChildNames(name);
for (size_t i = 0; i < childNames.size(); ++i)
{
bfQueue.push_front(childNames[i]);
}
}
}
}
<commit_msg>fix error message<commit_after>/*
* Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu)
*
* Released under the MIT license, see LICENSE.txt
*/
#include <sstream>
#include <deque>
#include <iostream>
#include "halValidate.h"
#include "hal.h"
using namespace std;
using namespace hal;
// current implementation is poor and hacky. should fix up to
// use iterators to properly scan the segments.
void hal::validateBottomSegment(const BottomSegment* bottomSegment)
{
const Genome* genome = bottomSegment->getGenome();
hal_index_t index = bottomSegment->getArrayIndex();
if (index < 0 || index >= (hal_index_t)genome->getSequenceLength())
{
stringstream ss;
ss << "Bottom segment out of range " << index << " in genome "
<< genome->getName();
throw hal_exception(ss.str());
}
if (bottomSegment->getLength() < 1)
{
stringstream ss;
ss << "Bottom segment " << index << " in genome " << genome->getName()
<< " has length 0 which is not currently supported";
throw hal_exception(ss.str());
}
hal_size_t numChildren = bottomSegment->getNumChildren();
for (hal_size_t child = 0; child < numChildren; ++child)
{
const Genome* childGenome = genome->getChild(child);
const hal_index_t childIndex = bottomSegment->getChildIndex(child);
if (childGenome != NULL && childIndex != NULL_INDEX)
{
if (childIndex >= (hal_index_t)childGenome->getNumTopSegments())
{
stringstream ss;
ss << "Child " << child << " index " <<childIndex << " of segment "
<< bottomSegment->getArrayIndex() << " out of range in genome "
<< childGenome->getName();
throw hal_exception(ss.str());
}
TopSegmentIteratorConstPtr topSegmentIteratr =
childGenome->getTopSegmentIterator(childIndex);
const TopSegment* childSegment = topSegmentIteratr->getTopSegment();
if (childSegment->getLength() != bottomSegment->getLength())
{
stringstream ss;
ss << "Child " << child << " length of segment "
<< bottomSegment->getArrayIndex()
<< " in genome " << genome->getName() << " has length "
<< childSegment->getLength() << " which does not match "
<< bottomSegment->getLength();
throw hal_exception(ss.str());
}
if (childSegment->getNextParalogyIndex() == NULL_INDEX &&
childSegment->getParentIndex() != bottomSegment->getArrayIndex())
{
throw hal_exception("parent / child index mismatch (parent=" +
genome->getName() + " child=" +
childGenome->getName());
}
}
}
const hal_index_t parseIndex = bottomSegment->getTopParseIndex();
if (parseIndex == NULL_INDEX)
{
if (genome->getParent() != NULL)
{
stringstream ss;
ss << "Bottom segment " << bottomSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has null parse index";
throw hal_exception(ss.str());
}
}
else
{
if (parseIndex >= (hal_index_t)genome->getNumTopSegments())
{
stringstream ss;
ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has parse index " << parseIndex
<< " greater than the number of top segments, "
<< (hal_index_t)genome->getNumTopSegments();
throw hal_exception(ss.str());
}
TopSegmentIteratorConstPtr parseIterator =
genome->getTopSegmentIterator(parseIndex);
const TopSegment* parseSegment = parseIterator->getTopSegment();
hal_offset_t parseOffset = bottomSegment->getTopParseOffset();
if (parseOffset >= parseSegment->getLength())
{
stringstream ss;
ss << "BottomSegment " << bottomSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has parse offset, " << parseOffset
<< ", greater than the length of the segment, "
<< parseSegment->getLength();
throw hal_exception(ss.str());
}
if ((hal_index_t)parseOffset + parseSegment->getStartPosition() !=
bottomSegment->getStartPosition())
{
throw hal_exception("parse index broken in bottom segment in genome " +
genome->getName());
}
}
}
void hal::validateTopSegment(const TopSegment* topSegment)
{
const Genome* genome = topSegment->getGenome();
hal_index_t index = topSegment->getArrayIndex();
if (index < 0 || index >= (hal_index_t)genome->getSequenceLength())
{
stringstream ss;
ss << "Segment out of range " << index << " in genome "
<< genome->getName();
throw hal_exception(ss.str());
}
if (topSegment->getLength() < 1)
{
stringstream ss;
ss << "Top segment " << index << " in genome " << genome->getName()
<< " has length 0 which is not currently supported";
throw hal_exception(ss.str());
}
const Genome* parentGenome = genome->getParent();
const hal_index_t parentIndex = topSegment->getParentIndex();
if (parentGenome != NULL && parentIndex != NULL_INDEX)
{
if (parentIndex >= (hal_index_t)parentGenome->getNumBottomSegments())
{
stringstream ss;
ss << "Parent index " << parentIndex << " of segment "
<< topSegment->getArrayIndex() << " out of range in genome "
<< parentGenome->getName();
throw hal_exception(ss.str());
}
BottomSegmentIteratorConstPtr bottomSegmentIterator =
parentGenome->getBottomSegmentIterator(parentIndex);
const BottomSegment* parentSegment =
bottomSegmentIterator->getBottomSegment();
if (topSegment->getLength() != parentSegment->getLength())
{
stringstream ss;
ss << "Parent length of segment " << topSegment->getArrayIndex()
<< " in genome " << genome->getName() << " has length "
<< parentSegment->getLength() << " which does not match "
<< topSegment->getLength();
throw hal_exception(ss.str());
}
}
const hal_index_t parseIndex = topSegment->getBottomParseIndex();
if (parseIndex == NULL_INDEX)
{
if (genome->getNumChildren() != 0)
{
stringstream ss;
ss << "Top Segment " << topSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has null parse index";
throw hal_exception(ss.str());
}
}
else
{
if (parseIndex >= (hal_index_t)genome->getNumBottomSegments())
{
stringstream ss;
ss << "Top Segment " << topSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has parse index out of range";
throw hal_exception(ss.str());
}
hal_offset_t parseOffset = topSegment->getBottomParseOffset();
BottomSegmentIteratorConstPtr bottomSegmentIterator =
genome->getBottomSegmentIterator(parseIndex);
const BottomSegment* parseSegment =
bottomSegmentIterator->getBottomSegment();
if (parseOffset >= parseSegment->getLength())
{
stringstream ss;
ss << "Top Segment " << topSegment->getArrayIndex() << " in genome "
<< genome->getName() << " has parse offset out of range";
throw hal_exception(ss.str());
}
if ((hal_index_t)parseOffset + parseSegment->getStartPosition() !=
topSegment->getStartPosition())
{
throw hal_exception("parse index broken in top segment in genome " +
genome->getName());
}
}
const hal_index_t paralogyIndex = topSegment->getNextParalogyIndex();
if (paralogyIndex != NULL_INDEX)
{
TopSegmentIteratorConstPtr pti =
genome->getTopSegmentIterator(paralogyIndex);
if (pti->getTopSegment()->getParentIndex() != topSegment->getParentIndex())
{
stringstream ss;
ss << "Top segment " << topSegment->getArrayIndex() << " has parent index "
<< topSegment->getParentIndex() << ", but next paraglog "
<< topSegment->getNextParalogyIndex() << " has parent Index "
<< pti->getTopSegment()->getParentIndex()
<< ". Paralogous top segments must share same parent.";
throw hal_exception(ss.str());
}
}
}
void hal::validateSequence(const Sequence* sequence)
{
// Verify that the DNA sequence doesn't contain funny characters
DNAIteratorConstPtr dnaIt = sequence->getDNAIterator();
hal_size_t length = sequence->getSequenceLength();
for (hal_size_t i = 0; i < length; ++i)
{
hal_dna_t c = dnaIt->getChar();
if (isNucleotide(c) == false)
{
stringstream ss;
ss << "Non-nucleotide character discoverd at position "
<< i << " of sequence " << sequence->getName() << ": " << c;
throw hal_exception(ss.str());
}
}
// Check the top segments
if (sequence->getGenome()->getParent() != NULL)
{
hal_size_t totalTopLength = 0;
TopSegmentIteratorConstPtr topIt = sequence->getTopSegmentIterator();
hal_size_t numTopSegments = sequence->getNumTopSegments();
for (hal_size_t i = 0; i < numTopSegments; ++i)
{
const TopSegment* topSegment = topIt->getTopSegment();
validateTopSegment(topSegment);
totalTopLength += topSegment->getLength();
topIt->toRight();
}
if (totalTopLength != length)
{
stringstream ss;
ss << "Sequence " << sequence->getName() << " has length " << length
<< " but its top segments add up to " << totalTopLength;
throw hal_exception(ss.str());
}
}
// Check the bottom segments
if (sequence->getGenome()->getNumChildren() > 0)
{
hal_size_t totalBottomLength = 0;
BottomSegmentIteratorConstPtr bottomIt =
sequence->getBottomSegmentIterator();
hal_size_t numBottomSegments = sequence->getNumBottomSegments();
for (hal_size_t i = 0; i < numBottomSegments; ++i)
{
const BottomSegment* bottomSegment = bottomIt->getBottomSegment();
validateBottomSegment(bottomSegment);
totalBottomLength += bottomSegment->getLength();
bottomIt->toRight();
}
if (totalBottomLength != length)
{
stringstream ss;
ss << "Sequence " << sequence->getName() << " has length " << length
<< " but its bottom segments add up to " << totalBottomLength;
throw hal_exception(ss.str());
}
}
}
void hal::validateGenome(const Genome* genome)
{
// first we check the sequence coverage
hal_size_t totalTop = 0;
hal_size_t totalBottom = 0;
hal_size_t totalLength = 0;
SequenceIteratorConstPtr seqIt = genome->getSequenceIterator();
hal_size_t numSequences = genome->getNumSequences();
for (hal_size_t i = 0; i < numSequences; ++i)
{
const Sequence* sequence = seqIt->getSequence();
validateSequence(sequence);
totalTop += sequence->getNumTopSegments();
totalBottom += sequence->getNumBottomSegments();
totalLength += sequence->getSequenceLength();
// make sure it doesn't overlap any other sequences;
const Sequence* s1 =
genome->getSequenceBySite(sequence->getStartPosition());
if (s1 == NULL || s1->getName() != sequence->getName())
{
stringstream ss;
ss << "Sequence " << sequence->getName() << " has a bad overlap in "
<< genome->getName();
throw hal_exception(ss.str());
}
const Sequence* s2 =
genome->getSequenceBySite(sequence->getStartPosition() +
sequence->getSequenceLength() - 1);
if (s2 == NULL || s2->getName() != sequence->getName())
{
stringstream ss;
ss << "Sequence " << sequence->getName() << " has a bad overlap in "
<< genome->getName();
throw hal_exception(ss.str());
}
}
hal_size_t genomeLength = genome->getSequenceLength();
hal_size_t genomeTop = genome->getNumTopSegments();
hal_size_t genomeBottom = genome->getNumBottomSegments();
if (genomeLength != totalLength)
{
stringstream ss;
ss << "Problem: genome has length " << genomeLength
<< "But sequences total " << totalLength;
throw hal_exception(ss.str());
}
if (genomeTop != totalTop)
{
stringstream ss;
ss << "Problem: genome has " << genomeTop << " top segments but "
<< "sequences have " << totalTop << " top segments";
throw ss.str();
}
if (genomeBottom != totalBottom)
{
stringstream ss;
ss << "Problem: genome has " << genomeBottom << " bottom segments but "
<< "sequences have " << totalBottom << " bottom segments";
throw hal_exception(ss.str());
}
}
void hal::validateAlignment(AlignmentConstPtr alignment)
{
deque<string> bfQueue;
bfQueue.push_back(alignment->getRootName());
while (bfQueue.empty() == false)
{
string name = bfQueue.back();
bfQueue.pop_back();
if (name.empty() == false)
{
const Genome* genome = alignment->openGenome(name);
if (genome == NULL)
{
throw hal_exception("Failure to open genome " + name);
}
validateGenome(genome);
vector<string> childNames = alignment->getChildNames(name);
for (size_t i = 0; i < childNames.size(); ++i)
{
bfQueue.push_front(childNames[i]);
}
}
}
}
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (C) 2016 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "auth/default_authorizer.hh"
extern "C" {
#include <crypt.h>
#include <unistd.h>
}
#include <chrono>
#include <random>
#include <boost/algorithm/string/join.hpp>
#include <boost/range.hpp>
#include <seastar/core/reactor.hh>
#include "auth/authenticated_user.hh"
#include "auth/common.hh"
#include "auth/permission.hh"
#include "cql3/query_processor.hh"
#include "cql3/untyped_result_set.hh"
#include "exceptions/exceptions.hh"
#include "log.hh"
namespace auth {
const sstring& default_authorizer_name() {
static const sstring name = meta::AUTH_PACKAGE_NAME + "CassandraAuthorizer";
return name;
}
static const sstring ROLE_NAME = "role";
static const sstring RESOURCE_NAME = "resource";
static const sstring PERMISSIONS_NAME = "permissions";
static const sstring PERMISSIONS_CF = "role_permissions";
static logging::logger alogger("default_authorizer");
// To ensure correct initialization order, we unfortunately need to use a string literal.
static const class_registrator<
authorizer,
default_authorizer,
cql3::query_processor&,
::service::migration_manager&> password_auth_reg("org.apache.cassandra.auth.CassandraAuthorizer");
default_authorizer::default_authorizer(cql3::query_processor& qp, ::service::migration_manager& mm)
: _qp(qp)
, _migration_manager(mm) {
}
default_authorizer::~default_authorizer() {
}
future<> default_authorizer::start() {
static const sstring create_table = sprint(
"CREATE TABLE %s.%s ("
"%s text,"
"%s text,"
"%s set<text>,"
"PRIMARY KEY(%s, %s)"
") WITH gc_grace_seconds=%d",
meta::AUTH_KS,
PERMISSIONS_CF,
ROLE_NAME,
RESOURCE_NAME,
PERMISSIONS_NAME,
ROLE_NAME,
RESOURCE_NAME,
90 * 24 * 60 * 60); // 3 months.
return once_among_shards([this] {
return create_metadata_table_if_missing(
PERMISSIONS_CF,
_qp,
create_table,
_migration_manager);
});
}
future<> default_authorizer::stop() {
return make_ready_future<>();
}
future<permission_set> default_authorizer::authorize_role_directly(
stdx::string_view role_name,
const resource& r,
const service& ser) const {
return ser.has_superuser(role_name).then([this, role_name, &r](bool has_superuser) {
if (has_superuser) {
return make_ready_future<permission_set>(r.applicable_permissions());
}
static const sstring query = sprint(
"SELECT %s FROM %s.%s WHERE %s = ? AND %s = ?",
PERMISSIONS_NAME,
meta::AUTH_KS,
PERMISSIONS_CF,
ROLE_NAME,
RESOURCE_NAME);
return _qp.process(
query,
db::consistency_level::LOCAL_ONE,
{sstring(role_name), r.name()}).then([](::shared_ptr<cql3::untyped_result_set> results) {
if (results->empty()) {
return permissions::NONE;
}
return permissions::from_strings(results->one().get_set<sstring>(PERMISSIONS_NAME));
});
});
}
future<permission_set> default_authorizer::authorize(
stdx::string_view role_name,
const resource& r,
service& ser) const {
return do_with(permission_set(), [this, &ser, role_name, &r](auto& ps) {
return ser.get_roles(role_name).then([this, &ser, &ps, &r](std::unordered_set<sstring> all_roles) {
return do_with(std::move(all_roles), [this, &ser, &ps, &r](const auto& all_roles) {
return parallel_for_each(all_roles, [this, &ser, &ps, &r](stdx::string_view role_name) {
return this->authorize_role_directly(role_name, r, ser).then([&ps](permission_set rp) {
ps = permission_set::from_mask(ps.mask() | rp.mask());
});
});
});
}).then([&ps] {
return ps;
});
});
}
future<>
default_authorizer::modify(
stdx::string_view role_name,
permission_set set,
const resource& resource,
stdx::string_view op) {
// TODO: why does this not check super user?
auto query = sprint(
"UPDATE %s.%s SET %s = %s %s ? WHERE %s = ? AND %s = ?",
meta::AUTH_KS,
PERMISSIONS_CF,
PERMISSIONS_NAME,
PERMISSIONS_NAME,
op,
ROLE_NAME,
RESOURCE_NAME);
return _qp.process(
query,
db::consistency_level::ONE,
{permissions::to_strings(set), sstring(role_name), resource.name()}).discard_result();
}
future<> default_authorizer::grant(stdx::string_view role_name, permission_set set, const resource& resource) {
return modify(role_name, std::move(set), resource, "+");
}
future<> default_authorizer::revoke(stdx::string_view role_name, permission_set set, const resource& resource) {
return modify(role_name, std::move(set), resource, "-");
}
future<std::vector<permission_details>> default_authorizer::list(
permission_set set,
const std::optional<resource>& resource,
const std::optional<stdx::string_view>& role_name,
service& ser) const {
sstring query = sprint(
"SELECT %s, %s, %s FROM %s.%s",
ROLE_NAME,
RESOURCE_NAME,
PERMISSIONS_NAME,
meta::AUTH_KS,
PERMISSIONS_CF);
// Oh, look, it is a case where it does not pay off to have
// parameters to process in an initializer list.
future<::shared_ptr<cql3::untyped_result_set>> f = make_ready_future<::shared_ptr<cql3::untyped_result_set>>();
if (role_name) {
f = ser.get_roles(*role_name).then([this, &resource, query, &f](
std::unordered_set<sstring> all_roles) mutable {
if (resource) {
query += sprint(" WHERE %s IN ? AND %s = ?", ROLE_NAME, RESOURCE_NAME);
return _qp.process(query, db::consistency_level::ONE, {all_roles, resource->name()});
}
query += sprint(" WHERE %s IN ?", ROLE_NAME);
return _qp.process(query, db::consistency_level::ONE, {all_roles});
});
} else if (resource) {
query += sprint(" WHERE %s = ? ALLOW FILTERING", RESOURCE_NAME);
f = _qp.process(query, db::consistency_level::ONE, {resource->name()});
} else {
f = _qp.process(query, db::consistency_level::ONE, {});
}
return f.then([set](::shared_ptr<cql3::untyped_result_set> res) {
std::vector<permission_details> result;
for (auto& row : *res) {
if (row.has(PERMISSIONS_NAME)) {
auto username = row.get_as<sstring>(ROLE_NAME);
auto resource = parse_resource(row.get_as<sstring>(RESOURCE_NAME));
auto ps = permissions::from_strings(row.get_set<sstring>(PERMISSIONS_NAME));
ps = permission_set::from_mask(ps.mask() & set.mask());
result.emplace_back(permission_details {username, resource, ps});
}
}
return make_ready_future<std::vector<permission_details>>(std::move(result));
});
}
future<> default_authorizer::revoke_all(stdx::string_view role_name) {
auto query = sprint(
"DELETE FROM %s.%s WHERE %s = ?",
meta::AUTH_KS,
PERMISSIONS_CF,
ROLE_NAME);
return _qp.process(
query,
db::consistency_level::ONE,
{sstring(role_name)}).discard_result().handle_exception([role_name](auto ep) {
try {
std::rethrow_exception(ep);
} catch (exceptions::request_execution_exception& e) {
alogger.warn("CassandraAuthorizer failed to revoke all permissions of {}: {}", role_name, e);
}
});
}
future<> default_authorizer::revoke_all(const resource& resource) {
auto query = sprint(
"SELECT %s FROM %s.%s WHERE %s = ? ALLOW FILTERING",
ROLE_NAME,
meta::AUTH_KS,
PERMISSIONS_CF,
RESOURCE_NAME);
return _qp.process(
query,
db::consistency_level::LOCAL_ONE,
{resource.name()}).then_wrapped([this, resource](future<::shared_ptr<cql3::untyped_result_set>> f) {
try {
auto res = f.get0();
return parallel_for_each(
res->begin(),
res->end(),
[this, res, resource](const cql3::untyped_result_set::row& r) {
auto query = sprint(
"DELETE FROM %s.%s WHERE %s = ? AND %s = ?",
meta::AUTH_KS,
PERMISSIONS_CF,
ROLE_NAME,
RESOURCE_NAME);
return _qp.process(
query,
db::consistency_level::LOCAL_ONE,
{r.get_as<sstring>(ROLE_NAME), resource.name()}).discard_result().handle_exception(
[resource](auto ep) {
try {
std::rethrow_exception(ep);
} catch (exceptions::request_execution_exception& e) {
alogger.warn("CassandraAuthorizer failed to revoke all permissions on {}: {}", resource, e);
}
});
});
} catch (exceptions::request_execution_exception& e) {
alogger.warn("CassandraAuthorizer failed to revoke all permissions on {}: {}", resource, e);
return make_ready_future();
}
});
}
const resource_set& default_authorizer::protected_resources() const {
static const resource_set resources({ make_data_resource(meta::AUTH_KS, PERMISSIONS_CF) });
return resources;
}
}
<commit_msg>auth: Remove outdated "TODO"<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (C) 2016 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "auth/default_authorizer.hh"
extern "C" {
#include <crypt.h>
#include <unistd.h>
}
#include <chrono>
#include <random>
#include <boost/algorithm/string/join.hpp>
#include <boost/range.hpp>
#include <seastar/core/reactor.hh>
#include "auth/authenticated_user.hh"
#include "auth/common.hh"
#include "auth/permission.hh"
#include "cql3/query_processor.hh"
#include "cql3/untyped_result_set.hh"
#include "exceptions/exceptions.hh"
#include "log.hh"
namespace auth {
const sstring& default_authorizer_name() {
static const sstring name = meta::AUTH_PACKAGE_NAME + "CassandraAuthorizer";
return name;
}
static const sstring ROLE_NAME = "role";
static const sstring RESOURCE_NAME = "resource";
static const sstring PERMISSIONS_NAME = "permissions";
static const sstring PERMISSIONS_CF = "role_permissions";
static logging::logger alogger("default_authorizer");
// To ensure correct initialization order, we unfortunately need to use a string literal.
static const class_registrator<
authorizer,
default_authorizer,
cql3::query_processor&,
::service::migration_manager&> password_auth_reg("org.apache.cassandra.auth.CassandraAuthorizer");
default_authorizer::default_authorizer(cql3::query_processor& qp, ::service::migration_manager& mm)
: _qp(qp)
, _migration_manager(mm) {
}
default_authorizer::~default_authorizer() {
}
future<> default_authorizer::start() {
static const sstring create_table = sprint(
"CREATE TABLE %s.%s ("
"%s text,"
"%s text,"
"%s set<text>,"
"PRIMARY KEY(%s, %s)"
") WITH gc_grace_seconds=%d",
meta::AUTH_KS,
PERMISSIONS_CF,
ROLE_NAME,
RESOURCE_NAME,
PERMISSIONS_NAME,
ROLE_NAME,
RESOURCE_NAME,
90 * 24 * 60 * 60); // 3 months.
return once_among_shards([this] {
return create_metadata_table_if_missing(
PERMISSIONS_CF,
_qp,
create_table,
_migration_manager);
});
}
future<> default_authorizer::stop() {
return make_ready_future<>();
}
future<permission_set> default_authorizer::authorize_role_directly(
stdx::string_view role_name,
const resource& r,
const service& ser) const {
return ser.has_superuser(role_name).then([this, role_name, &r](bool has_superuser) {
if (has_superuser) {
return make_ready_future<permission_set>(r.applicable_permissions());
}
static const sstring query = sprint(
"SELECT %s FROM %s.%s WHERE %s = ? AND %s = ?",
PERMISSIONS_NAME,
meta::AUTH_KS,
PERMISSIONS_CF,
ROLE_NAME,
RESOURCE_NAME);
return _qp.process(
query,
db::consistency_level::LOCAL_ONE,
{sstring(role_name), r.name()}).then([](::shared_ptr<cql3::untyped_result_set> results) {
if (results->empty()) {
return permissions::NONE;
}
return permissions::from_strings(results->one().get_set<sstring>(PERMISSIONS_NAME));
});
});
}
future<permission_set> default_authorizer::authorize(
stdx::string_view role_name,
const resource& r,
service& ser) const {
return do_with(permission_set(), [this, &ser, role_name, &r](auto& ps) {
return ser.get_roles(role_name).then([this, &ser, &ps, &r](std::unordered_set<sstring> all_roles) {
return do_with(std::move(all_roles), [this, &ser, &ps, &r](const auto& all_roles) {
return parallel_for_each(all_roles, [this, &ser, &ps, &r](stdx::string_view role_name) {
return this->authorize_role_directly(role_name, r, ser).then([&ps](permission_set rp) {
ps = permission_set::from_mask(ps.mask() | rp.mask());
});
});
});
}).then([&ps] {
return ps;
});
});
}
future<>
default_authorizer::modify(
stdx::string_view role_name,
permission_set set,
const resource& resource,
stdx::string_view op) {
auto query = sprint(
"UPDATE %s.%s SET %s = %s %s ? WHERE %s = ? AND %s = ?",
meta::AUTH_KS,
PERMISSIONS_CF,
PERMISSIONS_NAME,
PERMISSIONS_NAME,
op,
ROLE_NAME,
RESOURCE_NAME);
return _qp.process(
query,
db::consistency_level::ONE,
{permissions::to_strings(set), sstring(role_name), resource.name()}).discard_result();
}
future<> default_authorizer::grant(stdx::string_view role_name, permission_set set, const resource& resource) {
return modify(role_name, std::move(set), resource, "+");
}
future<> default_authorizer::revoke(stdx::string_view role_name, permission_set set, const resource& resource) {
return modify(role_name, std::move(set), resource, "-");
}
future<std::vector<permission_details>> default_authorizer::list(
permission_set set,
const std::optional<resource>& resource,
const std::optional<stdx::string_view>& role_name,
service& ser) const {
sstring query = sprint(
"SELECT %s, %s, %s FROM %s.%s",
ROLE_NAME,
RESOURCE_NAME,
PERMISSIONS_NAME,
meta::AUTH_KS,
PERMISSIONS_CF);
// Oh, look, it is a case where it does not pay off to have
// parameters to process in an initializer list.
future<::shared_ptr<cql3::untyped_result_set>> f = make_ready_future<::shared_ptr<cql3::untyped_result_set>>();
if (role_name) {
f = ser.get_roles(*role_name).then([this, &resource, query, &f](
std::unordered_set<sstring> all_roles) mutable {
if (resource) {
query += sprint(" WHERE %s IN ? AND %s = ?", ROLE_NAME, RESOURCE_NAME);
return _qp.process(query, db::consistency_level::ONE, {all_roles, resource->name()});
}
query += sprint(" WHERE %s IN ?", ROLE_NAME);
return _qp.process(query, db::consistency_level::ONE, {all_roles});
});
} else if (resource) {
query += sprint(" WHERE %s = ? ALLOW FILTERING", RESOURCE_NAME);
f = _qp.process(query, db::consistency_level::ONE, {resource->name()});
} else {
f = _qp.process(query, db::consistency_level::ONE, {});
}
return f.then([set](::shared_ptr<cql3::untyped_result_set> res) {
std::vector<permission_details> result;
for (auto& row : *res) {
if (row.has(PERMISSIONS_NAME)) {
auto username = row.get_as<sstring>(ROLE_NAME);
auto resource = parse_resource(row.get_as<sstring>(RESOURCE_NAME));
auto ps = permissions::from_strings(row.get_set<sstring>(PERMISSIONS_NAME));
ps = permission_set::from_mask(ps.mask() & set.mask());
result.emplace_back(permission_details {username, resource, ps});
}
}
return make_ready_future<std::vector<permission_details>>(std::move(result));
});
}
future<> default_authorizer::revoke_all(stdx::string_view role_name) {
auto query = sprint(
"DELETE FROM %s.%s WHERE %s = ?",
meta::AUTH_KS,
PERMISSIONS_CF,
ROLE_NAME);
return _qp.process(
query,
db::consistency_level::ONE,
{sstring(role_name)}).discard_result().handle_exception([role_name](auto ep) {
try {
std::rethrow_exception(ep);
} catch (exceptions::request_execution_exception& e) {
alogger.warn("CassandraAuthorizer failed to revoke all permissions of {}: {}", role_name, e);
}
});
}
future<> default_authorizer::revoke_all(const resource& resource) {
auto query = sprint(
"SELECT %s FROM %s.%s WHERE %s = ? ALLOW FILTERING",
ROLE_NAME,
meta::AUTH_KS,
PERMISSIONS_CF,
RESOURCE_NAME);
return _qp.process(
query,
db::consistency_level::LOCAL_ONE,
{resource.name()}).then_wrapped([this, resource](future<::shared_ptr<cql3::untyped_result_set>> f) {
try {
auto res = f.get0();
return parallel_for_each(
res->begin(),
res->end(),
[this, res, resource](const cql3::untyped_result_set::row& r) {
auto query = sprint(
"DELETE FROM %s.%s WHERE %s = ? AND %s = ?",
meta::AUTH_KS,
PERMISSIONS_CF,
ROLE_NAME,
RESOURCE_NAME);
return _qp.process(
query,
db::consistency_level::LOCAL_ONE,
{r.get_as<sstring>(ROLE_NAME), resource.name()}).discard_result().handle_exception(
[resource](auto ep) {
try {
std::rethrow_exception(ep);
} catch (exceptions::request_execution_exception& e) {
alogger.warn("CassandraAuthorizer failed to revoke all permissions on {}: {}", resource, e);
}
});
});
} catch (exceptions::request_execution_exception& e) {
alogger.warn("CassandraAuthorizer failed to revoke all permissions on {}: {}", resource, e);
return make_ready_future();
}
});
}
const resource_set& default_authorizer::protected_resources() const {
static const resource_set resources({ make_data_resource(meta::AUTH_KS, PERMISSIONS_CF) });
return resources;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 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 "net/base/keygen_handler.h"
#include <windows.h>
#include <wincrypt.h>
#pragma comment(lib, "crypt32.lib")
#include <rpc.h>
#pragma comment(lib, "rpcrt4.lib")
#include <list>
#include <string>
#include <vector>
#include "base/base64.h"
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/string_piece.h"
#include "base/utf_string_conversions.h"
namespace net {
// TODO(rsleevi): The following encoding functions are adapted from
// base/crypto/rsa_private_key.h and can/should probably be refactored.
static const uint8 kSequenceTag = 0x30;
void PrependLength(size_t size, std::list<BYTE>* data) {
// The high bit is used to indicate whether additional octets are needed to
// represent the length.
if (size < 0x80) {
data->push_front(static_cast<BYTE>(size));
} else {
uint8 num_bytes = 0;
while (size > 0) {
data->push_front(static_cast<BYTE>(size & 0xFF));
size >>= 8;
num_bytes++;
}
CHECK_LE(num_bytes, 4);
data->push_front(0x80 | num_bytes);
}
}
void PrependTypeHeaderAndLength(uint8 type, uint32 length,
std::vector<BYTE>* output) {
std::list<BYTE> type_and_length;
PrependLength(length, &type_and_length);
type_and_length.push_front(type);
output->insert(output->begin(), type_and_length.begin(),
type_and_length.end());
}
bool EncodeAndAppendType(LPCSTR type, const void* to_encode,
std::vector<BYTE>* output) {
BOOL ok;
DWORD size = 0;
ok = CryptEncodeObject(X509_ASN_ENCODING, type, to_encode, NULL, &size);
DCHECK(ok);
if (!ok)
return false;
std::vector<BYTE>::size_type old_size = output->size();
output->resize(old_size + size);
ok = CryptEncodeObject(X509_ASN_ENCODING, type, to_encode,
&(*output)[old_size], &size);
DCHECK(ok);
if (!ok)
return false;
// Sometimes the initial call to CryptEncodeObject gave a generous estimate
// of the size, so shrink back to what was actually used.
output->resize(old_size + size);
return true;
}
// Appends a DER IA5String containing |challenge| to |output|.
// Returns true if encoding was successful.
bool EncodeChallenge(const std::string& challenge, std::vector<BYTE>* output) {
CERT_NAME_VALUE challenge_nv;
challenge_nv.dwValueType = CERT_RDN_IA5_STRING;
challenge_nv.Value.pbData = const_cast<BYTE*>(
reinterpret_cast<const BYTE*>(challenge.data()));
challenge_nv.Value.cbData = challenge.size();
return EncodeAndAppendType(X509_ANY_STRING, &challenge_nv, output);
}
// Appends a DER SubjectPublicKeyInfo structure for the signing key in |prov|
// to |output|.
// Returns true if encoding was successful.
bool EncodeSubjectPublicKeyInfo(HCRYPTPROV prov, std::vector<BYTE>* output) {
BOOL ok;
DWORD size = 0;
// From the private key stored in HCRYPTPROV, obtain the public key, stored
// as a CERT_PUBLIC_KEY_INFO structure. Currently, only RSA public keys are
// supported.
ok = CryptExportPublicKeyInfoEx(prov, AT_KEYEXCHANGE, X509_ASN_ENCODING,
szOID_RSA_RSA, 0, NULL, NULL, &size);
DCHECK(ok);
if (!ok)
return false;
std::vector<BYTE> public_key_info(size);
PCERT_PUBLIC_KEY_INFO public_key_casted =
reinterpret_cast<PCERT_PUBLIC_KEY_INFO>(&public_key_info[0]);
ok = CryptExportPublicKeyInfoEx(prov, AT_KEYEXCHANGE, X509_ASN_ENCODING,
szOID_RSA_RSA, 0, NULL, public_key_casted,
&size);
DCHECK(ok);
if (!ok)
return false;
public_key_info.resize(size);
return EncodeAndAppendType(X509_PUBLIC_KEY_INFO, &public_key_info[0],
output);
}
// Generates an ASN.1 DER representation of the PublicKeyAndChallenge structure
// from the signing key of |prov| and the specified |challenge| and appends it
// to |output|.
// True if the the encoding was successfully generated.
bool GetPublicKeyAndChallenge(HCRYPTPROV prov, const std::string& challenge,
std::vector<BYTE>* output) {
if (!EncodeSubjectPublicKeyInfo(prov, output) ||
!EncodeChallenge(challenge, output)) {
return false;
}
PrependTypeHeaderAndLength(kSequenceTag, output->size(), output);
return true;
}
// Generates a DER encoded SignedPublicKeyAndChallenge structure from the
// signing key of |prov| and the specified |challenge| string and appends it
// to |output|.
// True if the encoding was successfully generated.
bool GetSignedPublicKeyAndChallenge(HCRYPTPROV prov,
const std::string& challenge,
std::string* output) {
std::vector<BYTE> pkac;
if (!GetPublicKeyAndChallenge(prov, challenge, &pkac))
return false;
std::vector<BYTE> signature;
std::vector<BYTE> signed_pkac;
DWORD size = 0;
BOOL ok;
// While the MSDN documentation states that CERT_SIGNED_CONTENT_INFO should
// be an X.509 certificate type, for encoding this is not necessary. The
// result of encoding this structure will be a DER-encoded structure with
// the ASN.1 equivalent of
// ::= SEQUENCE {
// ToBeSigned IMPLICIT OCTET STRING,
// SignatureAlgorithm AlgorithmIdentifier,
// Signature BIT STRING
// }
//
// This happens to be the same naive type as an SPKAC, so this works.
CERT_SIGNED_CONTENT_INFO info;
info.ToBeSigned.cbData = pkac.size();
info.ToBeSigned.pbData = &pkac[0];
info.SignatureAlgorithm.pszObjId = szOID_RSA_MD5RSA;
info.SignatureAlgorithm.Parameters.cbData = 0;
info.SignatureAlgorithm.Parameters.pbData = NULL;
ok = CryptSignCertificate(prov, AT_KEYEXCHANGE, X509_ASN_ENCODING,
info.ToBeSigned.pbData, info.ToBeSigned.cbData,
&info.SignatureAlgorithm, NULL, NULL, &size);
DCHECK(ok);
if (!ok)
return false;
signature.resize(size);
info.Signature.cbData = signature.size();
info.Signature.pbData = &signature[0];
info.Signature.cUnusedBits = 0;
ok = CryptSignCertificate(prov, AT_KEYEXCHANGE, X509_ASN_ENCODING,
info.ToBeSigned.pbData, info.ToBeSigned.cbData,
&info.SignatureAlgorithm, NULL,
info.Signature.pbData, &info.Signature.cbData);
DCHECK(ok);
if (!ok || !EncodeAndAppendType(X509_CERT, &info, &signed_pkac))
return false;
output->assign(reinterpret_cast<char*>(&signed_pkac[0]),
signed_pkac.size());
return true;
}
// Generates a unique name for the container which will store the key that is
// generated. The traditional Windows approach is to use a GUID here.
std::wstring GetNewKeyContainerId() {
RPC_STATUS status = RPC_S_OK;
std::wstring result;
UUID id = { 0 };
status = UuidCreateSequential(&id);
if (status != RPC_S_OK && status != RPC_S_UUID_LOCAL_ONLY)
return result;
RPC_WSTR rpc_string = NULL;
status = UuidToString(&id, &rpc_string);
if (status != RPC_S_OK)
return result;
// RPC_WSTR is unsigned short*. wchar_t is a built-in type of Visual C++,
// so the type cast is necessary.
result.assign(reinterpret_cast<wchar_t*>(rpc_string));
RpcStringFree(&rpc_string);
return result;
}
void StoreKeyLocationInCache(HCRYPTPROV prov) {
BOOL ok;
DWORD size = 0;
// Though it is known the container and provider name, as they are supplied
// during GenKeyAndSignChallenge, explicitly resolving them via
// CryptGetProvParam ensures that any defaults (such as provider name being
// NULL) or any CSP modifications to the container name are properly
// reflected.
// Find the container name. Though the MSDN documentation states it will
// return the exact same value as supplied when the provider was aquired, it
// also notes the return type will be CHAR, /not/ WCHAR.
ok = CryptGetProvParam(prov, PP_CONTAINER, NULL, &size, 0);
if (!ok)
return;
std::vector<BYTE> buffer(size);
ok = CryptGetProvParam(prov, PP_CONTAINER, &buffer[0], &size, 0);
if (!ok)
return;
KeygenHandler::KeyLocation key_location;
UTF8ToWide(reinterpret_cast<char*>(&buffer[0]), size,
&key_location.container_name);
// Get the provider name. This will always resolve, even if NULL (indicating
// the default provider) was supplied to the CryptAcquireContext.
size = 0;
ok = CryptGetProvParam(prov, PP_NAME, NULL, &size, 0);
if (!ok)
return;
buffer.resize(size);
ok = CryptGetProvParam(prov, PP_NAME, &buffer[0], &size, 0);
if (!ok)
return;
UTF8ToWide(reinterpret_cast<char*>(&buffer[0]), size,
&key_location.provider_name);
std::vector<BYTE> public_key_info;
if (!EncodeSubjectPublicKeyInfo(prov, &public_key_info))
return;
KeygenHandler::Cache* cache = KeygenHandler::Cache::GetInstance();
cache->Insert(std::string(public_key_info.begin(), public_key_info.end()),
key_location);
}
bool KeygenHandler::KeyLocation::Equals(
const KeygenHandler::KeyLocation& location) const {
return container_name == location.container_name &&
provider_name == location.provider_name;
}
std::string KeygenHandler::GenKeyAndSignChallenge() {
std::string result;
bool is_success = true;
HCRYPTPROV prov = NULL;
HCRYPTKEY key = NULL;
DWORD flags = (key_size_in_bits_ << 16) | CRYPT_EXPORTABLE;
std::string spkac;
std::wstring new_key_id;
// TODO(rsleevi): Have the user choose which provider they should use, which
// needs to be filtered by those providers which can provide the key type
// requested or the key size requested. This is especially important for
// generating certificates that will be stored on smart cards.
const int kMaxAttempts = 5;
BOOL ok = FALSE;
for (int attempt = 0; attempt < kMaxAttempts; ++attempt) {
// Per MSDN documentation for CryptAcquireContext, if applications will be
// creating their own keys, they should ensure unique naming schemes to
// prevent overlap with any other applications or consumers of CSPs, and
// *should not* store new keys within the default, NULL key container.
new_key_id = GetNewKeyContainerId();
if (new_key_id.empty())
return result;
// Only create new key containers, so that existing key containers are not
// overwritten.
ok = CryptAcquireContext(&prov, new_key_id.c_str(), NULL, PROV_RSA_FULL,
CRYPT_SILENT | CRYPT_NEWKEYSET);
if (ok || GetLastError() != NTE_BAD_KEYSET)
break;
}
if (!ok) {
LOG(ERROR) << "Couldn't acquire a CryptoAPI provider context: "
<< GetLastError();
is_success = false;
goto failure;
}
if (!CryptGenKey(prov, CALG_RSA_KEYX, flags, &key)) {
LOG(ERROR) << "Couldn't generate an RSA key";
is_success = false;
goto failure;
}
if (!GetSignedPublicKeyAndChallenge(prov, challenge_, &spkac)) {
LOG(ERROR) << "Couldn't generate the signed public key and challenge";
is_success = false;
goto failure;
}
if (!base::Base64Encode(spkac, &result)) {
LOG(ERROR) << "Couldn't convert signed key into base64";
is_success = false;
goto failure;
}
StoreKeyLocationInCache(prov);
failure:
if (!is_success) {
LOG(ERROR) << "SSL Keygen failed";
} else {
LOG(INFO) << "SSL Key succeeded";
}
if (key) {
// Securely destroys the handle, but leaves the underlying key alone. The
// key can be obtained again by resolving the key location. If
// |stores_key_| is false, the underlying key will be destroyed below.
CryptDestroyKey(key);
}
if (prov) {
CryptReleaseContext(prov, 0);
prov = NULL;
if (!stores_key_) {
// Fully destroys any of the keys that were created and releases prov.
CryptAcquireContext(&prov, new_key_id.c_str(), NULL, PROV_RSA_FULL,
CRYPT_SILENT | CRYPT_DELETEKEYSET);
}
}
return result;
}
} // namespace net
<commit_msg>Simplify the Windows <keygen> implementation by making better use of CryptoAPI.<commit_after>// Copyright (c) 2010 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 "net/base/keygen_handler.h"
#include <windows.h>
#include <wincrypt.h>
#pragma comment(lib, "crypt32.lib")
#include <rpc.h>
#pragma comment(lib, "rpcrt4.lib")
#include <list>
#include <string>
#include <vector>
#include "base/base64.h"
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
namespace net {
bool EncodeAndAppendType(LPCSTR type, const void* to_encode,
std::vector<BYTE>* output) {
BOOL ok;
DWORD size = 0;
ok = CryptEncodeObject(X509_ASN_ENCODING, type, to_encode, NULL, &size);
DCHECK(ok);
if (!ok)
return false;
std::vector<BYTE>::size_type old_size = output->size();
output->resize(old_size + size);
ok = CryptEncodeObject(X509_ASN_ENCODING, type, to_encode,
&(*output)[old_size], &size);
DCHECK(ok);
if (!ok)
return false;
// Sometimes the initial call to CryptEncodeObject gave a generous estimate
// of the size, so shrink back to what was actually used.
output->resize(old_size + size);
return true;
}
// Assigns the contents of a CERT_PUBLIC_KEY_INFO structure for the signing
// key in |prov| to |output|. Returns true if encoding was successful.
bool GetSubjectPublicKeyInfo(HCRYPTPROV prov, std::vector<BYTE>* output) {
BOOL ok;
DWORD size = 0;
// From the private key stored in HCRYPTPROV, obtain the public key, stored
// as a CERT_PUBLIC_KEY_INFO structure. Currently, only RSA public keys are
// supported.
ok = CryptExportPublicKeyInfoEx(prov, AT_KEYEXCHANGE, X509_ASN_ENCODING,
szOID_RSA_RSA, 0, NULL, NULL, &size);
DCHECK(ok);
if (!ok)
return false;
output->resize(size);
PCERT_PUBLIC_KEY_INFO public_key_casted =
reinterpret_cast<PCERT_PUBLIC_KEY_INFO>(&(*output)[0]);
ok = CryptExportPublicKeyInfoEx(prov, AT_KEYEXCHANGE, X509_ASN_ENCODING,
szOID_RSA_RSA, 0, NULL, public_key_casted,
&size);
DCHECK(ok);
if (!ok)
return false;
output->resize(size);
return true;
}
// Appends a DER SubjectPublicKeyInfo structure for the signing key in |prov|
// to |output|.
// Returns true if encoding was successful.
bool EncodeSubjectPublicKeyInfo(HCRYPTPROV prov, std::vector<BYTE>* output) {
std::vector<BYTE> public_key_info;
if (!GetSubjectPublicKeyInfo(prov, &public_key_info))
return false;
return EncodeAndAppendType(X509_PUBLIC_KEY_INFO, &public_key_info[0],
output);
}
// Generates a DER encoded SignedPublicKeyAndChallenge structure from the
// signing key of |prov| and the specified ASCII |challenge| string and
// appends it to |output|.
// True if the encoding was successfully generated.
bool GetSignedPublicKeyAndChallenge(HCRYPTPROV prov,
const std::string& challenge,
std::string* output) {
std::wstring wide_challenge = ASCIIToWide(challenge);
std::vector<BYTE> spki;
if (!GetSubjectPublicKeyInfo(prov, &spki))
return false;
// PublicKeyAndChallenge ::= SEQUENCE {
// spki SubjectPublicKeyInfo,
// challenge IA5STRING
// }
CERT_KEYGEN_REQUEST_INFO pkac;
pkac.dwVersion = CERT_KEYGEN_REQUEST_V1;
pkac.SubjectPublicKeyInfo =
*reinterpret_cast<PCERT_PUBLIC_KEY_INFO>(&spki[0]);
pkac.pwszChallengeString = const_cast<wchar_t*>(wide_challenge.c_str());
CRYPT_ALGORITHM_IDENTIFIER sig_alg;
memset(&sig_alg, 0, sizeof(sig_alg));
sig_alg.pszObjId = szOID_RSA_MD5RSA;
BOOL ok;
DWORD size = 0;
std::vector<BYTE> signed_pkac;
ok = CryptSignAndEncodeCertificate(prov, AT_KEYEXCHANGE, X509_ASN_ENCODING,
X509_KEYGEN_REQUEST_TO_BE_SIGNED,
&pkac, &sig_alg, NULL,
NULL, &size);
DCHECK(ok);
if (!ok)
return false;
signed_pkac.resize(size);
ok = CryptSignAndEncodeCertificate(prov, AT_KEYEXCHANGE, X509_ASN_ENCODING,
X509_KEYGEN_REQUEST_TO_BE_SIGNED,
&pkac, &sig_alg, NULL,
&signed_pkac[0], &size);
DCHECK(ok);
if (!ok)
return false;
output->assign(reinterpret_cast<char*>(&signed_pkac[0]), size);
return true;
}
// Generates a unique name for the container which will store the key that is
// generated. The traditional Windows approach is to use a GUID here.
std::wstring GetNewKeyContainerId() {
RPC_STATUS status = RPC_S_OK;
std::wstring result;
UUID id = { 0 };
status = UuidCreateSequential(&id);
if (status != RPC_S_OK && status != RPC_S_UUID_LOCAL_ONLY)
return result;
RPC_WSTR rpc_string = NULL;
status = UuidToString(&id, &rpc_string);
if (status != RPC_S_OK)
return result;
// RPC_WSTR is unsigned short*. wchar_t is a built-in type of Visual C++,
// so the type cast is necessary.
result.assign(reinterpret_cast<wchar_t*>(rpc_string));
RpcStringFree(&rpc_string);
return result;
}
void StoreKeyLocationInCache(HCRYPTPROV prov) {
BOOL ok;
DWORD size = 0;
// Though it is known the container and provider name, as they are supplied
// during GenKeyAndSignChallenge, explicitly resolving them via
// CryptGetProvParam ensures that any defaults (such as provider name being
// NULL) or any CSP modifications to the container name are properly
// reflected.
// Find the container name. Though the MSDN documentation states it will
// return the exact same value as supplied when the provider was aquired, it
// also notes the return type will be CHAR, /not/ WCHAR.
ok = CryptGetProvParam(prov, PP_CONTAINER, NULL, &size, 0);
if (!ok)
return;
std::vector<BYTE> buffer(size);
ok = CryptGetProvParam(prov, PP_CONTAINER, &buffer[0], &size, 0);
if (!ok)
return;
KeygenHandler::KeyLocation key_location;
UTF8ToWide(reinterpret_cast<char*>(&buffer[0]), size,
&key_location.container_name);
// Get the provider name. This will always resolve, even if NULL (indicating
// the default provider) was supplied to the CryptAcquireContext.
size = 0;
ok = CryptGetProvParam(prov, PP_NAME, NULL, &size, 0);
if (!ok)
return;
buffer.resize(size);
ok = CryptGetProvParam(prov, PP_NAME, &buffer[0], &size, 0);
if (!ok)
return;
UTF8ToWide(reinterpret_cast<char*>(&buffer[0]), size,
&key_location.provider_name);
std::vector<BYTE> public_key_info;
if (!EncodeSubjectPublicKeyInfo(prov, &public_key_info))
return;
KeygenHandler::Cache* cache = KeygenHandler::Cache::GetInstance();
cache->Insert(std::string(public_key_info.begin(), public_key_info.end()),
key_location);
}
bool KeygenHandler::KeyLocation::Equals(
const KeygenHandler::KeyLocation& location) const {
return container_name == location.container_name &&
provider_name == location.provider_name;
}
std::string KeygenHandler::GenKeyAndSignChallenge() {
std::string result;
bool is_success = true;
HCRYPTPROV prov = NULL;
HCRYPTKEY key = NULL;
DWORD flags = (key_size_in_bits_ << 16) | CRYPT_EXPORTABLE;
std::string spkac;
std::wstring new_key_id;
// TODO(rsleevi): Have the user choose which provider they should use, which
// needs to be filtered by those providers which can provide the key type
// requested or the key size requested. This is especially important for
// generating certificates that will be stored on smart cards.
const int kMaxAttempts = 5;
BOOL ok = FALSE;
for (int attempt = 0; attempt < kMaxAttempts; ++attempt) {
// Per MSDN documentation for CryptAcquireContext, if applications will be
// creating their own keys, they should ensure unique naming schemes to
// prevent overlap with any other applications or consumers of CSPs, and
// *should not* store new keys within the default, NULL key container.
new_key_id = GetNewKeyContainerId();
if (new_key_id.empty())
return result;
// Only create new key containers, so that existing key containers are not
// overwritten.
ok = CryptAcquireContext(&prov, new_key_id.c_str(), NULL, PROV_RSA_FULL,
CRYPT_SILENT | CRYPT_NEWKEYSET);
if (ok || GetLastError() != NTE_BAD_KEYSET)
break;
}
if (!ok) {
LOG(ERROR) << "Couldn't acquire a CryptoAPI provider context: "
<< GetLastError();
is_success = false;
goto failure;
}
if (!CryptGenKey(prov, CALG_RSA_KEYX, flags, &key)) {
LOG(ERROR) << "Couldn't generate an RSA key";
is_success = false;
goto failure;
}
if (!GetSignedPublicKeyAndChallenge(prov, challenge_, &spkac)) {
LOG(ERROR) << "Couldn't generate the signed public key and challenge";
is_success = false;
goto failure;
}
if (!base::Base64Encode(spkac, &result)) {
LOG(ERROR) << "Couldn't convert signed key into base64";
is_success = false;
goto failure;
}
StoreKeyLocationInCache(prov);
failure:
if (!is_success) {
LOG(ERROR) << "SSL Keygen failed";
} else {
LOG(INFO) << "SSL Key succeeded";
}
if (key) {
// Securely destroys the handle, but leaves the underlying key alone. The
// key can be obtained again by resolving the key location. If
// |stores_key_| is false, the underlying key will be destroyed below.
CryptDestroyKey(key);
}
if (prov) {
CryptReleaseContext(prov, 0);
prov = NULL;
if (!stores_key_) {
// Fully destroys any of the keys that were created and releases prov.
CryptAcquireContext(&prov, new_key_id.c_str(), NULL, PROV_RSA_FULL,
CRYPT_SILENT | CRYPT_DELETEKEYSET);
}
}
return result;
}
} // namespace net
<|endoftext|>
|
<commit_before>/*
* NuoDB Adapter
*/
#include "nuodb/sqlapi/SqlEnvironment.h"
#include "nuodb/sqlapi/SqlConnection.h"
#include "nuodb/sqlapi/SqlDatabaseMetaData.h"
#include "nuodb/sqlapi/SqlStatement.h"
#include "nuodb/sqlapi/SqlExceptions.h"
using nuodb::sqlapi::ErrorCodeException;
using nuodb::sqlapi::SqlConnection;
using nuodb::sqlapi::SqlDatabaseMetaData;
using nuodb::sqlapi::SqlEnvironment;
using nuodb::sqlapi::SqlOption;
using nuodb::sqlapi::SqlOptionArray;
using nuodb::sqlapi::SqlStatement;
#include <ruby.h>
#include <iostream> // TODO temporary
using std::cout; // TODO temporary
//-------------------------------------------------------------------------
// Type definitions
class ClassType
{
public:
VALUE type;
};
#define DECLARE_CLASS_TYPE(classname) \
class classname : public ClassType \
{ public: void init(VALUE module); }
DECLARE_CLASS_TYPE(SqlEnvironmentType);
DECLARE_CLASS_TYPE(SqlConnectionType);
DECLARE_CLASS_TYPE(SqlDatabaseMetaDataType);
DECLARE_CLASS_TYPE(SqlStatementType);
DECLARE_CLASS_TYPE(SqlPreparedStatementType);
DECLARE_CLASS_TYPE(SqlResultSetType);
DECLARE_CLASS_TYPE(SqlColumnMetaDataType);
class AllTypes
{
VALUE module;
public:
SqlEnvironmentType env;
SqlConnectionType con;
SqlDatabaseMetaDataType dbmeta;
SqlStatementType stmt;
SqlPreparedStatementType pstmt;
SqlResultSetType rset;
SqlColumnMetaDataType colmeta;
void init();
};
static AllTypes types;
//-------------------------------------------------------------------------
#define WRAPPER_CTOR(WT, RT) \
WT(RT& arg) : ref(arg) {}
#define WRAPPER_RELEASE(WT) \
static void release(WT* self) { \
self->ref.release(); \
delete self; \
}
#define WRAPPER_AS_REF(WT, RT) \
static RT& asRef(VALUE value) { \
Check_Type(value, T_DATA); \
return ((WT*) DATA_PTR(value))->ref; \
}
#define WRAPPER_METHODS(WT, RT) \
WRAPPER_CTOR(WT, RT) \
WRAPPER_RELEASE(WT) \
WRAPPER_AS_REF(WT, RT)
class SqlDatabaseMetaDataWrapper
{
SqlDatabaseMetaData& ref;
public:
WRAPPER_METHODS(SqlDatabaseMetaDataWrapper, SqlDatabaseMetaData)
static VALUE getDatabaseVersion(VALUE self)
{
return rb_str_new2(asRef(self).getDatabaseVersion());
}
};
class SqlStatementWrapper
{
SqlStatement& ref;
public:
WRAPPER_METHODS(SqlStatementWrapper, SqlStatement)
};
class SqlConnectionWrapper
{
SqlConnection& ref;
public:
WRAPPER_METHODS(SqlConnectionWrapper, SqlConnection)
static VALUE createStatement(VALUE self)
{
SqlStatementWrapper* w = new SqlStatementWrapper(asRef(self).createStatement());
VALUE obj = Data_Wrap_Struct(types.stmt.type, 0, SqlStatementWrapper::release, w);
rb_obj_call_init(obj, 0, 0);
return obj;
}
static VALUE getMetaData(VALUE self)
{
SqlDatabaseMetaDataWrapper* w = new SqlDatabaseMetaDataWrapper(asRef(self).getMetaData());
VALUE obj = Data_Wrap_Struct(types.dbmeta.type, 0, SqlDatabaseMetaDataWrapper::release, w);
rb_obj_call_init(obj, 0, 0);
return obj;
}
};
class SqlEnvironmentWrapper
{
SqlEnvironment& ref;
public:
WRAPPER_METHODS(SqlEnvironmentWrapper, SqlEnvironment)
static VALUE create(VALUE klass)
{
try {
SqlOptionArray optsArray;
optsArray.count = 0;
SqlEnvironmentWrapper* w = new SqlEnvironmentWrapper(SqlEnvironment::createSqlEnvironment(&optsArray));
VALUE obj = Data_Wrap_Struct(types.env.type, 0, SqlEnvironmentWrapper::release, w);
rb_obj_call_init(obj, 0, 0);
return obj;
} catch (ErrorCodeException & e) {
rb_raise(rb_eRuntimeError, "failed to create SqlEnvironment: %s", e.what().c_str());
}
}
static VALUE createSqlConnection(VALUE self, VALUE database, VALUE username, VALUE password)
{
try {
SqlOption options[3];
options[0].option = "database";
options[0].extra = (void*) StringValuePtr(database);
options[1].option = "user";
options[1].extra = (void*) StringValuePtr(username);
options[2].option = "password";
options[2].extra = (void*) StringValuePtr(password);
SqlOptionArray optsArray;
optsArray.count = 3;
optsArray.array = options;
SqlConnectionWrapper* con = new SqlConnectionWrapper(asRef(self).createSqlConnection(&optsArray));
VALUE obj = Data_Wrap_Struct(types.con.type, 0, SqlConnectionWrapper::release, con);
rb_obj_call_init(obj, 0, 0);
return obj;
} catch (ErrorCodeException & e) {
rb_raise(rb_eRuntimeError, "failed to create SqlConnection: %s", e.what().c_str());
}
}
};
//-------------------------------------------------------------------------
// Initialization
#define DEF_CLASS(name) \
type = rb_define_class_under(module, name, rb_cObject)
#define DEF_SINGLETON(name, func, count) \
rb_define_singleton_method(type, name, RUBY_METHOD_FUNC(func), count)
#define DEF_METHOD(name, func, count) \
rb_define_method(type, name, RUBY_METHOD_FUNC(func), count)
void SqlEnvironmentType::init(VALUE module)
{
DEF_CLASS("SqlEnvironment");
DEF_SINGLETON("createSqlEnvironment", SqlEnvironmentWrapper::create, 0);
DEF_METHOD("createSqlConnection", SqlEnvironmentWrapper::createSqlConnection, 3);
}
void SqlConnectionType::init(VALUE module)
{
DEF_CLASS("SqlConnection");
DEF_METHOD("createStatement", SqlConnectionWrapper::createStatement, 0);
// TODO SqlStatement & createStatement();
// TODO SqlPreparedStatement & createPreparedStatement(char const * sql);
// TODO void setAutoCommit(bool autoCommit = true);
// TODO bool hasAutoCommit() const;
// TODO void commit();
// TODO void rollback();
DEF_METHOD("getMetaData", SqlConnectionWrapper::getMetaData, 0);
}
void SqlDatabaseMetaDataType::init(VALUE module)
{
DEF_CLASS("SqlDatabaseMetaData");
DEF_METHOD("getDatabaseVersion", SqlDatabaseMetaDataWrapper::getDatabaseVersion, 0);
}
void SqlStatementType::init(VALUE module)
{
DEF_CLASS("SqlStatement");
// TODO void execute(char const * sql);
// TODO SqlResultSet & executeQuery(char const * sql);
// TODO void release();
}
void SqlPreparedStatementType::init(VALUE module)
{
DEF_CLASS("SqlPreparedStatement");
// TODO void setInteger(size_t index, int32_t value);
// TODO void setDouble(size_t index, double value);
// TODO void setString(size_t index, char const * value);
// TODO void execute();
// TODO SqlResultSet & executeQuery();
// TODO void release();
}
void SqlResultSetType::init(VALUE module)
{
DEF_CLASS("SqlResultSet");
// TODO bool next();
// TODO size_t getColumnCount() const;
// TODO SqlColumnMetaData & getMetaData(size_t column) const;
// TODO int32_t getInteger(size_t column) const;
// TODO double getDouble(size_t column) const;
// TODO char const * getString(size_t column) const;
// TODO SqlDate const * getDate(size_t column) const;
// TODO void release();
}
void SqlColumnMetaDataType::init(VALUE module)
{
DEF_CLASS("SqlColumnMetaData");
// TODO char const * getColumnName() const;
// TODO SqlType getType() const;
// TODO void release();
}
void AllTypes::init()
{
module = rb_define_module("Nuodb");
env.init(module);
con.init(module);
dbmeta.init(module);
stmt.init(module);
pstmt.init(module);
rset.init(module);
colmeta.init(module);
}
extern "C"
void Init_nuodb(void)
{
types.init();
}
//-------------------------------------------------------------------------
<commit_msg>Update to latest NuoSqlApi. Disable release because of ordering bug.<commit_after>/*
* NuoDB Adapter
*/
#include "nuodb/sqlapi/SqlEnvironment.h"
#include "nuodb/sqlapi/SqlConnection.h"
#include "nuodb/sqlapi/SqlDatabaseMetaData.h"
#include "nuodb/sqlapi/SqlStatement.h"
#include "nuodb/sqlapi/SqlExceptions.h"
using nuodb::sqlapi::ErrorCodeException;
using nuodb::sqlapi::SqlConnection;
using nuodb::sqlapi::SqlDatabaseMetaData;
using nuodb::sqlapi::SqlEnvironment;
using nuodb::sqlapi::SqlOption;
using nuodb::sqlapi::SqlOptionArray;
using nuodb::sqlapi::SqlStatement;
#include <ruby.h>
#include <iostream> // TODO temporary
using std::cout; // TODO temporary
//-------------------------------------------------------------------------
// Type definitions
class ClassType
{
public:
VALUE type;
};
#define DECLARE_CLASS_TYPE(classname) \
class classname : public ClassType \
{ public: void init(VALUE module); }
DECLARE_CLASS_TYPE(SqlEnvironmentType);
DECLARE_CLASS_TYPE(SqlConnectionType);
DECLARE_CLASS_TYPE(SqlDatabaseMetaDataType);
DECLARE_CLASS_TYPE(SqlStatementType);
DECLARE_CLASS_TYPE(SqlPreparedStatementType);
DECLARE_CLASS_TYPE(SqlResultSetType);
DECLARE_CLASS_TYPE(SqlColumnMetaDataType);
class AllTypes
{
VALUE module;
public:
SqlEnvironmentType env;
SqlConnectionType con;
SqlDatabaseMetaDataType dbmeta;
SqlStatementType stmt;
SqlPreparedStatementType pstmt;
SqlResultSetType rset;
SqlColumnMetaDataType colmeta;
void init();
};
static AllTypes types;
//-------------------------------------------------------------------------
#define WRAPPER_CTOR(WT, RT) \
WT(RT& arg) : ref(arg) {}
#define WRAPPER_RELEASE(WT) \
static void release(WT* self) { \
cout << "DISABLED release " << #WT << " " << self << "\n"; \
/* self->ref.release(); */ \
delete self; \
}
#define WRAPPER_AS_REF(WT, RT) \
static RT& asRef(VALUE value) { \
Check_Type(value, T_DATA); \
return ((WT*) DATA_PTR(value))->ref; \
}
#define WRAPPER_METHODS(WT, RT) \
WRAPPER_CTOR(WT, RT) \
WRAPPER_RELEASE(WT) \
WRAPPER_AS_REF(WT, RT)
class SqlDatabaseMetaDataWrapper
{
SqlDatabaseMetaData& ref;
public:
WRAPPER_METHODS(SqlDatabaseMetaDataWrapper, SqlDatabaseMetaData)
static VALUE getDatabaseVersion(VALUE self)
{
return rb_str_new2(asRef(self).getDatabaseVersion());
}
};
class SqlStatementWrapper
{
SqlStatement& ref;
public:
WRAPPER_METHODS(SqlStatementWrapper, SqlStatement)
};
class SqlConnectionWrapper
{
SqlConnection& ref;
public:
WRAPPER_METHODS(SqlConnectionWrapper, SqlConnection)
static VALUE createStatement(VALUE self)
{
SqlStatementWrapper* w = new SqlStatementWrapper(asRef(self).createStatement());
VALUE obj = Data_Wrap_Struct(types.stmt.type, 0, SqlStatementWrapper::release, w);
rb_obj_call_init(obj, 0, 0);
return obj;
}
static VALUE getMetaData(VALUE self)
{
SqlDatabaseMetaDataWrapper* w = new SqlDatabaseMetaDataWrapper(asRef(self).getMetaData());
VALUE obj = Data_Wrap_Struct(types.dbmeta.type, 0, SqlDatabaseMetaDataWrapper::release, w);
rb_obj_call_init(obj, 0, 0);
return obj;
}
};
class SqlEnvironmentWrapper
{
SqlEnvironment& ref;
public:
WRAPPER_METHODS(SqlEnvironmentWrapper, SqlEnvironment)
static VALUE create(VALUE klass)
{
try {
SqlOptionArray optsArray;
optsArray.count = 0;
SqlEnvironmentWrapper* w = new SqlEnvironmentWrapper(SqlEnvironment::createSqlEnvironment(&optsArray));
VALUE obj = Data_Wrap_Struct(types.env.type, 0, SqlEnvironmentWrapper::release, w);
rb_obj_call_init(obj, 0, 0);
return obj;
} catch (ErrorCodeException & e) {
rb_raise(rb_eRuntimeError, "failed to create SqlEnvironment: %s", e.what());
}
}
static VALUE createSqlConnection(VALUE self, VALUE database, VALUE username, VALUE password)
{
try {
SqlOption options[3];
options[0].option = "database";
options[0].extra = (void*) StringValuePtr(database);
options[1].option = "user";
options[1].extra = (void*) StringValuePtr(username);
options[2].option = "password";
options[2].extra = (void*) StringValuePtr(password);
SqlOptionArray optsArray;
optsArray.count = 3;
optsArray.array = options;
SqlConnectionWrapper* con = new SqlConnectionWrapper(asRef(self).createSqlConnection(&optsArray));
VALUE obj = Data_Wrap_Struct(types.con.type, 0, SqlConnectionWrapper::release, con);
rb_obj_call_init(obj, 0, 0);
return obj;
} catch (ErrorCodeException & e) {
rb_raise(rb_eRuntimeError, "failed to create SqlConnection: %s", e.what());
}
}
};
//-------------------------------------------------------------------------
// Initialization
#define DEF_CLASS(name) \
type = rb_define_class_under(module, name, rb_cObject)
#define DEF_SINGLETON(name, func, count) \
rb_define_singleton_method(type, name, RUBY_METHOD_FUNC(func), count)
#define DEF_METHOD(name, func, count) \
rb_define_method(type, name, RUBY_METHOD_FUNC(func), count)
void SqlEnvironmentType::init(VALUE module)
{
DEF_CLASS("SqlEnvironment");
DEF_SINGLETON("createSqlEnvironment", SqlEnvironmentWrapper::create, 0);
DEF_METHOD("createSqlConnection", SqlEnvironmentWrapper::createSqlConnection, 3);
}
void SqlConnectionType::init(VALUE module)
{
DEF_CLASS("SqlConnection");
DEF_METHOD("createStatement", SqlConnectionWrapper::createStatement, 0);
// TODO SqlStatement & createStatement();
// TODO SqlPreparedStatement & createPreparedStatement(char const * sql);
// TODO void setAutoCommit(bool autoCommit = true);
// TODO bool hasAutoCommit() const;
// TODO void commit();
// TODO void rollback();
DEF_METHOD("getMetaData", SqlConnectionWrapper::getMetaData, 0);
}
void SqlDatabaseMetaDataType::init(VALUE module)
{
DEF_CLASS("SqlDatabaseMetaData");
DEF_METHOD("getDatabaseVersion", SqlDatabaseMetaDataWrapper::getDatabaseVersion, 0);
}
void SqlStatementType::init(VALUE module)
{
DEF_CLASS("SqlStatement");
// TODO void execute(char const * sql);
// TODO SqlResultSet & executeQuery(char const * sql);
// TODO void release();
}
void SqlPreparedStatementType::init(VALUE module)
{
DEF_CLASS("SqlPreparedStatement");
// TODO void setInteger(size_t index, int32_t value);
// TODO void setDouble(size_t index, double value);
// TODO void setString(size_t index, char const * value);
// TODO void execute();
// TODO SqlResultSet & executeQuery();
// TODO void release();
}
void SqlResultSetType::init(VALUE module)
{
DEF_CLASS("SqlResultSet");
// TODO bool next();
// TODO size_t getColumnCount() const;
// TODO SqlColumnMetaData & getMetaData(size_t column) const;
// TODO int32_t getInteger(size_t column) const;
// TODO double getDouble(size_t column) const;
// TODO char const * getString(size_t column) const;
// TODO SqlDate const * getDate(size_t column) const;
// TODO void release();
}
void SqlColumnMetaDataType::init(VALUE module)
{
DEF_CLASS("SqlColumnMetaData");
// TODO char const * getColumnName() const;
// TODO SqlType getType() const;
// TODO void release();
}
void AllTypes::init()
{
module = rb_define_module("Nuodb");
env.init(module);
con.init(module);
dbmeta.init(module);
stmt.init(module);
pstmt.init(module);
rset.init(module);
colmeta.init(module);
}
extern "C"
void Init_nuodb(void)
{
types.init();
}
//-------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
#include "PipelineView.h"
#include "ActiveObjects.h"
#include "CloneDataReaction.h"
#include "EditOperatorDialog.h"
#include "Module.h"
#include "ModuleManager.h"
#include "Operator.h"
#include "OperatorResult.h"
#include "PipelineModel.h"
#include "SaveDataReaction.h"
#include "ToggleDataTypeReaction.h"
#include "Utilities.h"
#include <pqCoreUtilities.h>
#include <pqSpreadSheetView.h>
#include <pqView.h>
#include <vtkNew.h>
#include <vtkSMParaViewPipelineControllerWithRendering.h>
#include <vtkSMViewProxy.h>
#include <vtkTable.h>
#include <QKeyEvent>
#include <QMainWindow>
#include <QMenu>
namespace tomviz {
PipelineView::PipelineView(QWidget* p) : QTreeView(p)
{
connect(this, SIGNAL(clicked(QModelIndex)), SLOT(rowActivated(QModelIndex)));
setIndentation(20);
setRootIsDecorated(false);
setItemsExpandable(false);
QString customStyle = "QTreeView::branch { background-color: white; }";
setStyleSheet(customStyle);
setAlternatingRowColors(true);
setSelectionBehavior(QAbstractItemView::SelectRows);
// track selection to update ActiveObjects.
connect(&ModuleManager::instance(), SIGNAL(dataSourceAdded(DataSource*)),
SLOT(setCurrent(DataSource*)));
connect(&ModuleManager::instance(), SIGNAL(moduleAdded(Module*)),
SLOT(setCurrent(Module*)));
connect(this, SIGNAL(doubleClicked(QModelIndex)),
SLOT(rowDoubleClicked(QModelIndex)));
}
PipelineView::~PipelineView() = default;
void PipelineView::keyPressEvent(QKeyEvent* e)
{
if (e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace) {
if (currentIndex().isValid()) {
deleteItem(currentIndex());
}
} else {
QTreeView::keyPressEvent(e);
}
}
void PipelineView::contextMenuEvent(QContextMenuEvent* e)
{
auto idx = indexAt(e->pos());
if (!idx.isValid()) {
return;
}
auto pipelineModel = qobject_cast<PipelineModel*>(model());
auto dataSource = pipelineModel->dataSource(idx);
auto result = pipelineModel->result(idx);
bool childData =
(dataSource && qobject_cast<Operator*>(dataSource->parent())) ||
(result && qobject_cast<Operator*>(result->parent()));
if (childData) {
return;
}
QMenu contextMenu;
QAction* cloneAction = nullptr;
QAction* markAsAction = nullptr;
QAction* saveDataAction = nullptr;
if (dataSource != nullptr) {
cloneAction = contextMenu.addAction("Clone");
new CloneDataReaction(cloneAction);
saveDataAction = contextMenu.addAction("Save Data");
new SaveDataReaction(saveDataAction);
if (dataSource->type() == DataSource::Volume) {
markAsAction = contextMenu.addAction("Mark as Tilt Series");
} else {
markAsAction = contextMenu.addAction("Mark as Volume");
}
}
auto deleteAction = contextMenu.addAction("Delete");
auto globalPoint = mapToGlobal(e->pos());
auto selectedItem = contextMenu.exec(globalPoint);
// Some action was selected, so process it.
if (selectedItem == deleteAction) {
deleteItem(idx);
} else if (markAsAction != nullptr && markAsAction == selectedItem) {
auto mainWindow = qobject_cast<QMainWindow*>(window());
ToggleDataTypeReaction::toggleDataType(mainWindow, dataSource);
}
}
void PipelineView::deleteItem(const QModelIndex& idx)
{
auto pipelineModel = qobject_cast<PipelineModel*>(model());
Q_ASSERT(pipelineModel);
auto dataSource = pipelineModel->dataSource(idx);
auto module = pipelineModel->module(idx);
auto op = pipelineModel->op(idx);
if (dataSource) {
pipelineModel->removeDataSource(dataSource);
} else if (module) {
pipelineModel->removeModule(module);
} else if (op) {
pipelineModel->removeOp(op);
}
ActiveObjects::instance().renderAllViews();
}
void PipelineView::rowActivated(const QModelIndex& idx)
{
if (idx.isValid() && idx.column() == 1) {
auto pipelineModel = qobject_cast<PipelineModel*>(model());
if (pipelineModel) {
if (auto module = pipelineModel->module(idx)) {
module->setVisibility(!module->visibility());
if (pqView* view = tomviz::convert<pqView*>(module->view())) {
view->render();
}
} else if (auto op = pipelineModel->op(idx)) {
pipelineModel->removeOp(op);
expandAll();
}
}
}
}
void PipelineView::rowDoubleClicked(const QModelIndex& idx)
{
auto pipelineModel = qobject_cast<PipelineModel*>(model());
Q_ASSERT(pipelineModel);
if (auto op = pipelineModel->op(idx)) {
if (op->hasCustomUI()) {
// Create a non-modal dialog, delete it once it has been closed.
EditOperatorDialog* dialog = new EditOperatorDialog(
op, op->dataSource(), false, pqCoreUtilities::mainWidget());
dialog->setAttribute(Qt::WA_DeleteOnClose, true);
dialog->show();
}
} else if (auto result = pipelineModel->result(idx)) {
if (vtkTable::SafeDownCast(result->dataObject())) {
auto view = ActiveObjects::instance().activeView();
vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;
controller->ShowInPreferredView(result->producerProxy(), 0, view);
}
}
}
void PipelineView::currentChanged(const QModelIndex& current,
const QModelIndex&)
{
if (!current.isValid()) {
return;
}
auto pipelineModel = qobject_cast<PipelineModel*>(model());
Q_ASSERT(pipelineModel);
auto dataSource = pipelineModel->dataSource(current);
auto module = pipelineModel->module(current);
if (dataSource) {
ActiveObjects::instance().setActiveDataSource(dataSource);
} else if (module) {
ActiveObjects::instance().setActiveModule(module);
}
}
void PipelineView::setCurrent(DataSource* dataSource)
{
auto pipelineModel = qobject_cast<PipelineModel*>(model());
setCurrentIndex(pipelineModel->dataSourceIndex(dataSource));
}
void PipelineView::setCurrent(Module* module)
{
auto pipelineModel = qobject_cast<PipelineModel*>(model());
setCurrentIndex(pipelineModel->moduleIndex(module));
}
void PipelineView::setCurrent(Operator*)
{
}
}
<commit_msg>Fix too many SpreadSheetViews being opened<commit_after>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
#include "PipelineView.h"
#include "ActiveObjects.h"
#include "CloneDataReaction.h"
#include "EditOperatorDialog.h"
#include "Module.h"
#include "ModuleManager.h"
#include "Operator.h"
#include "OperatorResult.h"
#include "PipelineModel.h"
#include "SaveDataReaction.h"
#include "ToggleDataTypeReaction.h"
#include "Utilities.h"
#include <pqCoreUtilities.h>
#include <pqSpreadSheetView.h>
#include <pqView.h>
#include <vtkNew.h>
#include <vtkSMParaViewPipelineControllerWithRendering.h>
#include <vtkSMProxyIterator.h>
#include <vtkSMViewProxy.h>
#include <vtkTable.h>
#include <QKeyEvent>
#include <QMainWindow>
#include <QMenu>
namespace tomviz {
PipelineView::PipelineView(QWidget* p) : QTreeView(p)
{
connect(this, SIGNAL(clicked(QModelIndex)), SLOT(rowActivated(QModelIndex)));
setIndentation(20);
setRootIsDecorated(false);
setItemsExpandable(false);
QString customStyle = "QTreeView::branch { background-color: white; }";
setStyleSheet(customStyle);
setAlternatingRowColors(true);
setSelectionBehavior(QAbstractItemView::SelectRows);
// track selection to update ActiveObjects.
connect(&ModuleManager::instance(), SIGNAL(dataSourceAdded(DataSource*)),
SLOT(setCurrent(DataSource*)));
connect(&ModuleManager::instance(), SIGNAL(moduleAdded(Module*)),
SLOT(setCurrent(Module*)));
connect(this, SIGNAL(doubleClicked(QModelIndex)),
SLOT(rowDoubleClicked(QModelIndex)));
}
PipelineView::~PipelineView() = default;
void PipelineView::keyPressEvent(QKeyEvent* e)
{
if (e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace) {
if (currentIndex().isValid()) {
deleteItem(currentIndex());
}
} else {
QTreeView::keyPressEvent(e);
}
}
void PipelineView::contextMenuEvent(QContextMenuEvent* e)
{
auto idx = indexAt(e->pos());
if (!idx.isValid()) {
return;
}
auto pipelineModel = qobject_cast<PipelineModel*>(model());
auto dataSource = pipelineModel->dataSource(idx);
auto result = pipelineModel->result(idx);
bool childData =
(dataSource && qobject_cast<Operator*>(dataSource->parent())) ||
(result && qobject_cast<Operator*>(result->parent()));
if (childData) {
return;
}
QMenu contextMenu;
QAction* cloneAction = nullptr;
QAction* markAsAction = nullptr;
QAction* saveDataAction = nullptr;
if (dataSource != nullptr) {
cloneAction = contextMenu.addAction("Clone");
new CloneDataReaction(cloneAction);
saveDataAction = contextMenu.addAction("Save Data");
new SaveDataReaction(saveDataAction);
if (dataSource->type() == DataSource::Volume) {
markAsAction = contextMenu.addAction("Mark as Tilt Series");
} else {
markAsAction = contextMenu.addAction("Mark as Volume");
}
}
auto deleteAction = contextMenu.addAction("Delete");
auto globalPoint = mapToGlobal(e->pos());
auto selectedItem = contextMenu.exec(globalPoint);
// Some action was selected, so process it.
if (selectedItem == deleteAction) {
deleteItem(idx);
} else if (markAsAction != nullptr && markAsAction == selectedItem) {
auto mainWindow = qobject_cast<QMainWindow*>(window());
ToggleDataTypeReaction::toggleDataType(mainWindow, dataSource);
}
}
void PipelineView::deleteItem(const QModelIndex& idx)
{
auto pipelineModel = qobject_cast<PipelineModel*>(model());
Q_ASSERT(pipelineModel);
auto dataSource = pipelineModel->dataSource(idx);
auto module = pipelineModel->module(idx);
auto op = pipelineModel->op(idx);
if (dataSource) {
pipelineModel->removeDataSource(dataSource);
} else if (module) {
pipelineModel->removeModule(module);
} else if (op) {
pipelineModel->removeOp(op);
}
ActiveObjects::instance().renderAllViews();
}
void PipelineView::rowActivated(const QModelIndex& idx)
{
if (idx.isValid() && idx.column() == 1) {
auto pipelineModel = qobject_cast<PipelineModel*>(model());
if (pipelineModel) {
if (auto module = pipelineModel->module(idx)) {
module->setVisibility(!module->visibility());
if (pqView* view = tomviz::convert<pqView*>(module->view())) {
view->render();
}
} else if (auto op = pipelineModel->op(idx)) {
pipelineModel->removeOp(op);
expandAll();
}
}
}
}
void PipelineView::rowDoubleClicked(const QModelIndex& idx)
{
auto pipelineModel = qobject_cast<PipelineModel*>(model());
Q_ASSERT(pipelineModel);
if (auto op = pipelineModel->op(idx)) {
if (op->hasCustomUI()) {
// Create a non-modal dialog, delete it once it has been closed.
EditOperatorDialog* dialog = new EditOperatorDialog(
op, op->dataSource(), false, pqCoreUtilities::mainWidget());
dialog->setAttribute(Qt::WA_DeleteOnClose, true);
dialog->show();
}
} else if (auto result = pipelineModel->result(idx)) {
if (vtkTable::SafeDownCast(result->dataObject())) {
auto view = ActiveObjects::instance().activeView();
// If the view is not a SpreadSheetView, look for the first one and
// use it if possible.
vtkNew<vtkSMProxyIterator> iter;
iter->SetSessionProxyManager(ActiveObjects::instance().proxyManager());
iter->SetModeToOneGroup();
for (iter->Begin("views"); !iter->IsAtEnd(); iter->Next()) {
auto viewProxy = vtkSMViewProxy::SafeDownCast(iter->GetProxy());
if (std::string(viewProxy->GetXMLName()) == "SpreadSheetView") {
view = viewProxy;
break;
}
}
// If a spreadsheet view wasn't found, controller->ShowInPreferredView()
// will create one.
vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;
view = controller->ShowInPreferredView(result->producerProxy(), 0, view);
ActiveObjects::instance().setActiveView(view);
}
}
}
void PipelineView::currentChanged(const QModelIndex& current,
const QModelIndex&)
{
if (!current.isValid()) {
return;
}
auto pipelineModel = qobject_cast<PipelineModel*>(model());
Q_ASSERT(pipelineModel);
auto dataSource = pipelineModel->dataSource(current);
auto module = pipelineModel->module(current);
if (dataSource) {
ActiveObjects::instance().setActiveDataSource(dataSource);
} else if (module) {
ActiveObjects::instance().setActiveModule(module);
}
}
void PipelineView::setCurrent(DataSource* dataSource)
{
auto pipelineModel = qobject_cast<PipelineModel*>(model());
setCurrentIndex(pipelineModel->dataSourceIndex(dataSource));
}
void PipelineView::setCurrent(Module* module)
{
auto pipelineModel = qobject_cast<PipelineModel*>(model());
setCurrentIndex(pipelineModel->moduleIndex(module));
}
void PipelineView::setCurrent(Operator*)
{
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbMultiChannelExtractROI.h"
#include "otbStandardFilterWatcher.h"
#include "otbWrapperNumericalParameter.h"
#include "otbWrapperTypes.h"
namespace otb
{
namespace Wrapper
{
class ExtractROI : public Application
{
public:
/** Standard class typedefs. */
typedef ExtractROI Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(ExtractROI, otb::Application);
/** Filters typedef */
typedef otb::MultiChannelExtractROI<FloatVectorImageType::InternalPixelType,
FloatVectorImageType::InternalPixelType> ExtractROIFilterType;
private:
void DoInit()
{
SetName("ExtractROI");
SetDescription("Extract a ROI defined by the user.");
// Documentation
SetDocName("Extract ROI");
SetDocLongDescription("This application extracts a Region Of Interest with user defined size.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Manip);
AddParameter(ParameterType_InputImage, "in", "Input Image");
SetParameterDescription("in", "Input image.");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription("out", "Output image.");
AddRAMParameter();
AddParameter(ParameterType_Int, "startx", "Start X");
SetParameterDescription("startx", "ROI start x position.");
AddParameter(ParameterType_Int, "starty", "Start Y");
SetParameterDescription("starty", "ROI start y position.");
AddParameter(ParameterType_Int, "sizex", "Size X");
SetParameterDescription("sizex","size along x in pixels.");
AddParameter(ParameterType_Int, "sizey", "Size Y");
SetParameterDescription("sizey","size along y in pixels.");
// Default values
SetDefaultParameterInt("startx", 0);
SetDefaultParameterInt("starty", 0);
SetDefaultParameterInt("sizex", 0);
SetDefaultParameterInt("sizey", 0);
// Channelist Parameters
AddParameter(ParameterType_ListView, "cl", "Output Image channels");
SetParameterDescription("cl","Channels to write in the output image.");
// Doc example parameter settings
SetDocExampleParameterValue("in", "VegetationIndex.hd");
SetDocExampleParameterValue("startx", "40");
SetDocExampleParameterValue("starty", "250");
SetDocExampleParameterValue("sizex", "150");
SetDocExampleParameterValue("sizey", "150");
SetDocExampleParameterValue("out", "ExtractROI.tif");
}
void DoUpdateParameters()
{
// Update the sizes only if the user does not defined a size
if ( HasValue("in") )
{
ExtractROIFilterType::InputImageType* inImage = GetParameterImage("in");
ExtractROIFilterType::InputImageType::RegionType largestRegion = inImage->GetLargestPossibleRegion();
// Update the values of the channels to be selected
unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();
ClearChoices("cl");
for (unsigned int idx = 0; idx < nbComponents; ++idx)
{
std::ostringstream key, item;
key<<"cl.channel"<<idx+1;
item<<"Channel"<<idx+1;
AddChoice(key.str(), item.str());
}
if (!HasUserValue("sizex") && !HasUserValue("sizey") )
{
SetParameterInt("sizex", largestRegion.GetSize()[0]);
SetParameterInt("sizey", largestRegion.GetSize()[1]);
}
// Put the limit of the index and the size relative the image
SetMinimumParameterIntValue("sizex", 0);
SetMaximumParameterIntValue("sizex", largestRegion.GetSize(0));
SetMinimumParameterIntValue("sizey", 0);
SetMaximumParameterIntValue("sizey", largestRegion.GetSize(1));
SetMinimumParameterIntValue("startx", 0);
SetMaximumParameterIntValue("startx", largestRegion.GetSize(0));
SetMinimumParameterIntValue("starty", 0);
SetMaximumParameterIntValue("starty", largestRegion.GetSize(1));
// Crop the roi region to be included in the largest possible
// region
if(!this->CropRegionOfInterest())
{
// Put the index of the ROI to origin and try to crop again
SetParameterInt("startx", 0);
SetParameterInt("starty", 0);
this->CropRegionOfInterest();
}
}
}
bool CropRegionOfInterest()
{
FloatVectorImageType::RegionType region;
region.SetSize(0, GetParameterInt("sizex"));
region.SetSize(1, GetParameterInt("sizey"));
region.SetIndex(0, GetParameterInt("startx"));
region.SetIndex(1, GetParameterInt("starty"));
if ( HasValue("in") )
{
if (region.Crop(GetParameterImage("in")->GetLargestPossibleRegion()))
{
SetParameterInt("sizex", region.GetSize(0));
SetParameterInt("sizey", region.GetSize(1));
SetParameterInt("startx", region.GetIndex(0));
SetParameterInt("starty", region.GetIndex(1));
return true;
}
}
return false;
}
void DoExecute()
{
ExtractROIFilterType::InputImageType* inImage = GetParameterImage("in");
m_ExtractROIFilter = ExtractROIFilterType::New();
m_ExtractROIFilter->SetInput(inImage);
m_ExtractROIFilter->SetStartX(GetParameterInt("startx"));
m_ExtractROIFilter->SetStartY(GetParameterInt("starty"));
m_ExtractROIFilter->SetSizeX(GetParameterInt("sizex"));
m_ExtractROIFilter->SetSizeY(GetParameterInt("sizey"));
for (unsigned int idx = 0; idx < GetSelectedItems("cl").size(); ++idx)
{
m_ExtractROIFilter->SetChannel(GetSelectedItems("cl")[idx] + 1 );
}
SetParameterOutputImage("out", m_ExtractROIFilter->GetOutput());
}
ExtractROIFilterType::Pointer m_ExtractROIFilter;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::ExtractROI)
<commit_msg>ENH: Adding a fit mode in ExtractROI, to set the ROI from a reference image<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbMultiChannelExtractROI.h"
#include "otbStandardFilterWatcher.h"
#include "otbWrapperNumericalParameter.h"
#include "otbWrapperTypes.h"
#include "otbWrapperElevationParametersHandler.h"
#include "otbGenericRSTransform.h"
namespace otb
{
namespace Wrapper
{
class ExtractROI : public Application
{
public:
/** Standard class typedefs. */
typedef ExtractROI Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef otb::GenericRSTransform<> RSTransformType;
typedef RSTransformType::InputPointType Point3DType;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(ExtractROI, otb::Application);
/** Filters typedef */
typedef otb::MultiChannelExtractROI<FloatVectorImageType::InternalPixelType,
FloatVectorImageType::InternalPixelType> ExtractROIFilterType;
private:
void DoInit()
{
SetName("ExtractROI");
SetDescription("Extract a ROI defined by the user.");
// Documentation
SetDocName("Extract ROI");
SetDocLongDescription("This application extracts a Region Of Interest with user defined size.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Manip);
AddParameter(ParameterType_InputImage, "in", "Input Image");
SetParameterDescription("in", "Input image.");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription("out", "Output image.");
AddRAMParameter();
AddParameter(ParameterType_Choice,"mode","Extraction mode");
AddChoice("mode.standard","Standard");
SetParameterDescription("mode.standard","In standard mode, extract is done according the coordinates entered by the user");
AddChoice("mode.fit","Fit");
SetParameterDescription("mode.fit","In fit mode, extract is made to best fit a reference image.");
AddParameter(ParameterType_InputImage,"mode.fit.ref","Reference image");
SetParameterDescription("mode.fit.ref","Reference image to define the ROI");
// Elevation
ElevationParametersHandler::AddElevationParameters(this,"mode.fit.elev");
AddParameter(ParameterType_Int, "startx", "Start X");
SetParameterDescription("startx", "ROI start x position.");
AddParameter(ParameterType_Int, "starty", "Start Y");
SetParameterDescription("starty", "ROI start y position.");
AddParameter(ParameterType_Int, "sizex", "Size X");
SetParameterDescription("sizex","size along x in pixels.");
AddParameter(ParameterType_Int, "sizey", "Size Y");
SetParameterDescription("sizey","size along y in pixels.");
// Default values
SetDefaultParameterInt("startx", 0);
SetDefaultParameterInt("starty", 0);
SetDefaultParameterInt("sizex", 0);
SetDefaultParameterInt("sizey", 0);
// Channelist Parameters
AddParameter(ParameterType_ListView, "cl", "Output Image channels");
SetParameterDescription("cl","Channels to write in the output image.");
// Doc example parameter settings
SetDocExampleParameterValue("in", "VegetationIndex.hd");
SetDocExampleParameterValue("startx", "40");
SetDocExampleParameterValue("starty", "250");
SetDocExampleParameterValue("sizex", "150");
SetDocExampleParameterValue("sizey", "150");
SetDocExampleParameterValue("out", "ExtractROI.tif");
}
void DoUpdateParameters()
{
// Update the sizes only if the user does not defined a size
if ( HasValue("in") )
{
ExtractROIFilterType::InputImageType* inImage = GetParameterImage("in");
ExtractROIFilterType::InputImageType::RegionType largestRegion = inImage->GetLargestPossibleRegion();
if (!HasUserValue("sizex") && !HasUserValue("sizey") )
{
SetParameterInt("sizex", largestRegion.GetSize()[0]);
SetParameterInt("sizey", largestRegion.GetSize()[1]);
}
// Update the values of the channels to be selected
unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();
ClearChoices("cl");
for (unsigned int idx = 0; idx < nbComponents; ++idx)
{
std::ostringstream key, item;
key<<"cl.channel"<<idx+1;
item<<"Channel"<<idx+1;
AddChoice(key.str(), item.str());
}
// Put the limit of the index and the size relative the image
SetMinimumParameterIntValue("sizex", 0);
SetMaximumParameterIntValue("sizex", largestRegion.GetSize(0));
SetMinimumParameterIntValue("sizey", 0);
SetMaximumParameterIntValue("sizey", largestRegion.GetSize(1));
SetMinimumParameterIntValue("startx", 0);
SetMaximumParameterIntValue("startx", largestRegion.GetSize(0));
SetMinimumParameterIntValue("starty", 0);
SetMaximumParameterIntValue("starty", largestRegion.GetSize(1));
// Crop the roi region to be included in the largest possible
// region
if(!this->CropRegionOfInterest())
{
// Put the index of the ROI to origin and try to crop again
SetParameterInt("startx", 0);
SetParameterInt("starty", 0);
this->CropRegionOfInterest();
}
}
if(GetParameterString("mode")=="fit")
{
this->SetParameterRole("startx",Role_Output);
this->SetParameterRole("starty",Role_Output);
this->SetParameterRole("sizex",Role_Output);
this->SetParameterRole("sizey",Role_Output);
}
else if(GetParameterString("mode")=="standard")
{
this->SetParameterRole("startx",Role_Input);
this->SetParameterRole("starty",Role_Input);
this->SetParameterRole("sizex",Role_Input);
this->SetParameterRole("sizey",Role_Input);
}
}
bool CropRegionOfInterest()
{
FloatVectorImageType::RegionType region;
region.SetSize(0, GetParameterInt("sizex"));
region.SetSize(1, GetParameterInt("sizey"));
region.SetIndex(0, GetParameterInt("startx"));
region.SetIndex(1, GetParameterInt("starty"));
if ( HasValue("in") )
{
if (region.Crop(GetParameterImage("in")->GetLargestPossibleRegion()))
{
SetParameterInt("sizex", region.GetSize(0));
SetParameterInt("sizey", region.GetSize(1));
SetParameterInt("startx", region.GetIndex(0));
SetParameterInt("starty", region.GetIndex(1));
return true;
}
}
return false;
}
void DoExecute()
{
ExtractROIFilterType::InputImageType* inImage = GetParameterImage("in");
inImage->UpdateOutputInformation();
if(GetParameterString("mode")=="fit")
{
// Setup the DEM Handler
otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,"elev");
FloatVectorImageType::Pointer referencePtr = this->GetParameterImage<FloatVectorImageType>("mode.fit.ref");
referencePtr->UpdateOutputInformation();
RSTransformType::Pointer rsTransform = RSTransformType::New();
rsTransform->SetInputKeywordList(referencePtr->GetImageKeywordlist());
rsTransform->SetInputProjectionRef(referencePtr->GetProjectionRef());
rsTransform->SetOutputKeywordList(inImage->GetImageKeywordlist());
rsTransform->SetOutputProjectionRef(inImage->GetProjectionRef());
rsTransform->InstanciateTransform();
FloatVectorImageType::IndexType uli_ref,uri_ref,lli_ref,lri_ref;
uli_ref = referencePtr->GetLargestPossibleRegion().GetIndex();
uri_ref = uli_ref;
uri_ref[0]+=referencePtr->GetLargestPossibleRegion().GetSize()[0];
lli_ref = uli_ref;
lli_ref[1]+=referencePtr->GetLargestPossibleRegion().GetSize()[1];
lri_ref = lli_ref;
lri_ref[0]+=referencePtr->GetLargestPossibleRegion().GetSize()[0];
FloatVectorImageType::PointType ulp_ref,urp_ref,llp_ref,lrp_ref;
referencePtr->TransformIndexToPhysicalPoint(uli_ref,ulp_ref);
referencePtr->TransformIndexToPhysicalPoint(uri_ref,urp_ref);
referencePtr->TransformIndexToPhysicalPoint(lli_ref,llp_ref);
referencePtr->TransformIndexToPhysicalPoint(lri_ref,lrp_ref);
FloatVectorImageType::PointType ulp_out, urp_out, llp_out,lrp_out;
ulp_out = rsTransform->TransformPoint(ulp_ref);
urp_out = rsTransform->TransformPoint(urp_ref);
llp_out = rsTransform->TransformPoint(llp_ref);
lrp_out = rsTransform->TransformPoint(lrp_ref);
FloatVectorImageType::IndexType uli_out, uri_out, lli_out, lri_out;
inImage->TransformPhysicalPointToIndex(ulp_out,uli_out);
inImage->TransformPhysicalPointToIndex(urp_out,uri_out);
inImage->TransformPhysicalPointToIndex(llp_out,lli_out);
inImage->TransformPhysicalPointToIndex(lrp_out,lri_out);
FloatVectorImageType::IndexType uli, lri;
uli[0] = std::min(std::min(uli_out[0],uri_out[0]),std::min(lli_out[0],lri_out[0]));
uli[1] = std::min(std::min(uli_out[1],uri_out[1]),std::min(lli_out[1],lri_out[1]));
lri[0] = std::max(std::max(uli_out[0],uri_out[0]),std::max(lli_out[0],lri_out[0]));
lri[1] = std::max(std::max(uli_out[1],uri_out[1]),std::max(lli_out[1],lri_out[1]));
SetParameterInt("startx",uli[0]);
SetParameterInt("starty",uli[1]);
SetParameterInt("sizex",lri[0]-uli[0]);
SetParameterInt("sizey",lri[1]-uli[1]);
this->CropRegionOfInterest();
}
m_ExtractROIFilter = ExtractROIFilterType::New();
m_ExtractROIFilter->SetInput(inImage);
m_ExtractROIFilter->SetStartX(GetParameterInt("startx"));
m_ExtractROIFilter->SetStartY(GetParameterInt("starty"));
m_ExtractROIFilter->SetSizeX(GetParameterInt("sizex"));
m_ExtractROIFilter->SetSizeY(GetParameterInt("sizey"));
for (unsigned int idx = 0; idx < GetSelectedItems("cl").size(); ++idx)
{
m_ExtractROIFilter->SetChannel(GetSelectedItems("cl")[idx] + 1 );
}
SetParameterOutputImage("out", m_ExtractROIFilter->GetOutput());
}
ExtractROIFilterType::Pointer m_ExtractROIFilter;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::ExtractROI)
<|endoftext|>
|
<commit_before>#include "writer/verilog/axi/master_controller.h"
#include "iroha/i_design.h"
#include "writer/verilog/axi/master_port.h"
#include "writer/verilog/module.h"
#include "writer/verilog/ports.h"
#include "writer/verilog/table.h"
namespace iroha {
namespace writer {
namespace verilog {
namespace axi {
MasterController::MasterController(const IResource &res, bool reset_polarity)
: AxiController(res, reset_polarity) {
MasterPort::GetReadWrite(res_, &r_, &w_);
}
MasterController::~MasterController() {
}
void MasterController::Write(ostream &os) {
AddSramPorts();
ports_->AddPort("addr", Port::INPUT, 32);
ports_->AddPort("len", Port::INPUT, sram_addr_width_);
ports_->AddPort("start", Port::INPUT, sram_addr_width_);
ports_->AddPort("wen", Port::INPUT, 0);
ports_->AddPort("req", Port::INPUT, 0);
ports_->AddPort("ack", Port::OUTPUT, 0);
string initials;
GenReadChannel(cfg_, true, nullptr, ports_.get(), &initials);
GenWriteChannel(cfg_, true, nullptr, ports_.get(), &initials);
string name = MasterPort::ControllerName(res_, reset_polarity_);
os << "module " << name << "(";
ports_->Output(Ports::PORT_NAME, os);
os << ");\n";
ports_->Output(Ports::PORT_TYPE, os);
os << "\n"
<< " `define S_IDLE 0\n"
<< " `define S_ADDR_WAIT 1\n";
if (r_) {
os << " `define S_READ_DATA 2\n"
<< " `define S_READ_DATA_WAIT 3\n";
}
if (w_) {
os << " `define S_WRITE_WAIT 4\n";
}
os << " reg [2:0] st;\n\n";
if (w_) {
os << " `define WS_IDLE 0\n"
<< " `define WS_WRITE 1\n"
<< " `define WS_WAIT 2\n"
<< " `define WS_SRAM 4\n"
<< " `define WS_AXI 5\n"
<< " reg [2:0] wst;\n"
<< " reg [" << sram_addr_width_ << ":0] wmax;\n\n";
}
if (r_) {
os << " reg [" << sram_addr_width_ << ":0] ridx;\n"
<< " reg read_last;\n\n";
}
if (w_) {
os << " reg [" << sram_addr_width_ << ":0] widx;\n\n";
}
os << " always @(posedge clk) begin\n"
<< " if (" << (reset_polarity_ ? "" : "!")
<< ResetName(reset_polarity_) << ") begin\n"
<< " ack <= 0;\n"
<< " sram_req <= 0;\n"
<< " sram_wen <= 0;\n"
<< " st <= `S_IDLE;\n";
if (w_) {
os << " wst <= `WS_IDLE;\n"
<< " wmax <= 0;\n";
}
os << initials
<< " end else begin\n";
OutputMainFsm(os);
if (w_) {
OutputWriterFsm(os);
}
os << " end\n"
<< " end\n"
<< "endmodule\n";
}
void MasterController::AddPorts(const PortConfig &cfg,
Module *mod, bool r, bool w,
string *s) {
Ports *ports = mod->GetPorts();
if (r) {
GenReadChannel(cfg, true, mod, ports, s);
}
if (w) {
GenWriteChannel(cfg, true, mod, ports, s);
}
}
void MasterController::OutputMainFsm(ostream &os) {
if (r_) {
os << " if (sram_EXCLUSIVE) begin\n"
<< " sram_wen <= (st == `S_READ_DATA && RVALID);\n"
<< " end\n";
} else {
os << " sram_wen <= 0;\n";
}
os << " case (st)\n"
<< " `S_IDLE: begin\n";
if (r_ || w_) {
os << " if (req) begin\n"
<< " ack <= 1;\n";
if (r_) {
os << " ridx <= 0;\n";
}
os << " st <= `S_ADDR_WAIT;\n";
if (r_ && !w_) {
os << " ARVALID <= 1;\n"
<< " ARADDR <= addr;\n"
<< " ARLEN <= len;\n";
}
if (!r_ && w_) {
os << " AWVALID <= 1;\n"
<< " AWADDR <= addr;\n"
<< " AWLEN <= len;\n"
<< " wmax <= len;\n";
}
if (r_ && w_) {
os << " if (wen) begin\n"
<< " ARVALID <= 1;\n"
<< " ARADDR <= addr;\n"
<< " ARLEN <= len;\n"
<< " end else begin\n"
<< " AWVALID <= 1;\n"
<< " AWADDR <= addr;\n"
<< " AWLEN <= len;\n"
<< " wmax <= len;\n"
<< " end\n";
}
os << " end\n";
}
os << " end\n";
if (r_ || w_) {
os << " `S_ADDR_WAIT: begin\n"
<< " ack <= 0;\n";
if (r_ && !w_) {
os << " if (ARREADY) begin\n"
<< " st <= `S_READ_DATA;\n"
<< " ARVALID <= 0;\n"
<< " RREADY <= 1;\n"
<< " end\n";
}
if (!r_ && w_) {
os << " if (AWREADY) begin\n"
<< " st <= `S_WRITE_WAIT;\n"
<< " AWVALID <= 0;\n"
<< " sram_addr <= start;\n"
<< " if (!sram_EXCLUSIVE) begin\n"
<< " sram_req <= 1;\n"
<< " end\n"
<< " end\n";
}
if (r_ && w_) {
os << " if (wen) begin\n"
<< " if (AWREADY) begin\n"
<< " st <= `S_WRITE_WAIT;\n"
<< " AWVALID <= 0;\n"
<< " sram_addr <= start;\n"
<< " if (!sram_EXCLUSIVE) begin\n"
<< " sram_req <= 1;\n"
<< " end\n"
<< " end\n"
<< " end else begin\n"
<< " if (ARREADY) begin\n"
<< " st <= `S_READ_DATA;\n"
<< " RREADY <= 1;\n"
<< " end\n"
<< " end\n";
}
os << " end\n";
}
if (r_) {
ReadState(os);
}
if (w_) {
os << " `S_WRITE_WAIT: begin\n"
<< " if (BVALID) begin\n"
<< " st <= `S_IDLE;\n"
<< " end\n"
<< " if (wst == `WS_WRITE) begin\n" // sram_EXCLUSIVE
<< " if (widx == 0 || (WREADY && WVALID)) begin\n"
<< " sram_addr <= sram_addr + 1;\n"
<< " end\n"
<< " end\n"
<< " if (wst == `WS_SRAM) begin\n" // !sram_EXCLUSIVE
<< " if (sram_ack) begin\n"
<< " sram_req <= 0;\n"
<< " end\n"
<< " end\n"
<< " if (wst == `WS_AXI) begin\n" // !sram_EXCLUSIVE
<< " if (WREADY && WVALID) begin\n"
<< " if (widx <= wmax) begin\n"
<< " sram_req <= 1;\n"
<< " sram_addr <= sram_addr + 1;\n"
<< " end\n"
<< " end\n"
<< " end\n"
<< " end\n";
}
os << " endcase\n";
}
void MasterController::ReadState(ostream &os) {
os << " `S_READ_DATA: begin\n"
<< " if (RVALID) begin\n"
<< " sram_addr <= start + ridx;\n"
<< " sram_wdata <= RDATA;\n"
<< " ridx <= ridx + 1;\n"
<< " if (sram_EXCLUSIVE) begin\n"
<< " if (RLAST) begin\n"
<< " RREADY <= 0;\n"
<< " st <= `S_IDLE;\n"
<< " end\n"
<< " end else begin\n"
<< " st <= `S_READ_DATA_WAIT;\n"
<< " sram_req <= 1;\n"
<< " sram_wen <= 1;\n"
<< " RREADY <= 0;\n"
<< " read_last <= RLAST;\n"
<< " end\n"
<< " end\n"
<< " end\n"
<< " `S_READ_DATA_WAIT: begin\n" // !sram_EXCLUSIVE
<< " if (sram_ack) begin\n"
<< " sram_req <= 0;\n"
<< " sram_wen <= 0;\n"
<< " if (read_last) begin\n"
<< " st <= `S_IDLE;\n"
<< " end else begin\n"
<< " st <= `S_READ_DATA;\n"
<< " RREADY <= 1;\n"
<< " end\n"
<< " end\n"
<< " end\n";
}
void MasterController::OutputWriterFsm(ostream &os) {
os << " case (wst)\n"
<< " `WS_IDLE: begin\n"
<< " if (AWVALID && AWREADY) begin\n"
<< " if (sram_EXCLUSIVE) begin\n"
<< " wst <= `WS_WRITE;\n"
<< " end else begin\n"
<< " wst <= `WS_SRAM;\n"
<< " end\n"
<< " widx <= 0;\n"
<< " end\n"
<< " end\n"
<< " `WS_WRITE: begin\n" // sram_EXCLUSIVE
<< " if (widx <= wmax) begin\n"
<< " WVALID <= 1;\n"
<< " WDATA <= sram_rdata;\n"
<< " if (widx == wmax) begin\n"
<< " WLAST <= 1;\n"
<< " end\n"
<< " if (widx == 0 || (WREADY && WVALID)) begin\n"
<< " widx <= widx + 1;\n"
<< " end\n"
<< " end else begin\n"
<< " WVALID <= 0;\n"
<< " WLAST <= 0;\n"
<< " wst <= `WS_WAIT;\n"
<< " BREADY <= 1;\n"
<< " end\n"
<< " end\n"
<< " `WS_SRAM: begin\n" // !sram_EXCLUSIVE
<< " if (sram_ack) begin\n"
<< " wst <= `WS_AXI;\n"
<< " WDATA <= sram_rdata;\n"
<< " widx <= widx + 1;\n"
<< " WVALID <= 1;\n"
<< " if (widx == wmax) begin\n"
<< " WLAST <= 1;\n"
<< " end\n"
<< " end\n"
<< " end\n"
<< " `WS_AXI: begin\n" // !sram_EXCLUSIVE
<< " if (WREADY && WVALID) begin\n"
<< " WVALID <= 0;\n"
<< " if (widx <= wmax) begin\n"
<< " wst <= `WS_SRAM;\n"
<< " end else begin\n"
<< " WLAST <= 0;\n"
<< " wst <= `WS_WAIT;\n"
<< " end\n"
<< " end\n"
<< " end\n"
<< " `WS_WAIT: begin\n"
<< " if (BVALID) begin\n"
<< " BREADY <= 0;\n"
<< " wst <= `WS_IDLE;\n"
<< " end\n"
<< " end\n"
<< " endcase\n";
}
} // namespace axi
} // namespace verilog
} // namespace writer
} // namespace iroha
<commit_msg>Fix FSM branch of axi master.<commit_after>#include "writer/verilog/axi/master_controller.h"
#include "iroha/i_design.h"
#include "writer/verilog/axi/master_port.h"
#include "writer/verilog/module.h"
#include "writer/verilog/ports.h"
#include "writer/verilog/table.h"
namespace iroha {
namespace writer {
namespace verilog {
namespace axi {
MasterController::MasterController(const IResource &res, bool reset_polarity)
: AxiController(res, reset_polarity) {
MasterPort::GetReadWrite(res_, &r_, &w_);
}
MasterController::~MasterController() {
}
void MasterController::Write(ostream &os) {
AddSramPorts();
ports_->AddPort("addr", Port::INPUT, 32);
ports_->AddPort("len", Port::INPUT, sram_addr_width_);
ports_->AddPort("start", Port::INPUT, sram_addr_width_);
ports_->AddPort("wen", Port::INPUT, 0);
ports_->AddPort("req", Port::INPUT, 0);
ports_->AddPort("ack", Port::OUTPUT, 0);
string initials;
GenReadChannel(cfg_, true, nullptr, ports_.get(), &initials);
GenWriteChannel(cfg_, true, nullptr, ports_.get(), &initials);
string name = MasterPort::ControllerName(res_, reset_polarity_);
os << "module " << name << "(";
ports_->Output(Ports::PORT_NAME, os);
os << ");\n";
ports_->Output(Ports::PORT_TYPE, os);
os << "\n"
<< " `define S_IDLE 0\n"
<< " `define S_ADDR_WAIT 1\n";
if (r_) {
os << " `define S_READ_DATA 2\n"
<< " `define S_READ_DATA_WAIT 3\n";
}
if (w_) {
os << " `define S_WRITE_WAIT 4\n";
}
os << " reg [2:0] st;\n\n";
if (w_) {
os << " `define WS_IDLE 0\n"
<< " `define WS_WRITE 1\n"
<< " `define WS_WAIT 2\n"
<< " `define WS_SRAM 4\n"
<< " `define WS_AXI 5\n"
<< " reg [2:0] wst;\n"
<< " reg [" << sram_addr_width_ << ":0] wmax;\n\n";
}
if (r_) {
os << " reg [" << sram_addr_width_ << ":0] ridx;\n"
<< " reg read_last;\n\n";
}
if (w_) {
os << " reg [" << sram_addr_width_ << ":0] widx;\n\n";
}
os << " always @(posedge clk) begin\n"
<< " if (" << (reset_polarity_ ? "" : "!")
<< ResetName(reset_polarity_) << ") begin\n"
<< " ack <= 0;\n"
<< " sram_req <= 0;\n"
<< " sram_wen <= 0;\n"
<< " st <= `S_IDLE;\n";
if (w_) {
os << " wst <= `WS_IDLE;\n"
<< " wmax <= 0;\n";
}
os << initials
<< " end else begin\n";
OutputMainFsm(os);
if (w_) {
OutputWriterFsm(os);
}
os << " end\n"
<< " end\n"
<< "endmodule\n";
}
void MasterController::AddPorts(const PortConfig &cfg,
Module *mod, bool r, bool w,
string *s) {
Ports *ports = mod->GetPorts();
if (r) {
GenReadChannel(cfg, true, mod, ports, s);
}
if (w) {
GenWriteChannel(cfg, true, mod, ports, s);
}
}
void MasterController::OutputMainFsm(ostream &os) {
if (r_) {
os << " if (sram_EXCLUSIVE) begin\n"
<< " sram_wen <= (st == `S_READ_DATA && RVALID);\n"
<< " end\n";
} else {
os << " sram_wen <= 0;\n";
}
os << " case (st)\n"
<< " `S_IDLE: begin\n";
if (r_ || w_) {
os << " if (req) begin\n"
<< " ack <= 1;\n";
if (r_) {
os << " ridx <= 0;\n";
}
os << " st <= `S_ADDR_WAIT;\n";
if (r_ && !w_) {
os << " ARVALID <= 1;\n"
<< " ARADDR <= addr;\n"
<< " ARLEN <= len;\n";
}
if (!r_ && w_) {
os << " AWVALID <= 1;\n"
<< " AWADDR <= addr;\n"
<< " AWLEN <= len;\n"
<< " wmax <= len;\n";
}
if (r_ && w_) {
os << " if (wen) begin\n"
<< " ARVALID <= 1;\n"
<< " ARADDR <= addr;\n"
<< " ARLEN <= len;\n"
<< " end else begin\n"
<< " AWVALID <= 1;\n"
<< " AWADDR <= addr;\n"
<< " AWLEN <= len;\n"
<< " wmax <= len;\n"
<< " end\n";
}
os << " end\n";
}
os << " end\n";
if (r_ || w_) {
os << " `S_ADDR_WAIT: begin\n"
<< " ack <= 0;\n";
if (r_ && !w_) {
os << " if (ARREADY) begin\n"
<< " st <= `S_READ_DATA;\n"
<< " ARVALID <= 0;\n"
<< " RREADY <= 1;\n"
<< " end\n";
}
if (!r_ && w_) {
os << " if (AWREADY) begin\n"
<< " st <= `S_WRITE_WAIT;\n"
<< " AWVALID <= 0;\n"
<< " sram_addr <= start;\n"
<< " if (!sram_EXCLUSIVE) begin\n"
<< " sram_req <= 1;\n"
<< " end\n"
<< " end\n";
}
if (r_ && w_) {
os << " if (AWVALID) begin\n"
<< " if (AWREADY) begin\n"
<< " st <= `S_WRITE_WAIT;\n"
<< " AWVALID <= 0;\n"
<< " sram_addr <= start;\n"
<< " if (!sram_EXCLUSIVE) begin\n"
<< " sram_req <= 1;\n"
<< " end\n"
<< " end\n"
<< " end else begin\n"
<< " if (ARREADY) begin\n"
<< " st <= `S_READ_DATA;\n"
<< " ARVALID <= 0;\n"
<< " RREADY <= 1;\n"
<< " end\n"
<< " end\n";
}
os << " end\n";
}
if (r_) {
ReadState(os);
}
if (w_) {
os << " `S_WRITE_WAIT: begin\n"
<< " if (BVALID) begin\n"
<< " st <= `S_IDLE;\n"
<< " end\n"
<< " if (wst == `WS_WRITE) begin\n" // sram_EXCLUSIVE
<< " if (widx == 0 || (WREADY && WVALID)) begin\n"
<< " sram_addr <= sram_addr + 1;\n"
<< " end\n"
<< " end\n"
<< " if (wst == `WS_SRAM) begin\n" // !sram_EXCLUSIVE
<< " if (sram_ack) begin\n"
<< " sram_req <= 0;\n"
<< " end\n"
<< " end\n"
<< " if (wst == `WS_AXI) begin\n" // !sram_EXCLUSIVE
<< " if (WREADY && WVALID) begin\n"
<< " if (widx <= wmax) begin\n"
<< " sram_req <= 1;\n"
<< " sram_addr <= sram_addr + 1;\n"
<< " end\n"
<< " end\n"
<< " end\n"
<< " end\n";
}
os << " endcase\n";
}
void MasterController::ReadState(ostream &os) {
os << " `S_READ_DATA: begin\n"
<< " if (RVALID) begin\n"
<< " sram_addr <= start + ridx;\n"
<< " sram_wdata <= RDATA;\n"
<< " ridx <= ridx + 1;\n"
<< " if (sram_EXCLUSIVE) begin\n"
<< " if (RLAST) begin\n"
<< " RREADY <= 0;\n"
<< " st <= `S_IDLE;\n"
<< " end\n"
<< " end else begin\n"
<< " st <= `S_READ_DATA_WAIT;\n"
<< " sram_req <= 1;\n"
<< " sram_wen <= 1;\n"
<< " RREADY <= 0;\n"
<< " read_last <= RLAST;\n"
<< " end\n"
<< " end\n"
<< " end\n"
<< " `S_READ_DATA_WAIT: begin\n" // !sram_EXCLUSIVE
<< " if (sram_ack) begin\n"
<< " sram_req <= 0;\n"
<< " sram_wen <= 0;\n"
<< " if (read_last) begin\n"
<< " st <= `S_IDLE;\n"
<< " end else begin\n"
<< " st <= `S_READ_DATA;\n"
<< " RREADY <= 1;\n"
<< " end\n"
<< " end\n"
<< " end\n";
}
void MasterController::OutputWriterFsm(ostream &os) {
os << " case (wst)\n"
<< " `WS_IDLE: begin\n"
<< " if (AWVALID && AWREADY) begin\n"
<< " if (sram_EXCLUSIVE) begin\n"
<< " wst <= `WS_WRITE;\n"
<< " end else begin\n"
<< " wst <= `WS_SRAM;\n"
<< " end\n"
<< " widx <= 0;\n"
<< " end\n"
<< " end\n"
<< " `WS_WRITE: begin\n" // sram_EXCLUSIVE
<< " if (widx <= wmax) begin\n"
<< " WVALID <= 1;\n"
<< " WDATA <= sram_rdata;\n"
<< " if (widx == wmax) begin\n"
<< " WLAST <= 1;\n"
<< " end\n"
<< " if (widx == 0 || (WREADY && WVALID)) begin\n"
<< " widx <= widx + 1;\n"
<< " end\n"
<< " end else begin\n"
<< " WVALID <= 0;\n"
<< " WLAST <= 0;\n"
<< " wst <= `WS_WAIT;\n"
<< " BREADY <= 1;\n"
<< " end\n"
<< " end\n"
<< " `WS_SRAM: begin\n" // !sram_EXCLUSIVE
<< " if (sram_ack) begin\n"
<< " wst <= `WS_AXI;\n"
<< " WDATA <= sram_rdata;\n"
<< " widx <= widx + 1;\n"
<< " WVALID <= 1;\n"
<< " if (widx == wmax) begin\n"
<< " WLAST <= 1;\n"
<< " end\n"
<< " end\n"
<< " end\n"
<< " `WS_AXI: begin\n" // !sram_EXCLUSIVE
<< " if (WREADY && WVALID) begin\n"
<< " WVALID <= 0;\n"
<< " if (widx <= wmax) begin\n"
<< " wst <= `WS_SRAM;\n"
<< " end else begin\n"
<< " WLAST <= 0;\n"
<< " wst <= `WS_WAIT;\n"
<< " end\n"
<< " end\n"
<< " end\n"
<< " `WS_WAIT: begin\n"
<< " if (BVALID) begin\n"
<< " BREADY <= 0;\n"
<< " wst <= `WS_IDLE;\n"
<< " end\n"
<< " end\n"
<< " endcase\n";
}
} // namespace axi
} // namespace verilog
} // namespace writer
} // namespace iroha
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.7 2004/01/29 11:46:29 cargilld
* Code cleanup changes to get rid of various compiler diagnostic messages.
*
* Revision 1.6 2003/11/28 05:14:34 neilg
* update XMLDocumentHandler to enable stateless passing of type information for elements. Note that this is as yet unimplemented.
*
* Revision 1.5 2003/03/07 18:08:10 tng
* Return a reference instead of void for operator=
*
* Revision 1.4 2002/11/04 15:00:21 tng
* C++ Namespace Support.
*
* Revision 1.3 2002/05/28 20:41:11 tng
* [Bug 9104] prefixes dissapearing when schema validation turned on.
*
* Revision 1.2 2002/02/20 18:17:01 tng
* [Bug 5977] Warnings on generating apiDocs.
*
* Revision 1.1.1.1 2002/02/01 22:21:51 peiyongz
* sane_include
*
* Revision 1.8 2000/03/02 19:54:24 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.7 2000/02/24 20:00:23 abagchi
* Swat for removing Log from API docs
*
* Revision 1.6 2000/02/16 20:29:20 aruna1
* API Doc++ summary changes in
*
* Revision 1.5 2000/02/16 19:48:56 roddey
* More documentation updates
*
* Revision 1.4 2000/02/15 01:21:30 roddey
* Some initial documentation improvements. More to come...
*
* Revision 1.3 2000/02/09 19:47:27 abagchi
* Added docs for startElement
*
* Revision 1.2 2000/02/06 07:47:48 rahulj
* Year 2K copyright swat.
*
* Revision 1.1.1.1 1999/11/09 01:08:31 twl
* Initial checkin
*
* Revision 1.3 1999/11/08 20:44:37 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
#if !defined(XMLDOCUMENTHANDLER_HPP)
#define XMLDOCUMENTHANDLER_HPP
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/RefVectorOf.hpp>
#include <xercesc/framework/XMLAttr.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class XMLElementDecl;
class XMLEntityDecl;
/**
* This abstract class provides the interface for the scanner to return
* XML document information up to the parser as it scans through the
* document.
*
* The interface is very similar to org.sax.DocumentHandler, but
* has some extra methods required to get all the data out.
*/
class XMLPARSER_EXPORT XMLDocumentHandler
{
public:
// -----------------------------------------------------------------------
// Constructors are hidden, just the virtual destructor is exposed
// -----------------------------------------------------------------------
/** @name Destructor */
//@{
virtual ~XMLDocumentHandler()
{
}
//@}
/** @name The document handler interface */
//@{
/** Receive notification of character data.
*
* <p>The scanner will call this method to report each chunk of
* character data. The scanner may return all contiguous character
* data in a single chunk, or they may split it into several
* chunks; however, all of the characters in any single event
* will come from the same external entity, so that the Locator
* provides useful information.</p>
*
* <p>The parser must not attempt to read from the array
* outside of the specified range.</p>
*
* @param chars The content (characters) between markup from the XML
* document.
* @param length The number of characters to read from the array.
* @param cdataSection Indicates that this data is inside a CDATA
* section.
* @see #ignorableWhitespace
* @see Locator
*/
virtual void docCharacters
(
const XMLCh* const chars
, const unsigned int length
, const bool cdataSection
) = 0;
/** Receive notification of comments in the XML content being parsed.
*
* This scanner will call this method for any comments found in the
* content of the document.
*
* @param comment The text of the comment.
*/
virtual void docComment
(
const XMLCh* const comment
) = 0;
/** Receive notification of PI's parsed in the XML content.
*
* The scanner will call this method for any PIs it finds within the
* content of the document.
*
* @param target The name of the PI.
* @param data The body of the PI. This may be an empty string since
* the body is optional.
*/
virtual void docPI
(
const XMLCh* const target
, const XMLCh* const data
) = 0;
/** Receive notification after the scanner has parsed the end of the
* document.
*
* The scanner will call this method when the current document has been
* fully parsed. The handler may use this opportunity to do something with
* the data, clean up temporary data, etc...
*/
virtual void endDocument() = 0;
/** Receive notification of the end of an element.
*
* This method is called when scanner encounters the end of element tag.
* There will be a corresponding startElement() event for every
* endElement() event, but not necessarily the other way around. For
* empty tags, there is only a startElement() call.
*
* @param elemDecl The name of the element whose end tag was just
* parsed.
* @param uriId The ID of the URI in the URI pool (only valid if
* name spaces is enabled)
* @param isRoot Indicates if this is the root element.
* @param prefixName The string representing the prefix name
*/
virtual void endElement
(
const XMLElementDecl& elemDecl
, const unsigned int uriId
, const bool isRoot
, const XMLCh* const prefixName = 0
) = 0;
/** Receive notification when a referenced entity's content ends
*
* This method is called when scanner encounters the end of an entity
* reference.
*
* @param entDecl The name of the entity reference just scanned.
*/
virtual void endEntityReference
(
const XMLEntityDecl& entDecl
) = 0;
/** Receive notification of ignorable whitespace in element content.
*
* <p>Validating Parsers must use this method to report each chunk
* of ignorable whitespace (see the W3C XML 1.0 recommendation,
* section 2.10): non-validating parsers may also use this method
* if they are capable of parsing and using content models.</p>
*
* <p>The scanner may return all contiguous whitespace in a single
* chunk, or it may split it into several chunks; however, all of
* the characters in any single event will come from the same
* external entity, so that the Locator provides useful
* information.</p>
*
* <p>The parser must not attempt to read from the array
* outside of the specified range.</p>
*
* @param chars The whitespace characters from the XML document.
* @param length The number of characters to read from the array.
* @param cdataSection Indicates that this data is inside a CDATA
* section.
* @see #characters
*/
virtual void ignorableWhitespace
(
const XMLCh* const chars
, const unsigned int length
, const bool cdataSection
) = 0;
/** Reset the document handler's state, if required
*
* This method is used to give the registered document handler a
* chance to reset itself. Its called by the scanner at the start of
* every parse.
*/
virtual void resetDocument() = 0;
/** Receive notification of the start of a new document
*
* This method is the first callback called the scanner at the
* start of every parse. This is before any content is parsed.
*/
virtual void startDocument() = 0;
/** Receive notification of a new start tag
*
* This method is called when scanner encounters the start of an element tag.
* All elements must always have a startElement() tag. Empty tags will
* only have the startElement() tag and no endElement() tag.
*
* @param elemDecl The name of the element whose start tag was just
* parsed.
* @param uriId The ID of the URI in the URI pool (only valid if
* name spaces is enabled)
* @param prefixName The string representing the prefix name
* @param attrList List of attributes in the element
* @param attrCount Count of the attributes in the element
* @param isEmpty Indicates if the element is empty, in which case
* you should not expect an endElement() event.
* @param isRoot Indicates if this is the root element.
*/
virtual void startElement
(
const XMLElementDecl& elemDecl
, const unsigned int uriId
, const XMLCh* const prefixName
, const RefVectorOf<XMLAttr>& attrList
, const unsigned int attrCount
, const bool isEmpty
, const bool isRoot
) = 0;
/** Receive notification when the scanner hits an entity reference.
*
* This is currently useful only to DOM parser configurations as SAX
* does not provide any api to return this information.
*
* @param entDecl The name of the entity that was referenced.
*/
virtual void startEntityReference(const XMLEntityDecl& entDecl) = 0;
/** Receive notification of an XML declaration
*
* Currently neither DOM nor SAX provide API's to return back this
* information.
*
* @param versionStr The value of the <code>version</code> pseudoattribute
* of the XML decl.
* @param encodingStr The value of the <code>encoding</code> pseudoattribute
* of the XML decl.
* @param standaloneStr The value of the <code>standalone</code>
* pseudoattribute of the XML decl.
* @param autoEncodingStr The encoding string auto-detected by the
* scanner. In absence of any 'encoding' attribute in the
* XML decl, the XML standard specifies how a parser can
* auto-detect. If there is no <code>encodingStr</code>
* this is what will be used to try to decode the file.
*/
virtual void XMLDecl
(
const XMLCh* const versionStr
, const XMLCh* const encodingStr
, const XMLCh* const standaloneStr
, const XMLCh* const autoEncodingStr
) = 0;
/** Receive notification of the name and namespace of the type that validated
* the element corresponding to the most recent endElement event.
* This event will be fired immediately after the
* endElement() event that signifies the end of the element
* to which it applies; no other events will intervene.
* This method is <emEXPERIMENTAL</em> and may change, disappear
* or become pure virtual at any time.
*
* This corresponds to a part of the information required by DOM Core
* level 3's TypeInfo interface.
*
* @param typeName local name of the type that actually validated
* the content of the element corresponding to the
* most recent endElement() callback
* @param typeURI namespace of the type that actually validated
* the content of the element corresponding to the
* most recent endElement() callback
* @experimental
*/
virtual void elementTypeInfo
(
const XMLCh* const
, const XMLCh* const
) { /* non pure virtual to permit backward compatibility of implementations. */ };
//@}
protected :
// -----------------------------------------------------------------------
// Hidden Constructors
// -----------------------------------------------------------------------
XMLDocumentHandler()
{
}
private:
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
XMLDocumentHandler(const XMLDocumentHandler&);
XMLDocumentHandler& operator=(const XMLDocumentHandler&);
};
XERCES_CPP_NAMESPACE_END
#endif
<commit_msg>Fixed typo in documentation<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.8 2004/02/25 18:29:16 amassari
* Fixed typo in documentation
*
* Revision 1.7 2004/01/29 11:46:29 cargilld
* Code cleanup changes to get rid of various compiler diagnostic messages.
*
* Revision 1.6 2003/11/28 05:14:34 neilg
* update XMLDocumentHandler to enable stateless passing of type information for elements. Note that this is as yet unimplemented.
*
* Revision 1.5 2003/03/07 18:08:10 tng
* Return a reference instead of void for operator=
*
* Revision 1.4 2002/11/04 15:00:21 tng
* C++ Namespace Support.
*
* Revision 1.3 2002/05/28 20:41:11 tng
* [Bug 9104] prefixes dissapearing when schema validation turned on.
*
* Revision 1.2 2002/02/20 18:17:01 tng
* [Bug 5977] Warnings on generating apiDocs.
*
* Revision 1.1.1.1 2002/02/01 22:21:51 peiyongz
* sane_include
*
* Revision 1.8 2000/03/02 19:54:24 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.7 2000/02/24 20:00:23 abagchi
* Swat for removing Log from API docs
*
* Revision 1.6 2000/02/16 20:29:20 aruna1
* API Doc++ summary changes in
*
* Revision 1.5 2000/02/16 19:48:56 roddey
* More documentation updates
*
* Revision 1.4 2000/02/15 01:21:30 roddey
* Some initial documentation improvements. More to come...
*
* Revision 1.3 2000/02/09 19:47:27 abagchi
* Added docs for startElement
*
* Revision 1.2 2000/02/06 07:47:48 rahulj
* Year 2K copyright swat.
*
* Revision 1.1.1.1 1999/11/09 01:08:31 twl
* Initial checkin
*
* Revision 1.3 1999/11/08 20:44:37 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
#if !defined(XMLDOCUMENTHANDLER_HPP)
#define XMLDOCUMENTHANDLER_HPP
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/RefVectorOf.hpp>
#include <xercesc/framework/XMLAttr.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class XMLElementDecl;
class XMLEntityDecl;
/**
* This abstract class provides the interface for the scanner to return
* XML document information up to the parser as it scans through the
* document.
*
* The interface is very similar to org.sax.DocumentHandler, but
* has some extra methods required to get all the data out.
*/
class XMLPARSER_EXPORT XMLDocumentHandler
{
public:
// -----------------------------------------------------------------------
// Constructors are hidden, just the virtual destructor is exposed
// -----------------------------------------------------------------------
/** @name Destructor */
//@{
virtual ~XMLDocumentHandler()
{
}
//@}
/** @name The document handler interface */
//@{
/** Receive notification of character data.
*
* <p>The scanner will call this method to report each chunk of
* character data. The scanner may return all contiguous character
* data in a single chunk, or they may split it into several
* chunks; however, all of the characters in any single event
* will come from the same external entity, so that the Locator
* provides useful information.</p>
*
* <p>The parser must not attempt to read from the array
* outside of the specified range.</p>
*
* @param chars The content (characters) between markup from the XML
* document.
* @param length The number of characters to read from the array.
* @param cdataSection Indicates that this data is inside a CDATA
* section.
* @see #ignorableWhitespace
* @see Locator
*/
virtual void docCharacters
(
const XMLCh* const chars
, const unsigned int length
, const bool cdataSection
) = 0;
/** Receive notification of comments in the XML content being parsed.
*
* This scanner will call this method for any comments found in the
* content of the document.
*
* @param comment The text of the comment.
*/
virtual void docComment
(
const XMLCh* const comment
) = 0;
/** Receive notification of PI's parsed in the XML content.
*
* The scanner will call this method for any PIs it finds within the
* content of the document.
*
* @param target The name of the PI.
* @param data The body of the PI. This may be an empty string since
* the body is optional.
*/
virtual void docPI
(
const XMLCh* const target
, const XMLCh* const data
) = 0;
/** Receive notification after the scanner has parsed the end of the
* document.
*
* The scanner will call this method when the current document has been
* fully parsed. The handler may use this opportunity to do something with
* the data, clean up temporary data, etc...
*/
virtual void endDocument() = 0;
/** Receive notification of the end of an element.
*
* This method is called when scanner encounters the end of element tag.
* There will be a corresponding startElement() event for every
* endElement() event, but not necessarily the other way around. For
* empty tags, there is only a startElement() call.
*
* @param elemDecl The name of the element whose end tag was just
* parsed.
* @param uriId The ID of the URI in the URI pool (only valid if
* name spaces is enabled)
* @param isRoot Indicates if this is the root element.
* @param prefixName The string representing the prefix name
*/
virtual void endElement
(
const XMLElementDecl& elemDecl
, const unsigned int uriId
, const bool isRoot
, const XMLCh* const prefixName = 0
) = 0;
/** Receive notification when a referenced entity's content ends
*
* This method is called when scanner encounters the end of an entity
* reference.
*
* @param entDecl The name of the entity reference just scanned.
*/
virtual void endEntityReference
(
const XMLEntityDecl& entDecl
) = 0;
/** Receive notification of ignorable whitespace in element content.
*
* <p>Validating Parsers must use this method to report each chunk
* of ignorable whitespace (see the W3C XML 1.0 recommendation,
* section 2.10): non-validating parsers may also use this method
* if they are capable of parsing and using content models.</p>
*
* <p>The scanner may return all contiguous whitespace in a single
* chunk, or it may split it into several chunks; however, all of
* the characters in any single event will come from the same
* external entity, so that the Locator provides useful
* information.</p>
*
* <p>The parser must not attempt to read from the array
* outside of the specified range.</p>
*
* @param chars The whitespace characters from the XML document.
* @param length The number of characters to read from the array.
* @param cdataSection Indicates that this data is inside a CDATA
* section.
* @see #characters
*/
virtual void ignorableWhitespace
(
const XMLCh* const chars
, const unsigned int length
, const bool cdataSection
) = 0;
/** Reset the document handler's state, if required
*
* This method is used to give the registered document handler a
* chance to reset itself. Its called by the scanner at the start of
* every parse.
*/
virtual void resetDocument() = 0;
/** Receive notification of the start of a new document
*
* This method is the first callback called the scanner at the
* start of every parse. This is before any content is parsed.
*/
virtual void startDocument() = 0;
/** Receive notification of a new start tag
*
* This method is called when scanner encounters the start of an element tag.
* All elements must always have a startElement() tag. Empty tags will
* only have the startElement() tag and no endElement() tag.
*
* @param elemDecl The name of the element whose start tag was just
* parsed.
* @param uriId The ID of the URI in the URI pool (only valid if
* name spaces is enabled)
* @param prefixName The string representing the prefix name
* @param attrList List of attributes in the element
* @param attrCount Count of the attributes in the element
* @param isEmpty Indicates if the element is empty, in which case
* you should not expect an endElement() event.
* @param isRoot Indicates if this is the root element.
*/
virtual void startElement
(
const XMLElementDecl& elemDecl
, const unsigned int uriId
, const XMLCh* const prefixName
, const RefVectorOf<XMLAttr>& attrList
, const unsigned int attrCount
, const bool isEmpty
, const bool isRoot
) = 0;
/** Receive notification when the scanner hits an entity reference.
*
* This is currently useful only to DOM parser configurations as SAX
* does not provide any api to return this information.
*
* @param entDecl The name of the entity that was referenced.
*/
virtual void startEntityReference(const XMLEntityDecl& entDecl) = 0;
/** Receive notification of an XML declaration
*
* Currently neither DOM nor SAX provide API's to return back this
* information.
*
* @param versionStr The value of the <code>version</code> pseudoattribute
* of the XML decl.
* @param encodingStr The value of the <code>encoding</code> pseudoattribute
* of the XML decl.
* @param standaloneStr The value of the <code>standalone</code>
* pseudoattribute of the XML decl.
* @param autoEncodingStr The encoding string auto-detected by the
* scanner. In absence of any 'encoding' attribute in the
* XML decl, the XML standard specifies how a parser can
* auto-detect. If there is no <code>encodingStr</code>
* this is what will be used to try to decode the file.
*/
virtual void XMLDecl
(
const XMLCh* const versionStr
, const XMLCh* const encodingStr
, const XMLCh* const standaloneStr
, const XMLCh* const autoEncodingStr
) = 0;
/** Receive notification of the name and namespace of the type that validated
* the element corresponding to the most recent endElement event.
* This event will be fired immediately after the
* endElement() event that signifies the end of the element
* to which it applies; no other events will intervene.
* This method is <em>EXPERIMENTAL</em> and may change, disappear
* or become pure virtual at any time.
*
* This corresponds to a part of the information required by DOM Core
* level 3's TypeInfo interface.
*
* @param typeName local name of the type that actually validated
* the content of the element corresponding to the
* most recent endElement() callback
* @param typeURI namespace of the type that actually validated
* the content of the element corresponding to the
* most recent endElement() callback
* @experimental
*/
virtual void elementTypeInfo
(
const XMLCh* const
, const XMLCh* const
) { /* non pure virtual to permit backward compatibility of implementations. */ };
//@}
protected :
// -----------------------------------------------------------------------
// Hidden Constructors
// -----------------------------------------------------------------------
XMLDocumentHandler()
{
}
private:
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
XMLDocumentHandler(const XMLDocumentHandler&);
XMLDocumentHandler& operator=(const XMLDocumentHandler&);
};
XERCES_CPP_NAMESPACE_END
#endif
<|endoftext|>
|
<commit_before>
#include <SkynetClient.h>
// #include <WiFi.h>
// WiFiClient client;
#include <Ethernet.h>
EthernetClient client;
#define TOKEN_STRING(js, t, s) \
(strncmp(js+(t).start, s, (t).end - (t).start) == 0 \
&& strlen(s) == (t).end - (t).start)
struct ring_buffer
{
unsigned char buffer[SKYNET_BUFFER_SIZE];
volatile unsigned int head;
volatile unsigned int tail;
};
ring_buffer socket_rx_buffer = { { 0 }, 0, 0};
inline void store_char(unsigned char c, ring_buffer *buffer)
{
int i = (unsigned int)(buffer->head + 1) % SKYNET_BUFFER_SIZE;
// if we should be storing the received character into the location
// just before the tail (meaning that the head would advance to the
// current location of the tail), we're about to overflow the buffer
// and so we don't write the character or advance the head.
if (i != buffer->tail) {
buffer->buffer[buffer->head] = c;
buffer->head = i;
}
}
SkynetClient::SkynetClient(){
}
int SkynetClient::connect(const char* host, uint16_t port) {
IPAddress remote_addr;
if (WiFi.hostByName(host, remote_addr))
{
return connect(remote_addr, port);
}
}
int SkynetClient::connect(IPAddress ip, uint16_t port) {
_rx_buffer = &socket_rx_buffer;
theip = ip;
//connect tcp or fail
if (!client.connect(theip, port))
return false;
//establish socket or fail
sendHandshake();
if(!readHandshake()){
stop();
return false;
}
//monitor to initiate communications with skynet TODO some fail condition
while(!status)
monitor();
return status;
}
uint8_t SkynetClient::connected() {
return status;
}
void SkynetClient::stop() {
status = 0;
client.stop();
}
//dump until peek is not a colon
void SkynetClient::dump(){
if(!client.available())
return;
DBGC(F("Dumping: "));
do{
char c = client.read();
DBGC(c);
}while ( client.available() && client.peek() == ':' );
DBGCN("");
}
//eg on first connect:
// 1::ÿ 5:::{"name":"identify","args":[{"socketid":"zb2gh9TSVZ-eyUf8YZ_4"}]}ÿ
// or after 2::ÿ or:
// 5:::{"name":"identify","args":[{"socketid":"zb2gh9TSVZ-eyUf8YZ_4"}]}ÿ
void SkynetClient::monitor()
{
char which = 0;
if(client.available()){
which = client.read();
}else{
return;
}
switch (which) {
//disconnect
case '0':
DBGCN(F("Disconnect"));
stop();
break;
//messages
case '1':
DBGCN(F("Socket Connect"));
break;
case '3':
case '5':
DBGCN(F("Message"));
dump();
process();
break;
//hearbeat
case '2':
client.print((char)0);
client.print(F("2::"));
client.print((char)255);
DBGCN(F("Heartbeat"));
break;
//huh?
default:
DBGC(F("Drop: "));
DBGCN(which);
break;
}
}
void SkynetClient::process()
{
DBGCN(F("Processing Message"));
if (client.available()) {
int size = readLine();
jsmn_parser p;
jsmntok_t tok[255];
jsmn_init(&p);
int r = jsmn_parse(&p, databuffer, tok, 255);
if (r != 0){
DBGCN(F("parse failed"));
DBGCN(r);
return;
}
if (TOKEN_STRING(databuffer, tok[2], IDENTIFY ))
{
DBGCN(F(IDENTIFY));
DBGC(F("Sending: "));
DBGC((char)0);
client.print((char)0);
DBGC(EMIT);
client.print(EMIT);
printByByte("{\"name\":\"identity\",\"args\":[{\"socketid\":\"");
printToken(databuffer, tok[7]);
if( eeprom_read_byte( (uint8_t*)EEPROMBLOCKADDRESS) == EEPROMBLOCK )
{
eeprom_read_bytes(token, TOKENADDRESS, TOKENSIZE);
token[TOKENSIZE-1]='\0'; //in case courrupted or not defined
eeprom_read_bytes(uuid, UUIDADDRESS, UUIDSIZE);
uuid[UUIDSIZE-1]='\0'; //in case courrupted or not defined
printByByte("\", \"uuid\":\"");
printByByte(uuid);
printByByte("\", \"token\":\"");
printByByte(token);
}
printByByte("\"}]}");
DBGCN((char)255);
client.print((char)255);
}
else if (TOKEN_STRING(databuffer, tok[2], READY ))
{
DBGCN(READY);
status = 1;
eeprom_read_bytes(token, TOKENADDRESS, TOKENSIZE);
token[TOKENSIZE-1]='\0'; //in case courrupted or not defined
//if token has been refreshed, save it
if (TOKEN_STRING(databuffer, tok[15], token ))
{
DBGCN(F("token refresh"));
strncpy(token, databuffer + tok[15].start, tok[15].end - tok[15].start);
DBGC(F("new: "));
DBGCN(token);
eeprom_write_bytes(token, TOKENADDRESS, TOKENSIZE);
//write block identifier, arduino should protect us from writing if it doesnt need it?
eeprom_write_byte((uint8_t *)EEPROMBLOCKADDRESS, (uint8_t)EEPROMBLOCK);
}else
{
DBGCN(F("no token refresh necessary"));
}
eeprom_read_bytes(uuid, UUIDADDRESS, UUIDSIZE);
uuid[UUIDSIZE-1]='\0'; //in case courrupted or not defined
//if uuid has been refreshed, save it
if (TOKEN_STRING(databuffer, tok[13], uuid ))
{
DBGCN(F("uuid refresh"));
strncpy(uuid, databuffer + tok[13].start, tok[13].end - tok[13].start);
DBGC(F("new: "));
DBGCN(uuid);
eeprom_write_bytes(uuid, UUIDADDRESS, UUIDSIZE);
//write block identifier, arduino should protect us from writing if it doesnt need it?
eeprom_write_byte((uint8_t *)EEPROMBLOCKADDRESS, (uint8_t)EEPROMBLOCK);
}else
{
DBGCN(F("no uuid refresh necessary"));
}
}
else if (TOKEN_STRING(databuffer, tok[2], NOTREADY ))
{
//send blank identify
DBGCN(NOTREADY);
printByByte("{\"name\":\"identity\",\"args\":[{\"socketid\":\"");
printToken(databuffer, tok[7]);
printByByte("\"}]}");
}
else if (TOKEN_STRING(databuffer, tok[2], MESSAGE ))
{
DBGCN(MESSAGE);
DBGCN("Storing: ");
for(int i = tok[9].start; i < tok[9].end; i++)
{
DBGC(databuffer[i]);
store_char( databuffer[i], &socket_rx_buffer);
}
DBGCN("");
if (messageDelegate != NULL) {
messageDelegate(databuffer);
}
}
else
{
DBGC(F("Unknown:"));
}
}
}
void SkynetClient::sendHandshake() {
client.println(F("GET /socket.io/1/ HTTP/1.1"));
client.print(F("Host: "));
client.println(theip);
client.println(F("Origin: Arduino\r\n"));
}
bool SkynetClient::waitForInput(void) {
unsigned long now = millis();
while (!client.available() && ((millis() - now) < 30000UL)) {;}
return client.available();
}
void SkynetClient::eatHeader(void) {
while (client.available()) { // consume the header
readLine();
if (strlen(databuffer) == 0) break;
}
}
int SkynetClient::readHandshake() {
if (!waitForInput()) return false;
// check for happy "HTTP/1.1 200" response
readLine();
if (atoi(&databuffer[8]) != 200) {
while (client.available()) readLine();
client.stop();
return 0;
}
eatHeader();
readLine(); // read first line of response
readLine(); // read sid : transport : timeout
char *iptr = databuffer;
char *optr = sid;
while (*iptr && (*iptr != ':') && (optr < &sid[SID_LEN-2])) *optr++ = *iptr++;
*optr = 0;
DBGC(F("Connected. SID="));
DBGCN(sid); // sid:transport:timeout
while (client.available()) readLine();
client.print(F("GET /socket.io/1/websocket/"));
client.print(sid);
client.println(F(" HTTP/1.1"));
client.print(F("Host: "));
client.println(theip);
client.println(F("Origin: ArduinoSkynetClient"));
client.println(F("Upgrade: WebSocket")); // must be camelcase ?!
client.println(F("Connection: Upgrade\r\n"));
if (!waitForInput()) return 0;
readLine();
if (atoi(&databuffer[8]) != 101) {
while (client.available()) readLine();
client.stop();
return false;
}
eatHeader();
monitor(); // treat the response as input
return 1;
}
int SkynetClient::readLine() {
int numBytes = 0;
dataptr = databuffer;
DBGC(F("Readline: "));
while (client.available() && (dataptr < &databuffer[DATA_BUFFER_LEN-2])) {
char c = client.read();
if (c == 0){
;
}else if (c == -1){
;
}else if (c == 255){
;
}else if (c == '\r') {
;
}else if (c == '\n')
break;
else {
DBGC(c);
*dataptr++ = c;
numBytes++;
}
}
DBGCN();
*dataptr = 0;
return numBytes;
}
//wifi client.print has a buffer that so far we've been unable to locate
//under 154 (our identify size) for sure.. so sending char by char for now
void SkynetClient::printByByte(char *data) {
int i = 0;
while ( data[i] != '\0' )
{
DBGC(data[i]);
client.print(data[i++]);
}
}
void SkynetClient::printToken(char *js, jsmntok_t t)
{
int i = 0;
for(i = t.start; i < t.end; i++) {
DBGC(js[i]);
client.print(js[i]);
}
}
size_t SkynetClient::write(const uint8_t *buf, size_t size) {
DBGC(F("Sending: "));
DBGC((char)0);
client.print((char)0);
DBGC(EMIT);
client.print(EMIT);
//wifi client.print has a buffer that so far we've been unable to locate
//under 154 (our identify size) for sure.. so sending char by char for now
int i = 0;
while ( i < size )
{
DBGC(buf[i]);
client.print(buf[i++]);
}
DBGCN((char)255);
client.print((char)255);
}
int SkynetClient::available() {
return (unsigned int)(SKYNET_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % SKYNET_BUFFER_SIZE
;
}
int SkynetClient::read() {
// if the head isn't ahead of the tail, we don't have any characters
if (_rx_buffer->head == _rx_buffer->tail) {
return -1;
} else {
unsigned char c = _rx_buffer->buffer[_rx_buffer->tail];
_rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % SKYNET_BUFFER_SIZE;
return c;
}
}
// //TODO
// int SkynetClient::read(uint8_t *buf, size_t size) {
// }
int SkynetClient::peek() {
if (_rx_buffer->head == _rx_buffer->tail) {
return -1;
} else {
return _rx_buffer->buffer[_rx_buffer->tail];
}
}
void SkynetClient::flush() {
client.flush();
}
// the next function allows us to use the client returned by
// SkynetClient::available() as the condition in an if-statement.
SkynetClient::operator bool() {
return true;
}
void SkynetClient::setMessageDelegate(MessageDelegate newMessageDelegate) {
messageDelegate = newMessageDelegate;
}
void SkynetClient::eeprom_write_bytes(char *buf, int address, int bufSize){
for(int i = 0; i<bufSize; i++){
EEPROM.write(address+i, buf[i]);
}
}
void SkynetClient::eeprom_read_bytes(char *buf, int address, int bufSize){
for(int i = 0; i<bufSize; i++){
buf[i] = EEPROM.read(address+i);
}
}
void SkynetClient::sendMessage(char device[], char object[])
{
DBGC(F("Sending: "));
DBGC((char)0);
client.print((char)0);
DBGC(EMIT);
client.print(EMIT);
printByByte("{\"name\":\"message\",\"args\":[{\"devices\":\"");
printByByte(device);
printByByte("\",\"payload\":\"");
printByByte(object);
printByByte("\"}]}");
DBGCN((char)255);
client.print((char)255);
}<commit_msg>fix and confirm eeprom update from 882b312c105b43f23cbf7c2931e9bf143af96ed8<commit_after>
#include <SkynetClient.h>
// #include <WiFi.h>
// WiFiClient client;
#include <Ethernet.h>
EthernetClient client;
#define TOKEN_STRING(js, t, s) \
(strncmp(js+(t).start, s, (t).end - (t).start) == 0 \
&& strlen(s) == (t).end - (t).start)
struct ring_buffer
{
unsigned char buffer[SKYNET_BUFFER_SIZE];
volatile unsigned int head;
volatile unsigned int tail;
};
ring_buffer socket_rx_buffer = { { 0 }, 0, 0};
inline void store_char(unsigned char c, ring_buffer *buffer)
{
int i = (unsigned int)(buffer->head + 1) % SKYNET_BUFFER_SIZE;
// if we should be storing the received character into the location
// just before the tail (meaning that the head would advance to the
// current location of the tail), we're about to overflow the buffer
// and so we don't write the character or advance the head.
if (i != buffer->tail) {
buffer->buffer[buffer->head] = c;
buffer->head = i;
}
}
SkynetClient::SkynetClient(){
}
int SkynetClient::connect(const char* host, uint16_t port) {
IPAddress remote_addr;
if (WiFi.hostByName(host, remote_addr))
{
return connect(remote_addr, port);
}
}
int SkynetClient::connect(IPAddress ip, uint16_t port) {
_rx_buffer = &socket_rx_buffer;
theip = ip;
//connect tcp or fail
if (!client.connect(theip, port))
return false;
//establish socket or fail
sendHandshake();
if(!readHandshake()){
stop();
return false;
}
//monitor to initiate communications with skynet TODO some fail condition
while(!status)
monitor();
return status;
}
uint8_t SkynetClient::connected() {
return status;
}
void SkynetClient::stop() {
status = 0;
client.stop();
}
//dump until peek is not a colon
void SkynetClient::dump(){
if(!client.available())
return;
DBGC(F("Dumping: "));
do{
char c = client.read();
DBGC(c);
}while ( client.available() && client.peek() == ':' );
DBGCN("");
}
//eg on first connect:
// 1::ÿ 5:::{"name":"identify","args":[{"socketid":"zb2gh9TSVZ-eyUf8YZ_4"}]}ÿ
// or after 2::ÿ or:
// 5:::{"name":"identify","args":[{"socketid":"zb2gh9TSVZ-eyUf8YZ_4"}]}ÿ
void SkynetClient::monitor()
{
char which = 0;
if(client.available()){
which = client.read();
}else{
return;
}
switch (which) {
//disconnect
case '0':
DBGCN(F("Disconnect"));
stop();
break;
//messages
case '1':
DBGCN(F("Socket Connect"));
break;
case '3':
case '5':
DBGCN(F("Message"));
dump();
process();
break;
//hearbeat
case '2':
client.print((char)0);
client.print(F("2::"));
client.print((char)255);
DBGCN(F("Heartbeat"));
break;
//huh?
default:
DBGC(F("Drop: "));
DBGCN(which);
break;
}
}
void SkynetClient::process()
{
DBGCN(F("Processing Message"));
if (client.available()) {
int size = readLine();
jsmn_parser p;
jsmntok_t tok[255];
jsmn_init(&p);
int r = jsmn_parse(&p, databuffer, tok, 255);
if (r != 0){
DBGCN(F("parse failed"));
DBGCN(r);
return;
}
if (TOKEN_STRING(databuffer, tok[2], IDENTIFY ))
{
DBGCN(F(IDENTIFY));
DBGC(F("Sending: "));
DBGC((char)0);
client.print((char)0);
DBGC(EMIT);
client.print(EMIT);
printByByte("{\"name\":\"identity\",\"args\":[{\"socketid\":\"");
printToken(databuffer, tok[7]);
if( eeprom_read_byte( (uint8_t*)EEPROMBLOCKADDRESS) == EEPROMBLOCK )
{
eeprom_read_bytes(token, TOKENADDRESS, TOKENSIZE);
token[TOKENSIZE-1]='\0'; //in case courrupted or not defined
eeprom_read_bytes(uuid, UUIDADDRESS, UUIDSIZE);
uuid[UUIDSIZE-1]='\0'; //in case courrupted or not defined
printByByte("\", \"uuid\":\"");
printByByte(uuid);
printByByte("\", \"token\":\"");
printByByte(token);
}
printByByte("\"}]}");
DBGCN((char)255);
client.print((char)255);
}
else if (TOKEN_STRING(databuffer, tok[2], READY ))
{
DBGCN(READY);
status = 1;
eeprom_read_bytes(token, TOKENADDRESS, TOKENSIZE);
token[TOKENSIZE-1]='\0'; //in case courrupted or not defined
//if token has been refreshed, save it
if (!TOKEN_STRING(databuffer, tok[15], token ))
{
DBGCN(F("token refresh"));
strncpy(token, databuffer + tok[15].start, tok[15].end - tok[15].start);
DBGC(F("new: "));
DBGCN(token);
eeprom_write_bytes(token, TOKENADDRESS, TOKENSIZE);
//write block identifier, arduino should protect us from writing if it doesnt need it?
eeprom_write_byte((uint8_t *)EEPROMBLOCKADDRESS, (uint8_t)EEPROMBLOCK);
}else
{
DBGCN(F("no token refresh necessary"));
}
eeprom_read_bytes(uuid, UUIDADDRESS, UUIDSIZE);
uuid[UUIDSIZE-1]='\0'; //in case courrupted or not defined
//if uuid has been refreshed, save it
if (!TOKEN_STRING(databuffer, tok[13], uuid ))
{
DBGCN(F("uuid refresh"));
strncpy(uuid, databuffer + tok[13].start, tok[13].end - tok[13].start);
DBGC(F("new: "));
DBGCN(uuid);
eeprom_write_bytes(uuid, UUIDADDRESS, UUIDSIZE);
//write block identifier, arduino should protect us from writing if it doesnt need it?
eeprom_write_byte((uint8_t *)EEPROMBLOCKADDRESS, (uint8_t)EEPROMBLOCK);
}else
{
DBGCN(F("no uuid refresh necessary"));
}
}
else if (TOKEN_STRING(databuffer, tok[2], NOTREADY ))
{
//send blank identify
DBGCN(NOTREADY);
printByByte("{\"name\":\"identity\",\"args\":[{\"socketid\":\"");
printToken(databuffer, tok[7]);
printByByte("\"}]}");
}
else if (TOKEN_STRING(databuffer, tok[2], MESSAGE ))
{
DBGCN(MESSAGE);
DBGCN("Storing: ");
for(int i = tok[9].start; i < tok[9].end; i++)
{
DBGC(databuffer[i]);
store_char( databuffer[i], &socket_rx_buffer);
}
DBGCN("");
if (messageDelegate != NULL) {
messageDelegate(databuffer);
}
}
else
{
DBGC(F("Unknown:"));
}
}
}
void SkynetClient::sendHandshake() {
client.println(F("GET /socket.io/1/ HTTP/1.1"));
client.print(F("Host: "));
client.println(theip);
client.println(F("Origin: Arduino\r\n"));
}
bool SkynetClient::waitForInput(void) {
unsigned long now = millis();
while (!client.available() && ((millis() - now) < 30000UL)) {;}
return client.available();
}
void SkynetClient::eatHeader(void) {
while (client.available()) { // consume the header
readLine();
if (strlen(databuffer) == 0) break;
}
}
int SkynetClient::readHandshake() {
if (!waitForInput()) return false;
// check for happy "HTTP/1.1 200" response
readLine();
if (atoi(&databuffer[8]) != 200) {
while (client.available()) readLine();
client.stop();
return 0;
}
eatHeader();
readLine(); // read first line of response
readLine(); // read sid : transport : timeout
char *iptr = databuffer;
char *optr = sid;
while (*iptr && (*iptr != ':') && (optr < &sid[SID_LEN-2])) *optr++ = *iptr++;
*optr = 0;
DBGC(F("Connected. SID="));
DBGCN(sid); // sid:transport:timeout
while (client.available()) readLine();
client.print(F("GET /socket.io/1/websocket/"));
client.print(sid);
client.println(F(" HTTP/1.1"));
client.print(F("Host: "));
client.println(theip);
client.println(F("Origin: ArduinoSkynetClient"));
client.println(F("Upgrade: WebSocket")); // must be camelcase ?!
client.println(F("Connection: Upgrade\r\n"));
if (!waitForInput()) return 0;
readLine();
if (atoi(&databuffer[8]) != 101) {
while (client.available()) readLine();
client.stop();
return false;
}
eatHeader();
monitor(); // treat the response as input
return 1;
}
int SkynetClient::readLine() {
int numBytes = 0;
dataptr = databuffer;
DBGC(F("Readline: "));
while (client.available() && (dataptr < &databuffer[DATA_BUFFER_LEN-2])) {
char c = client.read();
if (c == 0){
;
}else if (c == -1){
;
}else if (c == 255){
;
}else if (c == '\r') {
;
}else if (c == '\n')
break;
else {
DBGC(c);
*dataptr++ = c;
numBytes++;
}
}
DBGCN();
*dataptr = 0;
return numBytes;
}
//wifi client.print has a buffer that so far we've been unable to locate
//under 154 (our identify size) for sure.. so sending char by char for now
void SkynetClient::printByByte(char *data) {
int i = 0;
while ( data[i] != '\0' )
{
DBGC(data[i]);
client.print(data[i++]);
}
}
void SkynetClient::printToken(char *js, jsmntok_t t)
{
int i = 0;
for(i = t.start; i < t.end; i++) {
DBGC(js[i]);
client.print(js[i]);
}
}
size_t SkynetClient::write(const uint8_t *buf, size_t size) {
DBGC(F("Sending: "));
DBGC((char)0);
client.print((char)0);
DBGC(EMIT);
client.print(EMIT);
//wifi client.print has a buffer that so far we've been unable to locate
//under 154 (our identify size) for sure.. so sending char by char for now
int i = 0;
while ( i < size )
{
DBGC(buf[i]);
client.print(buf[i++]);
}
DBGCN((char)255);
client.print((char)255);
}
int SkynetClient::available() {
return (unsigned int)(SKYNET_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % SKYNET_BUFFER_SIZE
;
}
int SkynetClient::read() {
// if the head isn't ahead of the tail, we don't have any characters
if (_rx_buffer->head == _rx_buffer->tail) {
return -1;
} else {
unsigned char c = _rx_buffer->buffer[_rx_buffer->tail];
_rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % SKYNET_BUFFER_SIZE;
return c;
}
}
// //TODO
// int SkynetClient::read(uint8_t *buf, size_t size) {
// }
int SkynetClient::peek() {
if (_rx_buffer->head == _rx_buffer->tail) {
return -1;
} else {
return _rx_buffer->buffer[_rx_buffer->tail];
}
}
void SkynetClient::flush() {
client.flush();
}
// the next function allows us to use the client returned by
// SkynetClient::available() as the condition in an if-statement.
SkynetClient::operator bool() {
return true;
}
void SkynetClient::setMessageDelegate(MessageDelegate newMessageDelegate) {
messageDelegate = newMessageDelegate;
}
void SkynetClient::eeprom_write_bytes(char *buf, int address, int bufSize){
for(int i = 0; i<bufSize; i++){
EEPROM.write(address+i, buf[i]);
}
}
void SkynetClient::eeprom_read_bytes(char *buf, int address, int bufSize){
for(int i = 0; i<bufSize; i++){
buf[i] = EEPROM.read(address+i);
}
}
void SkynetClient::sendMessage(char device[], char object[])
{
DBGC(F("Sending: "));
DBGC((char)0);
client.print((char)0);
DBGC(EMIT);
client.print(EMIT);
printByByte("{\"name\":\"message\",\"args\":[{\"devices\":\"");
printByByte(device);
printByByte("\",\"payload\":\"");
printByByte(object);
printByByte("\"}]}");
DBGCN((char)255);
client.print((char)255);
}<|endoftext|>
|
<commit_before>// Copyright (c) 2010 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 "remoting/host/capturer_mac.h"
#include <stddef.h>
#include <OpenGL/CGLMacro.h>
namespace remoting {
CapturerMac::CapturerMac(MessageLoop* message_loop)
: Capturer(message_loop),
cgl_context_(NULL) {
// TODO(dmaclach): move this initialization out into session_manager,
// or at least have session_manager call into here to initialize it.
CGError err =
CGRegisterScreenRefreshCallback(CapturerMac::ScreenRefreshCallback,
this);
DCHECK_EQ(err, kCGErrorSuccess);
err = CGScreenRegisterMoveCallback(CapturerMac::ScreenUpdateMoveCallback,
this);
DCHECK_EQ(err, kCGErrorSuccess);
err = CGDisplayRegisterReconfigurationCallback(
CapturerMac::DisplaysReconfiguredCallback, this);
DCHECK_EQ(err, kCGErrorSuccess);
ScreenConfigurationChanged();
}
CapturerMac::~CapturerMac() {
ReleaseBuffers();
CGUnregisterScreenRefreshCallback(CapturerMac::ScreenRefreshCallback, this);
CGScreenUnregisterMoveCallback(CapturerMac::ScreenUpdateMoveCallback, this);
CGDisplayRemoveReconfigurationCallback(
CapturerMac::DisplaysReconfiguredCallback, this);
}
void CapturerMac::ReleaseBuffers() {
if (cgl_context_) {
CGLDestroyContext(cgl_context_);
cgl_context_ = NULL;
}
}
void CapturerMac::ScreenConfigurationChanged() {
ReleaseBuffers();
CGDirectDisplayID mainDevice = CGMainDisplayID();
width_ = CGDisplayPixelsWide(mainDevice);
height_ = CGDisplayPixelsHigh(mainDevice);
pixel_format_ = media::VideoFrame::RGB32;
bytes_per_row_ = width_ * sizeof(uint32_t);
size_t buffer_size = height() * bytes_per_row_;
for (int i = 0; i < kNumBuffers; ++i) {
buffers_[i].reset(new uint8[buffer_size]);
}
CGLPixelFormatAttribute attributes[] = {
kCGLPFAFullScreen,
kCGLPFADisplayMask,
(CGLPixelFormatAttribute)CGDisplayIDToOpenGLDisplayMask(mainDevice),
(CGLPixelFormatAttribute)0
};
CGLPixelFormatObj pixel_format = NULL;
GLint matching_pixel_format_count = 0;
CGLError err = CGLChoosePixelFormat(attributes,
&pixel_format,
&matching_pixel_format_count);
DCHECK_EQ(err, kCGLNoError);
err = CGLCreateContext(pixel_format, NULL, &cgl_context_);
DCHECK_EQ(err, kCGLNoError);
CGLDestroyPixelFormat(pixel_format);
CGLSetFullScreen(cgl_context_);
CGLSetCurrentContext(cgl_context_);
}
void CapturerMac::CalculateInvalidRects() {
// Since the Mac gets its list of invalid rects via calls to InvalidateRect(),
// this step only needs to perform post-processing optimizations on the rect
// list (if needed).
}
void CapturerMac::CaptureRects(const InvalidRects& rects,
CaptureCompletedCallback* callback) {
// TODO(dmaclach): something smarter here in the future.
gfx::Rect dirtyRect;
for (InvalidRects::const_iterator i = rects.begin(); i != rects.end(); ++i) {
dirtyRect = dirtyRect.Union(*i);
}
CGLContextObj CGL_MACRO_CONTEXT = cgl_context_;
glReadBuffer(GL_FRONT);
glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
glPixelStorei(GL_PACK_ALIGNMENT, 4); // Force 4-byte alignment.
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
glPixelStorei(GL_PACK_SKIP_ROWS, 0);
glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
// Read a block of pixels from the frame buffer.
glReadPixels(0, 0, width(), height(), GL_BGRA, GL_UNSIGNED_BYTE,
buffers_[current_buffer_].get());
glPopClientAttrib();
DataPlanes planes;
planes.data[0] = buffers_[current_buffer_].get();
planes.strides[0] = bytes_per_row_;
scoped_refptr<CaptureData> data(new CaptureData(planes,
width(),
height(),
pixel_format()));
data->mutable_dirty_rects().clear();
data->mutable_dirty_rects().insert(dirtyRect);
FinishCapture(data, callback);
}
void CapturerMac::ScreenRefresh(CGRectCount count, const CGRect *rect_array) {
InvalidRects rects;
for (CGRectCount i = 0; i < count; ++i) {
CGRect rect = rect_array[i];
rect.origin.y = height() - rect.size.height;
rects.insert(gfx::Rect(rect));
}
InvalidateRects(rects);
}
void CapturerMac::ScreenUpdateMove(CGScreenUpdateMoveDelta delta,
size_t count,
const CGRect *rect_array) {
InvalidRects rects;
for (CGRectCount i = 0; i < count; ++i) {
CGRect rect = rect_array[i];
rect.origin.y = height() - rect.size.height;
rects.insert(gfx::Rect(rect));
rect = CGRectOffset(rect, delta.dX, delta.dY);
rects.insert(gfx::Rect(rect));
}
InvalidateRects(rects);
}
void CapturerMac::ScreenRefreshCallback(CGRectCount count,
const CGRect *rect_array,
void *user_parameter) {
CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter);
capturer->ScreenRefresh(count, rect_array);
}
void CapturerMac::ScreenUpdateMoveCallback(CGScreenUpdateMoveDelta delta,
size_t count,
const CGRect *rect_array,
void *user_parameter) {
CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter);
capturer->ScreenUpdateMove(delta, count, rect_array);
}
void CapturerMac::DisplaysReconfiguredCallback(
CGDirectDisplayID display,
CGDisplayChangeSummaryFlags flags,
void *user_parameter) {
if ((display == CGMainDisplayID()) &&
!(flags & kCGDisplayBeginConfigurationFlag)) {
CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter);
capturer->ScreenConfigurationChanged();
}
}
// static
Capturer* Capturer::Create(MessageLoop* message_loop) {
return new CapturerMac(message_loop);
}
} // namespace remoting
<commit_msg>Fix Capturer for Mac to cope gracefully when there are no invalid rects.<commit_after>// Copyright (c) 2010 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 "remoting/host/capturer_mac.h"
#include <stddef.h>
#include <OpenGL/CGLMacro.h>
namespace remoting {
CapturerMac::CapturerMac(MessageLoop* message_loop)
: Capturer(message_loop),
cgl_context_(NULL) {
// TODO(dmaclach): move this initialization out into session_manager,
// or at least have session_manager call into here to initialize it.
CGError err =
CGRegisterScreenRefreshCallback(CapturerMac::ScreenRefreshCallback,
this);
DCHECK_EQ(err, kCGErrorSuccess);
err = CGScreenRegisterMoveCallback(CapturerMac::ScreenUpdateMoveCallback,
this);
DCHECK_EQ(err, kCGErrorSuccess);
err = CGDisplayRegisterReconfigurationCallback(
CapturerMac::DisplaysReconfiguredCallback, this);
DCHECK_EQ(err, kCGErrorSuccess);
ScreenConfigurationChanged();
}
CapturerMac::~CapturerMac() {
ReleaseBuffers();
CGUnregisterScreenRefreshCallback(CapturerMac::ScreenRefreshCallback, this);
CGScreenUnregisterMoveCallback(CapturerMac::ScreenUpdateMoveCallback, this);
CGDisplayRemoveReconfigurationCallback(
CapturerMac::DisplaysReconfiguredCallback, this);
}
void CapturerMac::ReleaseBuffers() {
if (cgl_context_) {
CGLDestroyContext(cgl_context_);
cgl_context_ = NULL;
}
}
void CapturerMac::ScreenConfigurationChanged() {
ReleaseBuffers();
CGDirectDisplayID mainDevice = CGMainDisplayID();
width_ = CGDisplayPixelsWide(mainDevice);
height_ = CGDisplayPixelsHigh(mainDevice);
pixel_format_ = media::VideoFrame::RGB32;
bytes_per_row_ = width_ * sizeof(uint32_t);
size_t buffer_size = height() * bytes_per_row_;
for (int i = 0; i < kNumBuffers; ++i) {
buffers_[i].reset(new uint8[buffer_size]);
}
CGLPixelFormatAttribute attributes[] = {
kCGLPFAFullScreen,
kCGLPFADisplayMask,
(CGLPixelFormatAttribute)CGDisplayIDToOpenGLDisplayMask(mainDevice),
(CGLPixelFormatAttribute)0
};
CGLPixelFormatObj pixel_format = NULL;
GLint matching_pixel_format_count = 0;
CGLError err = CGLChoosePixelFormat(attributes,
&pixel_format,
&matching_pixel_format_count);
DCHECK_EQ(err, kCGLNoError);
err = CGLCreateContext(pixel_format, NULL, &cgl_context_);
DCHECK_EQ(err, kCGLNoError);
CGLDestroyPixelFormat(pixel_format);
CGLSetFullScreen(cgl_context_);
CGLSetCurrentContext(cgl_context_);
}
void CapturerMac::CalculateInvalidRects() {
// Since the Mac gets its list of invalid rects via calls to InvalidateRect(),
// this step only needs to perform post-processing optimizations on the rect
// list (if needed).
}
void CapturerMac::CaptureRects(const InvalidRects& rects,
CaptureCompletedCallback* callback) {
CGLContextObj CGL_MACRO_CONTEXT = cgl_context_;
glReadBuffer(GL_FRONT);
glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
glPixelStorei(GL_PACK_ALIGNMENT, 4); // Force 4-byte alignment.
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
glPixelStorei(GL_PACK_SKIP_ROWS, 0);
glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
// Read a block of pixels from the frame buffer.
glReadPixels(0, 0, width(), height(), GL_BGRA, GL_UNSIGNED_BYTE,
buffers_[current_buffer_].get());
glPopClientAttrib();
DataPlanes planes;
planes.data[0] = buffers_[current_buffer_].get();
planes.strides[0] = bytes_per_row_;
scoped_refptr<CaptureData> data(new CaptureData(planes,
width(),
height(),
pixel_format()));
data->mutable_dirty_rects() = rects;
FinishCapture(data, callback);
}
void CapturerMac::ScreenRefresh(CGRectCount count, const CGRect *rect_array) {
InvalidRects rects;
for (CGRectCount i = 0; i < count; ++i) {
CGRect rect = rect_array[i];
rect.origin.y = height() - rect.size.height;
rects.insert(gfx::Rect(rect));
}
InvalidateRects(rects);
}
void CapturerMac::ScreenUpdateMove(CGScreenUpdateMoveDelta delta,
size_t count,
const CGRect *rect_array) {
InvalidRects rects;
for (CGRectCount i = 0; i < count; ++i) {
CGRect rect = rect_array[i];
rect.origin.y = height() - rect.size.height;
rects.insert(gfx::Rect(rect));
rect = CGRectOffset(rect, delta.dX, delta.dY);
rects.insert(gfx::Rect(rect));
}
InvalidateRects(rects);
}
void CapturerMac::ScreenRefreshCallback(CGRectCount count,
const CGRect *rect_array,
void *user_parameter) {
CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter);
capturer->ScreenRefresh(count, rect_array);
}
void CapturerMac::ScreenUpdateMoveCallback(CGScreenUpdateMoveDelta delta,
size_t count,
const CGRect *rect_array,
void *user_parameter) {
CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter);
capturer->ScreenUpdateMove(delta, count, rect_array);
}
void CapturerMac::DisplaysReconfiguredCallback(
CGDirectDisplayID display,
CGDisplayChangeSummaryFlags flags,
void *user_parameter) {
if ((display == CGMainDisplayID()) &&
!(flags & kCGDisplayBeginConfigurationFlag)) {
CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter);
capturer->ScreenConfigurationChanged();
}
}
// static
Capturer* Capturer::Create(MessageLoop* message_loop) {
return new CapturerMac(message_loop);
}
} // namespace remoting
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.5 2003/11/28 22:41:04 neilg
* fix compilation error
*
* Revision 1.4 2003/11/28 20:20:54 neilg
* make use of canonical representation in PSVIAttribute implementation
*
* Revision 1.3 2003/11/27 06:10:32 neilg
* PSVIAttribute implementation
*
* Revision 1.2 2003/11/06 21:50:33 neilg
* fix compilation errors under gcc 3.3.
*
* Revision 1.1 2003/09/16 14:33:36 neilg
* PSVI/schema component model classes, with Makefile/configuration changes necessary to build them
*
*/
#include <xercesc/framework/psvi/PSVIAttribute.hpp>
XERCES_CPP_NAMESPACE_BEGIN
PSVIAttribute::PSVIAttribute( MemoryManager* const manager ):
PSVIItem(manager),
fAttributeDecl(0)
{
}
void PSVIAttribute::reset(
const XMLCh * const valContext
, PSVIItem::VALIDITY_STATE state
, PSVIItem::ASSESSMENT_TYPE assessmentType
, const XMLCh * const normalizedValue
, XSSimpleTypeDefinition * validatingType
, XSSimpleTypeDefinition * memberType
, const XMLCh * const defaultValue
, const bool isSpecified
, XSAttributeDeclaration * attrDecl
, DatatypeValidator *dv
)
{
fValidationContext = valContext;
fValidityState = state;
fAssessmentType = assessmentType;
fNormalizedValue = normalizedValue;
fType = validatingType;
fMemberType = memberType;
fDefaultValue = defaultValue;
fIsSpecified = isSpecified;
fMemoryManager->deallocate((void *)fCanonicalValue);
if(normalizedValue && dv)
fCanonicalValue = (XMLCh *)dv->getCanonicalRepresentation(normalizedValue, fMemoryManager);
else
fCanonicalValue = 0;
fAttributeDecl = attrDecl;
}
XERCES_CPP_NAMESPACE_END
<commit_msg>since there are certain things, such as schemaLocation attributes, that have a datatype and which we nonetheless do not validate, make canonical-value production dependent on validity being valid<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.6 2003/12/02 17:31:42 neilg
* since there are certain things, such as schemaLocation attributes, that have a datatype and which we nonetheless do not validate, make canonical-value production dependent on validity being valid
*
* Revision 1.5 2003/11/28 22:41:04 neilg
* fix compilation error
*
* Revision 1.4 2003/11/28 20:20:54 neilg
* make use of canonical representation in PSVIAttribute implementation
*
* Revision 1.3 2003/11/27 06:10:32 neilg
* PSVIAttribute implementation
*
* Revision 1.2 2003/11/06 21:50:33 neilg
* fix compilation errors under gcc 3.3.
*
* Revision 1.1 2003/09/16 14:33:36 neilg
* PSVI/schema component model classes, with Makefile/configuration changes necessary to build them
*
*/
#include <xercesc/framework/psvi/PSVIAttribute.hpp>
XERCES_CPP_NAMESPACE_BEGIN
PSVIAttribute::PSVIAttribute( MemoryManager* const manager ):
PSVIItem(manager),
fAttributeDecl(0)
{
}
void PSVIAttribute::reset(
const XMLCh * const valContext
, PSVIItem::VALIDITY_STATE state
, PSVIItem::ASSESSMENT_TYPE assessmentType
, const XMLCh * const normalizedValue
, XSSimpleTypeDefinition * validatingType
, XSSimpleTypeDefinition * memberType
, const XMLCh * const defaultValue
, const bool isSpecified
, XSAttributeDeclaration * attrDecl
, DatatypeValidator *dv
)
{
fValidationContext = valContext;
fValidityState = state;
fAssessmentType = assessmentType;
fNormalizedValue = normalizedValue;
fType = validatingType;
fMemberType = memberType;
fDefaultValue = defaultValue;
fIsSpecified = isSpecified;
fMemoryManager->deallocate((void *)fCanonicalValue);
if(normalizedValue && dv && fValidityState == VALIDITY_STATE::VALID)
fCanonicalValue = (XMLCh *)dv->getCanonicalRepresentation(normalizedValue, fMemoryManager);
else
fCanonicalValue = 0;
fAttributeDecl = attrDecl;
}
XERCES_CPP_NAMESPACE_END
<|endoftext|>
|
<commit_before>/// @file {{ device.class_name|lower }}.hpp
///
/// (c) Koheron 2014-2015
#ifndef __{{ device.class_name|upper }}_HPP__
#define __{{ device.class_name|upper }}_HPP__
{% for include in device.includes -%}
#include <{{ include }}>
{% endfor -%}
#include <drivers/dev_mem.hpp>
#if KSERVER_HAS_THREADS
#include <mutex>
#endif
#include "../core/kdevice.hpp"
#include "../core/devices_manager.hpp"
namespace kserver {
class {{ device.class_name }} : public KDevice<{{ device.class_name }},{{ device.name }}>
{
public:
const device_t kind = {{ device.name }};
enum { __kind = {{ device.name }} };
public:
{{ device.class_name }}(KServer* kserver, Klib::DevMem& dev_mem_)
: KDevice<{{ device.class_name }},{{ device.name }}>(kserver)
, dev_mem(dev_mem_)
{% if device.objects|length -%}
{% for object in device.objects -%}
, {{ object["name"] }}(dev_mem_)
{% endfor -%}
{% endif -%}
{}
enum Operation {
{% for operation in device.operations -%}
{{ operation["name"] }},
{% endfor -%}
{{ device.name|lower }}_op_num
};
#if KSERVER_HAS_THREADS
std::mutex mutex;
#endif
Klib::DevMem& dev_mem;
{% if device.objects|length -%}
{% for object in device.objects -%}
{{ object["type"] }} {{ object["name"] }};
{% endfor -%}
{% endif %}
}; // class KS_{{ device.name|capitalize }}
{% for operation in device.operations -%}
template<>
template<>
struct KDevice<{{ device.class_name }},{{ device.name }}>::
Argument<{{ device.class_name }}::{{ operation["name"] }}>
{
{%- macro print_param_line(arg) %}
{{ arg["type"] }} {{ arg["name"]}}; ///< {{ arg["description"] }}
{%- endmacro -%}
{% for arg in operation["arguments"] -%}
{% if not ("flag" in arg and arg["flag"] == 'CLIENT_ONLY') -%}
{#- TODO : implement elementary type check -#}
{% if not "cast" in arg -%}
{% if ("description" in arg) and (arg["description"] != None) -%}
{{ print_param_line(arg) }}
{% else -%}
{{ arg["type"] }} {{ arg["name"]}};
{% endif -%}
{% else -%}
{% if ("description" in arg) and (arg["description"] != None)-%}
{{ arg["cast"] }} {{ arg["name"]}}; ///< {{ arg["description"] }}
{% else -%}
{{ arg["cast"] }} {{ arg["name"]}};
{% endif -%}
{% endif -%}
{% endif -%}
{% endfor -%}
};
{% endfor -%}
} // namespace kserver
#endif //__{{ device.class_name|upper }}_HPP__
<commit_msg>Update ks_device.hpp<commit_after>/// @file {{ device.class_name|lower }}.hpp
///
/// (c) Koheron
#ifndef __{{ device.class_name|upper }}_HPP__
#define __{{ device.class_name|upper }}_HPP__
{% for include in device.includes -%}
#include <{{ include }}>
{% endfor -%}
#include <drivers/dev_mem.hpp>
#if KSERVER_HAS_THREADS
#include <mutex>
#endif
#include "../core/kdevice.hpp"
#include "../core/devices_manager.hpp"
namespace kserver {
class {{ device.class_name }} : public KDevice<{{ device.class_name }},{{ device.name }}>
{
public:
const device_t kind = {{ device.name }};
enum { __kind = {{ device.name }} };
public:
{{ device.class_name }}(KServer* kserver, Klib::DevMem& dev_mem_)
: KDevice<{{ device.class_name }},{{ device.name }}>(kserver)
, dev_mem(dev_mem_)
{% if device.objects|length -%}
{% for object in device.objects -%}
, {{ object["name"] }}(dev_mem_)
{% endfor -%}
{% endif -%}
{}
enum Operation {
{% for operation in device.operations -%}
{{ operation["name"] }},
{% endfor -%}
{{ device.name|lower }}_op_num
};
#if KSERVER_HAS_THREADS
std::mutex mutex;
#endif
Klib::DevMem& dev_mem;
{% if device.objects|length -%}
{% for object in device.objects -%}
{{ object["type"] }} {{ object["name"] }};
{% endfor -%}
{% endif %}
}; // class KS_{{ device.name|capitalize }}
{% for operation in device.operations -%}
template<>
template<>
struct KDevice<{{ device.class_name }},{{ device.name }}>::
Argument<{{ device.class_name }}::{{ operation["name"] }}>
{
{%- macro print_param_line(arg) %}
{{ arg["type"] }} {{ arg["name"]}}; ///< {{ arg["description"] }}
{%- endmacro -%}
{% for arg in operation["arguments"] -%}
{% if not ("flag" in arg and arg["flag"] == 'CLIENT_ONLY') -%}
{#- TODO : implement elementary type check -#}
{% if not "cast" in arg -%}
{% if ("description" in arg) and (arg["description"] != None) -%}
{{ print_param_line(arg) }}
{% else -%}
{{ arg["type"] }} {{ arg["name"]}};
{% endif -%}
{% else -%}
{% if ("description" in arg) and (arg["description"] != None)-%}
{{ arg["cast"] }} {{ arg["name"]}}; ///< {{ arg["description"] }}
{% else -%}
{{ arg["cast"] }} {{ arg["name"]}};
{% endif -%}
{% endif -%}
{% endif -%}
{% endfor -%}
};
{% endfor -%}
} // namespace kserver
#endif //__{{ device.class_name|upper }}_HPP__
<|endoftext|>
|
<commit_before>std::vector<std::string> split(std::string str,std::string sep){
char* cstr=const_cast<char*>(str.c_str());
char* current;
std::vector<std::string> arr;
current=strtok(cstr,sep.c_str());
while(current!=NULL){
arr.push_back(current);
current=strtok(NULL,sep.c_str());
}
return arr;
}
<commit_msg>Add split.cpp<commit_after>#include <string>
#include <vector>
std::vector<std::string> split(std::string str, std::string sep){
std::vector<std::string> res;
size_t begin = 0;
while(1){
size_t pos = str.find(sep, begin);
if(pos == std::string::npos) break;
res.push_back( str.substr(begin, pos-begin) );
begin = pos + sep.size();
}
res.push_back( str.substr(begin, str.length() - begin) );
return res;
}
#ifdef EBUG
#include <iostream>
using namespace std;
int main(void){
string str = "abc def ghi jkl";
vector<string> v = split(str, "bc");
for(int i = 0; i < v.size(); i++){
cout << v[i] << endl;
}
return 0;
}
#endif
<|endoftext|>
|
<commit_before>//
// Application.cpp
// ouzel
//
// Created by Elviss Strazdins on 20/12/15.
// Copyright © 2015 Bool Games. All rights reserved.
//
#include "Application.h"
namespace ouzel
{
Application::Application(Engine* engine):
_engine(engine)
{
_engine->addEventHandler(this);
Sprite* sprite = new Sprite("tim-from-braid.png", _engine->getScene());
_engine->getScene()->getRootNode()->addChild(sprite);
Sprite* witch = new Sprite("witch.png", _engine->getScene());
witch->setPosition(Vector2(100.0f, 100.0f));
_engine->getScene()->getRootNode()->addChild(witch);
sprite->release();
}
Application::~Application()
{
_engine->removeEventHandler(this);
}
bool Application::handleEvent(const Event& event)
{
return true;
}
void Application::update(float delta)
{
}
}
<commit_msg>Release leaking witch<commit_after>//
// Application.cpp
// ouzel
//
// Created by Elviss Strazdins on 20/12/15.
// Copyright © 2015 Bool Games. All rights reserved.
//
#include "Application.h"
namespace ouzel
{
Application::Application(Engine* engine):
_engine(engine)
{
_engine->addEventHandler(this);
Sprite* sprite = new Sprite("tim-from-braid.png", _engine->getScene());
_engine->getScene()->getRootNode()->addChild(sprite);
Sprite* witch = new Sprite("witch.png", _engine->getScene());
witch->setPosition(Vector2(100.0f, 100.0f));
_engine->getScene()->getRootNode()->addChild(witch);
sprite->release();
witch->release();
}
Application::~Application()
{
_engine->removeEventHandler(this);
}
bool Application::handleEvent(const Event& event)
{
return true;
}
void Application::update(float delta)
{
}
}
<|endoftext|>
|
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*/
#include "routes.hh"
#include "reply.hh"
#include "exception.hh"
namespace httpd {
using namespace std;
void verify_param(const request& req, const sstring& param) {
if (req.get_query_param(param) == "") {
throw missing_param_exception(param);
}
}
routes::~routes() {
for (int i = 0; i < NUM_OPERATION; i++) {
for (auto kv : _map[i]) {
delete kv.second;
}
}
for (int i = 0; i < NUM_OPERATION; i++) {
for (auto r : _rules[i]) {
delete r;
}
}
}
future<std::unique_ptr<reply> > routes::handle(const sstring& path, std::unique_ptr<request> req, std::unique_ptr<reply> rep) {
handler_base* handler = get_handler(str2type(req->_method),
normalize_url(path), req->param);
if (handler != nullptr) {
try {
for (auto& i : handler->_mandatory_param) {
verify_param(*req.get(), i);
}
auto r = handler->handle(path, std::move(req), std::move(rep));
return r;
} catch (const redirect_exception& _e) {
rep.reset(new reply());
rep->add_header("Location", _e.url).set_status(_e.status()).done(
"json");
} catch (const base_exception& _e) {
rep.reset(new reply());
json_exception e(_e);
rep->set_status(_e.status(), e.to_json()).done("json");
} catch (exception& _e) {
rep.reset(new reply());
json_exception e(_e);
cerr << "exception was caught for " << path << ": " << _e.what()
<< endl;
rep->set_status(reply::status_type::internal_server_error,
e.to_json()).done("json");
}
} else {
rep.reset(new reply());
json_exception ex(not_found_exception("Not found"));
rep->set_status(reply::status_type::not_found, ex.to_json()).done(
"json");
}
cerr << "Failed with " << path << " " << rep->_content << endl;
return make_ready_future<std::unique_ptr<reply>>(std::move(rep));
}
sstring routes::normalize_url(const sstring& url) {
if (url.length() < 2 || url.at(url.length() - 1) != '/') {
return url;
}
return url.substr(0, url.length() - 1);
}
handler_base* routes::get_handler(operation_type type, const sstring& url,
parameters& params) {
handler_base* handler = get_exact_match(type, url);
if (handler != nullptr) {
return handler;
}
for (auto rule = _rules[type].cbegin(); rule != _rules[type].cend();
++rule) {
handler = (*rule)->get(url, params);
if (handler != nullptr) {
return handler;
}
params.clear();
}
return nullptr;
}
routes& routes::add(operation_type type, const url& url,
handler_base* handler) {
match_rule* rule = new match_rule(handler);
rule->add_str(url._path);
if (url._param != "") {
rule->add_param(url._param, true);
}
return add(rule, type);
}
}
<commit_msg>httpd: fix future exception handling<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*/
#include "routes.hh"
#include "reply.hh"
#include "exception.hh"
namespace httpd {
using namespace std;
void verify_param(const request& req, const sstring& param) {
if (req.get_query_param(param) == "") {
throw missing_param_exception(param);
}
}
routes::~routes() {
for (int i = 0; i < NUM_OPERATION; i++) {
for (auto kv : _map[i]) {
delete kv.second;
}
}
for (int i = 0; i < NUM_OPERATION; i++) {
for (auto r : _rules[i]) {
delete r;
}
}
}
static std::unique_ptr<reply> exception_reply(std::exception_ptr eptr) {
auto rep = std::make_unique<reply>();
try {
std::rethrow_exception(eptr);
} catch (const base_exception& e) {
rep->set_status(e.status(), json_exception(e).to_json());
} catch (exception& e) {
rep->set_status(reply::status_type::internal_server_error,
json_exception(e).to_json());
} catch (...) {
rep->set_status(reply::status_type::internal_server_error,
json_exception(std::runtime_error(
"Unknown unhandled exception")).to_json());
}
rep->done("json");
return rep;
}
future<std::unique_ptr<reply> > routes::handle(const sstring& path, std::unique_ptr<request> req, std::unique_ptr<reply> rep) {
handler_base* handler = get_handler(str2type(req->_method),
normalize_url(path), req->param);
if (handler != nullptr) {
try {
for (auto& i : handler->_mandatory_param) {
verify_param(*req.get(), i);
}
auto r = handler->handle(path, std::move(req), std::move(rep));
return r.handle_exception(exception_reply);
} catch (const redirect_exception& _e) {
rep.reset(new reply());
rep->add_header("Location", _e.url).set_status(_e.status()).done(
"json");
} catch (...) {
rep = exception_reply(std::current_exception());
}
} else {
rep.reset(new reply());
json_exception ex(not_found_exception("Not found"));
rep->set_status(reply::status_type::not_found, ex.to_json()).done(
"json");
}
cerr << "Failed with " << path << " " << rep->_content << endl;
return make_ready_future<std::unique_ptr<reply>>(std::move(rep));
}
sstring routes::normalize_url(const sstring& url) {
if (url.length() < 2 || url.at(url.length() - 1) != '/') {
return url;
}
return url.substr(0, url.length() - 1);
}
handler_base* routes::get_handler(operation_type type, const sstring& url,
parameters& params) {
handler_base* handler = get_exact_match(type, url);
if (handler != nullptr) {
return handler;
}
for (auto rule = _rules[type].cbegin(); rule != _rules[type].cend();
++rule) {
handler = (*rule)->get(url, params);
if (handler != nullptr) {
return handler;
}
params.clear();
}
return nullptr;
}
routes& routes::add(operation_type type, const url& url,
handler_base* handler) {
match_rule* rule = new match_rule(handler);
rule->add_str(url._path);
if (url._param != "") {
rule->add_param(url._param, true);
}
return add(rule, type);
}
}
<|endoftext|>
|
<commit_before>#include "IndexStructureFactory.h"
//
#include "SequentialScan.h"
#include "Octree.h"
namespace mdsearch
{
/* ALL INDEX STRUCTURE GENERATORS ARE DEFINED HERE */
IndexStructure* generateSequentialScan(unsigned int numDimensions,
const std::vector<std::string>& args)
{
return new SequentialScan(numDimensions);
}
IndexStructure* generateOctree(unsigned int numDimensions,
const std::vector<std::string>& args)
{
// TODO
return NULL;
}
IndexStructureFactory::IndexStructureFactory()
{
// Add generators defined in this source file
addGenerator("sequential_scan", generateSequentialScan);
addGenerator("octree", generateOctree);
}
void IndexStructureFactory::addGenerator(const std::string& structureType,
StructureGenerator generator)
{
std::pair<std::string, StructureGenerator> newEntry(structureType, generator);
generators.insert(newEntry);
}
IndexStructure* IndexStructureFactory::constructIndexStructure(
const std::string& structureType, unsigned int numDimensions,
const std::vector<std::string>& arguments) const
{
// Search map for a generator for the requested structure type
GeneratorMap::const_iterator it = generators.find(structureType);
if (it != generators.end())
{
StructureGenerator generator = it->second;
return generator(numDimensions, arguments);
}
// Return NULL if the given structure type does not exist
else
{
return NULL;
}
}
}<commit_msg>Implemented Octree factory method<commit_after>#include "IndexStructureFactory.h"
//
#include "SequentialScan.h"
#include "Octree.h"
#include <boost/lexical_cast.hpp>
namespace mdsearch
{
/* ALL INDEX STRUCTURE GENERATORS ARE DEFINED HERE */
IndexStructure* generateSequentialScan(unsigned int numDimensions,
const std::vector<std::string>& args)
{
return new SequentialScan(numDimensions);
}
IndexStructure* generateOctree(unsigned int numDimensions,
const std::vector<std::string>& args)
{
// Check there are enough arguments to construct n-dimensional boundary
if (args.size() < numDimensions * 2) // min + max args needed per dimension
return NULL;
Region boundary(numDimensions);
for (unsigned int d = 0; (d < numDimensions); d++)
{
// Parse string arguments into real numbers
try
{
Real min = boost::lexical_cast<Real>(args[d * 2]);
Real max = boost::lexical_cast<Real>(args[d * 2 + 1]);
boundary[d] = Interval(min, max);
}
// If an argument could not be converted into a real number,
// return NULL as the structure cannot be constructed
catch (const boost::bad_lexical_cast& ex)
{
return NULL;
}
}
return new Octree(numDimensions, boundary);
}
IndexStructureFactory::IndexStructureFactory()
{
// Add generators defined in this source file
addGenerator("sequential_scan", generateSequentialScan);
addGenerator("octree", generateOctree);
}
void IndexStructureFactory::addGenerator(const std::string& structureType,
StructureGenerator generator)
{
std::pair<std::string, StructureGenerator> newEntry(structureType, generator);
generators.insert(newEntry);
}
IndexStructure* IndexStructureFactory::constructIndexStructure(
const std::string& structureType, unsigned int numDimensions,
const std::vector<std::string>& arguments) const
{
// Search map for a generator for the requested structure type
GeneratorMap::const_iterator it = generators.find(structureType);
if (it != generators.end())
{
StructureGenerator generator = it->second;
return generator(numDimensions, arguments);
}
// Return NULL if the given structure type does not exist
else
{
return NULL;
}
}
}<|endoftext|>
|
<commit_before>// Polygon.cpp
#include "Polygon.h"
#include "Triangle.h"
#include "IndexTriangle.h"
#include "LineSegment.h"
#include "Surface.h"
using namespace _3DMath;
Polygon::Polygon( void )
{
vertexArray = new VectorArray();
indexTriangleList = new IndexTriangleList();
}
/*virtual*/ Polygon::~Polygon( void )
{
delete vertexArray;
delete indexTriangleList;
}
bool Polygon::GetPlane( Plane& plane ) const
{
if( vertexArray->size() < 3 )
return false;
Vector normal, center;
normal.Set( 0.0, 0.0, 0.0 );
center.Set( 0.0, 0.0, 0.0 );
for( int i = 0; i < ( signed )vertexArray->size(); i++ )
{
// This is the Newel method.
int j = ( i + 1 ) % vertexArray->size();
const Vector& pointA = ( *vertexArray )[i];
const Vector& pointB = ( *vertexArray )[j];
normal.x += ( pointA.y - pointB.y ) * ( pointA.z + pointB.z );
normal.y += ( pointA.z - pointB.z ) * ( pointA.x + pointB.x );
normal.z += ( pointA.x - pointB.x ) * ( pointA.y + pointB.y );
center.Add( pointA );
}
center.Scale( 1.0 / double( vertexArray->size() ) );
plane.SetCenterAndNormal( center, normal );
return true;
}
bool Polygon::SplitAgainstSurface( const Surface* surface, Polygon& insidePolygon, Polygon& outsidePolygon, double maxDistanceFromSurface ) const
{
struct Node
{
Vector point;
Surface::Side side;
};
std::vector< Node > nodeArray;
for( int i = 0; i < ( signed )vertexArray->size(); i++ )
{
Node node;
node.point = ( *vertexArray )[i];
node.side = surface->GetSide( node.point );
nodeArray.push_back( node );
}
for( int i = 0; i < ( signed )nodeArray.size(); i++ )
{
int j = ( i + 1 ) % nodeArray.size();
if( ( nodeArray[i].side == Surface::INSIDE && nodeArray[j].side == Surface::OUTSIDE ) ||
( nodeArray[i].side == Surface::OUTSIDE && nodeArray[j].side == Surface::INSIDE ) )
{
LineSegment lineSegment;
lineSegment.vertex[0] = nodeArray[i].point;
lineSegment.vertex[1] = nodeArray[j].point;
SurfacePoint* surfacePoint = surface->FindSingleIntersection( lineSegment );
if( !surfacePoint )
return false;
Node node;
surfacePoint->GetLocation( node.point );
node.side = Surface::NEITHER_SIDE;
std::vector< Node >::iterator iter( nodeArray.begin() + j );
nodeArray.insert( iter, node );
}
}
for( int i = 0; i < 2; i++ )
{
Polygon* polygon = nullptr;
Surface::Side currentSide, otherSide;
if( i == 0 )
{
currentSide = Surface::INSIDE;
otherSide = Surface::OUTSIDE;
polygon = &insidePolygon;
}
else
{
currentSide = Surface::OUTSIDE;
otherSide = Surface::INSIDE;
polygon = &outsidePolygon;
}
int j;
for( j = 0; j < ( signed )nodeArray.size(); j++ )
if( nodeArray[j].side == currentSide )
break;
if( j == ( signed )nodeArray.size() )
return false;
int k = j;
do
{
int l = ( k + 1 ) % nodeArray.size();
if( nodeArray[k].side == Surface::NEITHER_SIDE && nodeArray[l].side == otherSide )
{
while( nodeArray[l].side != Surface::NEITHER_SIDE )
l = ( l + 1 ) % nodeArray.size();
SurfacePoint* surfacePointA = surface->GetNearestSurfacePoint( nodeArray[k].point );
SurfacePoint* surfacePointB = surface->GetNearestSurfacePoint( nodeArray[l].point );
surface->FindDirectPath( surfacePointA, surfacePointB, *polygon->vertexArray, maxDistanceFromSurface );
l = ( l + 1 ) % nodeArray.size();
}
else
{
polygon->vertexArray->push_back( nodeArray[k].point );
}
k = l;
}
while( k != j );
}
return true;
}
bool Polygon::Tessellate( void ) const
{
indexTriangleList->clear();
VectorArray pointArray;
for( int i = 0; i < ( signed )vertexArray->size(); i++ )
pointArray.push_back( ( *vertexArray )[i] );
while( pointArray.size() > 2 )
{
for( int i = 0; i < ( signed )vertexArray->size(); i++ )
{
IndexTriangle indexTriangle( i, ( i + 1 ) % vertexArray->size(), ( i + 2 ) % vertexArray->size() );
Triangle triangle;
indexTriangle.GetTriangle( triangle, &pointArray );
int j;
for( j = 0; j < ( signed )vertexArray->size(); j++ )
{
if( j == i )
continue;
if( triangle.ProperlyContainsPoint( ( *vertexArray )[j] ) )
break;
}
if( j < ( signed )vertexArray->size() )
continue;
indexTriangleList->push_back( indexTriangle );
pointArray.erase( pointArray.begin() + ( i + 1 ) % vertexArray->size() );
break;
}
}
return true;
}
// Polygon.cpp<commit_msg>this has bugs; i need to rethink it<commit_after>// Polygon.cpp
#include "Polygon.h"
#include "Triangle.h"
#include "IndexTriangle.h"
#include "LineSegment.h"
#include "Surface.h"
using namespace _3DMath;
Polygon::Polygon( void )
{
vertexArray = new VectorArray();
indexTriangleList = new IndexTriangleList();
}
/*virtual*/ Polygon::~Polygon( void )
{
delete vertexArray;
delete indexTriangleList;
}
bool Polygon::GetPlane( Plane& plane ) const
{
if( vertexArray->size() < 3 )
return false;
Vector normal, center;
normal.Set( 0.0, 0.0, 0.0 );
center.Set( 0.0, 0.0, 0.0 );
for( int i = 0; i < ( signed )vertexArray->size(); i++ )
{
// This is the Newel method.
int j = ( i + 1 ) % vertexArray->size();
const Vector& pointA = ( *vertexArray )[i];
const Vector& pointB = ( *vertexArray )[j];
normal.x += ( pointA.y - pointB.y ) * ( pointA.z + pointB.z );
normal.y += ( pointA.z - pointB.z ) * ( pointA.x + pointB.x );
normal.z += ( pointA.x - pointB.x ) * ( pointA.y + pointB.y );
center.Add( pointA );
}
center.Scale( 1.0 / double( vertexArray->size() ) );
plane.SetCenterAndNormal( center, normal );
return true;
}
bool Polygon::SplitAgainstSurface( const Surface* surface, Polygon& insidePolygon, Polygon& outsidePolygon, double maxDistanceFromSurface ) const
{
struct Node
{
Vector point;
Surface::Side side;
};
std::vector< Node > nodeArray;
for( int i = 0; i < ( signed )vertexArray->size(); i++ )
{
Node node;
node.point = ( *vertexArray )[i];
node.side = surface->GetSide( node.point );
nodeArray.push_back( node );
}
for( int i = 0; i < ( signed )nodeArray.size(); i++ )
{
int j = ( i + 1 ) % nodeArray.size();
if( ( nodeArray[i].side == Surface::INSIDE && nodeArray[j].side == Surface::OUTSIDE ) ||
( nodeArray[i].side == Surface::OUTSIDE && nodeArray[j].side == Surface::INSIDE ) )
{
LineSegment lineSegment;
lineSegment.vertex[0] = nodeArray[i].point;
lineSegment.vertex[1] = nodeArray[j].point;
SurfacePoint* surfacePoint = surface->FindSingleIntersection( lineSegment );
if( !surfacePoint )
return false;
Node node;
surfacePoint->GetLocation( node.point );
node.side = Surface::NEITHER_SIDE;
std::vector< Node >::iterator iter( nodeArray.begin() + j );
nodeArray.insert( iter, node );
}
}
for( int i = 0; i < 2; i++ )
{
Polygon* polygon = nullptr;
Surface::Side currentSide, otherSide;
if( i == 0 )
{
currentSide = Surface::INSIDE;
otherSide = Surface::OUTSIDE;
polygon = &insidePolygon;
}
else
{
currentSide = Surface::OUTSIDE;
otherSide = Surface::INSIDE;
polygon = &outsidePolygon;
}
int j;
for( j = 0; j < ( signed )nodeArray.size(); j++ )
if( nodeArray[j].side == currentSide )
break;
if( j == ( signed )nodeArray.size() )
return false;
int k = j;
do
{
int l = ( k + 1 ) % nodeArray.size();
if( nodeArray[k].side == Surface::NEITHER_SIDE && nodeArray[l].side == otherSide )
{
while( nodeArray[l].side != Surface::NEITHER_SIDE )
l = ( l + 1 ) % nodeArray.size();
SurfacePoint* surfacePointA = surface->GetNearestSurfacePoint( nodeArray[k].point );
SurfacePoint* surfacePointB = surface->GetNearestSurfacePoint( nodeArray[l].point );
surface->FindDirectPath( surfacePointA, surfacePointB, *polygon->vertexArray, maxDistanceFromSurface );
l = ( l + 1 ) % nodeArray.size();
}
else
{
polygon->vertexArray->push_back( nodeArray[k].point );
}
k = l;
}
while( k != j );
}
return true;
}
bool Polygon::Tessellate( void ) const
{
indexTriangleList->clear();
VectorArray pointArray;
for( int i = 0; i < ( signed )vertexArray->size(); i++ )
pointArray.push_back( ( *vertexArray )[i] );
while( pointArray.size() > 2 )
{
for( int i = 0; i < ( signed )vertexArray->size(); i++ )
{
IndexTriangle indexTriangle( i, ( i + 1 ) % vertexArray->size(), ( i + 2 ) % vertexArray->size() );
Triangle triangle;
indexTriangle.GetTriangle( triangle, &pointArray );
// TODO: I need to rethink this. There are some obvious things wrong with this.
int j;
for( j = 0; j < ( signed )vertexArray->size(); j++ )
{
if( j == i )
continue;
if( triangle.ProperlyContainsPoint( ( *vertexArray )[j] ) )
break;
}
if( j < ( signed )vertexArray->size() )
continue;
indexTriangleList->push_back( indexTriangle );
pointArray.erase( pointArray.begin() + ( i + 1 ) % vertexArray->size() );
break;
}
}
return true;
}
// Polygon.cpp<|endoftext|>
|
<commit_before>#include <yuni/yuni.h>
#include <yuni/core/noncopyable.h>
#include <yuni/io/file.h>
#include <yuni/core/system/console.h>
#include <yuni/core/getopt.h>
#include <yuni/io/directory.h>
#include <yuni/io/directory/info.h>
#include <yuni/datetime/timestamp.h>
#include <yuni/core/logs/logs.h>
#include "nany/nany.h"
#include <algorithm>
#include <yuni/datetime/timestamp.h>
#include <iostream>
#include <vector>
using namespace Yuni;
namespace {
struct Settings {
//! List of filenames to verify
std::vector<String> filenames;
// no colors
bool noColors = false;
// Result expected from filename convention
bool useFilenameConvention = false;
};
template<class LeftType = Logs::NullDecorator>
struct ParseVerbosity: public LeftType {
template<class Handler, class VerbosityType, class O>
void internalDecoratorAddPrefix(O& out, const AnyString& s) const {
// Write the verbosity to the output
if (VerbosityType::hasName) {
AnyString name{VerbosityType::Name()};
if (s.empty()) {
}
else if (name == "info")
printInfo<Handler>(out);
else if (name == "error")
printError<Handler>(out);
else if (name == "warning")
printWarning<Handler>(out);
else
printOtherVerbosity<Handler, VerbosityType>(out);
}
// Transmit the message to the next decorator
LeftType::template internalDecoratorAddPrefix<Handler, VerbosityType,O>(out, s);
}
template<class Handler, class O>
static void printInfo(O& out) {
if (Handler::colorsAllowed)
System::Console::TextColor<System::Console::yellow>::Set(out);
#ifndef YUNI_OS_WINDOWS
out << " \u2713 ";
#else
out << " ok ";
#endif
if (Handler::colorsAllowed) {
System::Console::ResetTextColor(out);
System::Console::TextColor<System::Console::bold>::Set(out);
}
out << "parsing";
if (Handler::colorsAllowed)
System::Console::ResetTextColor(out);
}
template<class Handler, class O>
static void printError(O& out) {
if (Handler::colorsAllowed)
System::Console::TextColor<System::Console::red>::Set(out);
out << " ERR ";
if (Handler::colorsAllowed) {
System::Console::ResetTextColor(out);
System::Console::TextColor<System::Console::bold>::Set(out);
}
out << "parsing";
if (Handler::colorsAllowed)
System::Console::ResetTextColor(out);
}
template<class Handler, class O>
static void printWarning(O& out) {
if (Handler::colorsAllowed)
System::Console::TextColor<System::Console::yellow>::Set(out);
out << " warn ";
if (Handler::colorsAllowed) {
System::Console::ResetTextColor(out);
System::Console::TextColor<System::Console::bold>::Set(out);
}
out << "parsing";
if (Handler::colorsAllowed)
System::Console::ResetTextColor(out);
}
template<class Handler, class VerbosityType, class O>
static void printOtherVerbosity(O& out) {
// Set Color
if (Handler::colorsAllowed && VerbosityType::color != System::Console::none)
System::Console::TextColor<VerbosityType::color>::Set(out);
// The verbosity
VerbosityType::AppendName(out);
// Reset Color
if (Handler::colorsAllowed && VerbosityType::color != System::Console::none)
System::Console::ResetTextColor(out);
}
}; // struct VerbosityLevel
using Logging = Logs::Logger<Logs::StdCout<>, ParseVerbosity<Logs::Message<>>>;
static Logging logs;
uint32_t findCommonFolderLength(const std::vector<String>& filenames) {
if (filenames.empty())
return 0;
uint32_t len = 0;
auto& firstElement = filenames[0];
const char sep = IO::Separator;
for (; ; ++len) {
for (auto& filename: filenames) {
if (len == firstElement.size())
return len;
if (len < filename.size() and filename[len] != '\0' and filename[len] == firstElement[len])
continue;
while (len > 0 and firstElement[--len] != sep) { // back to the last sep
}
return len;
}
}
return len;
}
bool expandAndCanonicalizeFilenames(std::vector<String>& filenames) {
std::vector<String> filelist;
filelist.reserve(512);
String currentfile;
currentfile.reserve(4096);
for (auto& filename: filenames) {
IO::Canonicalize(currentfile, filename);
switch (IO::TypeOf(currentfile)) {
case IO::typeFile: {
filelist.emplace_back(currentfile);
break;
}
case IO::typeFolder: {
ShortString16 ext;
IO::Directory::Info info(currentfile);
auto end = info.recursive_file_end();
for (auto i = info.recursive_file_begin(); i != end; ++i)
{
IO::ExtractExtension(ext, *i);
if (ext == ".ny")
filelist.emplace_back(i.filename());
}
break;
}
default: {
logs.error() << "impossible to find '" << currentfile << "'";
return false;
}
}
}
// for beauty in singled-threaded (and to always produce the same output)
std::sort(filelist.begin(), filelist.end());
filenames.swap(filelist);
return true;
}
template<class F>
bool IterateThroughAllFiles(const std::vector<String>& filenames, const F& callback) {
String currentfile;
uint32_t testOK = 0;
uint32_t testFAILED = 0;
int64_t maxCheckDuration = 0;
int64_t startTime = DateTime::NowMilliSeconds();
for (auto& filename: filenames) {
int64_t duration = 0;
if (callback(filename, duration))
++testOK;
else
++testFAILED;
if (duration > maxCheckDuration)
maxCheckDuration = duration;
}
int64_t endTime = DateTime::NowMilliSeconds();
uint32_t total = testOK + testFAILED;
if (total > 0) {
int64_t duration = (endTime - startTime);
String durationStr;
durationStr << " (in " << duration << "ms, max: " << maxCheckDuration << "ms)";
if (total > 1) {
if (0 != testFAILED) {
switch (total) {
case 1:
logs.warning() << "-- FAILED -- 1 file, +" << testOK << ", -" << testFAILED << durationStr;
break;
default:
logs.warning() << "-- FAILED -- " << total << " files, +" << testOK << ", -" << testFAILED << durationStr;
}
}
else
{
switch (total) {
case 1:
logs.info() << "success: 1 file, +" << testOK << ", -0" << durationStr;
break;
default:
logs.info() << "success: " << total << " files, +" << testOK << ", -0" << durationStr;
}
}
}
}
else
logs.warning() << "no input file";
return (0 == testFAILED);
}
bool batchCheckIfFilenamesConformToGrammar(Settings& settings) {
if (not expandAndCanonicalizeFilenames(settings.filenames))
return false;
auto commonFolder = (settings.filenames.size() > 1 ? findCommonFolderLength(settings.filenames) : 0);
if (0 != commonFolder)
++commonFolder;
return IterateThroughAllFiles(settings.filenames, [&](const AnyString& file, int64_t& duration) -> bool {
String barefile;
IO::ExtractFileName(barefile, file);
bool expected = true;
bool canfail = false;
if (settings.useFilenameConvention)
{
if (barefile.startsWith("ko-"))
expected = false;
if (barefile.find("-canfail-") < barefile.size())
canfail = true;
}
// PARSE
int64_t start = DateTime::NowMilliSeconds();
bool success = (nytrue == nytry_parse_file_n(file.c_str(), file.size()));
duration = DateTime::NowMilliSeconds() - start;
success = (success == expected);
if (success and duration < 300) {
logs.info() << AnyString{file, commonFolder} << " [" << duration << "ms]";
}
else {
if (not success) {
if (not canfail)
logs.error() << AnyString{file, commonFolder} << " [" << duration << "ms]";
else
logs.warning() << AnyString{file, commonFolder} << " [" << duration << "ms, can fail]";
}
else
logs.error() << AnyString{file, commonFolder} << " [" << duration << "ms - time limit reached]";
success = canfail;
}
return success;
});
}
bool parseCommandLine(Settings& settings, int argc, char** argv) {
GetOpt::Parser options;
options.add(settings.filenames, 'i', "input", "Input files (or folders)");
options.remainingArguments(settings.filenames);
options.addFlag(settings.noColors, ' ', "no-color", "Disable color output");
options.addFlag(settings.useFilenameConvention, ' ', "use-filename-convention",
"Use the filename to determine if the test should succeed or not (should succeed if starting with 'ok-'");
bool optVersion = false;
options.addFlag(optVersion, ' ', "version", "Display the version of the compiler and exit");
if (not options(argc, argv)) {
// The program should not continue here
// The user may have requested the help or an error has happened
// If an error has happened, the exit status should be different from 0
if (options.errors())
throw std::runtime_error("Abort due to error");
return false;
}
if (optVersion) {
std::cout << "0.0\n";
return false;
}
if (settings.filenames.empty())
throw std::runtime_error("no input file");
return true;
}
} // namespace
int main(int argc, char** argv)
{
try {
Settings settings;
if (not parseCommandLine(settings, argc, argv))
return EXIT_SUCCESS;
bool success = batchCheckIfFilenamesConformToGrammar(settings);
return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
catch (const std::exception& e) {
std::cerr << argv[0] << ": " << e.what() << '\n';
}
return EXIT_FAILURE;
}
<commit_msg>check-syntax: simplified filenames expansion<commit_after>#include <yuni/yuni.h>
#include <yuni/core/noncopyable.h>
#include <yuni/io/file.h>
#include <yuni/core/system/console.h>
#include <yuni/core/getopt.h>
#include <yuni/io/directory.h>
#include <yuni/io/directory/info.h>
#include <yuni/datetime/timestamp.h>
#include <yuni/core/logs/logs.h>
#include "nany/nany.h"
#include <algorithm>
#include <yuni/datetime/timestamp.h>
#include <iostream>
#include <vector>
using namespace Yuni;
namespace {
struct Settings {
//! List of filenames to verify
std::vector<String> filenames;
// no colors
bool noColors = false;
// Result expected from filename convention
bool useFilenameConvention = false;
};
template<class LeftType = Logs::NullDecorator>
struct ParseVerbosity: public LeftType {
template<class Handler, class VerbosityType, class O>
void internalDecoratorAddPrefix(O& out, const AnyString& s) const {
// Write the verbosity to the output
if (VerbosityType::hasName) {
AnyString name{VerbosityType::Name()};
if (s.empty()) {
}
else if (name == "info")
printInfo<Handler>(out);
else if (name == "error")
printError<Handler>(out);
else if (name == "warning")
printWarning<Handler>(out);
else
printOtherVerbosity<Handler, VerbosityType>(out);
}
// Transmit the message to the next decorator
LeftType::template internalDecoratorAddPrefix<Handler, VerbosityType,O>(out, s);
}
template<class Handler, class O>
static void printInfo(O& out) {
if (Handler::colorsAllowed)
System::Console::TextColor<System::Console::yellow>::Set(out);
#ifndef YUNI_OS_WINDOWS
out << " \u2713 ";
#else
out << " ok ";
#endif
if (Handler::colorsAllowed) {
System::Console::ResetTextColor(out);
System::Console::TextColor<System::Console::bold>::Set(out);
}
out << "parsing";
if (Handler::colorsAllowed)
System::Console::ResetTextColor(out);
}
template<class Handler, class O>
static void printError(O& out) {
if (Handler::colorsAllowed)
System::Console::TextColor<System::Console::red>::Set(out);
out << " ERR ";
if (Handler::colorsAllowed) {
System::Console::ResetTextColor(out);
System::Console::TextColor<System::Console::bold>::Set(out);
}
out << "parsing";
if (Handler::colorsAllowed)
System::Console::ResetTextColor(out);
}
template<class Handler, class O>
static void printWarning(O& out) {
if (Handler::colorsAllowed)
System::Console::TextColor<System::Console::yellow>::Set(out);
out << " warn ";
if (Handler::colorsAllowed) {
System::Console::ResetTextColor(out);
System::Console::TextColor<System::Console::bold>::Set(out);
}
out << "parsing";
if (Handler::colorsAllowed)
System::Console::ResetTextColor(out);
}
template<class Handler, class VerbosityType, class O>
static void printOtherVerbosity(O& out) {
// Set Color
if (Handler::colorsAllowed && VerbosityType::color != System::Console::none)
System::Console::TextColor<VerbosityType::color>::Set(out);
// The verbosity
VerbosityType::AppendName(out);
// Reset Color
if (Handler::colorsAllowed && VerbosityType::color != System::Console::none)
System::Console::ResetTextColor(out);
}
}; // struct VerbosityLevel
using Logging = Logs::Logger<Logs::StdCout<>, ParseVerbosity<Logs::Message<>>>;
static Logging logs;
uint32_t findCommonFolderLength(const std::vector<String>& filenames) {
if (filenames.empty())
return 0;
uint32_t len = 0;
auto& firstElement = filenames[0];
const char sep = IO::Separator;
for (; ; ++len) {
for (auto& filename: filenames) {
if (len == firstElement.size())
return len;
if (len < filename.size() and filename[len] != '\0' and filename[len] == firstElement[len])
continue;
while (len > 0 and firstElement[--len] != sep) { // back to the last sep
}
return len;
}
}
return len;
}
template<class F>
bool IterateThroughAllFiles(const std::vector<String>& filenames, const F& callback) {
String tmpstr;
uint32_t testOK = 0;
uint32_t testFAILED = 0;
int64_t maxCheckDuration = 0;
int64_t startTime = DateTime::NowMilliSeconds();
for (auto& filename: filenames) {
int64_t duration = 0;
if (callback(filename, duration))
++testOK;
else
++testFAILED;
if (duration > maxCheckDuration)
maxCheckDuration = duration;
}
int64_t endTime = DateTime::NowMilliSeconds();
uint32_t total = testOK + testFAILED;
if (total > 0) {
int64_t duration = (endTime - startTime);
String durationStr;
durationStr << " (in " << duration << "ms, max: " << maxCheckDuration << "ms)";
if (total > 1) {
if (0 != testFAILED) {
switch (total) {
case 1:
logs.warning() << "-- FAILED -- 1 file, +" << testOK << ", -" << testFAILED << durationStr;
break;
default:
logs.warning() << "-- FAILED -- " << total << " files, +" << testOK << ", -" << testFAILED << durationStr;
}
}
else
{
switch (total) {
case 1:
logs.info() << "success: 1 file, +" << testOK << ", -0" << durationStr;
break;
default:
logs.info() << "success: " << total << " files, +" << testOK << ", -0" << durationStr;
}
}
}
}
else
logs.warning() << "no input file";
return (0 == testFAILED);
}
bool batchCheckIfFilenamesConformToGrammar(Settings& settings) {
auto commonFolder = (settings.filenames.size() > 1 ? findCommonFolderLength(settings.filenames) : 0);
if (0 != commonFolder)
++commonFolder;
return IterateThroughAllFiles(settings.filenames, [&](const AnyString& file, int64_t& duration) -> bool {
String barefile;
IO::ExtractFileName(barefile, file);
bool expected = true;
bool canfail = false;
if (settings.useFilenameConvention)
{
if (barefile.startsWith("ko-"))
expected = false;
if (barefile.find("-canfail-") < barefile.size())
canfail = true;
}
// PARSE
int64_t start = DateTime::NowMilliSeconds();
bool success = (nytrue == nytry_parse_file_n(file.c_str(), file.size()));
duration = DateTime::NowMilliSeconds() - start;
success = (success == expected);
if (success and duration < 300) {
logs.info() << AnyString{file, commonFolder} << " [" << duration << "ms]";
}
else {
if (not success) {
if (not canfail)
logs.error() << AnyString{file, commonFolder} << " [" << duration << "ms]";
else
logs.warning() << AnyString{file, commonFolder} << " [" << duration << "ms, can fail]";
}
else
logs.error() << AnyString{file, commonFolder} << " [" << duration << "ms - time limit reached]";
success = canfail;
}
return success;
});
}
std::vector<String> expandAndCanonicalizeFilenames(const std::vector<String>& filenames) {
std::vector<String> filelist;
filelist.reserve(filenames.size());
String tmpstr;
tmpstr.reserve(1024);
for (auto& filename: filenames) {
IO::Canonicalize(tmpstr, filename);
switch (IO::TypeOf(tmpstr)) {
case IO::typeFile: {
filelist.emplace_back(tmpstr);
break;
}
case IO::typeFolder: {
ShortString16 ext;
IO::Directory::Info info(tmpstr);
auto end = info.recursive_file_end();
for (auto i = info.recursive_file_begin(); i != end; ++i)
{
IO::ExtractExtension(ext, *i);
if (ext == ".ny")
filelist.emplace_back(i.filename());
}
break;
}
default:
throw std::runtime_error((std::string("impossible to find '") += tmpstr.c_str()) += '\'');
}
}
// for beauty in singled-threaded (and to always produce the same output)
std::sort(filelist.begin(), filelist.end());
return filelist;
}
bool parseCommandLine(Settings& settings, int argc, char** argv) {
GetOpt::Parser options;
std::vector<String> filenames;
options.add(filenames, 'i', "input", "Input files (or folders)");
options.remainingArguments(filenames);
options.addFlag(settings.noColors, ' ', "no-color", "Disable color output");
options.addFlag(settings.useFilenameConvention, ' ', "use-filename-convention",
"Use the filename to determine if the test should succeed or not (should succeed if starting with 'ok-'");
bool optVersion = false;
options.addFlag(optVersion, ' ', "version", "Display the version of the compiler and exit");
if (not options(argc, argv)) {
// The program should not continue here
// The user may have requested the help or an error has happened
// If an error has happened, the exit status should be different from 0
if (options.errors())
throw std::runtime_error("Abort due to error");
return false;
}
if (optVersion) {
std::cout << "0.0\n";
return false;
}
if (filenames.empty())
throw std::runtime_error("no input file");
settings.filenames = expandAndCanonicalizeFilenames(filenames);
return true;
}
} // namespace
int main(int argc, char** argv)
{
try {
Settings settings;
if (not parseCommandLine(settings, argc, argv))
return EXIT_SUCCESS;
bool success = batchCheckIfFilenamesConformToGrammar(settings);
return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
catch (const std::exception& e) {
std::cerr << argv[0] << ": " << e.what() << '\n';
}
return EXIT_FAILURE;
}
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#ifndef PCL_SURFACE_IMPL_MLS_OMP_H_
#define PCL_SURFACE_IMPL_MLS_OMP_H_
#include <pcl/surface/mls_omp.h>
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename NormalOutT> void
pcl::MovingLeastSquaresOMP<PointInT, NormalOutT>::performReconstruction (PointCloudIn &output)
{
// Compute the number of coefficients
nr_coeff_ = (order_ + 1) * (order_ + 2) / 2;
// Allocate enough space to hold the results of nearest neighbor searches
// \note resize is irrelevant for a radiusSearch ().
std::vector<int> nn_indices;
std::vector<float> nn_sqr_dists;
#pragma omp parallel for schedule (dynamic, threads_)
// For all points
for (size_t cp = 0; cp < indices_->size (); ++cp)
{
// Get the initial estimates of point positions and their neighborhoods
if (!searchForNeighbors ((*indices_)[cp], nn_indices, nn_sqr_dists))
continue;
// Check the number of nearest neighbors for normal estimation (and later
// for polynomial fit as well)
if (nn_indices.size () < 3)
continue;
PointCloudIn projected_points;
NormalCloudOut projected_points_normals;
// Get a plane approximating the local surface's tangent and project point onto it
computeMLSPointNormal ((*indices_)[cp], *input_, nn_indices, nn_sqr_dists, projected_points, projected_points_normals);
// Append projected points to output
output.insert (output.end (), projected_points.begin (), projected_points.end ());
normals_->insert (normals_->end (), projected_points_normals.begin (), projected_points_normals.end ());
}
// Set proper widths and heights for the clouds
if (upsample_method_ == MovingLeastSquares<PointInT, NormalOutT>::NONE && fake_indices_)
{
normals_->width = input_->width;
normals_->height = input_->height;
output.width = input_->width;
output.height = input_->height;
}
else
{
normals_->height = 1;
normals_->width = normals_->size ();
output.height = 1;
output.width = output.size ();
}
}
#define PCL_INSTANTIATE_MovingLeastSquaresOMP(T,OutT) template class PCL_EXPORTS pcl::MovingLeastSquaresOMP<T,OutT>;
#endif // PCL_SURFACE_IMPL_MLS_OMP_H_
<commit_msg>fixed compilation for windows: index variable in OpenMP 'for' statement must have signed integral type<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#ifndef PCL_SURFACE_IMPL_MLS_OMP_H_
#define PCL_SURFACE_IMPL_MLS_OMP_H_
#include <cstddef>
#include <pcl/surface/mls_omp.h>
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename NormalOutT> void
pcl::MovingLeastSquaresOMP<PointInT, NormalOutT>::performReconstruction (PointCloudIn &output)
{
typedef std::size_t size_t;
// Compute the number of coefficients
nr_coeff_ = (order_ + 1) * (order_ + 2) / 2;
// Allocate enough space to hold the results of nearest neighbor searches
// \note resize is irrelevant for a radiusSearch ().
std::vector<int> nn_indices;
std::vector<float> nn_sqr_dists;
#pragma omp parallel for schedule (dynamic, threads_)
// For all points
for (int cp = 0; cp < (int)indices_->size (); ++cp)
{
// Get the initial estimates of point positions and their neighborhoods
if (!searchForNeighbors ((*indices_)[cp], nn_indices, nn_sqr_dists))
continue;
// Check the number of nearest neighbors for normal estimation (and later
// for polynomial fit as well)
if (nn_indices.size () < 3)
continue;
PointCloudIn projected_points;
NormalCloudOut projected_points_normals;
// Get a plane approximating the local surface's tangent and project point onto it
computeMLSPointNormal ((*indices_)[cp], *input_, nn_indices, nn_sqr_dists, projected_points, projected_points_normals);
// Append projected points to output
output.insert (output.end (), projected_points.begin (), projected_points.end ());
normals_->insert (normals_->end (), projected_points_normals.begin (), projected_points_normals.end ());
}
// Set proper widths and heights for the clouds
if (upsample_method_ == MovingLeastSquares<PointInT, NormalOutT>::NONE && fake_indices_)
{
normals_->width = input_->width;
normals_->height = input_->height;
output.width = input_->width;
output.height = input_->height;
}
else
{
normals_->height = 1;
normals_->width = normals_->size ();
output.height = 1;
output.width = output.size ();
}
}
#define PCL_INSTANTIATE_MovingLeastSquaresOMP(T,OutT) template class PCL_EXPORTS pcl::MovingLeastSquaresOMP<T,OutT>;
#endif // PCL_SURFACE_IMPL_MLS_OMP_H_
<|endoftext|>
|
<commit_before>#include "llvm/Instructions.h"
#define OPT_LOCAL_REGISTERS //XXX
#include "libcpu.h"
#include "libcpu_llvm.h"
#include "frontend.h"
#include "fapra_internal.h"
#include <inttypes.h>
using namespace llvm;
//////////////////////////////////////////////////////////////////////
// fapra: instruction decoding
//////////////////////////////////////////////////////////////////////
// Instruction decoding helper functions.
static inline uint32_t opc(uint32_t ins) {
return ins >> 26;
}
static inline uint32_t rd(uint32_t ins) {
return (ins >> 21) & 0x1F;
}
static inline uint32_t ra(uint32_t ins) {
return (ins >> 16) & 0x1F;
}
static inline uint32_t rb(uint32_t ins) {
return (ins >> 11) & 0x1F;
}
static inline sint32_t simm(uint32_t ins) {
return ((int32_t) ((ins & 0xFFFF) << 16)) >> 16;
}
static inline uint32_t imm(uint32_t ins) {
return ins & 0xFFFF;
}
#define RD ((instr >> 21) & 0x1F)
#define RA ((instr >> 16) & 0x1F)
#define RB ((instr >> 11) & 0x1F)
#define GetImmediate (instr & 0xFFFF)
#define INST_SIZE 4
//////////////////////////////////////////////////////////////////////
// tagging
//////////////////////////////////////////////////////////////////////
#include "tag.h"
int arch_fapra_tag_instr(cpu_t *cpu, addr_t pc, tag_t *tag, addr_t *new_pc,
addr_t *next_pc) {
uint32_t ins = INSTR(pc);
switch (opc(ins)) {
case RFE:
case PERM:
case RDC8:
case TGE:
case TSE:
default:
fprintf(stderr, "Illegal instruction!\n");
exit(EXIT_FAILURE);
case LDW:
case STW:
case LDB:
case STB:
case LDIH:
case LDIL:
case ADDI:
case ADD:
case SUB:
case AND:
case OR:
case NOT:
case SARI:
case SAL:
case SAR:
case MUL:
case NOP:
*tag = TAG_CONTINUE;
break;
case JMP:
*tag = TAG_RET;
break;
case BRA:
*tag = TAG_BRANCH;
*new_pc = pc + simm(ins);
break;
case BZ:
case BNZ:
*tag = TAG_COND_BRANCH;
*new_pc = pc + simm(ins);
break;
case CALL: {
// Look for sequences like:
// ldih $X, 0x...
// ldil $X, 0x...
// call $Y, $X ($Y is the link register)
// FIXME Make sure those two memory accesses are not out of bounds.
uint32_t ldih = INSTR(pc - (INST_SIZE * 2));
uint32_t ldil = INSTR(pc - INST_SIZE);
if (opc(ldih) == LDIH && opc(ldil) == LDIL
&& rd(ldih) == rd(ldil) && rd(ldih) == ra(ins)) {
*new_pc = (imm(ldih) << 16) | imm(ldil);
} else {
*new_pc = NEW_PC_NONE;
}
*tag = TAG_CALL;
}
break;
case BL:
*tag = TAG_CALL;
*new_pc = pc + simm(ins);
break;
}
*next_pc = pc + INST_SIZE;
return INST_SIZE;
}
//////////////////////////////////////////////////////////////////////
Value *
arch_fapra_get_imm(cpu_t *cpu, uint32_t instr, uint32_t bits, bool sext,
BasicBlock *bb) {
uint64_t imm;
if (sext)
imm = (uint64_t)(sint16_t)GetImmediate;
else
imm = (uint64_t)(uint16_t)GetImmediate;
return ConstantInt::get(getIntegerType(bits? bits : cpu->info.word_size), imm);
}
#define IMM arch_fapra_get_imm(cpu, instr, 0, true, bb)
#define IMMU arch_fapra_get_imm(cpu, instr, 0, false, bb)
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
#define LET_PC(v) new StoreInst(v, cpu->ptr_PC, bb)
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
Value *
arch_fapra_translate_cond(cpu_t *cpu, addr_t pc, BasicBlock *bb)
{
uint32_t instr = INSTR(pc);
LOG("cond (%08" PRIx64 ") %08x\n", pc, instr);
switch (opc(instr)) {
default:
fprintf(stderr, "Illegal instruction!\n");
exit(EXIT_FAILURE);
case BZ:
// Emit nothing.
return ICMP_EQ(R(RA), CONST(0));
break;
case BNZ:
return ICMP_NE(R(RA), CONST(0));
break;
}
}
int
arch_fapra_translate_instr(cpu_t *cpu, addr_t pc, BasicBlock *bb)
{
#define BAD printf("%s:%d\n", __func__, __LINE__); exit(1);
#define LOGX LOG("%s:%d\n", __func__, __LINE__);
uint32_t instr = INSTR(pc);
LOG("translating (%08" PRIx64 ") %08x\n", pc, instr);
switch (opc(instr)) {
case PERM:
case RDC8:
case TGE:
case TSE:
case SARI:
case RFE:
default:
fprintf(stderr, "Illegal instruction!\n");
exit(EXIT_FAILURE);
case LDW:
LOAD32(RD, ADD(R(RA), IMM));
break;
case STW:
STORE32(R(RD), ADD(R(RA), IMM));
break;
case LDB:
LOAD8(RD, ADD(R(RA), IMM));
break;
case STB:
STORE8(R(RD), ADD(R(RA), IMM));
break;
case LDIH:
LET(RD, OR(AND(R(RD), CONST(0xFFFF)), CONST(GetImmediate << 16)));
break;
case LDIL:
LET(RD, OR(AND(R(RD), CONST(0xFFFF0000)), IMMU));
break;
case JMP:
LET_PC(R(RA));
break;
case BRA:
// LET_PC(CONST(pc + simm(instr)));
break;
case BZ:
// Emit nothing.
break;
case BNZ:
// Emit nothing.
break;
case NOP:
// Emit nothing.
break;
case CALL:
LET_PC(R(RA));
LET(RD, CONST(pc + INST_SIZE));
break;
case BL:
// LET_PC(CONST(pc + simm(instr)));
LET(RD, CONST(pc + INST_SIZE));
break;
case ADDI:
LET(RD, ADD(R(RA), IMM));
break;
case ADD:
LET(RD, ADD(R(RA), R(RB)));
break;
case SUB:
LET(RD, SUB(R(RA), R(RB)));
break;
case AND:
LET(RD, AND(R(RA), R(RB)));
break;
case OR:
LET(RD, OR(R(RA), R(RB)));
break;
case NOT:
LET(RD, COM(R(RA)));
break;
case SAL:
LET(RD, SHL(R(RA), R(RB)));
break;
case SAR:
LET(RD, ASHR(R(RA), R(RB)));
break;
case MUL:
LET(RD, MUL(R(RA), R(RB)));
break;
}
return INST_SIZE;
}
<commit_msg>fix build<commit_after>#include "llvm/IR/Instructions.h"
#define OPT_LOCAL_REGISTERS //XXX
#include "libcpu.h"
#include "libcpu_llvm.h"
#include "frontend.h"
#include "fapra_internal.h"
#include <inttypes.h>
using namespace llvm;
//////////////////////////////////////////////////////////////////////
// fapra: instruction decoding
//////////////////////////////////////////////////////////////////////
// Instruction decoding helper functions.
static inline uint32_t opc(uint32_t ins) {
return ins >> 26;
}
static inline uint32_t rd(uint32_t ins) {
return (ins >> 21) & 0x1F;
}
static inline uint32_t ra(uint32_t ins) {
return (ins >> 16) & 0x1F;
}
static inline uint32_t rb(uint32_t ins) {
return (ins >> 11) & 0x1F;
}
static inline sint32_t simm(uint32_t ins) {
return ((int32_t) ((ins & 0xFFFF) << 16)) >> 16;
}
static inline uint32_t imm(uint32_t ins) {
return ins & 0xFFFF;
}
#define RD ((instr >> 21) & 0x1F)
#define RA ((instr >> 16) & 0x1F)
#define RB ((instr >> 11) & 0x1F)
#define GetImmediate (instr & 0xFFFF)
#define INST_SIZE 4
//////////////////////////////////////////////////////////////////////
// tagging
//////////////////////////////////////////////////////////////////////
#include "tag.h"
int arch_fapra_tag_instr(cpu_t *cpu, addr_t pc, tag_t *tag, addr_t *new_pc,
addr_t *next_pc) {
uint32_t ins = INSTR(pc);
switch (opc(ins)) {
case RFE:
case PERM:
case RDC8:
case TGE:
case TSE:
default:
fprintf(stderr, "Illegal instruction!\n");
exit(EXIT_FAILURE);
case LDW:
case STW:
case LDB:
case STB:
case LDIH:
case LDIL:
case ADDI:
case ADD:
case SUB:
case AND:
case OR:
case NOT:
case SARI:
case SAL:
case SAR:
case MUL:
case NOP:
*tag = TAG_CONTINUE;
break;
case JMP:
*tag = TAG_RET;
break;
case BRA:
*tag = TAG_BRANCH;
*new_pc = pc + simm(ins);
break;
case BZ:
case BNZ:
*tag = TAG_COND_BRANCH;
*new_pc = pc + simm(ins);
break;
case CALL: {
// Look for sequences like:
// ldih $X, 0x...
// ldil $X, 0x...
// call $Y, $X ($Y is the link register)
// FIXME Make sure those two memory accesses are not out of bounds.
uint32_t ldih = INSTR(pc - (INST_SIZE * 2));
uint32_t ldil = INSTR(pc - INST_SIZE);
if (opc(ldih) == LDIH && opc(ldil) == LDIL
&& rd(ldih) == rd(ldil) && rd(ldih) == ra(ins)) {
*new_pc = (imm(ldih) << 16) | imm(ldil);
} else {
*new_pc = NEW_PC_NONE;
}
*tag = TAG_CALL;
}
break;
case BL:
*tag = TAG_CALL;
*new_pc = pc + simm(ins);
break;
}
*next_pc = pc + INST_SIZE;
return INST_SIZE;
}
//////////////////////////////////////////////////////////////////////
Value *
arch_fapra_get_imm(cpu_t *cpu, uint32_t instr, uint32_t bits, bool sext,
BasicBlock *bb) {
uint64_t imm;
if (sext)
imm = (uint64_t)(sint16_t)GetImmediate;
else
imm = (uint64_t)(uint16_t)GetImmediate;
return ConstantInt::get(getIntegerType(bits? bits : cpu->info.word_size), imm);
}
#define IMM arch_fapra_get_imm(cpu, instr, 0, true, bb)
#define IMMU arch_fapra_get_imm(cpu, instr, 0, false, bb)
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
#define LET_PC(v) new StoreInst(v, cpu->ptr_PC, bb)
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
Value *
arch_fapra_translate_cond(cpu_t *cpu, addr_t pc, BasicBlock *bb)
{
uint32_t instr = INSTR(pc);
LOG("cond (%08" PRIx64 ") %08x\n", pc, instr);
switch (opc(instr)) {
default:
fprintf(stderr, "Illegal instruction!\n");
exit(EXIT_FAILURE);
case BZ:
// Emit nothing.
return ICMP_EQ(R(RA), CONST(0));
break;
case BNZ:
return ICMP_NE(R(RA), CONST(0));
break;
}
}
int
arch_fapra_translate_instr(cpu_t *cpu, addr_t pc, BasicBlock *bb)
{
#define BAD printf("%s:%d\n", __func__, __LINE__); exit(1);
#define LOGX LOG("%s:%d\n", __func__, __LINE__);
uint32_t instr = INSTR(pc);
LOG("translating (%08" PRIx64 ") %08x\n", pc, instr);
switch (opc(instr)) {
case PERM:
case RDC8:
case TGE:
case TSE:
case SARI:
case RFE:
default:
fprintf(stderr, "Illegal instruction!\n");
exit(EXIT_FAILURE);
case LDW:
LOAD32(RD, ADD(R(RA), IMM));
break;
case STW:
STORE32(R(RD), ADD(R(RA), IMM));
break;
case LDB:
LOAD8(RD, ADD(R(RA), IMM));
break;
case STB:
STORE8(R(RD), ADD(R(RA), IMM));
break;
case LDIH:
LET(RD, OR(AND(R(RD), CONST(0xFFFF)), CONST(GetImmediate << 16)));
break;
case LDIL:
LET(RD, OR(AND(R(RD), CONST(0xFFFF0000)), IMMU));
break;
case JMP:
LET_PC(R(RA));
break;
case BRA:
// LET_PC(CONST(pc + simm(instr)));
break;
case BZ:
// Emit nothing.
break;
case BNZ:
// Emit nothing.
break;
case NOP:
// Emit nothing.
break;
case CALL:
LET_PC(R(RA));
LET(RD, CONST(pc + INST_SIZE));
break;
case BL:
// LET_PC(CONST(pc + simm(instr)));
LET(RD, CONST(pc + INST_SIZE));
break;
case ADDI:
LET(RD, ADD(R(RA), IMM));
break;
case ADD:
LET(RD, ADD(R(RA), R(RB)));
break;
case SUB:
LET(RD, SUB(R(RA), R(RB)));
break;
case AND:
LET(RD, AND(R(RA), R(RB)));
break;
case OR:
LET(RD, OR(R(RA), R(RB)));
break;
case NOT:
LET(RD, COM(R(RA)));
break;
case SAL:
LET(RD, SHL(R(RA), R(RB)));
break;
case SAR:
LET(RD, ASHR(R(RA), R(RB)));
break;
case MUL:
LET(RD, MUL(R(RA), R(RB)));
break;
}
return INST_SIZE;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tabvwshg.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: kz $ $Date: 2008-03-07 17:00:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// INCLUDE ---------------------------------------------------------------
//#define SI_VCDRAWOBJ
#include <tools/urlobj.hxx>
#include <svx/fmglob.hxx>
#include <svx/svdouno.hxx>
#include <svx/svdpagv.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/docfile.hxx>
#include <com/sun/star/form/FormButtonType.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/awt/XControlModel.hpp>
using namespace com::sun::star;
#include "tabvwsh.hxx"
#include "document.hxx"
#include "drawview.hxx"
#include "globstr.hrc"
#include <avmedia/mediawindow.hxx>
//------------------------------------------------------------------------
void ScTabViewShell::InsertURLButton( const String& rName, const String& rURL,
const String& rTarget,
const Point* pInsPos )
{
// Tabelle geschuetzt ?
ScViewData* pViewData = GetViewData();
ScDocument* pDoc = pViewData->GetDocument();
SCTAB nTab = pViewData->GetTabNo();
if ( pDoc->IsTabProtected(nTab) )
{
ErrorMessage(STR_PROTECTIONERR);
return;
}
MakeDrawLayer();
ScTabView* pView = pViewData->GetView();
// SdrView* pDrView = pView->GetSdrView();
ScDrawView* pDrView = pView->GetScDrawView();
SdrModel* pModel = pDrView->GetModel();
SdrObject* pObj = SdrObjFactory::MakeNewObject(FmFormInventor, OBJ_FM_BUTTON,
pDrView->GetSdrPageView()->GetPage(), pModel);
SdrUnoObj* pUnoCtrl = PTR_CAST(SdrUnoObj, pObj);
uno::Reference<awt::XControlModel> xControlModel = pUnoCtrl->GetUnoControlModel();
DBG_ASSERT( xControlModel.is(), "UNO-Control ohne Model" );
if( !xControlModel.is() )
return;
uno::Reference< beans::XPropertySet > xPropSet( xControlModel, uno::UNO_QUERY );
uno::Any aAny;
aAny <<= rtl::OUString(rName);
xPropSet->setPropertyValue( rtl::OUString::createFromAscii( "Label" ), aAny );
::rtl::OUString aTmp = INetURLObject::GetAbsURL( pDoc->GetDocumentShell()->GetMedium()->GetBaseURL(), rURL );
aAny <<= aTmp;
xPropSet->setPropertyValue( rtl::OUString::createFromAscii( "TargetURL" ), aAny );
if( rTarget.Len() )
{
aAny <<= rtl::OUString(rTarget);
xPropSet->setPropertyValue( rtl::OUString::createFromAscii( "TargetFrame" ), aAny );
}
form::FormButtonType eButtonType = form::FormButtonType_URL;
aAny <<= eButtonType;
xPropSet->setPropertyValue( rtl::OUString::createFromAscii( "ButtonType" ), aAny );
if ( ::avmedia::MediaWindow::isMediaURL( rURL ) )
{
// #105638# OJ
aAny <<= sal_True;
xPropSet->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DispatchURLInternal" )), aAny );
}
Point aPos;
if (pInsPos)
aPos = *pInsPos;
else
aPos = GetInsertPos();
// Groesse wie in 3.1:
Size aSize = GetActiveWin()->PixelToLogic(Size(140, 20));
if ( pDoc->IsNegativePage(nTab) )
aPos.X() -= aSize.Width();
pObj->SetLogicRect(Rectangle(aPos, aSize));
// pObj->Resize(Point(), Fraction(1, 1), Fraction(1, 1));
// am alten VC-Button musste die Position/Groesse nochmal explizit
// gesetzt werden - das scheint mit UnoControls nicht noetig zu sein
// nicht markieren wenn Ole
pDrView->InsertObjectSafe( pObj, *pDrView->GetSdrPageView() );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.12.34); FILE MERGED 2008/03/31 17:20:02 rt 1.12.34.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tabvwshg.cxx,v $
* $Revision: 1.13 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// INCLUDE ---------------------------------------------------------------
//#define SI_VCDRAWOBJ
#include <tools/urlobj.hxx>
#include <svx/fmglob.hxx>
#include <svx/svdouno.hxx>
#include <svx/svdpagv.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/docfile.hxx>
#include <com/sun/star/form/FormButtonType.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/awt/XControlModel.hpp>
using namespace com::sun::star;
#include "tabvwsh.hxx"
#include "document.hxx"
#include "drawview.hxx"
#include "globstr.hrc"
#include <avmedia/mediawindow.hxx>
//------------------------------------------------------------------------
void ScTabViewShell::InsertURLButton( const String& rName, const String& rURL,
const String& rTarget,
const Point* pInsPos )
{
// Tabelle geschuetzt ?
ScViewData* pViewData = GetViewData();
ScDocument* pDoc = pViewData->GetDocument();
SCTAB nTab = pViewData->GetTabNo();
if ( pDoc->IsTabProtected(nTab) )
{
ErrorMessage(STR_PROTECTIONERR);
return;
}
MakeDrawLayer();
ScTabView* pView = pViewData->GetView();
// SdrView* pDrView = pView->GetSdrView();
ScDrawView* pDrView = pView->GetScDrawView();
SdrModel* pModel = pDrView->GetModel();
SdrObject* pObj = SdrObjFactory::MakeNewObject(FmFormInventor, OBJ_FM_BUTTON,
pDrView->GetSdrPageView()->GetPage(), pModel);
SdrUnoObj* pUnoCtrl = PTR_CAST(SdrUnoObj, pObj);
uno::Reference<awt::XControlModel> xControlModel = pUnoCtrl->GetUnoControlModel();
DBG_ASSERT( xControlModel.is(), "UNO-Control ohne Model" );
if( !xControlModel.is() )
return;
uno::Reference< beans::XPropertySet > xPropSet( xControlModel, uno::UNO_QUERY );
uno::Any aAny;
aAny <<= rtl::OUString(rName);
xPropSet->setPropertyValue( rtl::OUString::createFromAscii( "Label" ), aAny );
::rtl::OUString aTmp = INetURLObject::GetAbsURL( pDoc->GetDocumentShell()->GetMedium()->GetBaseURL(), rURL );
aAny <<= aTmp;
xPropSet->setPropertyValue( rtl::OUString::createFromAscii( "TargetURL" ), aAny );
if( rTarget.Len() )
{
aAny <<= rtl::OUString(rTarget);
xPropSet->setPropertyValue( rtl::OUString::createFromAscii( "TargetFrame" ), aAny );
}
form::FormButtonType eButtonType = form::FormButtonType_URL;
aAny <<= eButtonType;
xPropSet->setPropertyValue( rtl::OUString::createFromAscii( "ButtonType" ), aAny );
if ( ::avmedia::MediaWindow::isMediaURL( rURL ) )
{
// #105638# OJ
aAny <<= sal_True;
xPropSet->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DispatchURLInternal" )), aAny );
}
Point aPos;
if (pInsPos)
aPos = *pInsPos;
else
aPos = GetInsertPos();
// Groesse wie in 3.1:
Size aSize = GetActiveWin()->PixelToLogic(Size(140, 20));
if ( pDoc->IsNegativePage(nTab) )
aPos.X() -= aSize.Width();
pObj->SetLogicRect(Rectangle(aPos, aSize));
// pObj->Resize(Point(), Fraction(1, 1), Fraction(1, 1));
// am alten VC-Button musste die Position/Groesse nochmal explizit
// gesetzt werden - das scheint mit UnoControls nicht noetig zu sein
// nicht markieren wenn Ole
pDrView->InsertObjectSafe( pObj, *pDrView->GetSdrPageView() );
}
<|endoftext|>
|
<commit_before><commit_msg>RemoteFilesDialog: CMIS subtypes<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: svtaccessiblefactory.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2007-07-10 09:20:25 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#ifndef SVTOOLS_ACCESSIBLE_FACTORY_ACCESS_HXX
#include "svtaccessiblefactory.hxx"
#endif
#ifndef _OSL_MODULE_H_
#include <osl/module.h>
#endif
// #define UNLOAD_ON_LAST_CLIENT_DYING
// this is not recommended currently. If enabled, the implementation will log
// the number of active clients, and unload the acc library when the last client
// goes away.
// Sounds like a good idea, unfortunately, there's no guarantee that all objects
// implemented in this library are already dead.
// Iow, just because an object implementing an XAccessible (implemented in this lib
// here) died, it's not said that everybody released all references to the
// XAccessibleContext used by this component, and implemented in the acc lib.
// So we cannot really unload the lib.
//
// Alternatively, if the lib would us own "usage counting", i.e. every component
// implemented therein would affect a static ref count, the acc lib could care
// for unloading itself.
//........................................................................
namespace svt
{
//........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::accessibility;
namespace
{
#ifdef UNLOAD_ON_LAST_CLIENT_DYING
static oslInterlockedCount s_nAccessibleFactoryAccesss = 0;
#endif // UNLOAD_ON_LAST_CLIENT_DYING
static oslModule s_hAccessibleImplementationModule = NULL;
static GetSvtAccessibilityComponentFactory s_pAccessibleFactoryFunc = NULL;
static ::rtl::Reference< IAccessibleFactory > s_pFactory;
//====================================================================
//= AccessibleDummyFactory
//====================================================================
class AccessibleDummyFactory : public IAccessibleFactory
{
public:
AccessibleDummyFactory();
protected:
virtual ~AccessibleDummyFactory();
private:
AccessibleDummyFactory( const AccessibleDummyFactory& ); // never implemented
AccessibleDummyFactory& operator=( const AccessibleDummyFactory& ); // never implemented
oslInterlockedCount m_refCount;
public:
// IReference
virtual oslInterlockedCount SAL_CALL acquire();
virtual oslInterlockedCount SAL_CALL release();
// IAccessibleFactory
virtual IAccessibleTabListBox*
createAccessibleTabListBox(
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& /*rxParent*/,
SvHeaderTabListBox& /*rBox*/
) const
{
return NULL;
}
virtual IAccessibleBrowseBox*
createAccessibleBrowseBox(
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& /*_rxParent*/,
IAccessibleTableProvider& /*_rBrowseBox*/
) const
{
return NULL;
}
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
createAccessibleIconChoiceCtrl(
SvtIconChoiceCtrl& /*_rIconCtrl*/,
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& /*_xParent*/
) const
{
return NULL;
}
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
createAccessibleTabBar(
TabBar& /*_rTabBar*/
) const
{
return NULL;
}
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleTextWindowContext(
VCLXWindow* /*pVclXWindow*/, TextEngine& /*rEngine*/, TextView& /*rView*/, bool /*bCompoundControlChild*/
) const
{
return NULL;
}
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
createAccessibleTreeListBox(
SvTreeListBox& /*_rListBox*/,
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& /*_xParent*/
) const
{
return NULL;
}
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
createAccessibleBrowseBoxHeaderBar(
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& /*rxParent*/,
IAccessibleTableProvider& /*_rOwningTable*/,
AccessibleBrowseBoxObjType /*_eObjType*/
) const
{
return NULL;
}
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
createAccessibleBrowseBoxTableCell(
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& /*_rxParent*/,
IAccessibleTableProvider& /*_rBrowseBox*/,
const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >& /*_xFocusWindow*/,
sal_Int32 /*_nRowId*/,
sal_uInt16 /*_nColId*/,
sal_Int32 /*_nOffset*/
) const
{
return NULL;
}
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
createAccessibleBrowseBoxHeaderCell(
sal_Int32 /*_nColumnRowId*/,
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& /*rxParent*/,
IAccessibleTableProvider& /*_rBrowseBox*/,
const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >& /*_xFocusWindow*/,
AccessibleBrowseBoxObjType /*_eObjType*/
) const
{
return NULL;
}
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
createAccessibleCheckBoxCell(
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& /*_rxParent*/,
IAccessibleTableProvider& /*_rBrowseBox*/,
const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >& /*_xFocusWindow*/,
sal_Int32 /*_nRowPos*/,
sal_uInt16 /*_nColPos*/,
const TriState& /*_eState*/,
sal_Bool /*_bEnabled*/,
sal_Bool /*_bIsTriState*/
) const
{
return NULL;
}
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
createEditBrowseBoxTableCellAccess(
const ::com::sun::star::uno::Reference< com::sun::star::accessibility::XAccessible >& /*_rxParent*/,
const ::com::sun::star::uno::Reference< com::sun::star::accessibility::XAccessible >& /*_rxControlAccessible*/,
const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >& /*_rxFocusWindow*/,
IAccessibleTableProvider& /*_rBrowseBox*/,
sal_Int32 /*_nRowPos*/,
sal_uInt16 /*_nColPos*/
) const
{
return NULL;
}
};
//----------------------------------------------------------------
AccessibleDummyFactory::AccessibleDummyFactory()
{
}
//----------------------------------------------------------------
AccessibleDummyFactory::~AccessibleDummyFactory()
{
}
//----------------------------------------------------------------
oslInterlockedCount SAL_CALL AccessibleDummyFactory::acquire()
{
return osl_incrementInterlockedCount( &m_refCount );
}
//----------------------------------------------------------------
oslInterlockedCount SAL_CALL AccessibleDummyFactory::release()
{
if ( 0 == osl_decrementInterlockedCount( &m_refCount ) )
{
delete this;
return 0;
}
return m_refCount;
}
}
//====================================================================
//= AccessibleFactoryAccess
//====================================================================
//--------------------------------------------------------------------
AccessibleFactoryAccess::AccessibleFactoryAccess()
:m_bInitialized( false )
{
}
//--------------------------------------------------------------------
void AccessibleFactoryAccess::ensureInitialized()
{
if ( m_bInitialized )
return;
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
#ifdef UNLOAD_ON_LAST_CLIENT_DYING
if ( 1 == osl_incrementInterlockedCount( &s_nAccessibleFactoryAccesss ) )
{ // the first client
#endif // UNLOAD_ON_LAST_CLIENT_DYING
// load the library implementing the factory
if ( !s_pFactory.get() )
{
const ::rtl::OUString sModuleName = ::rtl::OUString::createFromAscii(
SVLIBRARY( "acc" )
);
s_hAccessibleImplementationModule = osl_loadModule( sModuleName.pData, 0 );
if ( s_hAccessibleImplementationModule != NULL )
{
const ::rtl::OUString sFactoryCreationFunc =
::rtl::OUString::createFromAscii( "getSvtAccessibilityComponentFactory" );
s_pAccessibleFactoryFunc = (GetSvtAccessibilityComponentFactory)
osl_getFunctionSymbol( s_hAccessibleImplementationModule, sFactoryCreationFunc.pData );
}
OSL_ENSURE( s_pAccessibleFactoryFunc, "ac_registerClient: could not load the library, or not retrieve the needed symbol!" );
// get a factory instance
if ( s_pAccessibleFactoryFunc )
{
IAccessibleFactory* pFactory = static_cast< IAccessibleFactory* >( (*s_pAccessibleFactoryFunc)() );
if ( pFactory )
{
s_pFactory = pFactory;
pFactory->release();
}
}
}
if ( !s_pFactory.get() )
// the attempt to load the lib, or to create the factory, failed
// -> fall back to a dummy factory
s_pFactory = new AccessibleDummyFactory;
#ifdef UNLOAD_ON_LAST_CLIENT_DYING
}
#endif
m_bInitialized = true;
}
//--------------------------------------------------------------------
AccessibleFactoryAccess::~AccessibleFactoryAccess()
{
if ( m_bInitialized )
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
#ifdef UNLOAD_ON_LAST_CLIENT_DYING
if( 0 == osl_decrementInterlockedCount( &s_nAccessibleFactoryAccesss ) )
{
s_pFactory = NULL;
s_pAccessibleFactoryFunc = NULL;
if ( s_hAccessibleImplementationModule )
{
osl_unloadModule( s_hAccessibleImplementationModule );
s_hAccessibleImplementationModule = NULL;
}
}
#endif // UNLOAD_ON_LAST_CLIENT_DYING
}
}
//--------------------------------------------------------------------
IAccessibleFactory& AccessibleFactoryAccess::getFactory()
{
ensureInitialized();
DBG_ASSERT( s_pFactory.is(), "AccessibleFactoryAccess::getFactory: at least a dummy factory should have been created!" );
return *s_pFactory;
}
//........................................................................
} // namespace svt
//........................................................................
<commit_msg>INTEGRATION: CWS finalsisslremoval (1.3.14); FILE MERGED 2007/07/15 08:00:02 pjanik 1.3.14.1: #i79627#: Remove SISSL.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svtaccessiblefactory.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2007-07-18 10:04:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#ifndef SVTOOLS_ACCESSIBLE_FACTORY_ACCESS_HXX
#include "svtaccessiblefactory.hxx"
#endif
#ifndef _OSL_MODULE_H_
#include <osl/module.h>
#endif
// #define UNLOAD_ON_LAST_CLIENT_DYING
// this is not recommended currently. If enabled, the implementation will log
// the number of active clients, and unload the acc library when the last client
// goes away.
// Sounds like a good idea, unfortunately, there's no guarantee that all objects
// implemented in this library are already dead.
// Iow, just because an object implementing an XAccessible (implemented in this lib
// here) died, it's not said that everybody released all references to the
// XAccessibleContext used by this component, and implemented in the acc lib.
// So we cannot really unload the lib.
//
// Alternatively, if the lib would us own "usage counting", i.e. every component
// implemented therein would affect a static ref count, the acc lib could care
// for unloading itself.
//........................................................................
namespace svt
{
//........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::accessibility;
namespace
{
#ifdef UNLOAD_ON_LAST_CLIENT_DYING
static oslInterlockedCount s_nAccessibleFactoryAccesss = 0;
#endif // UNLOAD_ON_LAST_CLIENT_DYING
static oslModule s_hAccessibleImplementationModule = NULL;
static GetSvtAccessibilityComponentFactory s_pAccessibleFactoryFunc = NULL;
static ::rtl::Reference< IAccessibleFactory > s_pFactory;
//====================================================================
//= AccessibleDummyFactory
//====================================================================
class AccessibleDummyFactory : public IAccessibleFactory
{
public:
AccessibleDummyFactory();
protected:
virtual ~AccessibleDummyFactory();
private:
AccessibleDummyFactory( const AccessibleDummyFactory& ); // never implemented
AccessibleDummyFactory& operator=( const AccessibleDummyFactory& ); // never implemented
oslInterlockedCount m_refCount;
public:
// IReference
virtual oslInterlockedCount SAL_CALL acquire();
virtual oslInterlockedCount SAL_CALL release();
// IAccessibleFactory
virtual IAccessibleTabListBox*
createAccessibleTabListBox(
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& /*rxParent*/,
SvHeaderTabListBox& /*rBox*/
) const
{
return NULL;
}
virtual IAccessibleBrowseBox*
createAccessibleBrowseBox(
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& /*_rxParent*/,
IAccessibleTableProvider& /*_rBrowseBox*/
) const
{
return NULL;
}
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
createAccessibleIconChoiceCtrl(
SvtIconChoiceCtrl& /*_rIconCtrl*/,
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& /*_xParent*/
) const
{
return NULL;
}
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
createAccessibleTabBar(
TabBar& /*_rTabBar*/
) const
{
return NULL;
}
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleTextWindowContext(
VCLXWindow* /*pVclXWindow*/, TextEngine& /*rEngine*/, TextView& /*rView*/, bool /*bCompoundControlChild*/
) const
{
return NULL;
}
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
createAccessibleTreeListBox(
SvTreeListBox& /*_rListBox*/,
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& /*_xParent*/
) const
{
return NULL;
}
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
createAccessibleBrowseBoxHeaderBar(
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& /*rxParent*/,
IAccessibleTableProvider& /*_rOwningTable*/,
AccessibleBrowseBoxObjType /*_eObjType*/
) const
{
return NULL;
}
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
createAccessibleBrowseBoxTableCell(
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& /*_rxParent*/,
IAccessibleTableProvider& /*_rBrowseBox*/,
const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >& /*_xFocusWindow*/,
sal_Int32 /*_nRowId*/,
sal_uInt16 /*_nColId*/,
sal_Int32 /*_nOffset*/
) const
{
return NULL;
}
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
createAccessibleBrowseBoxHeaderCell(
sal_Int32 /*_nColumnRowId*/,
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& /*rxParent*/,
IAccessibleTableProvider& /*_rBrowseBox*/,
const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >& /*_xFocusWindow*/,
AccessibleBrowseBoxObjType /*_eObjType*/
) const
{
return NULL;
}
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
createAccessibleCheckBoxCell(
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& /*_rxParent*/,
IAccessibleTableProvider& /*_rBrowseBox*/,
const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >& /*_xFocusWindow*/,
sal_Int32 /*_nRowPos*/,
sal_uInt16 /*_nColPos*/,
const TriState& /*_eState*/,
sal_Bool /*_bEnabled*/,
sal_Bool /*_bIsTriState*/
) const
{
return NULL;
}
virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
createEditBrowseBoxTableCellAccess(
const ::com::sun::star::uno::Reference< com::sun::star::accessibility::XAccessible >& /*_rxParent*/,
const ::com::sun::star::uno::Reference< com::sun::star::accessibility::XAccessible >& /*_rxControlAccessible*/,
const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >& /*_rxFocusWindow*/,
IAccessibleTableProvider& /*_rBrowseBox*/,
sal_Int32 /*_nRowPos*/,
sal_uInt16 /*_nColPos*/
) const
{
return NULL;
}
};
//----------------------------------------------------------------
AccessibleDummyFactory::AccessibleDummyFactory()
{
}
//----------------------------------------------------------------
AccessibleDummyFactory::~AccessibleDummyFactory()
{
}
//----------------------------------------------------------------
oslInterlockedCount SAL_CALL AccessibleDummyFactory::acquire()
{
return osl_incrementInterlockedCount( &m_refCount );
}
//----------------------------------------------------------------
oslInterlockedCount SAL_CALL AccessibleDummyFactory::release()
{
if ( 0 == osl_decrementInterlockedCount( &m_refCount ) )
{
delete this;
return 0;
}
return m_refCount;
}
}
//====================================================================
//= AccessibleFactoryAccess
//====================================================================
//--------------------------------------------------------------------
AccessibleFactoryAccess::AccessibleFactoryAccess()
:m_bInitialized( false )
{
}
//--------------------------------------------------------------------
void AccessibleFactoryAccess::ensureInitialized()
{
if ( m_bInitialized )
return;
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
#ifdef UNLOAD_ON_LAST_CLIENT_DYING
if ( 1 == osl_incrementInterlockedCount( &s_nAccessibleFactoryAccesss ) )
{ // the first client
#endif // UNLOAD_ON_LAST_CLIENT_DYING
// load the library implementing the factory
if ( !s_pFactory.get() )
{
const ::rtl::OUString sModuleName = ::rtl::OUString::createFromAscii(
SVLIBRARY( "acc" )
);
s_hAccessibleImplementationModule = osl_loadModule( sModuleName.pData, 0 );
if ( s_hAccessibleImplementationModule != NULL )
{
const ::rtl::OUString sFactoryCreationFunc =
::rtl::OUString::createFromAscii( "getSvtAccessibilityComponentFactory" );
s_pAccessibleFactoryFunc = (GetSvtAccessibilityComponentFactory)
osl_getFunctionSymbol( s_hAccessibleImplementationModule, sFactoryCreationFunc.pData );
}
OSL_ENSURE( s_pAccessibleFactoryFunc, "ac_registerClient: could not load the library, or not retrieve the needed symbol!" );
// get a factory instance
if ( s_pAccessibleFactoryFunc )
{
IAccessibleFactory* pFactory = static_cast< IAccessibleFactory* >( (*s_pAccessibleFactoryFunc)() );
if ( pFactory )
{
s_pFactory = pFactory;
pFactory->release();
}
}
}
if ( !s_pFactory.get() )
// the attempt to load the lib, or to create the factory, failed
// -> fall back to a dummy factory
s_pFactory = new AccessibleDummyFactory;
#ifdef UNLOAD_ON_LAST_CLIENT_DYING
}
#endif
m_bInitialized = true;
}
//--------------------------------------------------------------------
AccessibleFactoryAccess::~AccessibleFactoryAccess()
{
if ( m_bInitialized )
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
#ifdef UNLOAD_ON_LAST_CLIENT_DYING
if( 0 == osl_decrementInterlockedCount( &s_nAccessibleFactoryAccesss ) )
{
s_pFactory = NULL;
s_pAccessibleFactoryFunc = NULL;
if ( s_hAccessibleImplementationModule )
{
osl_unloadModule( s_hAccessibleImplementationModule );
s_hAccessibleImplementationModule = NULL;
}
}
#endif // UNLOAD_ON_LAST_CLIENT_DYING
}
}
//--------------------------------------------------------------------
IAccessibleFactory& AccessibleFactoryAccess::getFactory()
{
ensureInitialized();
DBG_ASSERT( s_pFactory.is(), "AccessibleFactoryAccess::getFactory: at least a dummy factory should have been created!" );
return *s_pFactory;
}
//........................................................................
} // namespace svt
//........................................................................
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.