text
stringlengths
54
60.6k
<commit_before> #include "NNApplication.h" #include "NNInputSystem.h" #include "NNAudioSystem.h" #include "NNResourceManager.h" #include "NNNetworkSystem.h" NNApplication* NNApplication::m_pInstance = nullptr; NNApplication::NNApplication() : m_Hwnd(nullptr), m_hInstance(nullptr), m_ScreenHeight(0), m_ScreenWidth(0), m_Fps(0.f), m_ElapsedTime(0.f), m_DeltaTime(0.f),m_FpsTimer(0.f), m_PrevTime(0), m_NowTime(0), m_Renderer(nullptr), m_pSceneDirector(nullptr), m_RendererStatus(UNKNOWN),m_DestroyWindow(false) { } NNApplication::~NNApplication() { } NNApplication* NNApplication::GetInstance() { if ( m_pInstance == nullptr ) { m_pInstance = new NNApplication(); } return m_pInstance; } void NNApplication::ReleaseInstance() { if ( m_pInstance != nullptr ) { delete m_pInstance; m_pInstance = nullptr; } } bool NNApplication::Init( wchar_t* title, int width, int height, RendererStatus renderStatus ) { m_hInstance = GetModuleHandle(0); m_Title = title; m_ScreenWidth = width; m_ScreenHeight = height; m_RendererStatus = renderStatus; _CreateWindow( m_Title, m_ScreenWidth, m_ScreenHeight ); _CreateRenderer( renderStatus ); m_pSceneDirector = NNSceneDirector::GetInstance(); m_Renderer->Init(); m_pSceneDirector->Init(); return true; } bool NNApplication::Release() { if ( m_DestroyWindow == true ) { ReleaseInstance(); return true; } m_pSceneDirector->Release(); NNSceneDirector::ReleaseInstance(); NNResourceManager::ReleaseInstance(); NNInputSystem::ReleaseInstance(); NNAudioSystem::ReleaseInstance(); NNNetworkSystem::ReleaseInstance(); SafeDelete( m_Renderer ); ReleaseInstance(); return true; } bool NNApplication::Run() { MSG msg; ZeroMemory( &msg, sizeof(msg) ); while (true) { if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { if ( msg.message == WM_QUIT ) { return true; } TranslateMessage( &msg ); DispatchMessage( &msg ); } else{ m_FrameCount++; m_NowTime = timeGetTime(); if ( m_PrevTime == 0.f ) { m_PrevTime = m_NowTime; } m_DeltaTime = (static_cast<float>(m_NowTime - m_PrevTime)) / 1000.f; m_ElapsedTime += m_DeltaTime; m_FpsTimer += m_DeltaTime; if(m_FpsTimer > 0.1f) { m_Fps = ((float)m_FrameCount) / m_FpsTimer; m_FrameCount = 0; m_FpsTimer = 0.f; } m_PrevTime = m_NowTime; NNInputSystem::GetInstance()->UpdateKeyState(); m_pSceneDirector->UpdateScene( m_DeltaTime ); m_Renderer->Begin(); m_Renderer->Clear(); m_pSceneDirector->RenderScene(); m_Renderer->End(); if ( NNInputSystem::GetInstance()->GetKeyState( VK_ESCAPE ) == KEY_DOWN ) { PostQuitMessage(0); } } } return true; } bool NNApplication::_CreateWindow( wchar_t* title, int width, int height ) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = NULL; wcex.cbWndExtra = NULL; wcex.hInstance = m_hInstance; wcex.hIcon = NULL; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = NULL; wcex.lpszClassName = L"NNApplication"; wcex.hIconSm = NULL; wcex.hIcon = NULL; RegisterClassEx( &wcex ); DWORD style = WS_OVERLAPPEDWINDOW; RECT wr = {0, 0, width, height}; AdjustWindowRect( &wr, WS_OVERLAPPEDWINDOW, FALSE ); m_Hwnd = CreateWindow( L"NNApplication", title, style, CW_USEDEFAULT, CW_USEDEFAULT, wr.right-wr.left, wr.bottom-wr.top, NULL, NULL, m_hInstance, NULL); ShowWindow( m_Hwnd, SW_SHOWNORMAL ); return true; } bool NNApplication::_CreateRenderer( RendererStatus renderStatus ) { switch( renderStatus ) { case D2D: m_Renderer = new NND2DRenderer(); break; default: return false; } return true; } LRESULT CALLBACK NNApplication::WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) { switch( message ) { case WM_DESTROY: NNApplication::GetInstance()->Release(); NNApplication::GetInstance()->m_DestroyWindow = true; PostQuitMessage(0); return 0; case WM_PAINT: PAINTSTRUCT ps; HDC hdc = BeginPaint( hWnd, &ps ); EndPaint( hWnd, &ps ); } return(DefWindowProc(hWnd,message,wParam,lParam)); }<commit_msg>* Fixed NNApplication Bug<commit_after> #include "NNApplication.h" #include "NNInputSystem.h" #include "NNAudioSystem.h" #include "NNResourceManager.h" #include "NNNetworkSystem.h" NNApplication* NNApplication::m_pInstance = nullptr; NNApplication::NNApplication() : m_Hwnd(nullptr), m_hInstance(nullptr), m_ScreenHeight(0), m_ScreenWidth(0), m_Fps(0.f), m_ElapsedTime(0.f), m_DeltaTime(0.f),m_FpsTimer(0.f), m_PrevTime(0), m_NowTime(0), m_Renderer(nullptr), m_pSceneDirector(nullptr), m_RendererStatus(UNKNOWN),m_DestroyWindow(false) { } NNApplication::~NNApplication() { } NNApplication* NNApplication::GetInstance() { if ( m_pInstance == nullptr ) { m_pInstance = new NNApplication(); } return m_pInstance; } void NNApplication::ReleaseInstance() { if ( m_pInstance != nullptr ) { delete m_pInstance; m_pInstance = nullptr; } } bool NNApplication::Init( wchar_t* title, int width, int height, RendererStatus renderStatus ) { m_hInstance = GetModuleHandle(0); m_Title = title; m_ScreenWidth = width; m_ScreenHeight = height; m_RendererStatus = renderStatus; _CreateWindow( m_Title, m_ScreenWidth, m_ScreenHeight ); _CreateRenderer( renderStatus ); m_pSceneDirector = NNSceneDirector::GetInstance(); m_Renderer->Init(); m_pSceneDirector->Init(); srand( time(NULL) ) ; return true; } bool NNApplication::Release() { if ( m_DestroyWindow ) { ReleaseInstance(); return true; } m_pSceneDirector->Release(); NNSceneDirector::ReleaseInstance(); NNResourceManager::ReleaseInstance(); NNInputSystem::ReleaseInstance(); NNAudioSystem::ReleaseInstance(); NNNetworkSystem::ReleaseInstance(); SafeDelete( m_Renderer ); ReleaseInstance(); return true; } bool NNApplication::Run() { MSG msg; ZeroMemory( &msg, sizeof(msg) ); while (true) { if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { if ( msg.message == WM_QUIT ) { return true; } TranslateMessage( &msg ); DispatchMessage( &msg ); } else{ m_FrameCount++; m_NowTime = timeGetTime(); if ( m_PrevTime == 0.f ) { m_PrevTime = m_NowTime; } m_DeltaTime = (static_cast<float>(m_NowTime - m_PrevTime)) / 1000.f; m_ElapsedTime += m_DeltaTime; m_FpsTimer += m_DeltaTime; if(m_FpsTimer > 0.1f) { m_Fps = ((float)m_FrameCount) / m_FpsTimer; m_FrameCount = 0; m_FpsTimer = 0.f; } m_PrevTime = m_NowTime; NNInputSystem::GetInstance()->UpdateKeyState(); m_pSceneDirector->UpdateScene( m_DeltaTime ); m_Renderer->Begin(); m_Renderer->Clear(); m_pSceneDirector->RenderScene(); m_Renderer->End(); if ( NNInputSystem::GetInstance()->GetKeyState( VK_ESCAPE ) == KEY_DOWN ) { PostQuitMessage(0); } } } return true; } bool NNApplication::_CreateWindow( wchar_t* title, int width, int height ) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = NULL; wcex.cbWndExtra = NULL; wcex.hInstance = m_hInstance; wcex.hIcon = NULL; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = NULL; wcex.lpszClassName = L"NNApplication"; wcex.hIconSm = NULL; wcex.hIcon = NULL; RegisterClassEx( &wcex ); DWORD style = WS_OVERLAPPEDWINDOW; RECT wr = {0, 0, width, height}; AdjustWindowRect( &wr, WS_OVERLAPPEDWINDOW, FALSE ); m_Hwnd = CreateWindow( L"NNApplication", title, style, CW_USEDEFAULT, CW_USEDEFAULT, wr.right-wr.left, wr.bottom-wr.top, NULL, NULL, m_hInstance, NULL); ShowWindow( m_Hwnd, SW_SHOWNORMAL ); return true; } bool NNApplication::_CreateRenderer( RendererStatus renderStatus ) { switch( renderStatus ) { case D2D: m_Renderer = new NND2DRenderer(); break; default: return false; } return true; } LRESULT CALLBACK NNApplication::WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) { switch( message ) { case WM_CREATE: { break; } case WM_DESTROY: { NNApplication::GetInstance()->Release(); NNApplication::GetInstance()->m_DestroyWindow = true; PostQuitMessage(0); break; } case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint( hWnd, &ps ); EndPaint( hWnd, &ps ); break; } case WM_SOCKET: { if (WSAGETSELECTERROR(lParam)) { MessageBox(hWnd,L"WSAGETSELECTERROR", L"Error", MB_OK|MB_ICONERROR); SendMessage(hWnd,WM_DESTROY,NULL,NULL); break; } switch (WSAGETSELECTEVENT(lParam)) { case FD_CONNECT: { /// NAGLE /// NAGLE Algorithm /// http://en.wikipedia.org/wiki/Nagle's_algorithm int opt = 1 ; ::setsockopt(NNNetworkSystem::GetInstance()->m_Socket, IPPROTO_TCP, TCP_NODELAY, (const char*)&opt, sizeof(int)) ; int nResult = WSAAsyncSelect(NNNetworkSystem::GetInstance()->m_Socket, hWnd, WM_SOCKET, (FD_CLOSE|FD_READ|FD_WRITE) ) ; if (nResult) { assert(false) ; break; } } break ; case FD_READ: { char inBuf[4096] = {0, } ; int recvLen = recv(NNNetworkSystem::GetInstance()->m_Socket, inBuf, 4096, 0) ; if ( !NNNetworkSystem::GetInstance()->m_RecvBuffer.Write(inBuf, recvLen) ) { /// á. assert(false) ; } NNNetworkSystem::GetInstance()->ProcessPacket() ; } break; case FD_WRITE: { /// ۿ ִ°͵ int size = NNNetworkSystem::GetInstance()->m_SendBuffer.GetCurrentSize() ; if ( size > 0 ) { char* data = new char[size] ; NNNetworkSystem::GetInstance()->m_SendBuffer.Peek(data) ; int sent = send(NNNetworkSystem::GetInstance()->m_Socket, data, size, 0) ; /// ٸ ִ if ( sent != size ) OutputDebugStringA("sent != request\n") ; NNNetworkSystem::GetInstance()->m_SendBuffer.Consume(sent) ; delete [] data ; } } break ; case FD_CLOSE: { MessageBox(hWnd, L"Server closed connection", L"Connection closed!", MB_ICONINFORMATION|MB_OK); closesocket(NNNetworkSystem::GetInstance()->m_Socket); SendMessage(hWnd,WM_DESTROY,NULL,NULL); } break; } } break ; } return(DefWindowProc(hWnd,message,wParam,lParam)); }<|endoftext|>
<commit_before>/* * This file is part of the Electron Orbital Explorer. The Electron * Orbital Explorer is distributed under the Simplified BSD License * (also called the "BSD 2-Clause License"), in hopes that these * rendering techniques might be used by other programmers in * applications such as scientific visualization, video gaming, and so * on. If you find value in this software and use its technologies for * another purpose, I would love to hear back from you at bjthinks (at) * gmail (dot) com. If you improve this software and agree to release * your modifications under the below license, I encourage you to fork * the development tree on github and push your modifications. The * Electron Orbital Explorer's development URL is: * https://github.com/bjthinks/orbital-explorer * (This paragraph is not part of the software license and may be * removed.) * * Copyright (c) 2013, Brian W. Johnson * 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. * * 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 HOLDER 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. */ #include <stdexcept> #include <string> #include <iostream> #include <cstdlib> #include <SDL.h> #include "config.hh" #include "glprocs.hh" #include "render.hh" #include "viewport.hh" #include "controls.hh" #include "icon.hh" #include "draw_ui.hh" using namespace std; void set_sdl_attr(SDL_GLattr attr, int value) { if (SDL_GL_SetAttribute(attr, value) < 0) { fprintf(stderr, "SDL_GL_SetAttribute(): %s\n", SDL_GetError()); exit(1); } } static int go() { // // Initialize SDL // if (SDL_Init(SDL_INIT_VIDEO) < 0 ) { fprintf(stderr, "SDL_Init(): %s\n", SDL_GetError()); return 1; } atexit(SDL_Quit); // Request at least 24-bit color set_sdl_attr(SDL_GL_RED_SIZE, 8); set_sdl_attr(SDL_GL_GREEN_SIZE, 8); set_sdl_attr(SDL_GL_BLUE_SIZE, 8); // Tell OpenGL we don't need a depth or alpha buffer set_sdl_attr(SDL_GL_DEPTH_SIZE, 0); set_sdl_attr(SDL_GL_ALPHA_SIZE, 0); // Request double buffering set_sdl_attr(SDL_GL_DOUBLEBUFFER, 1); #ifdef __APPLE__ // Apple defaults to an OpenGL 2.1 Compatibility context unless you // specify otherwise. set_sdl_attr(SDL_GL_CONTEXT_MAJOR_VERSION, 3); set_sdl_attr(SDL_GL_CONTEXT_MINOR_VERSION, 2); set_sdl_attr(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); #endif Viewport viewport(640, 480); // Create a window SDL_Window *window = SDL_CreateWindow("Electron Orbital Explorer", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, viewport.getWidth(), viewport.getHeight(), SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); if (!window) { fprintf(stderr, "SDL_CreateWindow(): %s\n", SDL_GetError()); exit(1); } SDL_Surface *icon = getIcon(); SDL_SetWindowIcon(window, icon); SDL_FreeSurface(icon); // Create an OpenGL context associated with the window SDL_GLContext glcontext = SDL_GL_CreateContext(window); if (!glcontext) { fprintf(stderr, "SDL_GL_CreateContext(): %s\n", SDL_GetError()); exit(1); } // // Get access to OpenGL functions // initGLProcs(); // // Initialize orbital rendering pipeline // initialize(); resizeTextures(viewport); // // Initialize controls // initControls(viewport); // // Main loop // Camera camera; SDL_Event event; bool show_controls = true; Container ui; Window w(ui, Region(0, 0, 400, 100)); Font font(24); String abc(w, font); abc.point(Vector2(0, 0)); abc.set("EXTERMINATE! 123@%& electrons rule"); abc.color(yellow); while (1) { // Clear the event queue, then redraw a frame while (SDL_PollEvent(&event)) { // Can controls handle the event, or is it a resize event? int handled = false; if (show_controls || event.type == SDL_WINDOWEVENT) handled = handleControls(event); // If event hasn't been fully handled by controls, process it if (!handled) { switch (event.type) { case SDL_WINDOWEVENT: if (event.window.event == SDL_WINDOWEVENT_RESIZED) { viewport.resize(event.window.data1, event.window.data2); resizeTextures(viewport); } break; case SDL_MOUSEMOTION: if (event.motion.state == SDL_BUTTON_LMASK) { camera.rotate(double(event.motion.xrel) / viewport.getWidth(), double(event.motion.yrel) / viewport.getHeight()); } else if (event.motion.state == SDL_BUTTON_RMASK) { camera.spin(-double(event.motion.xrel) / viewport.getWidth()); camera.zoom(double(event.motion.yrel) / viewport.getHeight()); } break; case SDL_MOUSEWHEEL: camera.zoom(-DISCRETE_ZOOM_SIZE * event.wheel.y); break; case SDL_KEYDOWN: int key, mod; key = event.key.keysym.sym; // Ignore the Num Lock key state mod = event.key.keysym.mod & ~KMOD_NUM; if (mod == KMOD_NONE) { switch (key) { case SDLK_LEFT: camera.rotate(-DISCRETE_ROTATION_SIZE, 0); break; case SDLK_RIGHT: camera.rotate(DISCRETE_ROTATION_SIZE, 0); break; case SDLK_UP: camera.rotate(0, -DISCRETE_ROTATION_SIZE); break; case SDLK_DOWN: camera.rotate(0, DISCRETE_ROTATION_SIZE); break; case SDLK_PAGEUP: camera.zoom(-DISCRETE_ZOOM_SIZE); break; case SDLK_PAGEDOWN: camera.zoom(DISCRETE_ZOOM_SIZE); break; case SDLK_F11: static int fullscreen_mode = 0; fullscreen_mode ^= SDL_WINDOW_FULLSCREEN_DESKTOP; SDL_SetWindowFullscreen(window, fullscreen_mode); break; case SDLK_F10: show_controls = !show_controls; break; default: break; } } else if (mod == KMOD_LSHIFT || mod == KMOD_RSHIFT || mod == KMOD_SHIFT) { switch (key) { case SDLK_LEFT: camera.spin(DISCRETE_ROTATION_SIZE); break; case SDLK_RIGHT: camera.spin(-DISCRETE_ROTATION_SIZE); break; case SDLK_UP: camera.zoom(-DISCRETE_ZOOM_SIZE); break; case SDLK_DOWN: camera.zoom(DISCRETE_ZOOM_SIZE); break; default: break; } } break; case SDL_QUIT: return 0; } } } display(viewport, camera); if (show_controls) drawControls(); ui.draw(Region(0, 0, viewport.getWidth(), viewport.getHeight())); SDL_GL_SwapWindow(window); } return 0; } int main(int argc, char *argv[]) { #ifdef __APPLE__ // // Compensate for a bug in some versions of AntTweakBar. ATB // attempts to dynamically link with the OpenGL framework without // specifying a full pathname. Setting DYLD_LIBRARY_PATH fixes the // issue, but this environment variable must be set prior to running // the app. So we check it, and, if needed, set it properly and // re-exec ourself. :-( // const char *pathvar = "DYLD_LIBRARY_PATH"; string new_path("/System/Library/Frameworks/OpenGL.framework/" "Versions/Current"); const char *actual_path_cstr = getenv(pathvar); string actual_path(actual_path_cstr ? actual_path_cstr : ""); if (new_path != actual_path.substr(0, new_path.length()) && // Try to prevent an infinite loop, in case something goes wrong actual_path.length() < 4000) { if (actual_path != "") new_path += ":" + actual_path; setenv(pathvar, new_path.c_str(), 1); execvp(argv[0], argv); // If the exec fails, the best we can do is simply continue... } #endif const string polite_error_message = "I\'m sorry, Electron Orbital Explorer has crashed.\n" "This should never happen and is a bug in the program.\n" "Please copy and paste the following error message,\n" "and send it to the developer.\n"; try { return go(); } catch (exception &e) { cerr << polite_error_message; cerr << "Exception: " << e.what() << "\n"; return 1; } catch (...) { cerr << polite_error_message; cerr << "Exception: unknown uncaught object thrown\n"; return 1; } } <commit_msg>Remove test UI elements<commit_after>/* * This file is part of the Electron Orbital Explorer. The Electron * Orbital Explorer is distributed under the Simplified BSD License * (also called the "BSD 2-Clause License"), in hopes that these * rendering techniques might be used by other programmers in * applications such as scientific visualization, video gaming, and so * on. If you find value in this software and use its technologies for * another purpose, I would love to hear back from you at bjthinks (at) * gmail (dot) com. If you improve this software and agree to release * your modifications under the below license, I encourage you to fork * the development tree on github and push your modifications. The * Electron Orbital Explorer's development URL is: * https://github.com/bjthinks/orbital-explorer * (This paragraph is not part of the software license and may be * removed.) * * Copyright (c) 2013, Brian W. Johnson * 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. * * 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 HOLDER 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. */ #include <stdexcept> #include <string> #include <iostream> #include <cstdlib> #include <SDL.h> #include "config.hh" #include "glprocs.hh" #include "render.hh" #include "viewport.hh" #include "controls.hh" #include "icon.hh" #include "draw_ui.hh" using namespace std; void set_sdl_attr(SDL_GLattr attr, int value) { if (SDL_GL_SetAttribute(attr, value) < 0) { fprintf(stderr, "SDL_GL_SetAttribute(): %s\n", SDL_GetError()); exit(1); } } static int go() { // // Initialize SDL // if (SDL_Init(SDL_INIT_VIDEO) < 0 ) { fprintf(stderr, "SDL_Init(): %s\n", SDL_GetError()); return 1; } atexit(SDL_Quit); // Request at least 24-bit color set_sdl_attr(SDL_GL_RED_SIZE, 8); set_sdl_attr(SDL_GL_GREEN_SIZE, 8); set_sdl_attr(SDL_GL_BLUE_SIZE, 8); // Tell OpenGL we don't need a depth or alpha buffer set_sdl_attr(SDL_GL_DEPTH_SIZE, 0); set_sdl_attr(SDL_GL_ALPHA_SIZE, 0); // Request double buffering set_sdl_attr(SDL_GL_DOUBLEBUFFER, 1); #ifdef __APPLE__ // Apple defaults to an OpenGL 2.1 Compatibility context unless you // specify otherwise. set_sdl_attr(SDL_GL_CONTEXT_MAJOR_VERSION, 3); set_sdl_attr(SDL_GL_CONTEXT_MINOR_VERSION, 2); set_sdl_attr(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); #endif Viewport viewport(640, 480); // Create a window SDL_Window *window = SDL_CreateWindow("Electron Orbital Explorer", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, viewport.getWidth(), viewport.getHeight(), SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); if (!window) { fprintf(stderr, "SDL_CreateWindow(): %s\n", SDL_GetError()); exit(1); } SDL_Surface *icon = getIcon(); SDL_SetWindowIcon(window, icon); SDL_FreeSurface(icon); // Create an OpenGL context associated with the window SDL_GLContext glcontext = SDL_GL_CreateContext(window); if (!glcontext) { fprintf(stderr, "SDL_GL_CreateContext(): %s\n", SDL_GetError()); exit(1); } // // Get access to OpenGL functions // initGLProcs(); // // Initialize orbital rendering pipeline // initialize(); resizeTextures(viewport); // // Initialize controls // initControls(viewport); // // Main loop // Camera camera; SDL_Event event; bool show_controls = true; Container ui; while (1) { // Clear the event queue, then redraw a frame while (SDL_PollEvent(&event)) { // Can controls handle the event, or is it a resize event? int handled = false; if (show_controls || event.type == SDL_WINDOWEVENT) handled = handleControls(event); // If event hasn't been fully handled by controls, process it if (!handled) { switch (event.type) { case SDL_WINDOWEVENT: if (event.window.event == SDL_WINDOWEVENT_RESIZED) { viewport.resize(event.window.data1, event.window.data2); resizeTextures(viewport); } break; case SDL_MOUSEMOTION: if (event.motion.state == SDL_BUTTON_LMASK) { camera.rotate(double(event.motion.xrel) / viewport.getWidth(), double(event.motion.yrel) / viewport.getHeight()); } else if (event.motion.state == SDL_BUTTON_RMASK) { camera.spin(-double(event.motion.xrel) / viewport.getWidth()); camera.zoom(double(event.motion.yrel) / viewport.getHeight()); } break; case SDL_MOUSEWHEEL: camera.zoom(-DISCRETE_ZOOM_SIZE * event.wheel.y); break; case SDL_KEYDOWN: int key, mod; key = event.key.keysym.sym; // Ignore the Num Lock key state mod = event.key.keysym.mod & ~KMOD_NUM; if (mod == KMOD_NONE) { switch (key) { case SDLK_LEFT: camera.rotate(-DISCRETE_ROTATION_SIZE, 0); break; case SDLK_RIGHT: camera.rotate(DISCRETE_ROTATION_SIZE, 0); break; case SDLK_UP: camera.rotate(0, -DISCRETE_ROTATION_SIZE); break; case SDLK_DOWN: camera.rotate(0, DISCRETE_ROTATION_SIZE); break; case SDLK_PAGEUP: camera.zoom(-DISCRETE_ZOOM_SIZE); break; case SDLK_PAGEDOWN: camera.zoom(DISCRETE_ZOOM_SIZE); break; case SDLK_F11: static int fullscreen_mode = 0; fullscreen_mode ^= SDL_WINDOW_FULLSCREEN_DESKTOP; SDL_SetWindowFullscreen(window, fullscreen_mode); break; case SDLK_F10: show_controls = !show_controls; break; default: break; } } else if (mod == KMOD_LSHIFT || mod == KMOD_RSHIFT || mod == KMOD_SHIFT) { switch (key) { case SDLK_LEFT: camera.spin(DISCRETE_ROTATION_SIZE); break; case SDLK_RIGHT: camera.spin(-DISCRETE_ROTATION_SIZE); break; case SDLK_UP: camera.zoom(-DISCRETE_ZOOM_SIZE); break; case SDLK_DOWN: camera.zoom(DISCRETE_ZOOM_SIZE); break; default: break; } } break; case SDL_QUIT: return 0; } } } display(viewport, camera); if (show_controls) drawControls(); ui.draw(Region(0, 0, viewport.getWidth(), viewport.getHeight())); SDL_GL_SwapWindow(window); } return 0; } int main(int argc, char *argv[]) { #ifdef __APPLE__ // // Compensate for a bug in some versions of AntTweakBar. ATB // attempts to dynamically link with the OpenGL framework without // specifying a full pathname. Setting DYLD_LIBRARY_PATH fixes the // issue, but this environment variable must be set prior to running // the app. So we check it, and, if needed, set it properly and // re-exec ourself. :-( // const char *pathvar = "DYLD_LIBRARY_PATH"; string new_path("/System/Library/Frameworks/OpenGL.framework/" "Versions/Current"); const char *actual_path_cstr = getenv(pathvar); string actual_path(actual_path_cstr ? actual_path_cstr : ""); if (new_path != actual_path.substr(0, new_path.length()) && // Try to prevent an infinite loop, in case something goes wrong actual_path.length() < 4000) { if (actual_path != "") new_path += ":" + actual_path; setenv(pathvar, new_path.c_str(), 1); execvp(argv[0], argv); // If the exec fails, the best we can do is simply continue... } #endif const string polite_error_message = "I\'m sorry, Electron Orbital Explorer has crashed.\n" "This should never happen and is a bug in the program.\n" "Please copy and paste the following error message,\n" "and send it to the developer.\n"; try { return go(); } catch (exception &e) { cerr << polite_error_message; cerr << "Exception: " << e.what() << "\n"; return 1; } catch (...) { cerr << polite_error_message; cerr << "Exception: unknown uncaught object thrown\n"; return 1; } } <|endoftext|>
<commit_before>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // This is a GPU-backend specific test. It relies on static intializers to work #include "SkTypes.h" #if SK_SUPPORT_GPU && SK_ALLOW_STATIC_GLOBAL_INITIALIZERS #include "GrAutoLocaleSetter.h" #include "GrContextFactory.h" #include "GrContextPriv.h" #include "GrDrawOpTest.h" #include "GrDrawingManager.h" #include "GrPipeline.h" #include "GrRenderTargetContextPriv.h" #include "GrResourceProvider.h" #include "GrTest.h" #include "GrXferProcessor.h" #include "SkChecksum.h" #include "SkRandom.h" #include "Test.h" #include "ops/GrDrawOp.h" #include "effects/GrConfigConversionEffect.h" #include "effects/GrPorterDuffXferProcessor.h" #include "effects/GrXfermodeFragmentProcessor.h" #include "gl/GrGLGpu.h" #include "glsl/GrGLSLFragmentProcessor.h" #include "glsl/GrGLSLFragmentShaderBuilder.h" #include "glsl/GrGLSLProgramBuilder.h" /* * A dummy processor which just tries to insert a massive key and verify that it can retrieve the * whole thing correctly */ static const uint32_t kMaxKeySize = 1024; class GLBigKeyProcessor : public GrGLSLFragmentProcessor { public: void emitCode(EmitArgs& args) override { // pass through GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder; if (args.fInputColor) { fragBuilder->codeAppendf("%s = %s;\n", args.fOutputColor, args.fInputColor); } else { fragBuilder->codeAppendf("%s = vec4(1.0);\n", args.fOutputColor); } } static void GenKey(const GrProcessor&, const GrShaderCaps&, GrProcessorKeyBuilder* b) { for (uint32_t i = 0; i < kMaxKeySize; i++) { b->add32(i); } } private: typedef GrGLSLFragmentProcessor INHERITED; }; class BigKeyProcessor : public GrFragmentProcessor { public: static sk_sp<GrFragmentProcessor> Make() { return sk_sp<GrFragmentProcessor>(new BigKeyProcessor); } const char* name() const override { return "Big Ole Key"; } GrGLSLFragmentProcessor* onCreateGLSLInstance() const override { return new GLBigKeyProcessor; } private: BigKeyProcessor() : INHERITED(kNone_OptimizationFlags) { this->initClassID<BigKeyProcessor>(); } virtual void onGetGLSLProcessorKey(const GrShaderCaps& caps, GrProcessorKeyBuilder* b) const override { GLBigKeyProcessor::GenKey(*this, caps, b); } bool onIsEqual(const GrFragmentProcessor&) const override { return true; } GR_DECLARE_FRAGMENT_PROCESSOR_TEST; typedef GrFragmentProcessor INHERITED; }; GR_DEFINE_FRAGMENT_PROCESSOR_TEST(BigKeyProcessor); #if GR_TEST_UTILS sk_sp<GrFragmentProcessor> BigKeyProcessor::TestCreate(GrProcessorTestData*) { return BigKeyProcessor::Make(); } #endif ////////////////////////////////////////////////////////////////////////////// class BlockInputFragmentProcessor : public GrFragmentProcessor { public: static sk_sp<GrFragmentProcessor> Make(sk_sp<GrFragmentProcessor> fp) { return sk_sp<GrFragmentProcessor>(new BlockInputFragmentProcessor(fp)); } const char* name() const override { return "Block Input"; } GrGLSLFragmentProcessor* onCreateGLSLInstance() const override { return new GLFP; } private: class GLFP : public GrGLSLFragmentProcessor { public: void emitCode(EmitArgs& args) override { this->emitChild(0, args); } private: typedef GrGLSLFragmentProcessor INHERITED; }; BlockInputFragmentProcessor(sk_sp<GrFragmentProcessor> child) : INHERITED(kNone_OptimizationFlags) { this->initClassID<BlockInputFragmentProcessor>(); this->registerChildProcessor(std::move(child)); } void onGetGLSLProcessorKey(const GrShaderCaps& caps, GrProcessorKeyBuilder* b) const override {} bool onIsEqual(const GrFragmentProcessor&) const override { return true; } typedef GrFragmentProcessor INHERITED; }; ////////////////////////////////////////////////////////////////////////////// /* * Begin test code */ static const int kRenderTargetHeight = 1; static const int kRenderTargetWidth = 1; static sk_sp<GrRenderTargetContext> random_render_target_context(GrContext* context, SkRandom* random, const GrCaps* caps) { GrSurfaceOrigin origin = random->nextBool() ? kTopLeft_GrSurfaceOrigin : kBottomLeft_GrSurfaceOrigin; int sampleCnt = random->nextBool() ? SkTMin(4, caps->maxSampleCount()) : 0; sk_sp<GrRenderTargetContext> renderTargetContext(context->makeDeferredRenderTargetContext( SkBackingFit::kExact, kRenderTargetWidth, kRenderTargetHeight, kRGBA_8888_GrPixelConfig, nullptr, sampleCnt, origin)); return renderTargetContext; } #if GR_TEST_UTILS static void set_random_xpf(GrPaint* paint, GrProcessorTestData* d) { paint->setXPFactory(GrXPFactoryTestFactory::Get(d)); } static sk_sp<GrFragmentProcessor> create_random_proc_tree(GrProcessorTestData* d, int minLevels, int maxLevels) { SkASSERT(1 <= minLevels); SkASSERT(minLevels <= maxLevels); // Return a leaf node if maxLevels is 1 or if we randomly chose to terminate. // If returning a leaf node, make sure that it doesn't have children (e.g. another // GrComposeEffect) const float terminateProbability = 0.3f; if (1 == minLevels) { bool terminate = (1 == maxLevels) || (d->fRandom->nextF() < terminateProbability); if (terminate) { sk_sp<GrFragmentProcessor> fp; while (true) { fp = GrProcessorTestFactory<GrFragmentProcessor>::Make(d); SkASSERT(fp); if (0 == fp->numChildProcessors()) { break; } } return fp; } } // If we didn't terminate, choose either the left or right subtree to fulfill // the minLevels requirement of this tree; the other child can have as few levels as it wants. // Also choose a random xfer mode. if (minLevels > 1) { --minLevels; } sk_sp<GrFragmentProcessor> minLevelsChild(create_random_proc_tree(d, minLevels, maxLevels - 1)); sk_sp<GrFragmentProcessor> otherChild(create_random_proc_tree(d, 1, maxLevels - 1)); SkBlendMode mode = static_cast<SkBlendMode>(d->fRandom->nextRangeU(0, (int)SkBlendMode::kLastMode)); sk_sp<GrFragmentProcessor> fp; if (d->fRandom->nextF() < 0.5f) { fp = GrXfermodeFragmentProcessor::MakeFromTwoProcessors(std::move(minLevelsChild), std::move(otherChild), mode); SkASSERT(fp); } else { fp = GrXfermodeFragmentProcessor::MakeFromTwoProcessors(std::move(otherChild), std::move(minLevelsChild), mode); SkASSERT(fp); } return fp; } static void set_random_color_coverage_stages(GrPaint* paint, GrProcessorTestData* d, int maxStages) { // Randomly choose to either create a linear pipeline of procs or create one proc tree const float procTreeProbability = 0.5f; if (d->fRandom->nextF() < procTreeProbability) { // A full tree with 5 levels (31 nodes) may cause a program that exceeds shader limits // (e.g. uniform or varying limits); maxTreeLevels should be a number from 1 to 4 inclusive. const int maxTreeLevels = 4; sk_sp<GrFragmentProcessor> fp(create_random_proc_tree(d, 2, maxTreeLevels)); paint->addColorFragmentProcessor(std::move(fp)); } else { int numProcs = d->fRandom->nextULessThan(maxStages + 1); int numColorProcs = d->fRandom->nextULessThan(numProcs + 1); for (int s = 0; s < numProcs;) { sk_sp<GrFragmentProcessor> fp(GrProcessorTestFactory<GrFragmentProcessor>::Make(d)); SkASSERT(fp); // finally add the stage to the correct pipeline in the drawstate if (s < numColorProcs) { paint->addColorFragmentProcessor(std::move(fp)); } else { paint->addCoverageFragmentProcessor(std::move(fp)); } ++s; } } } static void set_random_state(GrPaint* paint, SkRandom* random) { if (random->nextBool()) { paint->setDisableOutputConversionToSRGB(true); } if (random->nextBool()) { paint->setAllowSRGBInputs(true); } } #endif #if !GR_TEST_UTILS bool GrDrawingManager::ProgramUnitTest(GrContext*, int) { return true; } #else bool GrDrawingManager::ProgramUnitTest(GrContext* context, int maxStages) { GrDrawingManager* drawingManager = context->contextPriv().drawingManager(); sk_sp<GrTextureProxy> proxies[2]; // setup dummy textures GrSurfaceDesc dummyDesc; dummyDesc.fFlags = kRenderTarget_GrSurfaceFlag; dummyDesc.fOrigin = kBottomLeft_GrSurfaceOrigin; dummyDesc.fConfig = kRGBA_8888_GrPixelConfig; dummyDesc.fWidth = 34; dummyDesc.fHeight = 18; proxies[0] = GrSurfaceProxy::MakeDeferred(context->resourceProvider(), dummyDesc, SkBudgeted::kNo, nullptr, 0); dummyDesc.fFlags = kNone_GrSurfaceFlags; dummyDesc.fOrigin = kTopLeft_GrSurfaceOrigin; dummyDesc.fConfig = kAlpha_8_GrPixelConfig; dummyDesc.fWidth = 16; dummyDesc.fHeight = 22; proxies[1] = GrSurfaceProxy::MakeDeferred(context->resourceProvider(), dummyDesc, SkBudgeted::kNo, nullptr, 0); if (!proxies[0] || !proxies[1]) { SkDebugf("Could not allocate dummy textures"); return false; } // dummy scissor state GrScissorState scissor; SkRandom random; static const int NUM_TESTS = 1024; for (int t = 0; t < NUM_TESTS; t++) { // setup random render target(can fail) sk_sp<GrRenderTargetContext> renderTargetContext(random_render_target_context( context, &random, context->caps())); if (!renderTargetContext) { SkDebugf("Could not allocate renderTargetContext"); return false; } GrPaint paint; GrProcessorTestData ptd(&random, context, renderTargetContext.get(), proxies); set_random_color_coverage_stages(&paint, &ptd, maxStages); set_random_xpf(&paint, &ptd); set_random_state(&paint, &random); GrDrawRandomOp(&random, renderTargetContext.get(), std::move(paint)); } // Flush everything, test passes if flush is successful(ie, no asserts are hit, no crashes) drawingManager->flush(nullptr); // Validate that GrFPs work correctly without an input. sk_sp<GrRenderTargetContext> renderTargetContext(context->makeDeferredRenderTargetContext( SkBackingFit::kExact, kRenderTargetWidth, kRenderTargetHeight, kRGBA_8888_GrPixelConfig, nullptr)); if (!renderTargetContext) { SkDebugf("Could not allocate a renderTargetContext"); return false; } int fpFactoryCnt = GrProcessorTestFactory<GrFragmentProcessor>::Count(); for (int i = 0; i < fpFactoryCnt; ++i) { // Since FP factories internally randomize, call each 10 times. for (int j = 0; j < 10; ++j) { GrProcessorTestData ptd(&random, context, renderTargetContext.get(), proxies); GrPaint paint; paint.setXPFactory(GrPorterDuffXPFactory::Get(SkBlendMode::kSrc)); sk_sp<GrFragmentProcessor> fp( GrProcessorTestFactory<GrFragmentProcessor>::MakeIdx(i, &ptd)); sk_sp<GrFragmentProcessor> blockFP( BlockInputFragmentProcessor::Make(std::move(fp))); paint.addColorFragmentProcessor(std::move(blockFP)); GrDrawRandomOp(&random, renderTargetContext.get(), std::move(paint)); drawingManager->flush(nullptr); } } return true; } #endif static int get_glprograms_max_stages(GrContext* context) { GrGLGpu* gpu = static_cast<GrGLGpu*>(context->getGpu()); int maxStages = 6; if (kGLES_GrGLStandard == gpu->glStandard()) { // We've had issues with driver crashes and HW limits being exceeded with many effects on // Android devices. We have passes on ARM devices with the default number of stages. // TODO When we run ES 3.00 GLSL in more places, test again #ifdef SK_BUILD_FOR_ANDROID if (kARM_GrGLVendor != gpu->ctxInfo().vendor()) { maxStages = 1; } #endif // On iOS we can exceed the maximum number of varyings. http://skbug.com/6627. #ifdef SK_BUILD_FOR_IOS maxStages = 3; #endif } return maxStages; } static void test_glprograms(skiatest::Reporter* reporter, const sk_gpu_test::ContextInfo& ctxInfo) { int maxStages = get_glprograms_max_stages(ctxInfo.grContext()); if (maxStages == 0) { return; } REPORTER_ASSERT(reporter, GrDrawingManager::ProgramUnitTest(ctxInfo.grContext(), maxStages)); } DEF_GPUTEST(GLPrograms, reporter, /*factory*/) { // Set a locale that would cause shader compilation to fail because of , as decimal separator. // skbug 3330 #ifdef SK_BUILD_FOR_WIN GrAutoLocaleSetter als("sv-SE"); #else GrAutoLocaleSetter als("sv_SE.UTF-8"); #endif // We suppress prints to avoid spew GrContextOptions opts; opts.fSuppressPrints = true; sk_gpu_test::GrContextFactory debugFactory(opts); skiatest::RunWithGPUTestContexts(test_glprograms, &skiatest::IsRenderingGLContextType, reporter, &debugFactory); } #endif <commit_msg>Reduce tree depth on iOS too<commit_after>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // This is a GPU-backend specific test. It relies on static intializers to work #include "SkTypes.h" #if SK_SUPPORT_GPU && SK_ALLOW_STATIC_GLOBAL_INITIALIZERS #include "GrAutoLocaleSetter.h" #include "GrContextFactory.h" #include "GrContextPriv.h" #include "GrDrawOpTest.h" #include "GrDrawingManager.h" #include "GrPipeline.h" #include "GrRenderTargetContextPriv.h" #include "GrResourceProvider.h" #include "GrTest.h" #include "GrXferProcessor.h" #include "SkChecksum.h" #include "SkRandom.h" #include "Test.h" #include "ops/GrDrawOp.h" #include "effects/GrConfigConversionEffect.h" #include "effects/GrPorterDuffXferProcessor.h" #include "effects/GrXfermodeFragmentProcessor.h" #include "gl/GrGLGpu.h" #include "glsl/GrGLSLFragmentProcessor.h" #include "glsl/GrGLSLFragmentShaderBuilder.h" #include "glsl/GrGLSLProgramBuilder.h" /* * A dummy processor which just tries to insert a massive key and verify that it can retrieve the * whole thing correctly */ static const uint32_t kMaxKeySize = 1024; class GLBigKeyProcessor : public GrGLSLFragmentProcessor { public: void emitCode(EmitArgs& args) override { // pass through GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder; if (args.fInputColor) { fragBuilder->codeAppendf("%s = %s;\n", args.fOutputColor, args.fInputColor); } else { fragBuilder->codeAppendf("%s = vec4(1.0);\n", args.fOutputColor); } } static void GenKey(const GrProcessor&, const GrShaderCaps&, GrProcessorKeyBuilder* b) { for (uint32_t i = 0; i < kMaxKeySize; i++) { b->add32(i); } } private: typedef GrGLSLFragmentProcessor INHERITED; }; class BigKeyProcessor : public GrFragmentProcessor { public: static sk_sp<GrFragmentProcessor> Make() { return sk_sp<GrFragmentProcessor>(new BigKeyProcessor); } const char* name() const override { return "Big Ole Key"; } GrGLSLFragmentProcessor* onCreateGLSLInstance() const override { return new GLBigKeyProcessor; } private: BigKeyProcessor() : INHERITED(kNone_OptimizationFlags) { this->initClassID<BigKeyProcessor>(); } virtual void onGetGLSLProcessorKey(const GrShaderCaps& caps, GrProcessorKeyBuilder* b) const override { GLBigKeyProcessor::GenKey(*this, caps, b); } bool onIsEqual(const GrFragmentProcessor&) const override { return true; } GR_DECLARE_FRAGMENT_PROCESSOR_TEST; typedef GrFragmentProcessor INHERITED; }; GR_DEFINE_FRAGMENT_PROCESSOR_TEST(BigKeyProcessor); #if GR_TEST_UTILS sk_sp<GrFragmentProcessor> BigKeyProcessor::TestCreate(GrProcessorTestData*) { return BigKeyProcessor::Make(); } #endif ////////////////////////////////////////////////////////////////////////////// class BlockInputFragmentProcessor : public GrFragmentProcessor { public: static sk_sp<GrFragmentProcessor> Make(sk_sp<GrFragmentProcessor> fp) { return sk_sp<GrFragmentProcessor>(new BlockInputFragmentProcessor(fp)); } const char* name() const override { return "Block Input"; } GrGLSLFragmentProcessor* onCreateGLSLInstance() const override { return new GLFP; } private: class GLFP : public GrGLSLFragmentProcessor { public: void emitCode(EmitArgs& args) override { this->emitChild(0, args); } private: typedef GrGLSLFragmentProcessor INHERITED; }; BlockInputFragmentProcessor(sk_sp<GrFragmentProcessor> child) : INHERITED(kNone_OptimizationFlags) { this->initClassID<BlockInputFragmentProcessor>(); this->registerChildProcessor(std::move(child)); } void onGetGLSLProcessorKey(const GrShaderCaps& caps, GrProcessorKeyBuilder* b) const override {} bool onIsEqual(const GrFragmentProcessor&) const override { return true; } typedef GrFragmentProcessor INHERITED; }; ////////////////////////////////////////////////////////////////////////////// /* * Begin test code */ static const int kRenderTargetHeight = 1; static const int kRenderTargetWidth = 1; static sk_sp<GrRenderTargetContext> random_render_target_context(GrContext* context, SkRandom* random, const GrCaps* caps) { GrSurfaceOrigin origin = random->nextBool() ? kTopLeft_GrSurfaceOrigin : kBottomLeft_GrSurfaceOrigin; int sampleCnt = random->nextBool() ? SkTMin(4, caps->maxSampleCount()) : 0; sk_sp<GrRenderTargetContext> renderTargetContext(context->makeDeferredRenderTargetContext( SkBackingFit::kExact, kRenderTargetWidth, kRenderTargetHeight, kRGBA_8888_GrPixelConfig, nullptr, sampleCnt, origin)); return renderTargetContext; } #if GR_TEST_UTILS static void set_random_xpf(GrPaint* paint, GrProcessorTestData* d) { paint->setXPFactory(GrXPFactoryTestFactory::Get(d)); } static sk_sp<GrFragmentProcessor> create_random_proc_tree(GrProcessorTestData* d, int minLevels, int maxLevels) { SkASSERT(1 <= minLevels); SkASSERT(minLevels <= maxLevels); // Return a leaf node if maxLevels is 1 or if we randomly chose to terminate. // If returning a leaf node, make sure that it doesn't have children (e.g. another // GrComposeEffect) const float terminateProbability = 0.3f; if (1 == minLevels) { bool terminate = (1 == maxLevels) || (d->fRandom->nextF() < terminateProbability); if (terminate) { sk_sp<GrFragmentProcessor> fp; while (true) { fp = GrProcessorTestFactory<GrFragmentProcessor>::Make(d); SkASSERT(fp); if (0 == fp->numChildProcessors()) { break; } } return fp; } } // If we didn't terminate, choose either the left or right subtree to fulfill // the minLevels requirement of this tree; the other child can have as few levels as it wants. // Also choose a random xfer mode. if (minLevels > 1) { --minLevels; } sk_sp<GrFragmentProcessor> minLevelsChild(create_random_proc_tree(d, minLevels, maxLevels - 1)); sk_sp<GrFragmentProcessor> otherChild(create_random_proc_tree(d, 1, maxLevels - 1)); SkBlendMode mode = static_cast<SkBlendMode>(d->fRandom->nextRangeU(0, (int)SkBlendMode::kLastMode)); sk_sp<GrFragmentProcessor> fp; if (d->fRandom->nextF() < 0.5f) { fp = GrXfermodeFragmentProcessor::MakeFromTwoProcessors(std::move(minLevelsChild), std::move(otherChild), mode); SkASSERT(fp); } else { fp = GrXfermodeFragmentProcessor::MakeFromTwoProcessors(std::move(otherChild), std::move(minLevelsChild), mode); SkASSERT(fp); } return fp; } static void set_random_color_coverage_stages(GrPaint* paint, GrProcessorTestData* d, int maxStages) { // Randomly choose to either create a linear pipeline of procs or create one proc tree const float procTreeProbability = 0.5f; if (d->fRandom->nextF() < procTreeProbability) { // A full tree with 5 levels (31 nodes) may cause a program that exceeds shader limits // (e.g. uniform or varying limits); maxTreeLevels should be a number from 1 to 4 inclusive. int maxTreeLevels = 4; // On iOS we can exceed the maximum number of varyings. http://skbug.com/6627. #ifdef SK_BUILD_FOR_IOS maxTreeLevels = 2; #endif sk_sp<GrFragmentProcessor> fp(create_random_proc_tree(d, 2, maxTreeLevels)); paint->addColorFragmentProcessor(std::move(fp)); } else { int numProcs = d->fRandom->nextULessThan(maxStages + 1); int numColorProcs = d->fRandom->nextULessThan(numProcs + 1); for (int s = 0; s < numProcs;) { sk_sp<GrFragmentProcessor> fp(GrProcessorTestFactory<GrFragmentProcessor>::Make(d)); SkASSERT(fp); // finally add the stage to the correct pipeline in the drawstate if (s < numColorProcs) { paint->addColorFragmentProcessor(std::move(fp)); } else { paint->addCoverageFragmentProcessor(std::move(fp)); } ++s; } } } static void set_random_state(GrPaint* paint, SkRandom* random) { if (random->nextBool()) { paint->setDisableOutputConversionToSRGB(true); } if (random->nextBool()) { paint->setAllowSRGBInputs(true); } } #endif #if !GR_TEST_UTILS bool GrDrawingManager::ProgramUnitTest(GrContext*, int) { return true; } #else bool GrDrawingManager::ProgramUnitTest(GrContext* context, int maxStages) { GrDrawingManager* drawingManager = context->contextPriv().drawingManager(); sk_sp<GrTextureProxy> proxies[2]; // setup dummy textures GrSurfaceDesc dummyDesc; dummyDesc.fFlags = kRenderTarget_GrSurfaceFlag; dummyDesc.fOrigin = kBottomLeft_GrSurfaceOrigin; dummyDesc.fConfig = kRGBA_8888_GrPixelConfig; dummyDesc.fWidth = 34; dummyDesc.fHeight = 18; proxies[0] = GrSurfaceProxy::MakeDeferred(context->resourceProvider(), dummyDesc, SkBudgeted::kNo, nullptr, 0); dummyDesc.fFlags = kNone_GrSurfaceFlags; dummyDesc.fOrigin = kTopLeft_GrSurfaceOrigin; dummyDesc.fConfig = kAlpha_8_GrPixelConfig; dummyDesc.fWidth = 16; dummyDesc.fHeight = 22; proxies[1] = GrSurfaceProxy::MakeDeferred(context->resourceProvider(), dummyDesc, SkBudgeted::kNo, nullptr, 0); if (!proxies[0] || !proxies[1]) { SkDebugf("Could not allocate dummy textures"); return false; } // dummy scissor state GrScissorState scissor; SkRandom random; static const int NUM_TESTS = 1024; for (int t = 0; t < NUM_TESTS; t++) { // setup random render target(can fail) sk_sp<GrRenderTargetContext> renderTargetContext(random_render_target_context( context, &random, context->caps())); if (!renderTargetContext) { SkDebugf("Could not allocate renderTargetContext"); return false; } GrPaint paint; GrProcessorTestData ptd(&random, context, renderTargetContext.get(), proxies); set_random_color_coverage_stages(&paint, &ptd, maxStages); set_random_xpf(&paint, &ptd); set_random_state(&paint, &random); GrDrawRandomOp(&random, renderTargetContext.get(), std::move(paint)); } // Flush everything, test passes if flush is successful(ie, no asserts are hit, no crashes) drawingManager->flush(nullptr); // Validate that GrFPs work correctly without an input. sk_sp<GrRenderTargetContext> renderTargetContext(context->makeDeferredRenderTargetContext( SkBackingFit::kExact, kRenderTargetWidth, kRenderTargetHeight, kRGBA_8888_GrPixelConfig, nullptr)); if (!renderTargetContext) { SkDebugf("Could not allocate a renderTargetContext"); return false; } int fpFactoryCnt = GrProcessorTestFactory<GrFragmentProcessor>::Count(); for (int i = 0; i < fpFactoryCnt; ++i) { // Since FP factories internally randomize, call each 10 times. for (int j = 0; j < 10; ++j) { GrProcessorTestData ptd(&random, context, renderTargetContext.get(), proxies); GrPaint paint; paint.setXPFactory(GrPorterDuffXPFactory::Get(SkBlendMode::kSrc)); sk_sp<GrFragmentProcessor> fp( GrProcessorTestFactory<GrFragmentProcessor>::MakeIdx(i, &ptd)); sk_sp<GrFragmentProcessor> blockFP( BlockInputFragmentProcessor::Make(std::move(fp))); paint.addColorFragmentProcessor(std::move(blockFP)); GrDrawRandomOp(&random, renderTargetContext.get(), std::move(paint)); drawingManager->flush(nullptr); } } return true; } #endif static int get_glprograms_max_stages(GrContext* context) { GrGLGpu* gpu = static_cast<GrGLGpu*>(context->getGpu()); int maxStages = 6; if (kGLES_GrGLStandard == gpu->glStandard()) { // We've had issues with driver crashes and HW limits being exceeded with many effects on // Android devices. We have passes on ARM devices with the default number of stages. // TODO When we run ES 3.00 GLSL in more places, test again #ifdef SK_BUILD_FOR_ANDROID if (kARM_GrGLVendor != gpu->ctxInfo().vendor()) { maxStages = 1; } #endif // On iOS we can exceed the maximum number of varyings. http://skbug.com/6627. #ifdef SK_BUILD_FOR_IOS maxStages = 3; #endif } return maxStages; } static void test_glprograms(skiatest::Reporter* reporter, const sk_gpu_test::ContextInfo& ctxInfo) { int maxStages = get_glprograms_max_stages(ctxInfo.grContext()); if (maxStages == 0) { return; } REPORTER_ASSERT(reporter, GrDrawingManager::ProgramUnitTest(ctxInfo.grContext(), maxStages)); } DEF_GPUTEST(GLPrograms, reporter, /*factory*/) { // Set a locale that would cause shader compilation to fail because of , as decimal separator. // skbug 3330 #ifdef SK_BUILD_FOR_WIN GrAutoLocaleSetter als("sv-SE"); #else GrAutoLocaleSetter als("sv_SE.UTF-8"); #endif // We suppress prints to avoid spew GrContextOptions opts; opts.fSuppressPrints = true; sk_gpu_test::GrContextFactory debugFactory(opts); skiatest::RunWithGPUTestContexts(test_glprograms, &skiatest::IsRenderingGLContextType, reporter, &debugFactory); } #endif <|endoftext|>
<commit_before>/***************************************************************************** * Project: RooFit * * Package: RooFitModels * * @(#)root/roofit:$Id$ * Authors: * * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * * * * Copyright (c) 2000-2005, Regents of the University of California * * and Stanford University. All rights reserved. * * * * Redistribution and use in source and binary forms, * * with or without modification, are permitted according to the terms * * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ /** \class RooPolynomial \ingroup Roofit RooPolynomial implements a polynomial p.d.f of the form \f[ f(x) = \mathcal{N} \cdot \sum_{i} a_{i} * x^i \f] By default, the coefficient \f$ a_0 \f$ is chosen to be 1, as polynomial probability density functions have one degree of freedom less than polynomial functions due to the normalisation condition. \f$ \mathcal{N} \f$ is a normalisation constant that is automatically calculated when the polynomial is used in computations. The sum can be truncated at the low end. See the main constructor RooPolynomial::RooPolynomial(const char*, const char*, RooAbsReal&, const RooArgList&, Int_t) **/ #include "RooPolynomial.h" #include "RooAbsReal.h" #include "RooArgList.h" #include "RooMsgService.h" #include "BatchHelpers.h" #include "TError.h" #include <cmath> #include <cassert> #include <vector> using namespace std; ClassImp(RooPolynomial); //////////////////////////////////////////////////////////////////////////////// /// coverity[UNINIT_CTOR] RooPolynomial::RooPolynomial() { } //////////////////////////////////////////////////////////////////////////////// /// Create a polynomial in the variable `x`. /// \param[in] name Name of the PDF /// \param[in] title Title for plotting the PDF /// \param[in] x The variable of the polynomial /// \param[in] coefList The coefficients \f$ a_i \f$ /// \param[in] lowestOrder [optional] Truncate the sum such that it skips the lower orders: /// \f[ /// 1. + \sum_{i=0}^{\mathrm{coefList.size()}} a_{i} * x^{(i + \mathrm{lowestOrder})} /// \f] /// /// This means that /// \code{.cpp} /// RooPolynomial pol("pol", "pol", x, RooArgList(a, b), lowestOrder = 2) /// \endcode /// computes /// \f[ /// \mathrm{pol}(x) = 1 * x^0 + (0 * x^{\ldots}) + a * x^2 + b * x^3. /// \f] RooPolynomial::RooPolynomial(const char* name, const char* title, RooAbsReal& x, const RooArgList& coefList, Int_t lowestOrder) : RooAbsPdf(name, title), _x("x", "Dependent", this, x), _coefList("coefList","List of coefficients",this), _lowestOrder(lowestOrder) { // Check lowest order if (_lowestOrder<0) { coutE(InputArguments) << "RooPolynomial::ctor(" << GetName() << ") WARNING: lowestOrder must be >=0, setting value to 0" << endl ; _lowestOrder=0 ; } RooFIter coefIter = coefList.fwdIterator() ; RooAbsArg* coef ; while((coef = (RooAbsArg*)coefIter.next())) { if (!dynamic_cast<RooAbsReal*>(coef)) { coutE(InputArguments) << "RooPolynomial::ctor(" << GetName() << ") ERROR: coefficient " << coef->GetName() << " is not of type RooAbsReal" << endl ; R__ASSERT(0) ; } _coefList.add(*coef) ; } } //////////////////////////////////////////////////////////////////////////////// RooPolynomial::RooPolynomial(const char* name, const char* title, RooAbsReal& x) : RooAbsPdf(name, title), _x("x", "Dependent", this, x), _coefList("coefList","List of coefficients",this), _lowestOrder(1) { } //////////////////////////////////////////////////////////////////////////////// /// Copy constructor RooPolynomial::RooPolynomial(const RooPolynomial& other, const char* name) : RooAbsPdf(other, name), _x("x", this, other._x), _coefList("coefList",this,other._coefList), _lowestOrder(other._lowestOrder) { } //////////////////////////////////////////////////////////////////////////////// /// Destructor RooPolynomial::~RooPolynomial() { } //////////////////////////////////////////////////////////////////////////////// Double_t RooPolynomial::evaluate() const { // Calculate and return value of polynomial const unsigned sz = _coefList.getSize(); const int lowestOrder = _lowestOrder; if (!sz) return lowestOrder ? 1. : 0.; _wksp.clear(); _wksp.reserve(sz); { const RooArgSet* nset = _coefList.nset(); RooFIter it = _coefList.fwdIterator(); RooAbsReal* c; while ((c = (RooAbsReal*) it.next())) _wksp.push_back(c->getVal(nset)); } const Double_t x = _x; Double_t retVal = _wksp[sz - 1]; for (unsigned i = sz - 1; i--; ) retVal = _wksp[i] + x * retVal; return retVal * std::pow(x, lowestOrder) + (lowestOrder ? 1.0 : 0.0); } //////////////////////////////////////////////////////////////////////////////// namespace PolynomialEvaluate{ //Author: Emmanouil Michalainas, CERN 15 AUGUST 2019 void compute( size_t batchSize, const int lowestOrder, double * __restrict__ output, const double * __restrict__ const X, const std::vector<BatchHelpers::BracketAdapterWithMask>& coefList ) { const int nCoef = coefList.size(); if (nCoef==0 && lowestOrder==0) { for (size_t i=0; i<batchSize; i++) { output[i] = 0.0; } } else if (nCoef==0 && lowestOrder>0) { for (size_t i=0; i<batchSize; i++) { output[i] = 1.0; } } else { for (size_t i=0; i<batchSize; i++) { output[i] = coefList[nCoef-1][i]; } } if (nCoef == 0) return; /* Indexes are in range 0..nCoef-1 but coefList[nCoef-1] * has already been processed. In order to traverse the list, * with step of 2 we have to start at index nCoef-3 and use * coefList[k+1] and coefList[k] */ for (int k=nCoef-3; k>=0; k-=2) { for (size_t i=0; i<batchSize; i++) { double coef1 = coefList[k+1][i]; double coef2 = coefList[ k ][i]; output[i] = X[i]*(output[i]*X[i] + coef1) + coef2; } } // If nCoef is odd, then the coefList[0] didn't get processed if (nCoef%2 == 0) { for (size_t i=0; i<batchSize; i++) { output[i] = output[i]*X[i] + coefList[0][i]; } } //Increase the order of the polynomial, first by myltiplying with X[i]^2 if (lowestOrder == 0) return; for (int k=2; k<=lowestOrder; k+=2) { for (size_t i=0; i<batchSize; i++) { output[i] *= X[i]*X[i]; } } const bool isOdd = lowestOrder%2; for (size_t i=0; i<batchSize; i++) { if (isOdd) output[i] *= X[i]; output[i] += 1.0; } } }; //////////////////////////////////////////////////////////////////////////////// RooSpan<double> RooPolynomial::evaluateBatch(std::size_t begin, std::size_t batchSize) const { RooSpan<const double> xData = _x.getValBatch(begin, batchSize); batchSize = xData.size(); if (xData.empty()) { return {}; } auto output = _batchData.makeWritableBatchUnInit(begin, batchSize); const int nCoef = _coefList.getSize(); const RooArgSet* normSet = _coefList.nset(); std::vector<BatchHelpers::BracketAdapterWithMask> coefList; for (int i=0; i<nCoef; i++) { auto val = static_cast<RooAbsReal&>(_coefList[i]).getVal(normSet); auto valBatch = static_cast<RooAbsReal&>(_coefList[i]).getValBatch(begin, batchSize, normSet); coefList.push_back( BatchHelpers::BracketAdapterWithMask(val, valBatch) ); } PolynomialEvaluate::compute(batchSize, _lowestOrder, output.data(), xData.data(), coefList); return output; } //////////////////////////////////////////////////////////////////////////////// /// Advertise to RooFit that this function can be analytically integrated. Int_t RooPolynomial::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* /*rangeName*/) const { if (matchArgs(allVars, analVars, _x)) return 1; return 0; } //////////////////////////////////////////////////////////////////////////////// /// Do the analytical integral according to the code that was returned by getAnalyticalIntegral(). Double_t RooPolynomial::analyticalIntegral(Int_t code, const char* rangeName) const { R__ASSERT(code==1) ; const Double_t xmin = _x.min(rangeName), xmax = _x.max(rangeName); const int lowestOrder = _lowestOrder; const unsigned sz = _coefList.getSize(); if (!sz) return xmax - xmin; _wksp.clear(); _wksp.reserve(sz); { const RooArgSet* nset = _coefList.nset(); RooFIter it = _coefList.fwdIterator(); unsigned i = 1 + lowestOrder; RooAbsReal* c; while ((c = (RooAbsReal*) it.next())) { _wksp.push_back(c->getVal(nset) / Double_t(i)); ++i; } } Double_t min = _wksp[sz - 1], max = _wksp[sz - 1]; for (unsigned i = sz - 1; i--; ) min = _wksp[i] + xmin * min, max = _wksp[i] + xmax * max; return max * std::pow(xmax, 1 + lowestOrder) - min * std::pow(xmin, 1 + lowestOrder) + (lowestOrder ? (xmax - xmin) : 0.); } <commit_msg>[RF] Fix batch implementation of RooPolynomial.<commit_after>/***************************************************************************** * Project: RooFit * * Package: RooFitModels * * @(#)root/roofit:$Id$ * Authors: * * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu * * DK, David Kirkby, UC Irvine, dkirkby@uci.edu * * * * Copyright (c) 2000-2005, Regents of the University of California * * and Stanford University. All rights reserved. * * * * Redistribution and use in source and binary forms, * * with or without modification, are permitted according to the terms * * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ /** \class RooPolynomial \ingroup Roofit RooPolynomial implements a polynomial p.d.f of the form \f[ f(x) = \mathcal{N} \cdot \sum_{i} a_{i} * x^i \f] By default, the coefficient \f$ a_0 \f$ is chosen to be 1, as polynomial probability density functions have one degree of freedom less than polynomial functions due to the normalisation condition. \f$ \mathcal{N} \f$ is a normalisation constant that is automatically calculated when the polynomial is used in computations. The sum can be truncated at the low end. See the main constructor RooPolynomial::RooPolynomial(const char*, const char*, RooAbsReal&, const RooArgList&, Int_t) **/ #include "RooPolynomial.h" #include "RooAbsReal.h" #include "RooArgList.h" #include "RooMsgService.h" #include "BatchHelpers.h" #include "TError.h" #include <cmath> #include <cassert> #include <vector> using namespace std; ClassImp(RooPolynomial); //////////////////////////////////////////////////////////////////////////////// /// coverity[UNINIT_CTOR] RooPolynomial::RooPolynomial() { } //////////////////////////////////////////////////////////////////////////////// /// Create a polynomial in the variable `x`. /// \param[in] name Name of the PDF /// \param[in] title Title for plotting the PDF /// \param[in] x The variable of the polynomial /// \param[in] coefList The coefficients \f$ a_i \f$ /// \param[in] lowestOrder [optional] Truncate the sum such that it skips the lower orders: /// \f[ /// 1. + \sum_{i=0}^{\mathrm{coefList.size()}} a_{i} * x^{(i + \mathrm{lowestOrder})} /// \f] /// /// This means that /// \code{.cpp} /// RooPolynomial pol("pol", "pol", x, RooArgList(a, b), lowestOrder = 2) /// \endcode /// computes /// \f[ /// \mathrm{pol}(x) = 1 * x^0 + (0 * x^{\ldots}) + a * x^2 + b * x^3. /// \f] RooPolynomial::RooPolynomial(const char* name, const char* title, RooAbsReal& x, const RooArgList& coefList, Int_t lowestOrder) : RooAbsPdf(name, title), _x("x", "Dependent", this, x), _coefList("coefList","List of coefficients",this), _lowestOrder(lowestOrder) { // Check lowest order if (_lowestOrder<0) { coutE(InputArguments) << "RooPolynomial::ctor(" << GetName() << ") WARNING: lowestOrder must be >=0, setting value to 0" << endl ; _lowestOrder=0 ; } RooFIter coefIter = coefList.fwdIterator() ; RooAbsArg* coef ; while((coef = (RooAbsArg*)coefIter.next())) { if (!dynamic_cast<RooAbsReal*>(coef)) { coutE(InputArguments) << "RooPolynomial::ctor(" << GetName() << ") ERROR: coefficient " << coef->GetName() << " is not of type RooAbsReal" << endl ; R__ASSERT(0) ; } _coefList.add(*coef) ; } } //////////////////////////////////////////////////////////////////////////////// RooPolynomial::RooPolynomial(const char* name, const char* title, RooAbsReal& x) : RooAbsPdf(name, title), _x("x", "Dependent", this, x), _coefList("coefList","List of coefficients",this), _lowestOrder(1) { } //////////////////////////////////////////////////////////////////////////////// /// Copy constructor RooPolynomial::RooPolynomial(const RooPolynomial& other, const char* name) : RooAbsPdf(other, name), _x("x", this, other._x), _coefList("coefList",this,other._coefList), _lowestOrder(other._lowestOrder) { } //////////////////////////////////////////////////////////////////////////////// /// Destructor RooPolynomial::~RooPolynomial() { } //////////////////////////////////////////////////////////////////////////////// Double_t RooPolynomial::evaluate() const { // Calculate and return value of polynomial const unsigned sz = _coefList.getSize(); const int lowestOrder = _lowestOrder; if (!sz) return lowestOrder ? 1. : 0.; _wksp.clear(); _wksp.reserve(sz); { const RooArgSet* nset = _coefList.nset(); RooFIter it = _coefList.fwdIterator(); RooAbsReal* c; while ((c = (RooAbsReal*) it.next())) _wksp.push_back(c->getVal(nset)); } const Double_t x = _x; Double_t retVal = _wksp[sz - 1]; for (unsigned i = sz - 1; i--; ) retVal = _wksp[i] + x * retVal; return retVal * std::pow(x, lowestOrder) + (lowestOrder ? 1.0 : 0.0); } //////////////////////////////////////////////////////////////////////////////// namespace { //Author: Emmanouil Michalainas, CERN 15 AUGUST 2019 void compute( size_t batchSize, const int lowestOrder, double * __restrict__ output, const double * __restrict__ const X, const std::vector<BatchHelpers::BracketAdapterWithMask>& coefList ) { const int nCoef = coefList.size(); if (nCoef==0 && lowestOrder==0) { for (size_t i=0; i<batchSize; i++) { output[i] = 0.0; } } else if (nCoef==0 && lowestOrder>0) { for (size_t i=0; i<batchSize; i++) { output[i] = 1.0; } } else { for (size_t i=0; i<batchSize; i++) { output[i] = coefList[nCoef-1][i]; } } if (nCoef == 0) return; /* Indexes are in range 0..nCoef-1 but coefList[nCoef-1] * has already been processed. In order to traverse the list, * with step of 2 we have to start at index nCoef-3 and use * coefList[k+1] and coefList[k] */ for (int k=nCoef-3; k>=0; k-=2) { for (size_t i=0; i<batchSize; i++) { double coef1 = coefList[k+1][i]; double coef2 = coefList[ k ][i]; output[i] = X[i]*(output[i]*X[i] + coef1) + coef2; } } // If nCoef is odd, then the coefList[0] didn't get processed if (nCoef%2 == 0) { for (size_t i=0; i<batchSize; i++) { output[i] = output[i]*X[i] + coefList[0][i]; } } //Increase the order of the polynomial, first by myltiplying with X[i]^2 if (lowestOrder == 0) return; for (int k=2; k<=lowestOrder; k+=2) { for (size_t i=0; i<batchSize; i++) { output[i] *= X[i]*X[i]; } } const bool isOdd = lowestOrder%2; for (size_t i=0; i<batchSize; i++) { if (isOdd) output[i] *= X[i]; output[i] += 1.0; } } }; //////////////////////////////////////////////////////////////////////////////// RooSpan<double> RooPolynomial::evaluateBatch(std::size_t begin, std::size_t batchSize) const { RooSpan<const double> xData = _x.getValBatch(begin, batchSize); batchSize = xData.size(); if (xData.empty()) { return {}; } auto output = _batchData.makeWritableBatchUnInit(begin, batchSize); const int nCoef = _coefList.getSize(); const RooArgSet* normSet = _coefList.nset(); std::vector<BatchHelpers::BracketAdapterWithMask> coefList; for (int i=0; i<nCoef; i++) { auto val = static_cast<RooAbsReal&>(_coefList[i]).getVal(normSet); auto valBatch = static_cast<RooAbsReal&>(_coefList[i]).getValBatch(begin, batchSize, normSet); coefList.push_back( BatchHelpers::BracketAdapterWithMask(val, valBatch) ); } compute(batchSize, _lowestOrder, output.data(), xData.data(), coefList); return output; } //////////////////////////////////////////////////////////////////////////////// /// Advertise to RooFit that this function can be analytically integrated. Int_t RooPolynomial::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars, const char* /*rangeName*/) const { if (matchArgs(allVars, analVars, _x)) return 1; return 0; } //////////////////////////////////////////////////////////////////////////////// /// Do the analytical integral according to the code that was returned by getAnalyticalIntegral(). Double_t RooPolynomial::analyticalIntegral(Int_t code, const char* rangeName) const { R__ASSERT(code==1) ; const Double_t xmin = _x.min(rangeName), xmax = _x.max(rangeName); const int lowestOrder = _lowestOrder; const unsigned sz = _coefList.getSize(); if (!sz) return xmax - xmin; _wksp.clear(); _wksp.reserve(sz); { const RooArgSet* nset = _coefList.nset(); RooFIter it = _coefList.fwdIterator(); unsigned i = 1 + lowestOrder; RooAbsReal* c; while ((c = (RooAbsReal*) it.next())) { _wksp.push_back(c->getVal(nset) / Double_t(i)); ++i; } } Double_t min = _wksp[sz - 1], max = _wksp[sz - 1]; for (unsigned i = sz - 1; i--; ) min = _wksp[i] + xmin * min, max = _wksp[i] + xmax * max; return max * std::pow(xmax, 1 + lowestOrder) - min * std::pow(xmin, 1 + lowestOrder) + (lowestOrder ? (xmax - xmin) : 0.); } <|endoftext|>
<commit_before>/* * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu) * * Released under the MIT license, see LICENSE.txt */ #include <cstdlib> #include <iostream> #include <fstream> #include <algorithm> #include "hal.h" using namespace std; using namespace hal; static void printSequenceLine(ostream& outStream, const Sequence* sequence, hal_size_t start, hal_size_t length, string& buffer); static void printSequence(ostream& outStream, const Sequence* sequence, hal_size_t lineWidth, hal_size_t start, hal_size_t length); static void printGenome(ostream& outStream, const Genome* genome, const Sequence* sequence, hal_size_t lineWidth, hal_size_t start, hal_size_t length); static const hal_size_t StringBufferSize = 1024; static CLParserPtr initParser() { CLParserPtr optionsParser = hdf5CLParserInstance(true); optionsParser->addArgument("inHalPath", "input hal file"); optionsParser->addArgument("genome", "genome to export"); optionsParser->addOption("outFaPath", "output fasta file (stdout if none)", "stdout"); optionsParser->addOption("lineWidth", "Line width for output", 80); optionsParser->addOption("sequence", "sequence name to export (" "all sequences by default)", "\"\""); optionsParser->addOption("start", "coordinate within reference genome (or sequence" " if specified) to start at", 0); optionsParser->addOption("length", "length of the reference genome (or sequence" " if specified) to convert. If set to 0," " the entire thing is converted", 0); optionsParser->setDescription("Export single genome from hal database to " "fasta file."); return optionsParser; } int main(int argc, char** argv) { CLParserPtr optionsParser = initParser(); string halPath; string faPath; hal_size_t lineWidth; string genomeName; string sequenceName; hal_size_t start; hal_size_t length; try { optionsParser->parseOptions(argc, argv); halPath = optionsParser->getArgument<string>("inHalPath"); genomeName = optionsParser->getArgument<string>("genome"); faPath = optionsParser->getOption<string>("outFaPath"); lineWidth = optionsParser->getOption<hal_size_t>("lineWidth"); sequenceName = optionsParser->getOption<string>("sequence"); start = optionsParser->getOption<hal_size_t>("start"); length = optionsParser->getOption<hal_size_t>("length"); } catch(exception& e) { cerr << e.what() << endl; optionsParser->printUsage(cerr); exit(1); } try { AlignmentConstPtr alignment = openHalAlignmentReadOnly(halPath, optionsParser); if (alignment->getNumGenomes() == 0) { throw hal_exception("input hal alignmenet is empty"); } const Genome* genome = alignment->openGenome(genomeName); if (genome == NULL) { throw hal_exception(string("Genome ") + genomeName + " not found"); } const Sequence* sequence = NULL; if (sequenceName != "\"\"") { sequence = genome->getSequence(sequenceName); if (sequence == NULL) { throw hal_exception(string("Sequence ") + sequenceName + " not found"); } } ofstream ofile; ostream& outStream = faPath == "stdout" ? cout : ofile; if (faPath != "stdout") { ofile.open(faPath.c_str()); if (!ofile) { throw hal_exception(string("Error opening output file ") + faPath); } } printGenome(outStream, genome, sequence, lineWidth, start, length); } catch(hal_exception& e) { cerr << "hal exception caught: " << e.what() << endl; return 1; } catch(exception& e) { cerr << "Exception caught: " << e.what() << endl; return 1; } return 0; } void printSequenceLine(ostream& outStream, const Sequence* sequence, hal_size_t start, hal_size_t length, string& buffer) { hal_size_t last = start + length; hal_size_t readLen; for (hal_size_t i = start; i < last; i += StringBufferSize) { readLen = std::min(StringBufferSize, last - i); sequence->getSubString(buffer, i, readLen); outStream << buffer; } } void printSequence(ostream& outStream, const Sequence* sequence, hal_size_t lineWidth, hal_size_t start, hal_size_t length) { hal_size_t seqLen = sequence->getSequenceLength(); if (length == 0) { length = seqLen - start; } hal_size_t last = start + length; if (last > seqLen) { stringstream ss; ss << "Specified range [" << start << "," << length << "] is" << "out of range for sequence " << sequence->getName() << ", which has length " << seqLen; throw (hal_exception(ss.str())); } outStream << '>' << sequence->getName() << '\n'; hal_size_t readLen; string buffer; for (hal_size_t i = start; i < last; i += lineWidth) { readLen = std::min(lineWidth, last - i); printSequenceLine(outStream, sequence, i, readLen, buffer); outStream << '\n'; } } void printGenome(ostream& outStream, const Genome* genome, const Sequence* sequence, hal_size_t lineWidth, hal_size_t start, hal_size_t length) { if (sequence != NULL) { printSequence(outStream, sequence, lineWidth, start, length); } else { if (start + length > genome->getSequenceLength()) { stringstream ss; ss << "Specified range [" << start << "," << length << "] is" << "out of range for genome " << genome->getName() << ", which has length " << genome->getSequenceLength(); throw (hal_exception(ss.str())); } if (length == 0) { length = genome->getSequenceLength() - start; } SequenceIteratorConstPtr seqIt = genome->getSequenceIterator(); SequenceIteratorConstPtr seqEndIt = genome->getSequenceEndIterator(); hal_size_t runningLength = 0; for (; seqIt != seqEndIt; seqIt->toNext()) { const Sequence* sequence = seqIt->getSequence(); hal_size_t seqLen = sequence->getSequenceLength(); hal_size_t seqStart = (hal_size_t)sequence->getStartPosition(); if (start + length >= seqStart && start < seqStart + seqLen && runningLength < length) { hal_size_t readStart = seqStart >= start ? 0 : seqStart - start; hal_size_t readLen = std::min(seqLen - start, length - runningLength); cerr << sequence->getName() << " (" << seqLen << ") " << readStart << " " << readLen << endl; printSequence(outStream, sequence, lineWidth, readStart, readLen); runningLength += readLen; } } } } <commit_msg>fix typos<commit_after>/* * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu) * * Released under the MIT license, see LICENSE.txt */ #include <cstdlib> #include <iostream> #include <fstream> #include <algorithm> #include "hal.h" using namespace std; using namespace hal; static void printSequenceLine(ostream& outStream, const Sequence* sequence, hal_size_t start, hal_size_t length, string& buffer); static void printSequence(ostream& outStream, const Sequence* sequence, hal_size_t lineWidth, hal_size_t start, hal_size_t length); static void printGenome(ostream& outStream, const Genome* genome, const Sequence* sequence, hal_size_t lineWidth, hal_size_t start, hal_size_t length); static const hal_size_t StringBufferSize = 1024; static CLParserPtr initParser() { CLParserPtr optionsParser = hdf5CLParserInstance(false); optionsParser->addArgument("inHalPath", "input hal file"); optionsParser->addArgument("genome", "genome to export"); optionsParser->addOption("outFaPath", "output fasta file (stdout if none)", "stdout"); optionsParser->addOption("lineWidth", "Line width for output", 80); optionsParser->addOption("sequence", "sequence name to export (" "all sequences by default)", "\"\""); optionsParser->addOption("start", "coordinate within reference genome (or sequence" " if specified) to start at", 0); optionsParser->addOption("length", "length of the reference genome (or sequence" " if specified) to convert. If set to 0," " the entire thing is converted", 0); optionsParser->setDescription("Export single genome from hal database to " "fasta file."); return optionsParser; } int main(int argc, char** argv) { CLParserPtr optionsParser = initParser(); string halPath; string faPath; hal_size_t lineWidth; string genomeName; string sequenceName; hal_size_t start; hal_size_t length; try { optionsParser->parseOptions(argc, argv); halPath = optionsParser->getArgument<string>("inHalPath"); genomeName = optionsParser->getArgument<string>("genome"); faPath = optionsParser->getOption<string>("outFaPath"); lineWidth = optionsParser->getOption<hal_size_t>("lineWidth"); sequenceName = optionsParser->getOption<string>("sequence"); start = optionsParser->getOption<hal_size_t>("start"); length = optionsParser->getOption<hal_size_t>("length"); } catch(exception& e) { cerr << e.what() << endl; optionsParser->printUsage(cerr); exit(1); } try { AlignmentConstPtr alignment = openHalAlignmentReadOnly(halPath, optionsParser); if (alignment->getNumGenomes() == 0) { throw hal_exception("input hal alignmenet is empty"); } const Genome* genome = alignment->openGenome(genomeName); if (genome == NULL) { throw hal_exception(string("Genome ") + genomeName + " not found"); } const Sequence* sequence = NULL; if (sequenceName != "\"\"") { sequence = genome->getSequence(sequenceName); if (sequence == NULL) { throw hal_exception(string("Sequence ") + sequenceName + " not found"); } } ofstream ofile; ostream& outStream = faPath == "stdout" ? cout : ofile; if (faPath != "stdout") { ofile.open(faPath.c_str()); if (!ofile) { throw hal_exception(string("Error opening output file ") + faPath); } } printGenome(outStream, genome, sequence, lineWidth, start, length); } catch(hal_exception& e) { cerr << "hal exception caught: " << e.what() << endl; return 1; } catch(exception& e) { cerr << "Exception caught: " << e.what() << endl; return 1; } return 0; } void printSequenceLine(ostream& outStream, const Sequence* sequence, hal_size_t start, hal_size_t length, string& buffer) { hal_size_t last = start + length; hal_size_t readLen; for (hal_size_t i = start; i < last; i += StringBufferSize) { readLen = std::min(StringBufferSize, last - i); sequence->getSubString(buffer, i, readLen); outStream << buffer; } } void printSequence(ostream& outStream, const Sequence* sequence, hal_size_t lineWidth, hal_size_t start, hal_size_t length) { hal_size_t seqLen = sequence->getSequenceLength(); if (length == 0) { length = seqLen - start; } hal_size_t last = start + length; if (last > seqLen) { stringstream ss; ss << "Specified range [" << start << "," << length << "] is" << "out of range for sequence " << sequence->getName() << ", which has length " << seqLen; throw (hal_exception(ss.str())); } outStream << '>' << sequence->getName() << '\n'; hal_size_t readLen; string buffer; for (hal_size_t i = start; i < last; i += lineWidth) { readLen = std::min(lineWidth, last - i); printSequenceLine(outStream, sequence, i, readLen, buffer); outStream << '\n'; } } void printGenome(ostream& outStream, const Genome* genome, const Sequence* sequence, hal_size_t lineWidth, hal_size_t start, hal_size_t length) { if (sequence != NULL) { printSequence(outStream, sequence, lineWidth, start, length); } else { if (start + length > genome->getSequenceLength()) { stringstream ss; ss << "Specified range [" << start << "," << length << "] is" << "out of range for genome " << genome->getName() << ", which has length " << genome->getSequenceLength(); throw (hal_exception(ss.str())); } if (length == 0) { length = genome->getSequenceLength() - start; } SequenceIteratorConstPtr seqIt = genome->getSequenceIterator(); SequenceIteratorConstPtr seqEndIt = genome->getSequenceEndIterator(); hal_size_t runningLength = 0; for (; seqIt != seqEndIt; seqIt->toNext()) { const Sequence* sequence = seqIt->getSequence(); hal_size_t seqLen = sequence->getSequenceLength(); hal_size_t seqStart = (hal_size_t)sequence->getStartPosition(); if (start + length >= seqStart && start < seqStart + seqLen && runningLength < length) { hal_size_t readStart = seqStart >= start ? 0 : seqStart - start; hal_size_t readLen = std::min(seqLen - start, length - runningLength); printSequence(outStream, sequence, lineWidth, readStart, readLen); runningLength += readLen; } } } } <|endoftext|>
<commit_before>/* Copyright (c) 2009-2019, Intel Corporation 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 Intel Corporation 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. */ // written by Roman Dementiev, // Patrick Konsor // #include <iostream> #include <string.h> #ifndef _MSC_VER #include <sys/types.h> #endif #include <sys/stat.h> #include <fcntl.h> #include "pci.h" #include "mmio.h" #ifndef _MSC_VER #include <sys/mman.h> #include <errno.h> #endif #ifdef _MSC_VER #include <windows.h> class PCMPmem : public WinPmem { protected: virtual int load_driver_() { SYSTEM_INFO sys_info; ZeroMemory(&sys_info, sizeof(sys_info)); GetCurrentDirectory(MAX_PATH - 10, driver_filename); GetNativeSystemInfo(&sys_info); switch (sys_info.wProcessorArchitecture) { case PROCESSOR_ARCHITECTURE_AMD64: wcscat_s(driver_filename, MAX_PATH, L"\\winpmem_x64.sys"); if (GetFileAttributes(driver_filename) == INVALID_FILE_ATTRIBUTES) { std::cout << "ERROR: winpmem_x64.sys not found in current directory. Download it from https://github.com/google/rekall/raw/master/tools/pmem/resources/winpmem/winpmem_x64.sys ." << std::endl; std::cout << "ERROR: Memory bandwidth statistics will not be available." << std::endl; } break; case PROCESSOR_ARCHITECTURE_INTEL: wcscat_s(driver_filename, MAX_PATH, L"\\winpmem_x86.sys"); if (GetFileAttributes(driver_filename) == INVALID_FILE_ATTRIBUTES) { std::cout << "ERROR: winpmem_x86.sys not found in current directory. Download it from https://github.com/google/rekall/raw/master/tools/pmem/resources/winpmem/winpmem_x86.sys ." << std::endl; std::cout << "ERROR: Memory bandwidth statistics will not be available." << std::endl; } break; default: return -1; } return 1; } virtual int write_crashdump_header_(struct PmemMemoryInfo * info) { return -1; } }; std::shared_ptr<WinPmem> MMIORange::pmem; PCM_Util::Mutex MMIORange::mutex; bool MMIORange::writeSupported; MMIORange::MMIORange(uint64 baseAddr_, uint64 /* size_ */, bool readonly_) : startAddr(baseAddr_), readonly(readonly_) { mutex.lock(); if (pmem.get() == NULL) { pmem = std::make_shared<PCMPmem>(); pmem->install_driver(false); pmem->set_acquisition_mode(PMEM_MODE_IOSPACE); writeSupported = pmem->toggle_write_mode() >= 0; // since it is a global object enable write mode just in case someone needs it } mutex.unlock(); } #elif __APPLE__ #include "PCIDriverInterface.h" MMIORange::MMIORange(uint64 physical_address, uint64 size_, bool readonly_) : mmapAddr(NULL), size(size_), readonly(readonly_) { if (size > 4096) { std::cerr << "PCM Error: the driver does not support mapping of regions > 4KB" << std::endl; return; } if (physical_address) { PCIDriver_mapMemory((uint32_t)physical_address, (uint8_t **)&mmapAddr); } } uint32 MMIORange::read32(uint64 offset) { uint32 val = 0; PCIDriver_readMemory32((uint8_t *)mmapAddr + offset, &val); return val; } uint64 MMIORange::read64(uint64 offset) { uint64 val = 0; PCIDriver_readMemory64((uint8_t *)mmapAddr + offset, &val); return val; } void MMIORange::write32(uint64 offset, uint32 val) { std::cerr << "PCM Error: the driver does not support writing to MMIORange" << std::endl; } void MMIORange::write64(uint64 offset, uint64 val) { std::cerr << "PCM Error: the driver does not support writing to MMIORange" << std::endl; } MMIORange::~MMIORange() { if(mmapAddr) PCIDriver_unmapMemory((uint8_t *)mmapAddr); } #elif defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) MMIORange::MMIORange(uint64 baseAddr_, uint64 size_, bool readonly_) : fd(-1), mmapAddr(NULL), size(size_), readonly(readonly_) { const int oflag = readonly ? O_RDONLY : O_RDWR; int handle = ::open("/dev/mem", oflag); if (handle < 0) { std::cout << "opening /dev/mem failed: errno is " << errno << " (" << strerror(errno) << ")" << std::endl; throw std::exception(); } fd = handle; const int prot = readonly ? PROT_READ : (PROT_READ | PROT_WRITE); mmapAddr = (char *)mmap(NULL, size, prot, MAP_SHARED, fd, baseAddr_); if (mmapAddr == MAP_FAILED) { std::cout << "mmap failed: errno is " << errno << " (" << strerror(errno) << ")" << std::endl; throw std::exception(); } } uint32 MMIORange::read32(uint64 offset) { return *((uint32 *)(mmapAddr + offset)); } uint64 MMIORange::read64(uint64 offset) { return *((uint64 *)(mmapAddr + offset)); } void MMIORange::write32(uint64 offset, uint32 val) { if (readonly) { std::cerr << "PCM Error: attempting to write to a read-only MMIORange" << std::endl; return; } *((uint32 *)(mmapAddr + offset)) = val; } void MMIORange::write64(uint64 offset, uint64 val) { if (readonly) { std::cerr << "PCM Error: attempting to write to a read-only MMIORange" << std::endl; return; } *((uint64 *)(mmapAddr + offset)) = val; } MMIORange::~MMIORange() { if (mmapAddr) munmap(mmapAddr, size); if (fd >= 0) ::close(fd); } #endif <commit_msg>Replace endl with \n to get rid of many unnecessary flushes<commit_after>/* Copyright (c) 2009-2019, Intel Corporation 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 Intel Corporation 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. */ // written by Roman Dementiev, // Patrick Konsor // #include <iostream> #include <string.h> #ifndef _MSC_VER #include <sys/types.h> #endif #include <sys/stat.h> #include <fcntl.h> #include "pci.h" #include "mmio.h" #ifndef _MSC_VER #include <sys/mman.h> #include <errno.h> #endif #ifdef _MSC_VER #include <windows.h> class PCMPmem : public WinPmem { protected: virtual int load_driver_() { SYSTEM_INFO sys_info; ZeroMemory(&sys_info, sizeof(sys_info)); GetCurrentDirectory(MAX_PATH - 10, driver_filename); GetNativeSystemInfo(&sys_info); switch (sys_info.wProcessorArchitecture) { case PROCESSOR_ARCHITECTURE_AMD64: wcscat_s(driver_filename, MAX_PATH, L"\\winpmem_x64.sys"); if (GetFileAttributes(driver_filename) == INVALID_FILE_ATTRIBUTES) { std::cerr << "ERROR: winpmem_x64.sys not found in current directory. Download it from https://github.com/google/rekall/raw/master/tools/pmem/resources/winpmem/winpmem_x64.sys .\n"; std::cerr << "ERROR: Memory bandwidth statistics will not be available.\n"; } break; case PROCESSOR_ARCHITECTURE_INTEL: wcscat_s(driver_filename, MAX_PATH, L"\\winpmem_x86.sys"); if (GetFileAttributes(driver_filename) == INVALID_FILE_ATTRIBUTES) { std::cerr << "ERROR: winpmem_x86.sys not found in current directory. Download it from https://github.com/google/rekall/raw/master/tools/pmem/resources/winpmem/winpmem_x86.sys .\n"; std::cerr << "ERROR: Memory bandwidth statistics will not be available.\n"; } break; default: return -1; } return 1; } virtual int write_crashdump_header_(struct PmemMemoryInfo * info) { return -1; } }; std::shared_ptr<WinPmem> MMIORange::pmem; PCM_Util::Mutex MMIORange::mutex; bool MMIORange::writeSupported; MMIORange::MMIORange(uint64 baseAddr_, uint64 /* size_ */, bool readonly_) : startAddr(baseAddr_), readonly(readonly_) { mutex.lock(); if (pmem.get() == NULL) { pmem = std::make_shared<PCMPmem>(); pmem->install_driver(false); pmem->set_acquisition_mode(PMEM_MODE_IOSPACE); writeSupported = pmem->toggle_write_mode() >= 0; // since it is a global object enable write mode just in case someone needs it } mutex.unlock(); } #elif __APPLE__ #include "PCIDriverInterface.h" MMIORange::MMIORange(uint64 physical_address, uint64 size_, bool readonly_) : mmapAddr(NULL), size(size_), readonly(readonly_) { if (size > 4096) { std::cerr << "PCM Error: the driver does not support mapping of regions > 4KB\n"; return; } if (physical_address) { PCIDriver_mapMemory((uint32_t)physical_address, (uint8_t **)&mmapAddr); } } uint32 MMIORange::read32(uint64 offset) { uint32 val = 0; PCIDriver_readMemory32((uint8_t *)mmapAddr + offset, &val); return val; } uint64 MMIORange::read64(uint64 offset) { uint64 val = 0; PCIDriver_readMemory64((uint8_t *)mmapAddr + offset, &val); return val; } void MMIORange::write32(uint64 offset, uint32 val) { std::cerr << "PCM Error: the driver does not support writing to MMIORange\n"; } void MMIORange::write64(uint64 offset, uint64 val) { std::cerr << "PCM Error: the driver does not support writing to MMIORange\n"; } MMIORange::~MMIORange() { if(mmapAddr) PCIDriver_unmapMemory((uint8_t *)mmapAddr); } #elif defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) MMIORange::MMIORange(uint64 baseAddr_, uint64 size_, bool readonly_) : fd(-1), mmapAddr(NULL), size(size_), readonly(readonly_) { const int oflag = readonly ? O_RDONLY : O_RDWR; int handle = ::open("/dev/mem", oflag); if (handle < 0) { std::cerr << "opening /dev/mem failed: errno is " << errno << " (" << strerror(errno) << ")\n"; throw std::exception(); } fd = handle; const int prot = readonly ? PROT_READ : (PROT_READ | PROT_WRITE); mmapAddr = (char *)mmap(NULL, size, prot, MAP_SHARED, fd, baseAddr_); if (mmapAddr == MAP_FAILED) { std::cerr << "mmap failed: errno is " << errno << " (" << strerror(errno) << ")\n"; throw std::exception(); } } uint32 MMIORange::read32(uint64 offset) { return *((uint32 *)(mmapAddr + offset)); } uint64 MMIORange::read64(uint64 offset) { return *((uint64 *)(mmapAddr + offset)); } void MMIORange::write32(uint64 offset, uint32 val) { if (readonly) { std::cerr << "PCM Error: attempting to write to a read-only MMIORange\n"; return; } *((uint32 *)(mmapAddr + offset)) = val; } void MMIORange::write64(uint64 offset, uint64 val) { if (readonly) { std::cerr << "PCM Error: attempting to write to a read-only MMIORange\n"; return; } *((uint64 *)(mmapAddr + offset)) = val; } MMIORange::~MMIORange() { if (mmapAddr) munmap(mmapAddr, size); if (fd >= 0) ::close(fd); } #endif <|endoftext|>
<commit_before>/* * GAMS - General Algebraic Modeling System C++ API * * Copyright (c) 2017-2021 GAMS Software GmbH <support@gams.com> * Copyright (c) 2017-2021 GAMS Development Corp. <support@gams.com> * * 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 "gamsjobimpl.h" #include "gmomcc.h" #include "gamscheckpoint.h" #include "gamslog.h" #include "gamsoptions.h" #include "gamsplatform.h" #include "gamspath.h" #include "gamsexceptionexecution.h" #include <sstream> #include <fstream> #include <iostream> #include <array> using namespace std; namespace gams { GAMSJobImpl::GAMSJobImpl(GAMSWorkspace& workspace, const std::string& jobName, const std::string& fileName, const GAMSCheckpoint* checkpoint) : mWs(workspace), mJobName(jobName), mFileName(fileName) { DEB << "---- Entering GAMSJob constructor ----"; if (checkpoint != nullptr) { if (!GAMSPath::exists(checkpoint->fileName()) ) throw GAMSException("Checkpoint file " + checkpoint->fileName() + " does not exist"); mCheckpointStart = new GAMSCheckpoint(*checkpoint); } } bool GAMSJobImpl::operator!=(const GAMSJobImpl& other) const { return (mWs != other.mWs) || (mJobName != other.mJobName); } bool GAMSJobImpl::operator==(const GAMSJobImpl& other) const { return !(operator!=(other)); } GAMSDatabase GAMSJobImpl::outDB() { return mOutDb; } GAMSJobImpl::~GAMSJobImpl() { delete mCheckpointStart; // this is intended to only free the wrapper, not the *Impl if used anywhere } void GAMSJobImpl::run(GAMSOptions* gamsOptions, GAMSCheckpoint* checkpoint, ostream* output, bool createOutDb, vector<GAMSDatabase> databases) { // TODO(JM) backward replacement of pointer logic with instance of gamsOptions GAMSOptions tmpOpt = GAMSOptions(mWs, gamsOptions); GAMSCheckpoint* tmpCP = nullptr; if (mCheckpointStart) tmpOpt.setRestart(mCheckpointStart->fileName()); if (checkpoint) { if (mCheckpointStart != checkpoint) { tmpCP = new GAMSCheckpoint(mWs, ""); tmpOpt.setSave(tmpCP->fileName()); } else { tmpOpt.setSave(checkpoint->fileName()); } } if (mWs.debug() >= GAMSEnum::DebugLevel::ShowLog) { tmpOpt.setLogOption(3); } else { // can only happen if we are called from GAMSModelInstance if (tmpOpt.logOption() != 2) { if (output == nullptr) tmpOpt.setLogOption(0); else tmpOpt.setLogOption(3); } } if (!databases.empty()) { for (GAMSDatabase db: databases) { db.doExport(""); if (db.inModelName() != "") tmpOpt.setDefine(db.inModelName(), db.name()); } } GAMSPath jobFileInfo(GAMSPath(mWs.workingDirectory()) / mJobName); if (createOutDb && tmpOpt.gdx() == "") tmpOpt.setGdx(mWs.nextDatabaseName()); if (tmpOpt.logFile() == "") tmpOpt.setLogFile(jobFileInfo.suffix(".log").toStdString()); tmpOpt.setOutput(mJobName + ".lst"); tmpOpt.setCurDir(mWs.workingDirectory()); tmpOpt.setInput(mFileName); GAMSPath pfFileName = jobFileInfo.suffix(".pf"); try { tmpOpt.writeOptionFile(pfFileName); } catch (GAMSException& e) { throw GAMSException(e.what() + (" for GAMSJob " + mJobName)); } auto gamsExe = filesystem::path(mWs.systemDirectory()); gamsExe.append(string("gams") + cExeSuffix); string args = "dummy pf="; GAMSPath pf(mWs.workingDirectory(), mJobName + ".pf"); args.append(pf.string()); string result; int exitCode = runProcess(gamsExe.string(), args, result); if (createOutDb) { GAMSPath gdxPath(tmpOpt.gdx()); if (!gdxPath.is_absolute()) gdxPath = GAMSPath(mWs.workingDirectory()) / gdxPath; gdxPath.setSuffix(".gdx"); if (gdxPath.exists()) mOutDb = mWs.addDatabaseFromGDXForcedName(gdxPath.toStdString(), gdxPath.suffix("").filename().string(), ""); } if (output && mWs.debug() >= GAMSEnum::DebugLevel::ShowLog) MSG << result; else if (output) *output << result; if (exitCode != 0) { cerr << "GAMS Error code: " << exitCode << std::endl; cerr << " with args: " << args << std::endl; cerr << " in " << mWs.workingDirectory() << std::endl; if ((mWs.debug() < GAMSEnum::DebugLevel::KeepFiles) && mWs.usingTmpWorkingDir()) throw GAMSExceptionExecution("GAMS return code not 0 (" + to_string(exitCode) + "), set GAMSWorkspace.Debug to KeepFiles or higher or define the \ GAMSWorkspace.WorkingDirectory to receive a listing file with more details", exitCode); else throw GAMSExceptionExecution("GAMS return code not 0 (" + to_string(exitCode) + "), check " + (GAMSPath(mWs.workingDirectory()) / tmpOpt.output()).toStdString() + " for more details", exitCode); } if (tmpCP) { GAMSPath implFile(checkpoint->fileName()); if (implFile.exists()) implFile.remove(); implFile = tmpCP->fileName(); implFile.rename(checkpoint->fileName()); delete tmpCP; tmpCP=nullptr; } if (mWs.debug() < GAMSEnum::DebugLevel::KeepFiles) { // TODO(RG): this is not good style, but apparently needed try { pfFileName.remove(); } catch (...) { } } } bool GAMSJobImpl::interrupt() { /*qint64*/ int pid = 0 /*mProc.processId()*/; // TODO(RG): we need std process handling here if(pid == 0) return false; return GAMSPlatform::interrupt(pid); } int GAMSJobImpl::runProcess(const string what, const string args, string& output) { ostringstream ssp; string result; FILE* out; #ifdef _WIN32 filesystem::path p = filesystem::current_path(); ssp << "\"" << what << "\" " << args ; out = _popen(ssp.str().c_str(), "rt"); #else ssp << "\"" << what << "\" " << args; out = popen(ssp.str().c_str(), "r"); #endif if (!out) { std::cerr << "Couldn't start command: " << ssp.str() << std::endl; return -1; } std::array<char, 128> buffer; while (fgets(buffer.data(), 128, out)) result += buffer.data(); output = result; int exitCode; #ifdef _WIN32 exitCode = _pclose(out); #else exitCode = pclose(out); #endif return exitCode; } } <commit_msg>fixed accidental overwrite of GAMSOption::setOutput during gams run<commit_after>/* * GAMS - General Algebraic Modeling System C++ API * * Copyright (c) 2017-2021 GAMS Software GmbH <support@gams.com> * Copyright (c) 2017-2021 GAMS Development Corp. <support@gams.com> * * 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 "gamsjobimpl.h" #include "gmomcc.h" #include "gamscheckpoint.h" #include "gamslog.h" #include "gamsoptions.h" #include "gamsplatform.h" #include "gamspath.h" #include "gamsexceptionexecution.h" #include <sstream> #include <fstream> #include <iostream> #include <array> using namespace std; namespace gams { GAMSJobImpl::GAMSJobImpl(GAMSWorkspace& workspace, const std::string& jobName, const std::string& fileName, const GAMSCheckpoint* checkpoint) : mWs(workspace), mJobName(jobName), mFileName(fileName) { DEB << "---- Entering GAMSJob constructor ----"; if (checkpoint != nullptr) { if (!GAMSPath::exists(checkpoint->fileName()) ) throw GAMSException("Checkpoint file " + checkpoint->fileName() + " does not exist"); mCheckpointStart = new GAMSCheckpoint(*checkpoint); } } bool GAMSJobImpl::operator!=(const GAMSJobImpl& other) const { return (mWs != other.mWs) || (mJobName != other.mJobName); } bool GAMSJobImpl::operator==(const GAMSJobImpl& other) const { return !(operator!=(other)); } GAMSDatabase GAMSJobImpl::outDB() { return mOutDb; } GAMSJobImpl::~GAMSJobImpl() { delete mCheckpointStart; // this is intended to only free the wrapper, not the *Impl if used anywhere } void GAMSJobImpl::run(GAMSOptions* gamsOptions, GAMSCheckpoint* checkpoint, ostream* output, bool createOutDb, vector<GAMSDatabase> databases) { // TODO(JM) backward replacement of pointer logic with instance of gamsOptions GAMSOptions tmpOpt = GAMSOptions(mWs, gamsOptions); GAMSCheckpoint* tmpCP = nullptr; if (mCheckpointStart) tmpOpt.setRestart(mCheckpointStart->fileName()); if (checkpoint) { if (mCheckpointStart != checkpoint) { tmpCP = new GAMSCheckpoint(mWs, ""); tmpOpt.setSave(tmpCP->fileName()); } else { tmpOpt.setSave(checkpoint->fileName()); } } if (mWs.debug() >= GAMSEnum::DebugLevel::ShowLog) { tmpOpt.setLogOption(3); } else { // can only happen if we are called from GAMSModelInstance if (tmpOpt.logOption() != 2) { if (output == nullptr) tmpOpt.setLogOption(0); else tmpOpt.setLogOption(3); } } if (!databases.empty()) { for (GAMSDatabase db: databases) { db.doExport(""); if (db.inModelName() != "") tmpOpt.setDefine(db.inModelName(), db.name()); } } GAMSPath jobFileInfo(GAMSPath(mWs.workingDirectory()) / mJobName); if (createOutDb && tmpOpt.gdx() == "") tmpOpt.setGdx(mWs.nextDatabaseName()); if (tmpOpt.logFile() == "") tmpOpt.setLogFile(jobFileInfo.suffix(".log").toStdString()); if (!tmpOpt.output().empty()) tmpOpt.setOutput(mJobName + ".lst"); tmpOpt.setCurDir(mWs.workingDirectory()); tmpOpt.setInput(mFileName); GAMSPath pfFileName = jobFileInfo.suffix(".pf"); try { tmpOpt.writeOptionFile(pfFileName); } catch (GAMSException& e) { throw GAMSException(e.what() + (" for GAMSJob " + mJobName)); } auto gamsExe = filesystem::path(mWs.systemDirectory()); gamsExe.append(string("gams") + cExeSuffix); string args = "dummy pf="; GAMSPath pf(mWs.workingDirectory(), mJobName + ".pf"); args.append(pf.string()); string result; int exitCode = runProcess(gamsExe.string(), args, result); if (createOutDb) { GAMSPath gdxPath(tmpOpt.gdx()); if (!gdxPath.is_absolute()) gdxPath = GAMSPath(mWs.workingDirectory()) / gdxPath; gdxPath.setSuffix(".gdx"); if (gdxPath.exists()) mOutDb = mWs.addDatabaseFromGDXForcedName(gdxPath.toStdString(), gdxPath.suffix("").filename().string(), ""); } if (output && mWs.debug() >= GAMSEnum::DebugLevel::ShowLog) MSG << result; else if (output) *output << result; if (exitCode != 0) { cerr << "GAMS Error code: " << exitCode << std::endl; cerr << " with args: " << args << std::endl; cerr << " in " << mWs.workingDirectory() << std::endl; if ((mWs.debug() < GAMSEnum::DebugLevel::KeepFiles) && mWs.usingTmpWorkingDir()) throw GAMSExceptionExecution("GAMS return code not 0 (" + to_string(exitCode) + "), set GAMSWorkspace.Debug to KeepFiles or higher or define the \ GAMSWorkspace.WorkingDirectory to receive a listing file with more details", exitCode); else throw GAMSExceptionExecution("GAMS return code not 0 (" + to_string(exitCode) + "), check " + (GAMSPath(mWs.workingDirectory()) / tmpOpt.output()).toStdString() + " for more details", exitCode); } if (tmpCP) { GAMSPath implFile(checkpoint->fileName()); if (implFile.exists()) implFile.remove(); implFile = tmpCP->fileName(); implFile.rename(checkpoint->fileName()); delete tmpCP; tmpCP=nullptr; } if (mWs.debug() < GAMSEnum::DebugLevel::KeepFiles) { // TODO(RG): this is not good style, but apparently needed try { pfFileName.remove(); } catch (...) { } } } bool GAMSJobImpl::interrupt() { /*qint64*/ int pid = 0 /*mProc.processId()*/; // TODO(RG): we need std process handling here if(pid == 0) return false; return GAMSPlatform::interrupt(pid); } int GAMSJobImpl::runProcess(const string what, const string args, string& output) { ostringstream ssp; string result; FILE* out; #ifdef _WIN32 filesystem::path p = filesystem::current_path(); ssp << "\"" << what << "\" " << args ; out = _popen(ssp.str().c_str(), "rt"); #else ssp << "\"" << what << "\" " << args; out = popen(ssp.str().c_str(), "r"); #endif if (!out) { std::cerr << "Couldn't start command: " << ssp.str() << std::endl; return -1; } std::array<char, 128> buffer; while (fgets(buffer.data(), 128, out)) result += buffer.data(); output = result; int exitCode; #ifdef _WIN32 exitCode = _pclose(out); #else exitCode = pclose(out); #endif return exitCode; } } <|endoftext|>
<commit_before>#include "poke.h" Poke::Poke() : size(0), mode(PM_NOOP) {} Poke::Poke(uint8_t val, volatile uint8_t *addr_) : size(sizeof(uint8_t)), mode(PM_INT), addr(addr_), value8(val) { } Poke::Poke(uint16_t val, volatile uint16_t *addr_) : size(sizeof(uint16_t)), mode(PM_INT), addr(addr_), value16(val) { } Poke::Poke(uint32_t val, volatile uint32_t *addr_) : size(sizeof(uint32_t)), mode(PM_INT), addr(addr_), value32(val) { } Poke::Poke(std::unique_ptr<uint8_t[]> &&dataPtr, size_t dataSize, hwPtr addr_) : size(dataSize), mode(PM_MEMCPY), addr(addr_), valuePtr(std::move(dataPtr)) { } Poke::~Poke() { switch(mode) { case PM_DMA: case PM_MEMCPY: valuePtr.~unique_ptr(); break; default: break; } } void Poke::Perform() { switch(mode) { case PM_NOOP: break; case PM_INT: switch(size) { case sizeof(uint8_t): *((volatile uint8_t*)addr)=value8; break; case sizeof(uint16_t): *((volatile uint16_t*)addr)=value16; break; case sizeof(uint32_t): *((volatile uint32_t*)addr)=value32; break; } break; case PM_BITFIELD: break; case PM_DMA: break; case PM_MEMCPY: { volatile uint8_t *dst=valuePtr.get(); std::copy(dst,dst+size,(uint8_t *)addr); } break; } } PokeChainLink::PokeChainLink() {} PokeChainLink::PokeChainLink(Poke &&p, std::unique_ptr<PokeChainLink> &&next_) : next(std::move(next_)), poke(std::move(p)) {} PokeChainLink::~PokeChainLink() {}<commit_msg>Move constructor for poke<commit_after>#include "poke.h" Poke::Poke() : size(0), mode(PM_NOOP) {} Poke::Poke(uint8_t val, volatile uint8_t *addr_) : size(sizeof(uint8_t)), mode(PM_INT), addr(addr_), value8(val) { } Poke::Poke(uint16_t val, volatile uint16_t *addr_) : size(sizeof(uint16_t)), mode(PM_INT), addr(addr_), value16(val) { } Poke::Poke(uint32_t val, volatile uint32_t *addr_) : size(sizeof(uint32_t)), mode(PM_INT), addr(addr_), value32(val) { } Poke::Poke(std::unique_ptr<uint8_t[]> &&dataPtr, size_t dataSize, hwPtr addr_) : size(dataSize), mode(PM_MEMCPY), addr(addr_), valuePtr(std::move(dataPtr)) { } Poke::Poke(Poke &&p2) : size(p2.size), mode(p2.mode), addr(p2.addr) { switch(p2.mode) { case PM_NOOP: break; case PM_INT: switch(p2.size) { case sizeof(uint8_t): value8=p2.value8; break; case sizeof(uint16_t): value16=p2.value16; break; case sizeof(uint32_t): value32=p2.value32; break; } break; case PM_BITFIELD: break; case PM_DMA: case PM_MEMCPY: valuePtr=std::move(p2.valuePtr); break; } p2.mode=PM_NOOP; p2.size=0; } Poke::~Poke() { switch(mode) { case PM_DMA: case PM_MEMCPY: valuePtr.~unique_ptr(); break; default: break; } } void Poke::Perform() { switch(mode) { case PM_NOOP: break; case PM_INT: switch(size) { case sizeof(uint8_t): *((volatile uint8_t*)addr)=value8; break; case sizeof(uint16_t): *((volatile uint16_t*)addr)=value16; break; case sizeof(uint32_t): *((volatile uint32_t*)addr)=value32; break; } break; case PM_BITFIELD: break; case PM_DMA: break; case PM_MEMCPY: { volatile uint8_t *dst=valuePtr.get(); std::copy(dst,dst+size,(uint8_t *)addr); } break; } } PokeChainLink::PokeChainLink() {} PokeChainLink::PokeChainLink(Poke &&p, std::unique_ptr<PokeChainLink> &&next_) : next(std::move(next_)), poke(std::move(p)) {} PokeChainLink::~PokeChainLink() {}<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SdGlobalResourceContainer.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kz $ $Date: 2008-04-03 14:05:40 $ * * 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 SD_GLOBAL_RESOURCE_CONTAINER_HXX #define SD_GLOBAL_RESOURCE_CONTAINER_HXX #include "sdmod.hxx" #include <memory> #include <boost/shared_ptr.hpp> #include <com/sun/star/uno/XInterface.hpp> namespace css = ::com::sun::star; namespace sd { class SdGlobalResource { public: virtual ~SdGlobalResource (void) {}; }; /** The purpose of this container is to hold references to resources that are globally available to all interested objects and to destroy them when the sd module is destroyed. Examples for resources can be containers of bitmaps or the container of master pages used by the MasterPagesSelector objects in the task panel. It works like a singleton in that there is one instance per sd module. Resources can be added (by themselves or their owners) to the container. The main task of the container is the destruction of all resources that have been added to it. As you may note, there is no method to get a resource from the container. It is the task of the resource to provide other means of access to it. The reason for this design is not to have to change the SdModule destructor every time when there is a new resource. This is done by reversing the dependency between module and resource: the resource knows about the module--this container class to be more precisely--and tells it to destroy the resource when the sd module is at the end of its lifetime. */ class SdGlobalResourceContainer { public: static SdGlobalResourceContainer& Instance (void); /** Add a resource to the container. The ownership of the resource is transferred to the container. The resource is destroyed when the container is destroyed, i.e. when the sd module is destroyed. When in doubt, use the shared_ptr variant of this method. */ void AddResource (::std::auto_ptr<SdGlobalResource> pResource); /** Add a resource to the container. By using a shared_ptr and releasing it only when the SgGlobalResourceContainer is destroyed the given resource is kept alive at least that long. When at the time of the destruction of SgGlobalResourceContainer no other references exist the resource is destroyed as well. */ void AddResource (::boost::shared_ptr<SdGlobalResource> pResource); /** Add a resource that is implemented as UNO object. Destruction (when the sd modules is unloaded) is done by a) calling dispose() when the XComponent is supported and by b) releasing the reference. */ void AddResource (const ::css::uno::Reference<css::uno::XInterface>& rxResource); /** Tell the container that it is not any longer responsible for the specified resource. @return When the specified resource has previously added to the container the resource is returned (which is, of course, the same pointer as the given one.) Otherwise a NULL pointer is returned. */ ::std::auto_ptr<SdGlobalResource> ReleaseResource ( SdGlobalResource* pResource); protected: friend class ::SdModule; friend class ::std::auto_ptr<SdGlobalResourceContainer>; class Implementation; ::std::auto_ptr<Implementation> mpImpl; SdGlobalResourceContainer (void); ~SdGlobalResourceContainer (void); }; } // end of namespace sd #endif <commit_msg>INTEGRATION: CWS changefileheader (1.4.452); FILE MERGED 2008/03/31 13:58:42 rt 1.4.452.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: SdGlobalResourceContainer.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 SD_GLOBAL_RESOURCE_CONTAINER_HXX #define SD_GLOBAL_RESOURCE_CONTAINER_HXX #include "sdmod.hxx" #include <memory> #include <boost/shared_ptr.hpp> #include <com/sun/star/uno/XInterface.hpp> namespace css = ::com::sun::star; namespace sd { class SdGlobalResource { public: virtual ~SdGlobalResource (void) {}; }; /** The purpose of this container is to hold references to resources that are globally available to all interested objects and to destroy them when the sd module is destroyed. Examples for resources can be containers of bitmaps or the container of master pages used by the MasterPagesSelector objects in the task panel. It works like a singleton in that there is one instance per sd module. Resources can be added (by themselves or their owners) to the container. The main task of the container is the destruction of all resources that have been added to it. As you may note, there is no method to get a resource from the container. It is the task of the resource to provide other means of access to it. The reason for this design is not to have to change the SdModule destructor every time when there is a new resource. This is done by reversing the dependency between module and resource: the resource knows about the module--this container class to be more precisely--and tells it to destroy the resource when the sd module is at the end of its lifetime. */ class SdGlobalResourceContainer { public: static SdGlobalResourceContainer& Instance (void); /** Add a resource to the container. The ownership of the resource is transferred to the container. The resource is destroyed when the container is destroyed, i.e. when the sd module is destroyed. When in doubt, use the shared_ptr variant of this method. */ void AddResource (::std::auto_ptr<SdGlobalResource> pResource); /** Add a resource to the container. By using a shared_ptr and releasing it only when the SgGlobalResourceContainer is destroyed the given resource is kept alive at least that long. When at the time of the destruction of SgGlobalResourceContainer no other references exist the resource is destroyed as well. */ void AddResource (::boost::shared_ptr<SdGlobalResource> pResource); /** Add a resource that is implemented as UNO object. Destruction (when the sd modules is unloaded) is done by a) calling dispose() when the XComponent is supported and by b) releasing the reference. */ void AddResource (const ::css::uno::Reference<css::uno::XInterface>& rxResource); /** Tell the container that it is not any longer responsible for the specified resource. @return When the specified resource has previously added to the container the resource is returned (which is, of course, the same pointer as the given one.) Otherwise a NULL pointer is returned. */ ::std::auto_ptr<SdGlobalResource> ReleaseResource ( SdGlobalResource* pResource); protected: friend class ::SdModule; friend class ::std::auto_ptr<SdGlobalResourceContainer>; class Implementation; ::std::auto_ptr<Implementation> mpImpl; SdGlobalResourceContainer (void); ~SdGlobalResourceContainer (void); }; } // end of namespace sd #endif <|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 <atlbase.h> #include <vector> #include "base/file_path.h" #include "base/scoped_comptr_win.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/renderer_host/render_widget_host_view_win.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_type.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" namespace { class AccessibilityWinBrowserTest : public InProcessBrowserTest { public: void SetUpCommandLine(CommandLine* command_line) { // Turns on the accessibility in the renderer. Off by default until // http://crbug.com/25564 is fixed. command_line->AppendSwitch(switches::kEnableRendererAccessibility); } protected: IAccessible* GetRenderWidgetHostViewClientAccessible(); }; class AccessibleChecker { public: AccessibleChecker(std::wstring expected_name, int32 expected_role); // Append an AccessibleChecker that verifies accessibility information for // a child IAccessible. Order is important. void AppendExpectedChild(AccessibleChecker* expected_child); // Check that the name and role of the given IAccessible instance and its // descendants match the expected names and roles that this object was // initialized with. void CheckAccessible(IAccessible* accessible); typedef std::vector<AccessibleChecker*> AccessibleCheckerVector; private: void CheckAccessibleName(IAccessible* accessible); void CheckAccessibleRole(IAccessible* accessible); void CheckAccessibleChildren(IAccessible* accessible); private: // Expected accessible name. Checked against IAccessible::get_accName. std::wstring name_; // Expected accessible role. Checked against IAccessible::get_accRole. int32 role_; // Expected accessible children. Checked using IAccessible::get_accChildCount // and ::AccessibleChildren. AccessibleCheckerVector children_; }; VARIANT CreateI4Variant(LONG value) { VARIANT variant = {0}; V_VT(&variant) = VT_I4; V_I4(&variant) = value; return variant; } IAccessible* GetAccessibleFromResultVariant(IAccessible* parent, VARIANT *var) { switch (V_VT(var)) { case VT_DISPATCH: return CComQIPtr<IAccessible>(V_DISPATCH(var)).Detach(); break; case VT_I4: { CComPtr<IDispatch> dispatch; HRESULT hr = parent->get_accChild(CreateI4Variant(V_I4(var)), &dispatch); EXPECT_EQ(hr, S_OK); return CComQIPtr<IAccessible>(dispatch).Detach(); break; } } return NULL; } // Retrieve the MSAA client accessibility object for the Render Widget Host View // of the selected tab. IAccessible* AccessibilityWinBrowserTest::GetRenderWidgetHostViewClientAccessible() { HWND hwnd_render_widget_host_view = browser()->GetSelectedTabContents()->GetRenderWidgetHostView()-> GetNativeView(); IAccessible* accessible; HRESULT hr = AccessibleObjectFromWindow( hwnd_render_widget_host_view, OBJID_CLIENT, IID_IAccessible, reinterpret_cast<void**>(&accessible)); EXPECT_EQ(S_OK, hr); EXPECT_NE(accessible, reinterpret_cast<IAccessible*>(NULL)); return accessible; } AccessibleChecker::AccessibleChecker( std::wstring expected_name, int32 expected_role) : name_(expected_name), role_(expected_role) { } void AccessibleChecker::AppendExpectedChild( AccessibleChecker* expected_child) { children_.push_back(expected_child); } void AccessibleChecker::CheckAccessible(IAccessible* accessible) { CheckAccessibleName(accessible); CheckAccessibleRole(accessible); CheckAccessibleChildren(accessible); } void AccessibleChecker::CheckAccessibleName(IAccessible* accessible) { CComBSTR name; HRESULT hr = accessible->get_accName(CreateI4Variant(CHILDID_SELF), &name); if (name_.empty()) { // If the object doesn't have name S_FALSE should be returned. EXPECT_EQ(hr, S_FALSE); } else { // Test that the correct string was returned. EXPECT_EQ(hr, S_OK); EXPECT_EQ(CompareString(LOCALE_NEUTRAL, 0, name, SysStringLen(name), name_.c_str(), name_.length()), CSTR_EQUAL); } } void AccessibleChecker::CheckAccessibleRole(IAccessible* accessible) { VARIANT var_role = {0}; HRESULT hr = accessible->get_accRole(CreateI4Variant(CHILDID_SELF), &var_role); EXPECT_EQ(hr, S_OK); EXPECT_EQ(V_VT(&var_role), VT_I4); EXPECT_EQ(V_I4(&var_role), role_); } void AccessibleChecker::CheckAccessibleChildren(IAccessible* parent) { LONG child_count = 0; HRESULT hr = parent->get_accChildCount(&child_count); EXPECT_EQ(hr, S_OK); // TODO(dmazzoni): remove as soon as test passes on build bot printf("CheckAccessibleChildren: actual=%d expected=%d\n", static_cast<int>(child_count), static_cast<int>(children_.size())); ASSERT_EQ(child_count, children_.size()); std::auto_ptr<VARIANT> child_array(new VARIANT[child_count]); LONG obtained_count = 0; hr = AccessibleChildren(parent, 0, child_count, child_array.get(), &obtained_count); ASSERT_EQ(hr, S_OK); ASSERT_EQ(child_count, obtained_count); VARIANT* child = child_array.get(); for (AccessibleCheckerVector::iterator child_checker = children_.begin(); child_checker != children_.end(); ++child_checker, ++child) { ScopedComPtr<IAccessible> child_accessible; child_accessible.Attach(GetAccessibleFromResultVariant(parent, child)); (*child_checker)->CheckAccessible(child_accessible); } } // Flaky, http://crbug.com/44546. IN_PROC_BROWSER_TEST_F(AccessibilityWinBrowserTest, FLAKY_TestRendererAccessibilityTree) { GURL tree_url( "data:text/html,<html><head><title>Accessibility Win Test</title></head>" "<body><input type='button' value='push' /><input type='checkbox' />" "</body></html>"); browser()->OpenURL(tree_url, GURL(), CURRENT_TAB, PageTransition::TYPED); ui_test_utils::WaitForNotification( NotificationType::RENDER_VIEW_HOST_ACCESSIBILITY_TREE_UPDATED); ScopedComPtr<IAccessible> document_accessible( GetRenderWidgetHostViewClientAccessible()); AccessibleChecker button_checker(L"push", ROLE_SYSTEM_PUSHBUTTON); AccessibleChecker checkbox_checker(L"", ROLE_SYSTEM_CHECKBUTTON); AccessibleChecker grouping_checker(L"", ROLE_SYSTEM_GROUPING); grouping_checker.AppendExpectedChild(&button_checker); grouping_checker.AppendExpectedChild(&checkbox_checker); AccessibleChecker document_checker(L"", ROLE_SYSTEM_DOCUMENT); document_checker.AppendExpectedChild(&grouping_checker); // Check the accessible tree of the renderer. document_checker.CheckAccessible(document_accessible); // Check that document accessible has a parent accessible. ScopedComPtr<IDispatch> parent_dispatch; HRESULT hr = document_accessible->get_accParent(parent_dispatch.Receive()); EXPECT_EQ(hr, S_OK); EXPECT_NE(parent_dispatch, reinterpret_cast<IDispatch*>(NULL)); // Navigate to another page. GURL about_url("about:"); ui_test_utils::NavigateToURL(browser(), about_url); // Verify that the IAccessible reference still points to a valid object and // that it calls to its methods fail since the tree is no longer valid after // the page navagation. // Todo(ctguil): Currently this is giving a false positive because E_FAIL is // returned when BrowserAccessibilityManager::RequestAccessibilityInfo fails // since the previous render view host connection is lost. Verify that // instances are actually marked as invalid once the browse side cache is // checked in. CComBSTR name; hr = document_accessible->get_accName(CreateI4Variant(CHILDID_SELF), &name); ASSERT_EQ(E_FAIL, hr); } } // namespace. <commit_msg>Disabling AccessibilityWinBrowserTest.TestRenderereAccessibilityTree.<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 <atlbase.h> #include <vector> #include "base/file_path.h" #include "base/scoped_comptr_win.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/renderer_host/render_widget_host_view_win.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_type.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" namespace { class AccessibilityWinBrowserTest : public InProcessBrowserTest { public: void SetUpCommandLine(CommandLine* command_line) { // Turns on the accessibility in the renderer. Off by default until // http://crbug.com/25564 is fixed. command_line->AppendSwitch(switches::kEnableRendererAccessibility); } protected: IAccessible* GetRenderWidgetHostViewClientAccessible(); }; class AccessibleChecker { public: AccessibleChecker(std::wstring expected_name, int32 expected_role); // Append an AccessibleChecker that verifies accessibility information for // a child IAccessible. Order is important. void AppendExpectedChild(AccessibleChecker* expected_child); // Check that the name and role of the given IAccessible instance and its // descendants match the expected names and roles that this object was // initialized with. void CheckAccessible(IAccessible* accessible); typedef std::vector<AccessibleChecker*> AccessibleCheckerVector; private: void CheckAccessibleName(IAccessible* accessible); void CheckAccessibleRole(IAccessible* accessible); void CheckAccessibleChildren(IAccessible* accessible); private: // Expected accessible name. Checked against IAccessible::get_accName. std::wstring name_; // Expected accessible role. Checked against IAccessible::get_accRole. int32 role_; // Expected accessible children. Checked using IAccessible::get_accChildCount // and ::AccessibleChildren. AccessibleCheckerVector children_; }; VARIANT CreateI4Variant(LONG value) { VARIANT variant = {0}; V_VT(&variant) = VT_I4; V_I4(&variant) = value; return variant; } IAccessible* GetAccessibleFromResultVariant(IAccessible* parent, VARIANT *var) { switch (V_VT(var)) { case VT_DISPATCH: return CComQIPtr<IAccessible>(V_DISPATCH(var)).Detach(); break; case VT_I4: { CComPtr<IDispatch> dispatch; HRESULT hr = parent->get_accChild(CreateI4Variant(V_I4(var)), &dispatch); EXPECT_EQ(hr, S_OK); return CComQIPtr<IAccessible>(dispatch).Detach(); break; } } return NULL; } // Retrieve the MSAA client accessibility object for the Render Widget Host View // of the selected tab. IAccessible* AccessibilityWinBrowserTest::GetRenderWidgetHostViewClientAccessible() { HWND hwnd_render_widget_host_view = browser()->GetSelectedTabContents()->GetRenderWidgetHostView()-> GetNativeView(); IAccessible* accessible; HRESULT hr = AccessibleObjectFromWindow( hwnd_render_widget_host_view, OBJID_CLIENT, IID_IAccessible, reinterpret_cast<void**>(&accessible)); EXPECT_EQ(S_OK, hr); EXPECT_NE(accessible, reinterpret_cast<IAccessible*>(NULL)); return accessible; } AccessibleChecker::AccessibleChecker( std::wstring expected_name, int32 expected_role) : name_(expected_name), role_(expected_role) { } void AccessibleChecker::AppendExpectedChild( AccessibleChecker* expected_child) { children_.push_back(expected_child); } void AccessibleChecker::CheckAccessible(IAccessible* accessible) { CheckAccessibleName(accessible); CheckAccessibleRole(accessible); CheckAccessibleChildren(accessible); } void AccessibleChecker::CheckAccessibleName(IAccessible* accessible) { CComBSTR name; HRESULT hr = accessible->get_accName(CreateI4Variant(CHILDID_SELF), &name); if (name_.empty()) { // If the object doesn't have name S_FALSE should be returned. EXPECT_EQ(hr, S_FALSE); } else { // Test that the correct string was returned. EXPECT_EQ(hr, S_OK); EXPECT_EQ(CompareString(LOCALE_NEUTRAL, 0, name, SysStringLen(name), name_.c_str(), name_.length()), CSTR_EQUAL); } } void AccessibleChecker::CheckAccessibleRole(IAccessible* accessible) { VARIANT var_role = {0}; HRESULT hr = accessible->get_accRole(CreateI4Variant(CHILDID_SELF), &var_role); EXPECT_EQ(hr, S_OK); EXPECT_EQ(V_VT(&var_role), VT_I4); EXPECT_EQ(V_I4(&var_role), role_); } void AccessibleChecker::CheckAccessibleChildren(IAccessible* parent) { LONG child_count = 0; HRESULT hr = parent->get_accChildCount(&child_count); EXPECT_EQ(hr, S_OK); // TODO(dmazzoni): remove as soon as test passes on build bot printf("CheckAccessibleChildren: actual=%d expected=%d\n", static_cast<int>(child_count), static_cast<int>(children_.size())); ASSERT_EQ(child_count, children_.size()); std::auto_ptr<VARIANT> child_array(new VARIANT[child_count]); LONG obtained_count = 0; hr = AccessibleChildren(parent, 0, child_count, child_array.get(), &obtained_count); ASSERT_EQ(hr, S_OK); ASSERT_EQ(child_count, obtained_count); VARIANT* child = child_array.get(); for (AccessibleCheckerVector::iterator child_checker = children_.begin(); child_checker != children_.end(); ++child_checker, ++child) { ScopedComPtr<IAccessible> child_accessible; child_accessible.Attach(GetAccessibleFromResultVariant(parent, child)); (*child_checker)->CheckAccessible(child_accessible); } } // Flaky and crashing, http://crbug.com/44546. IN_PROC_BROWSER_TEST_F(AccessibilityWinBrowserTest, DISABLED_TestRendererAccessibilityTree) { GURL tree_url( "data:text/html,<html><head><title>Accessibility Win Test</title></head>" "<body><input type='button' value='push' /><input type='checkbox' />" "</body></html>"); browser()->OpenURL(tree_url, GURL(), CURRENT_TAB, PageTransition::TYPED); ui_test_utils::WaitForNotification( NotificationType::RENDER_VIEW_HOST_ACCESSIBILITY_TREE_UPDATED); ScopedComPtr<IAccessible> document_accessible( GetRenderWidgetHostViewClientAccessible()); AccessibleChecker button_checker(L"push", ROLE_SYSTEM_PUSHBUTTON); AccessibleChecker checkbox_checker(L"", ROLE_SYSTEM_CHECKBUTTON); AccessibleChecker grouping_checker(L"", ROLE_SYSTEM_GROUPING); grouping_checker.AppendExpectedChild(&button_checker); grouping_checker.AppendExpectedChild(&checkbox_checker); AccessibleChecker document_checker(L"", ROLE_SYSTEM_DOCUMENT); document_checker.AppendExpectedChild(&grouping_checker); // Check the accessible tree of the renderer. document_checker.CheckAccessible(document_accessible); // Check that document accessible has a parent accessible. ScopedComPtr<IDispatch> parent_dispatch; HRESULT hr = document_accessible->get_accParent(parent_dispatch.Receive()); EXPECT_EQ(hr, S_OK); EXPECT_NE(parent_dispatch, reinterpret_cast<IDispatch*>(NULL)); // Navigate to another page. GURL about_url("about:"); ui_test_utils::NavigateToURL(browser(), about_url); // Verify that the IAccessible reference still points to a valid object and // that it calls to its methods fail since the tree is no longer valid after // the page navagation. // Todo(ctguil): Currently this is giving a false positive because E_FAIL is // returned when BrowserAccessibilityManager::RequestAccessibilityInfo fails // since the previous render view host connection is lost. Verify that // instances are actually marked as invalid once the browse side cache is // checked in. CComBSTR name; hr = document_accessible->get_accName(CreateI4Variant(CHILDID_SELF), &name); ASSERT_EQ(E_FAIL, hr); } } // namespace. <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <avmedia/modeltools.hxx> #include <avmedia/mediaitem.hxx> #include <com/sun/star/embed/ElementModes.hpp> #include <com/sun/star/embed/XTransactedObject.hpp> #include <com/sun/star/document/XStorageBasedDocument.hpp> #include <com/sun/star/embed/XStorage.hpp> #include <osl/file.hxx> #include <comphelper/processfactory.hxx> #include <tools/urlobj.hxx> #include <ucbhelper/content.hxx> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/foreach.hpp> #include <string> #include <vector> using namespace ::com::sun::star; using namespace boost::property_tree; namespace avmedia { static void lcl_EmbedExternals(const OUString& rSourceURL, uno::Reference<embed::XStorage> xSubStorage, ::ucbhelper::Content& rContent) { // Create a temp file with which json parser can work. OUString sTempFileURL; const ::osl::FileBase::RC aErr = ::osl::FileBase::createTempFile(0, 0, &sTempFileURL); if (::osl::FileBase::E_None != aErr) { SAL_WARN("avmedia.model", "cannot create temp file"); return; } try { // Write json content to the temp file ::ucbhelper::Content aTempContent(sTempFileURL, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); aTempContent.writeStream(rContent.openStream(), true); } catch (uno::Exception const& e) { SAL_WARN("avmedia.model", "exception: '" << e.Message << "'"); return; } // Convert URL to a file path for loading const INetURLObject aURLObj(sTempFileURL); std::string sUrl = OUStringToOString( aURLObj.getFSysPath(INetURLObject::FSYS_DETECT), RTL_TEXTENCODING_UTF8 ).getStr(); // Parse json, read externals' URI and modify this relative URI's so they remain valid in the new context. std::vector<std::string> vExternals; ptree aTree; try { json_parser::read_json( sUrl, aTree ); // Buffers for geometry and animations BOOST_FOREACH(ptree::value_type &rVal,aTree.get_child("buffers")) { const std::string sBufferUri(rVal.second.get<std::string>("path")); vExternals.push_back(sBufferUri); // Change path: make it contain only a file name aTree.put("buffers." + rVal.first + ".path.",sBufferUri.substr(sBufferUri.find_last_of('/')+1)); } // Images for textures BOOST_FOREACH(ptree::value_type &rVal,aTree.get_child("images")) { const std::string sImageUri(rVal.second.get<std::string>("path")); vExternals.push_back(sImageUri); // Change path: make it contain only a file name aTree.put("images." + rVal.first + ".path.",sImageUri.substr(sImageUri.find_last_of('/')+1)); } // Shaders (contains names only) BOOST_FOREACH(ptree::value_type &rVal,aTree.get_child("programs")) { vExternals.push_back(rVal.second.get<std::string>("fragmentShader") + ".glsl"); vExternals.push_back(rVal.second.get<std::string>("vertexShader") + ".glsl"); } // Write out modified json json_parser::write_json( sUrl, aTree ); } catch ( boost::exception const& ) { SAL_WARN("avmedia.model", "failed to parse json file"); return; } // Reload json with modified path to external resources rContent = ::ucbhelper::Content("file://" + OUString::createFromAscii(sUrl.c_str()), uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); // Store all external files next to the json file for( std::vector<std::string>::iterator aCIter = vExternals.begin(); aCIter != vExternals.end(); ++aCIter ) { const OUString sAbsURL = INetURLObject::GetAbsURL(rSourceURL,OUString::createFromAscii(aCIter->c_str())); ::ucbhelper::Content aContent(sAbsURL, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); uno::Reference<io::XStream> const xStream( CreateStream(xSubStorage, GetFilename(sAbsURL)), uno::UNO_SET_THROW); uno::Reference<io::XOutputStream> const xOutStream( xStream->getOutputStream(), uno::UNO_SET_THROW); if (!aContent.openStream(xOutStream)) { SAL_WARN("avmedia.model", "openStream to storage failed"); return; } } } bool Embed3DModel( const uno::Reference<frame::XModel>& xModel, const OUString& rSourceURL, OUString& o_rEmbeddedURL) { try { ::ucbhelper::Content aSourceContent(rSourceURL, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); // Base storage uno::Reference<document::XStorageBasedDocument> const xSBD(xModel, uno::UNO_QUERY_THROW); uno::Reference<embed::XStorage> const xStorage( xSBD->getDocumentStorage(), uno::UNO_QUERY_THROW); // Model storage const OUString sModel("Model"); uno::Reference<embed::XStorage> const xModelStorage( xStorage->openStorageElement(sModel, embed::ElementModes::WRITE)); // Own storage of the corresponding model const OUString sFilename(GetFilename(rSourceURL)); const OUString sGLTFDir(sFilename.copy(0,sFilename.lastIndexOf('.'))); uno::Reference<embed::XStorage> const xSubStorage( xModelStorage->openStorageElement(sGLTFDir, embed::ElementModes::WRITE)); // Embed external resources lcl_EmbedExternals(rSourceURL, xSubStorage, aSourceContent); // Save model file (.json) uno::Reference<io::XStream> const xStream( CreateStream(xSubStorage, sFilename), uno::UNO_SET_THROW); uno::Reference<io::XOutputStream> const xOutStream( xStream->getOutputStream(), uno::UNO_SET_THROW); if (!aSourceContent.openStream(xOutStream)) { SAL_INFO("avmedia.model", "openStream to storage failed"); return false; } const uno::Reference<embed::XTransactedObject> xSubTransaction(xSubStorage, uno::UNO_QUERY); if (xSubTransaction.is()) { xSubTransaction->commit(); } const uno::Reference<embed::XTransactedObject> xModelTransaction(xModelStorage, uno::UNO_QUERY); if (xModelTransaction.is()) { xModelTransaction->commit(); } const uno::Reference<embed::XTransactedObject> xTransaction(xStorage, uno::UNO_QUERY); if (xTransaction.is()) { xTransaction->commit(); } o_rEmbeddedURL = "vnd.sun.star.Package:" + sModel + "/" + sGLTFDir + "/" + sFilename; return true; } catch (uno::Exception const&) { SAL_WARN("avmedia.model", "Exception while trying to embed model"); } return false; } } // namespace avemdia /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>gltf: Trying to re-create the temp path fails on Windows.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <avmedia/modeltools.hxx> #include <avmedia/mediaitem.hxx> #include <com/sun/star/embed/ElementModes.hpp> #include <com/sun/star/embed/XTransactedObject.hpp> #include <com/sun/star/document/XStorageBasedDocument.hpp> #include <com/sun/star/embed/XStorage.hpp> #include <osl/file.hxx> #include <comphelper/processfactory.hxx> #include <tools/urlobj.hxx> #include <ucbhelper/content.hxx> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/foreach.hpp> #include <string> #include <vector> using namespace ::com::sun::star; using namespace boost::property_tree; namespace avmedia { static void lcl_EmbedExternals(const OUString& rSourceURL, uno::Reference<embed::XStorage> xSubStorage, ::ucbhelper::Content& rContent) { // Create a temp file with which json parser can work. OUString sTempFileURL; const ::osl::FileBase::RC aErr = ::osl::FileBase::createTempFile(0, 0, &sTempFileURL); if (::osl::FileBase::E_None != aErr) { SAL_WARN("avmedia.model", "cannot create temp file"); return; } try { // Write json content to the temp file ::ucbhelper::Content aTempContent(sTempFileURL, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); aTempContent.writeStream(rContent.openStream(), true); } catch (uno::Exception const& e) { SAL_WARN("avmedia.model", "exception: '" << e.Message << "'"); return; } // Convert URL to a file path for loading const INetURLObject aURLObj(sTempFileURL); std::string sUrl = OUStringToOString( aURLObj.getFSysPath(INetURLObject::FSYS_DETECT), RTL_TEXTENCODING_UTF8 ).getStr(); // Parse json, read externals' URI and modify this relative URI's so they remain valid in the new context. std::vector<std::string> vExternals; ptree aTree; try { json_parser::read_json( sUrl, aTree ); // Buffers for geometry and animations BOOST_FOREACH(ptree::value_type &rVal,aTree.get_child("buffers")) { const std::string sBufferUri(rVal.second.get<std::string>("path")); vExternals.push_back(sBufferUri); // Change path: make it contain only a file name aTree.put("buffers." + rVal.first + ".path.",sBufferUri.substr(sBufferUri.find_last_of('/')+1)); } // Images for textures BOOST_FOREACH(ptree::value_type &rVal,aTree.get_child("images")) { const std::string sImageUri(rVal.second.get<std::string>("path")); vExternals.push_back(sImageUri); // Change path: make it contain only a file name aTree.put("images." + rVal.first + ".path.",sImageUri.substr(sImageUri.find_last_of('/')+1)); } // Shaders (contains names only) BOOST_FOREACH(ptree::value_type &rVal,aTree.get_child("programs")) { vExternals.push_back(rVal.second.get<std::string>("fragmentShader") + ".glsl"); vExternals.push_back(rVal.second.get<std::string>("vertexShader") + ".glsl"); } // Write out modified json json_parser::write_json( sUrl, aTree ); } catch ( boost::exception const& ) { SAL_WARN("avmedia.model", "failed to parse json file"); return; } // Reload json with modified path to external resources rContent = ::ucbhelper::Content(sTempFileURL, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); // Store all external files next to the json file for( std::vector<std::string>::iterator aCIter = vExternals.begin(); aCIter != vExternals.end(); ++aCIter ) { const OUString sAbsURL = INetURLObject::GetAbsURL(rSourceURL,OUString::createFromAscii(aCIter->c_str())); ::ucbhelper::Content aContent(sAbsURL, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); uno::Reference<io::XStream> const xStream( CreateStream(xSubStorage, GetFilename(sAbsURL)), uno::UNO_SET_THROW); uno::Reference<io::XOutputStream> const xOutStream( xStream->getOutputStream(), uno::UNO_SET_THROW); if (!aContent.openStream(xOutStream)) { SAL_WARN("avmedia.model", "openStream to storage failed"); return; } } } bool Embed3DModel( const uno::Reference<frame::XModel>& xModel, const OUString& rSourceURL, OUString& o_rEmbeddedURL) { try { ::ucbhelper::Content aSourceContent(rSourceURL, uno::Reference<ucb::XCommandEnvironment>(), comphelper::getProcessComponentContext()); // Base storage uno::Reference<document::XStorageBasedDocument> const xSBD(xModel, uno::UNO_QUERY_THROW); uno::Reference<embed::XStorage> const xStorage( xSBD->getDocumentStorage(), uno::UNO_QUERY_THROW); // Model storage const OUString sModel("Model"); uno::Reference<embed::XStorage> const xModelStorage( xStorage->openStorageElement(sModel, embed::ElementModes::WRITE)); // Own storage of the corresponding model const OUString sFilename(GetFilename(rSourceURL)); const OUString sGLTFDir(sFilename.copy(0,sFilename.lastIndexOf('.'))); uno::Reference<embed::XStorage> const xSubStorage( xModelStorage->openStorageElement(sGLTFDir, embed::ElementModes::WRITE)); // Embed external resources lcl_EmbedExternals(rSourceURL, xSubStorage, aSourceContent); // Save model file (.json) uno::Reference<io::XStream> const xStream( CreateStream(xSubStorage, sFilename), uno::UNO_SET_THROW); uno::Reference<io::XOutputStream> const xOutStream( xStream->getOutputStream(), uno::UNO_SET_THROW); if (!aSourceContent.openStream(xOutStream)) { SAL_INFO("avmedia.model", "openStream to storage failed"); return false; } const uno::Reference<embed::XTransactedObject> xSubTransaction(xSubStorage, uno::UNO_QUERY); if (xSubTransaction.is()) { xSubTransaction->commit(); } const uno::Reference<embed::XTransactedObject> xModelTransaction(xModelStorage, uno::UNO_QUERY); if (xModelTransaction.is()) { xModelTransaction->commit(); } const uno::Reference<embed::XTransactedObject> xTransaction(xStorage, uno::UNO_QUERY); if (xTransaction.is()) { xTransaction->commit(); } o_rEmbeddedURL = "vnd.sun.star.Package:" + sModel + "/" + sGLTFDir + "/" + sFilename; return true; } catch (uno::Exception const&) { SAL_WARN("avmedia.model", "Exception while trying to embed model"); } return false; } } // namespace avemdia /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include "core/itf/ray.h" #include "core/itf/triangle.h" #include "math/itf/constants.h" #include <iostream> using namespace lb; using namespace lb::math; Ray::Ray(const Vector &origin, const Vector &direction): o(origin), d(direction) { } bool Ray::intersectsGeometrically(const Triangle &triangle) const { double k = dot(triangle.n, d); // In case the ray and the triangle are parallel, the ray does not intersect // the triangle. if (k == 0) { return false; } double t = -(dot(triangle.n, o) + triangle.D) / k; // In case the intersection point lies behind the ray's origin, the ray does // not intersect the triangle. if (t < 0) { return false; } // Find the intersection point P. Vector P = o + t * d; // The ray intersects the plane of the triangle. Now determine whether the // intersection point lies within the triangle. return (dot(triangle.n, cross(triangle.e0, P - triangle.v0)) > 0 && dot(triangle.n, cross(triangle.v1v2, P - triangle.v1)) > 0 && dot(triangle.n, cross(triangle.v2v0, P - triangle.v2)) > 0); } bool Ray::intersectsMollerTrumbore(const Triangle &triangle) const { Vector T = o - triangle.v0; Vector P = cross(d, triangle.e1); double determinant = dot(P, triangle.e0); if (determinant < EPSILON) { return false; } // Now calculate the barycentric coordinates u and v. double u = dot(P, T); if (u < EPSILON || u > determinant) { return false; } // In case v lies between 0 and 1, we have an intersection. double v = dot(cross(T, triangle.e0), d); if (v < EPSILON || v > determinant) { return false; } return v >= EPSILON && (determinant - u - v) >= EPSILON; } std::ostream &lb::operator<<(std::ostream &out, const Ray &r) { out << "Ray, origin: " << r.o << ", direction: " << r.d << std::endl; return out; } <commit_msg>Defer calculation of vector T.<commit_after>#include "core/itf/ray.h" #include "core/itf/triangle.h" #include "math/itf/constants.h" #include <iostream> using namespace lb; using namespace lb::math; Ray::Ray(const Vector &origin, const Vector &direction): o(origin), d(direction) { } bool Ray::intersectsGeometrically(const Triangle &triangle) const { double k = dot(triangle.n, d); // In case the ray and the triangle are parallel, the ray does not intersect // the triangle. if (k == 0) { return false; } double t = -(dot(triangle.n, o) + triangle.D) / k; // In case the intersection point lies behind the ray's origin, the ray does // not intersect the triangle. if (t < 0) { return false; } // Find the intersection point P. Vector P = o + t * d; // The ray intersects the plane of the triangle. Now determine whether the // intersection point lies within the triangle. return (dot(triangle.n, cross(triangle.e0, P - triangle.v0)) > 0 && dot(triangle.n, cross(triangle.v1v2, P - triangle.v1)) > 0 && dot(triangle.n, cross(triangle.v2v0, P - triangle.v2)) > 0); } bool Ray::intersectsMollerTrumbore(const Triangle &triangle) const { Vector P = cross(d, triangle.e1); double determinant = dot(P, triangle.e0); if (determinant < EPSILON) { return false; } Vector T = o - triangle.v0; // Now calculate the barycentric coordinates u and v. double u = dot(P, T); if (u < EPSILON || u > determinant) { return false; } // In case v lies between 0 and 1, we have an intersection. double v = dot(cross(T, triangle.e0), d); if (v < EPSILON || v > determinant) { return false; } return v >= EPSILON && (determinant - u - v) >= EPSILON; } std::ostream &lb::operator<<(std::ostream &out, const Ray &r) { out << "Ray, origin: " << r.o << ", direction: " << r.d << std::endl; return out; } <|endoftext|>
<commit_before>// Steer TRD QA train for Reconstruction (Clusterizer, Tracking and PID). // // Usage: // run.C(tasks, files) // tasks : "ALL" or one/more of the following: // "EFF" : TRD Tracking Efficiency // "EFFC" : TRD Tracking Efficiency Combined (barrel + stand alone) - only in case of simulations // "MULT" : TRD single track selection // "RES" : TRD tracking Resolution // "CLRES": clusters Resolution // "CAL" : TRD calibration // "ALGN" : TRD alignment // "PID" : TRD PID - pion efficiency // "PIDR" : TRD PID - reference data // "DET" : Basic TRD Detector checks // "NOFR" : Data set does not have AliESDfriends.root // "NOMC" : Data set does not have Monte Carlo Informations (real data), so all tasks which rely // on MC information are switched off // // In compiled mode : // Don't forget to load first the libraries // gSystem->Load("libMemStat.so") // gSystem->Load("libMemStatGui.so") // gSystem->Load("libANALYSIS.so") // gSystem->Load("libANALYSISalice.so") // gSystem->Load("libTRDqaRec.so") // gSystem->Load("libPWG1.so"); // gSystem->Load("libNetx.so") ; // gSystem->Load("libRAliEn.so"); // // Authors: // Alex Bercuci (A.Bercuci@gsi.de) // Markus Fasel (m.Fasel@gsi.de) #ifndef __CINT__ #include <Riostream.h> #include "TStopwatch.h" #include "TMemStat.h" #include "TMemStatViewerGUI.h" #include "TROOT.h" #include "TClass.h" #include "TSystem.h" #include "TError.h" #include "TChain.h" #include "TGrid.h" #include "TAlienCollection.h" #include "TGridCollection.h" #include "TGridResult.h" #include "TGeoGlobalMagField.h" #include "AliMagF.h" #include "AliTracker.h" #include "AliLog.h" #include "AliCDBManager.h" #include "AliGRPManager.h" #include "AliGeomManager.h" #include "AliAnalysisManager.h" #include "AliAnalysisDataContainer.h" #include "AliMCEventHandler.h" #include "AliESDInputHandler.h" #include "TRD/AliTRDtrackerV1.h" #include "TRD/AliTRDcalibDB.h" #include "TRD/qaRec/macros/AddTRDcheckESD.C" #include "TRD/qaRec/macros/AddTRDinfoGen.C" #include "TRD/qaRec/macros/AddTRDcheckDET.C" #include "TRD/qaRec/macros/AddTRDefficiency.C" #include "TRD/qaRec/macros/AddTRDresolution.C" #include "TRD/qaRec/macros/AddTRDcheckPID.C" #include "../../PWG1/macros/AddPerformanceTask.C" #endif #include "macros/AliTRDperformanceTrain.h" #include "../../PWG1/macros/AddPerformanceTask.h" Bool_t MEM = kFALSE; TChain* MakeChainLST(const char* filename = 0x0); TChain* MakeChainXML(const char* filename = 0x0); void run(Char_t *trd="ALL", Char_t *tpc="ALL", const Char_t *files=0x0, Long64_t nev=1234567890, Long64_t first = 0) { TMemStat *mem = 0x0; if(MEM){ gSystem->Load("libMemStat.so"); gSystem->Load("libMemStatGui.so"); mem = new TMemStat("new, gnubuildin"); mem->AddStamp("Start"); } TStopwatch timer; timer.Start(); // VERY GENERAL SETTINGS AliLog::SetGlobalLogLevel(AliLog::kError); if(gSystem->Load("libANALYSIS.so")<0) return; if(gSystem->Load("libANALYSISalice.so")<0) return; Bool_t fHasMCdata = HasReadMCData(trd); Bool_t fHasFriends = HasReadFriendData(trd); // INITIALIZATION OF RUNNING ENVIRONMENT //TODO We should use the GRP if available similar to AliReconstruction::InitGRP()! // initialize OCDB manager AliCDBManager *cdbManager = AliCDBManager::Instance(); cdbManager->SetDefaultStorage("local://$ALICE_ROOT/OCDB"); cdbManager->SetSpecificStorage("GRP/GRP/Data", Form("local://%s",gSystem->pwd())); cdbManager->SetRun(0); cdbManager->SetCacheFlag(kFALSE); // initialize magnetic field from the GRP manager. AliGRPManager grpMan; grpMan.ReadGRPEntry(); grpMan.SetMagField(); //AliRunInfo *runInfo = grpMan.GetRunInfo(); AliGeomManager::LoadGeometry(); // DEFINE DATA CHAIN TChain *chain = 0x0; if(!files) chain = MakeChainLST(); else{ TString fn(files); if(fn.EndsWith("xml")) chain = MakeChainXML(files); else chain = MakeChainLST(files); } if(!chain) return; chain->SetBranchStatus("*FMD*",0); chain->SetBranchStatus("*Calo*",0); chain->SetBranchStatus("Tracks", 1); chain->SetBranchStatus("ESDfriend*",1); chain->Lookup(); chain->GetListOfFiles()->Print(); printf("\n ----> CHAIN HAS %d ENTRIES <----\n\n", (Int_t)chain->GetEntries()); // BUILD ANALYSIS MANAGER AliAnalysisManager *mgr = new AliAnalysisManager("Post Reconstruction Calibration/QA"); AliVEventHandler *esdH = 0x0, *mcH = 0x0; mgr->SetInputEventHandler(esdH = new AliESDInputHandler); if(fHasMCdata) mgr->SetMCtruthEventHandler(mcH = new AliMCEventHandler()); //mgr->SetDebugLevel(10); /////////////////////////////////////////////////////////// /////////////// TRD /////////// /////////////////////////////////////////////////////////// // TRD specific library if(gSystem->Load("libTRDqaRec.so")<0) return; // TRD data containers AliAnalysisDataContainer *ci[] = {0x0, 0x0, 0x0}; // initialize TRD settings AliTRDcalibDB *cal = AliTRDcalibDB::Instance(); AliTRDtrackerV1::SetNTimeBins(cal->GetNumberOfTimeBins()); // plug (set of) TRD wagons in the train if(trd){ for(Int_t it=0; it<NTRDQATASKS; it++){ if(gROOT->LoadMacro(Form("$ALICE_ROOT/TRD/qaRec/macros/Add%s.C+", TString(fgkTRDtaskClassName[it])(3,20).Data()))) { Error("run.C", Form("Error loading %s task.", fgkTRDtaskClassName[it])); return; } switch(it){ case kCheckESD: AddTRDcheckESD(mgr); break; case kInfoGen: AddTRDinfoGen(mgr, trd, 0x0, ci); break; case kCheckDET: AddTRDcheckDET(mgr, trd, ci); break; case kEfficiency: AddTRDefficiency(mgr, trd, ci); break; case kResolution: AddTRDresolution(mgr, trd, ci); break; case kCheckPID: AddTRDcheckPID(mgr, trd, ci); break; default: Warning("run.C", Form("No performance task registered at slot %d.", it)); } } } /////////////////////////////////////////////////////////// /////////////// TPC /////////// /////////////////////////////////////////////////////////// if(gSystem->Load("libPWG1.so")<0) return; // BUILD STEERING TASK FOR TPC if(tpc){ if(gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddPerformanceTask.C+")) { Error("run.C", "Error loading AliPerformanceTask task."); return; } AddPerformanceTask(mgr, tpc); } if (!mgr->InitAnalysis()) return; // verbosity printf("\n\tRUNNING TRAIN FOR TASKS:\n"); mgr->GetTasks()->ls(); //mgr->PrintStatus(); mgr->StartAnalysis("local", chain, nev, first); timer.Stop(); timer.Print(); cal->Terminate(); TGeoGlobalMagField::Instance()->SetField(NULL); delete cdbManager; // verbosity printf("\n\tCLEANING UP TRAIN:\n"); mgr->GetTasks()->Delete(); if(mcH) delete mcH; delete esdH; delete mgr; delete chain; if(MEM) delete mem; if(MEM) TMemStatViewerGUI::ShowGUI(); } //____________________________________________ TChain* MakeChainLST(const char* filename) { // Create the chain TChain* chain = new TChain("esdTree"); if(!filename){ chain->Add(Form("%s/AliESDs.root", gSystem->pwd())); return chain; } // read ESD files from the input list. ifstream in; in.open(filename); TString esdfile; while(in.good()) { in >> esdfile; if (!esdfile.Contains("root")) continue; // protection chain->Add(esdfile.Data()); } in.close(); return chain; } //____________________________________________ TChain* MakeChainXML(const char* xmlfile) { if (!TFile::Open(xmlfile)) { Error("MakeChainXML", Form("No file %s was found", xmlfile)); return 0x0; } if(gSystem->Load("libNetx.so")<0) return 0x0; if(gSystem->Load("libRAliEn.so")<0) return 0x0; TGrid::Connect("alien://") ; TGridCollection *collection = (TGridCollection*) TAlienCollection::Open(xmlfile); if (!collection) { Error("MakeChainXML", Form("No collection found in %s", xmlfile)) ; return 0x0; } //collection->CheckIfOnline(); TGridResult* result = collection->GetGridResult("",0 ,0); if(!result->GetEntries()){ Error("MakeChainXML", Form("No entries found in %s", xmlfile)) ; return 0x0; } // Makes the ESD chain TChain* chain = new TChain("esdTree"); for (Int_t idx = 0; idx < result->GetEntries(); idx++) { chain->Add(result->GetKey(idx, "turl")); } return chain; } <commit_msg>fix include statements<commit_after>// Steer TRD QA train for Reconstruction (Clusterizer, Tracking and PID). // // Usage: // run.C(tasks, files) // tasks : "ALL" or one/more of the following: // "EFF" : TRD Tracking Efficiency // "EFFC" : TRD Tracking Efficiency Combined (barrel + stand alone) - only in case of simulations // "MULT" : TRD single track selection // "RES" : TRD tracking Resolution // "CLRES": clusters Resolution // "CAL" : TRD calibration // "ALGN" : TRD alignment // "PID" : TRD PID - pion efficiency // "PIDR" : TRD PID - reference data // "DET" : Basic TRD Detector checks // "NOFR" : Data set does not have AliESDfriends.root // "NOMC" : Data set does not have Monte Carlo Informations (real data), so all tasks which rely // on MC information are switched off // // In compiled mode : // Don't forget to load first the libraries // gSystem->Load("libMemStat.so") // gSystem->Load("libMemStatGui.so") // gSystem->Load("libANALYSIS.so") // gSystem->Load("libANALYSISalice.so") // gSystem->Load("libTRDqaRec.so") // gSystem->Load("libPWG1.so"); // gSystem->Load("libNetx.so") ; // gSystem->Load("libRAliEn.so"); // // Authors: // Alex Bercuci (A.Bercuci@gsi.de) // Markus Fasel (m.Fasel@gsi.de) #ifndef __CINT__ #include <Riostream.h> #include "TStopwatch.h" #include "TMemStat.h" #include "TMemStatViewerGUI.h" #include "TROOT.h" #include "TClass.h" #include "TSystem.h" #include "TError.h" #include "TChain.h" #include "TGrid.h" #include "TAlienCollection.h" #include "TGridCollection.h" #include "TGridResult.h" #include "TGeoGlobalMagField.h" #include "AliMagF.h" #include "AliTracker.h" #include "AliLog.h" #include "AliCDBManager.h" #include "AliGRPManager.h" #include "AliGeomManager.h" #include "AliAnalysisManager.h" #include "AliAnalysisDataContainer.h" #include "AliMCEventHandler.h" #include "AliESDInputHandler.h" #include "TRD/AliTRDtrackerV1.h" #include "TRD/AliTRDcalibDB.h" #include "TRD/qaRec/macros/AddTRDcheckESD.C" #include "TRD/qaRec/macros/AddTRDinfoGen.C" #include "TRD/qaRec/macros/AddTRDcheckDET.C" #include "TRD/qaRec/macros/AddTRDefficiency.C" #include "TRD/qaRec/macros/AddTRDresolution.C" #include "TRD/qaRec/macros/AddTRDcheckPID.C" #include "PWG1/macros/AddPerformanceTask.C" #endif #include "TRD/qaRec/macros/AliTRDperformanceTrain.h" #include "PWG1/macros/AddPerformanceTask.h" Bool_t MEM = kFALSE; TChain* MakeChainLST(const char* filename = 0x0); TChain* MakeChainXML(const char* filename = 0x0); void run(Char_t *trd="ALL", Char_t *tpc="ALL", const Char_t *files=0x0, Long64_t nev=1234567890, Long64_t first = 0) { TMemStat *mem = 0x0; if(MEM){ gSystem->Load("libMemStat.so"); gSystem->Load("libMemStatGui.so"); mem = new TMemStat("new, gnubuildin"); mem->AddStamp("Start"); } TStopwatch timer; timer.Start(); // VERY GENERAL SETTINGS AliLog::SetGlobalLogLevel(AliLog::kError); if(gSystem->Load("libANALYSIS.so")<0) return; if(gSystem->Load("libANALYSISalice.so")<0) return; Bool_t fHasMCdata = HasReadMCData(trd); //Bool_t fHasFriends = HasReadFriendData(trd); // INITIALIZATION OF RUNNING ENVIRONMENT //TODO We should use the GRP if available similar to AliReconstruction::InitGRP()! // initialize OCDB manager AliCDBManager *cdbManager = AliCDBManager::Instance(); cdbManager->SetDefaultStorage("local://$ALICE_ROOT/OCDB"); cdbManager->SetSpecificStorage("GRP/GRP/Data", Form("local://%s",gSystem->pwd())); cdbManager->SetRun(0); cdbManager->SetCacheFlag(kFALSE); // initialize magnetic field from the GRP manager. AliGRPManager grpMan; grpMan.ReadGRPEntry(); grpMan.SetMagField(); //AliRunInfo *runInfo = grpMan.GetRunInfo(); AliGeomManager::LoadGeometry(); // DEFINE DATA CHAIN TChain *chain = 0x0; if(!files) chain = MakeChainLST(); else{ TString fn(files); if(fn.EndsWith("xml")) chain = MakeChainXML(files); else chain = MakeChainLST(files); } if(!chain) return; chain->SetBranchStatus("*FMD*",0); chain->SetBranchStatus("*Calo*",0); chain->SetBranchStatus("Tracks", 1); chain->SetBranchStatus("ESDfriend*",1); chain->Lookup(); chain->GetListOfFiles()->Print(); printf("\n ----> CHAIN HAS %d ENTRIES <----\n\n", (Int_t)chain->GetEntries()); // BUILD ANALYSIS MANAGER AliAnalysisManager *mgr = new AliAnalysisManager("Post Reconstruction Calibration/QA"); AliVEventHandler *esdH = 0x0, *mcH = 0x0; mgr->SetInputEventHandler(esdH = new AliESDInputHandler); if(fHasMCdata) mgr->SetMCtruthEventHandler(mcH = new AliMCEventHandler()); //mgr->SetDebugLevel(10); /////////////////////////////////////////////////////////// /////////////// TRD /////////// /////////////////////////////////////////////////////////// // TRD specific library if(gSystem->Load("libTRDqaRec.so")<0) return; // TRD data containers AliAnalysisDataContainer *ci[] = {0x0, 0x0, 0x0}; // initialize TRD settings AliTRDcalibDB *cal = AliTRDcalibDB::Instance(); AliTRDtrackerV1::SetNTimeBins(cal->GetNumberOfTimeBins()); // plug (set of) TRD wagons in the train if(trd){ for(Int_t it=0; it<NTRDQATASKS; it++){ if(gROOT->LoadMacro(Form("$ALICE_ROOT/TRD/qaRec/macros/Add%s.C+", TString(fgkTRDtaskClassName[it])(3,20).Data()))) { Error("run.C", Form("Error loading %s task.", fgkTRDtaskClassName[it])); return; } switch(it){ case kCheckESD: AddTRDcheckESD(mgr); break; case kInfoGen: AddTRDinfoGen(mgr, trd, 0x0, ci); break; case kCheckDET: AddTRDcheckDET(mgr, trd, ci); break; case kEfficiency: AddTRDefficiency(mgr, trd, ci); break; case kResolution: AddTRDresolution(mgr, trd, ci); break; case kCheckPID: AddTRDcheckPID(mgr, trd, ci); break; default: Warning("run.C", Form("No performance task registered at slot %d.", it)); } } } /////////////////////////////////////////////////////////// /////////////// TPC /////////// /////////////////////////////////////////////////////////// if(gSystem->Load("libPWG1.so")<0) return; // BUILD STEERING TASK FOR TPC if(tpc){ if(gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddPerformanceTask.C+")) { Error("run.C", "Error loading AliPerformanceTask task."); return; } AddPerformanceTask(mgr, tpc); } if (!mgr->InitAnalysis()) return; // verbosity printf("\n\tRUNNING TRAIN FOR TASKS:\n"); mgr->GetTasks()->ls(); //mgr->PrintStatus(); mgr->StartAnalysis("local", chain, nev, first); timer.Stop(); timer.Print(); cal->Terminate(); TGeoGlobalMagField::Instance()->SetField(NULL); delete cdbManager; // verbosity printf("\n\tCLEANING UP TRAIN:\n"); mgr->GetTasks()->Delete(); if(mcH) delete mcH; delete esdH; delete mgr; delete chain; if(MEM) delete mem; if(MEM) TMemStatViewerGUI::ShowGUI(); } //____________________________________________ TChain* MakeChainLST(const char* filename) { // Create the chain TChain* chain = new TChain("esdTree"); if(!filename){ chain->Add(Form("%s/AliESDs.root", gSystem->pwd())); return chain; } // read ESD files from the input list. ifstream in; in.open(filename); TString esdfile; while(in.good()) { in >> esdfile; if (!esdfile.Contains("root")) continue; // protection chain->Add(esdfile.Data()); } in.close(); return chain; } //____________________________________________ TChain* MakeChainXML(const char* xmlfile) { if (!TFile::Open(xmlfile)) { Error("MakeChainXML", Form("No file %s was found", xmlfile)); return 0x0; } if(gSystem->Load("libNetx.so")<0) return 0x0; if(gSystem->Load("libRAliEn.so")<0) return 0x0; TGrid::Connect("alien://") ; TGridCollection *collection = (TGridCollection*) TAlienCollection::Open(xmlfile); if (!collection) { Error("MakeChainXML", Form("No collection found in %s", xmlfile)) ; return 0x0; } //collection->CheckIfOnline(); TGridResult* result = collection->GetGridResult("",0 ,0); if(!result->GetEntries()){ Error("MakeChainXML", Form("No entries found in %s", xmlfile)) ; return 0x0; } // Makes the ESD chain TChain* chain = new TChain("esdTree"); for (Int_t idx = 0; idx < result->GetEntries(); idx++) { chain->Add(result->GetKey(idx, "turl")); } return chain; } <|endoftext|>
<commit_before>// This file is part of Poseidon. // Copyleft 2020, LH_Mouse. All wrongs reserved. #ifndef POSEIDON_FWD_HPP_ #define POSEIDON_FWD_HPP_ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <asteria/fwd.hpp> #include <rocket/ascii_case.hpp> #include <rocket/linear_buffer.hpp> #include <rocket/atomic.hpp> #include <rocket/mutex.hpp> #include <rocket/recursive_mutex.hpp> #include <rocket/condition_variable.hpp> #include <rocket/once_flag.hpp> #include <string> #include <vector> #include <deque> #include <unistd.h> namespace poseidon { namespace noadl = poseidon; // Macros #define POSEIDON_STATIC_CLASS_DECLARE(C) \ private: \ struct __attribute__((__visibility__("hidden"))) C##_self; \ static C##_self* const self; \ \ constexpr C() noexcept = default; \ C(const C&) = delete; \ C& operator=(const C&) = delete; \ ~C() = default // no semicolon #define POSEIDON_STATIC_CLASS_DEFINE(C) \ class C; \ struct C::C##_self* const C::self = \ ::rocket::make_unique<C::C##_self>().release(); \ struct C::C##_self : C \ // add members here // Aliases using ::std::initializer_list; using ::std::integer_sequence; using ::std::index_sequence; using ::std::nullptr_t; using ::std::max_align_t; using ::std::int8_t; using ::std::uint8_t; using ::std::int16_t; using ::std::uint16_t; using ::std::int32_t; using ::std::uint32_t; using ::std::int64_t; using ::std::uint64_t; using ::std::intptr_t; using ::std::uintptr_t; using ::std::intmax_t; using ::std::uintmax_t; using ::std::ptrdiff_t; using ::std::size_t; using ::std::wint_t; using ::std::exception; using ::std::type_info; using ::std::pair; using ::asteria::nullopt_t; using ::asteria::cow_string; using ::asteria::cow_u16string; using ::asteria::cow_u32string; using ::asteria::phsh_string; using ::asteria::tinybuf; using ::asteria::tinyfmt; using ::asteria::begin; using ::asteria::end; using ::asteria::swap; using ::asteria::xswap; using ::asteria::size; using ::asteria::nullopt; using ::asteria::sref; using ::asteria::uptr; using ::asteria::rcptr; using ::asteria::rcfwdp; using ::asteria::array; using ::asteria::opt; using ::asteria::static_pointer_cast; using ::asteria::dynamic_pointer_cast; using ::asteria::const_pointer_cast; using ::asteria::unerase_cast; using ::asteria::unerase_pointer_cast; using ::rocket::linear_buffer; using ::rocket::atomic; using ::rocket::atomic_relaxed; using ::rocket::atomic_acq_rel; using ::rocket::atomic_seq_cst; using atomic_signal = atomic_relaxed<int>; using simple_mutex = ::rocket::mutex; using ::rocket::recursive_mutex; using ::rocket::condition_variable; using ::rocket::once_flag; struct FD_Closer { constexpr int null() const noexcept { return -1; } constexpr bool is_null(int fd) const noexcept { return fd == -1; } void close(int fd) { ::close(fd); } }; using unique_FD = ::rocket::unique_handle<int, FD_Closer>; static_assert(sizeof(unique_FD) == sizeof(int)); // Core class Config_File; class Abstract_Timer; class Abstract_Async_Job; class Abstract_Future; class Abstract_Fiber; class URL; template<typename V> class Promise; template<typename V> class Future; template<typename V> using prom = Promise<V>; template<typename V> using futp = rcptr<const Future<V>>; // Socket enum IO_Result : ptrdiff_t; enum Connection_State : uint8_t; enum Socket_Address_Class : uint8_t; struct SSL_deleter; struct SSL_CTX_deleter; class Socket_Address; class Abstract_Socket; class Abstract_Accept_Socket; class Abstract_Stream_Socket; class Abstract_TCP_Socket; class Abstract_TCP_Server_Socket; class Abstract_TCP_Client_Socket; class Abstract_TLS_Socket; class Abstract_TLS_Server_Socket; class Abstract_TLS_Client_Socket; class Abstract_UDP_Socket; // HTTP enum HTTP_Version : uint16_t; enum HTTP_Verb : uint8_t; enum HTTP_Status : uint16_t; enum HTTP_Status_Class : uint8_t; class Option_Map; // Singletons class Main_Config; class Async_Logger; class Timer_Driver; class Network_Driver; class Worker_Pool; class Fiber_Scheduler; // Log levels // Note each level has a hardcoded name and number. // Don't change their values or reorder them. enum Log_Level : uint8_t { log_level_fatal = 0, log_level_error = 1, log_level_warn = 2, log_level_info = 3, log_level_debug = 4, log_level_trace = 5, }; // Future states enum Future_State : uint8_t { future_state_empty = 0, future_state_value = 1, future_state_except = 2, }; // Asynchronous function states enum Async_State : uint8_t { async_state_initial = 0, async_state_pending = 1, async_state_suspended = 2, async_state_running = 3, async_state_finished = 4, }; } // namespace poseidon #endif <commit_msg>fwd: Minor<commit_after>// This file is part of Poseidon. // Copyleft 2020, LH_Mouse. All wrongs reserved. #ifndef POSEIDON_FWD_HPP_ #define POSEIDON_FWD_HPP_ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <asteria/fwd.hpp> #include <rocket/ascii_case.hpp> #include <rocket/linear_buffer.hpp> #include <rocket/atomic.hpp> #include <rocket/mutex.hpp> #include <rocket/recursive_mutex.hpp> #include <rocket/condition_variable.hpp> #include <rocket/once_flag.hpp> #include <string> #include <vector> #include <deque> #include <unistd.h> namespace poseidon { namespace noadl = poseidon; // Macros #define POSEIDON_STATIC_CLASS_DECLARE(C) \ private: \ struct __attribute__((__visibility__("hidden"))) C##_self; \ static C##_self* const self; \ \ constexpr C() noexcept = default; \ C(const C&) = delete; \ C& operator=(const C&) = delete; \ ~C() = default // no semicolon #define POSEIDON_STATIC_CLASS_DEFINE(C) \ class C; \ struct C::C##_self* const C::self = \ ::rocket::make_unique<C::C##_self>().release(); \ struct C::C##_self : C \ // add members here // Aliases using ::std::initializer_list; using ::std::integer_sequence; using ::std::index_sequence; using ::std::nullptr_t; using ::std::max_align_t; using ::std::int8_t; using ::std::uint8_t; using ::std::int16_t; using ::std::uint16_t; using ::std::int32_t; using ::std::uint32_t; using ::std::int64_t; using ::std::uint64_t; using ::std::intptr_t; using ::std::uintptr_t; using ::std::intmax_t; using ::std::uintmax_t; using ::std::ptrdiff_t; using ::std::size_t; using ::std::wint_t; using ::std::exception; using ::std::type_info; using ::std::pair; using ::asteria::nullopt_t; using ::asteria::cow_string; using ::asteria::cow_u16string; using ::asteria::cow_u32string; using ::asteria::phsh_string; using ::asteria::tinybuf; using ::asteria::tinyfmt; using ::asteria::begin; using ::asteria::end; using ::asteria::swap; using ::asteria::xswap; using ::asteria::size; using ::asteria::nullopt; using ::asteria::sref; using ::asteria::uptr; using ::asteria::rcptr; using ::asteria::rcfwdp; using ::asteria::array; using ::asteria::opt; using ::asteria::static_pointer_cast; using ::asteria::dynamic_pointer_cast; using ::asteria::const_pointer_cast; using ::asteria::unerase_cast; using ::asteria::unerase_pointer_cast; using ::rocket::linear_buffer; using ::rocket::atomic; using ::rocket::atomic_relaxed; using ::rocket::atomic_acq_rel; using ::rocket::atomic_seq_cst; using atomic_signal = atomic_relaxed<int>; using simple_mutex = ::rocket::mutex; using ::rocket::recursive_mutex; using ::rocket::condition_variable; using ::rocket::once_flag; struct FD_Closer { constexpr int null() const noexcept { return -1; } constexpr bool is_null(int fd) const noexcept { return fd == -1; } void close(int fd) { ::close(fd); } }; using unique_FD = ::rocket::unique_handle<int, FD_Closer>; static_assert(sizeof(unique_FD) == sizeof(int)); // Core class Config_File; class Abstract_Timer; class Abstract_Async_Job; class Abstract_Future; class Abstract_Fiber; class URL; template<typename V> class Promise; template<typename V> class Future; template<typename V> using prom = Promise<V>; template<typename V> using futp = rcptr<const Future<V>>; // Socket enum IO_Result : ptrdiff_t; enum Connection_State : uint8_t; enum Socket_Address_Class : uint8_t; struct SSL_deleter; struct SSL_CTX_deleter; class Socket_Address; class Abstract_Socket; class Abstract_Accept_Socket; class Abstract_Stream_Socket; class Abstract_TCP_Socket; class Abstract_TCP_Server_Socket; class Abstract_TCP_Client_Socket; class Abstract_TLS_Socket; class Abstract_TLS_Server_Socket; class Abstract_TLS_Client_Socket; class Abstract_UDP_Socket; // HTTP enum HTTP_Version : uint16_t; enum HTTP_Verb : uint8_t; enum HTTP_Status : uint16_t; enum HTTP_Status_Class : uint8_t; class Option_Map; // Singletons class Main_Config; class Async_Logger; class Timer_Driver; class Network_Driver; class Worker_Pool; class Fiber_Scheduler; // Log levels // Note each level has a hardcoded name and number. // Don't change their values or reorder them. enum Log_Level : uint8_t { log_level_fatal = 0, log_level_error = 1, log_level_warn = 2, log_level_info = 3, log_level_debug = 4, log_level_trace = 5, }; // Future states enum Future_State : uint8_t { future_state_empty = 0, future_state_value = 1, future_state_except = 2, }; // Asynchronous function states enum Async_State : uint8_t { async_state_initial = 0, async_state_pending = 1, async_state_suspended = 2, async_state_running = 3, async_state_finished = 4, }; } // namespace poseidon #endif <|endoftext|>
<commit_before>/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/extension.h" #include "hphp/runtime/ext/std/ext_std_function.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/vm/native-data.h" #include "hphp/runtime/base/array-init.h" #include "hphp/system/systemlib.h" #include <vector> #include <memory> #include <gearman.h> namespace HPHP { const StaticString s_GearmanClientData("GearmanClientData"); class GearmanClientData { public: class Impl { public: Impl() { gearman_client_create(&client); } ~Impl() { gearman_client_free(&client); } gearman_client_st client; }; GearmanClientData() {} ~GearmanClientData() {} typedef std::shared_ptr<Impl> ImplPtr; ImplPtr m_impl; }; const StaticString s_GearmanWorkerData("GearmanWorkerData"); class GearmanWorkerData { public: class Impl { public: Impl() { gearman_worker_create(&worker); } ~Impl() { gearman_worker_free(&worker); } gearman_worker_st worker; }; struct UserDefinedFunc { Variant func; }; GearmanWorkerData() {} ~GearmanWorkerData() {} typedef std::shared_ptr<Impl> ImplPtr; std::vector<std::shared_ptr<UserDefinedFunc>> m_udfs; ImplPtr m_impl; }; const StaticString s_GearmanJobData("GearmanJobData"); class GearmanJobData { public: class Impl { public: Impl() { } ~Impl() { } }; GearmanJobData() {} ~GearmanJobData() {} typedef std::shared_ptr<Impl> Implptr; Implptr m_impl; }; const StaticString s_GearmanTaskData("GearmanTaskData"); class GearmanTaskData { public: class Impl { public: Impl() { } ~Impl() { } gearman_task_st task; }; GearmanTaskData() {} ~GearmanTaskData() {} typedef std::shared_ptr<Impl> Implptr; Implptr m_impl; }; void HHVM_METHOD(GearmanClient, __construct) { auto data = Native::data<GearmanClientData>(this_); data->m_impl.reset(new GearmanClientData::Impl); } bool HHVM_METHOD(GearmanClient, addServer, const String& host, int64_t port) { auto data = Native::data<GearmanClientData>(this_); const char* myHost = host.empty() ? nullptr : host.c_str(); gearman_return_t ret = gearman_client_add_server(&data->m_impl->client, myHost, port); return ret == GEARMAN_SUCCESS; } bool HHVM_METHOD(GearmanClient, addServers, const String& servers) { auto data = Native::data<GearmanClientData>(this_); const char* myServers = servers.empty() ? nullptr : servers.c_str(); gearman_return_t ret = gearman_client_add_servers(&data->m_impl->client, myServers); return ret == GEARMAN_SUCCESS; } #define GEARMAN_CLIENT_DO(function_name, workload, unique) \ auto data = Native::data<GearmanClientData>(this_); \ const char* myFunctionName = function_name.empty() ? nullptr : function_name.c_str(); \ const char* myWorkload = workload.empty() ? nullptr : workload.c_str(); \ size_t workload_size = workload.length(); \ const char* myUnique = unique.empty() ? NULL : unique.c_str(); \ String HHVM_METHOD(GearmanClient, doNormal, const String& function_name, const String& workload, const String& unique /*= null*/) { GEARMAN_CLIENT_DO(function_name, workload, unique); size_t result_size; gearman_return_t ret; char* result = (char*) gearman_client_do(&data->m_impl->client, myFunctionName, myUnique, myWorkload, workload_size, &result_size, &ret); String myResult = String(result, result_size, CopyString); delete result; return myResult; } String HHVM_METHOD(GearmanClient, doHigh, const String& function_name, const String& workload, const String& unique /*= null*/) { GEARMAN_CLIENT_DO(function_name, workload, unique); size_t result_size; gearman_return_t ret; char* result = (char*) gearman_client_do_high(&data->m_impl->client, myFunctionName, myUnique, myWorkload, workload_size, &result_size, &ret); String myResult = String(result, result_size, CopyString); delete result; return myResult; } String HHVM_METHOD(GearmanClient, doBackground, const String& function_name, const String& workload, const String& unique /*= null*/) { GEARMAN_CLIENT_DO(function_name, workload, unique); gearman_job_handle_t handle; gearman_return_t ret = gearman_client_do_background(&data->m_impl->client, myFunctionName, myUnique, myWorkload, workload_size, handle); if (ret != GEARMAN_SUCCESS) { return String(); } return String(handle); } String HHVM_METHOD(GearmanClient, doHighBackground, const String& function_name, const String& workload, const String& unique /*= null*/) { GEARMAN_CLIENT_DO(function_name, workload, unique); gearman_job_handle_t handle; printf("%s\n", myFunctionName); return String(); gearman_return_t ret = gearman_client_do_high_background(&data->m_impl->client, myFunctionName, myUnique, myWorkload, workload_size, handle); if (ret != GEARMAN_SUCCESS) { return String(); } return String(handle); } bool HHVM_METHOD(GearmanClient, ping, const String& workload) { auto data = Native::data<GearmanClientData>(this_); const char* myWorkload = workload.empty() ? nullptr : workload.c_str(); size_t workload_size = workload.length(); gearman_return_t ret = gearman_client_echo(&data->m_impl->client, myWorkload, workload_size); return ret == GEARMAN_SUCCESS; } bool HHVM_METHOD(GearmanClient, setTimeout, int64_t timeout) { auto data = Native::data<GearmanClientData>(this_); gearman_client_set_timeout(&data->m_impl->client, timeout); return true; } Array HHVM_METHOD(GearmanClient, jobStatus, const String& job_handle) { auto data = Native::data<GearmanClientData>(this_); bool is_known, is_running; uint32_t numerator, denominator; gearman_return_t ret = gearman_client_job_status(&data->m_impl->client, job_handle.c_str(), &is_known, &is_running, &numerator, &denominator); Array status; if (ret == GEARMAN_SUCCESS) { status.append(is_known); status.append(is_running); status.append((int64_t) numerator); status.append((int64_t) denominator); } return status; } bool HHVM_METHOD(GearmanClient, setOptions, int64_t options) { //auto data = Native::data<GearmanClientData>(this_); return true; } void HHVM_METHOD(GearmanWorker, __construct) { auto data = Native::data<GearmanWorkerData>(this_); data->m_impl.reset(new GearmanWorkerData::Impl); } bool HHVM_METHOD(GearmanWorker, addServer, const String& host, int64_t port) { auto data = Native::data<GearmanWorkerData>(this_); const char* myHost = host.empty() ? nullptr : host.c_str(); gearman_return_t ret = gearman_worker_add_server(&data->m_impl->worker, myHost, port); return ret == GEARMAN_SUCCESS; } bool HHVM_METHOD(GearmanWorker, addServers, const String& servers) { auto data = Native::data<GearmanWorkerData>(this_); const char* myServers = servers.empty() ? nullptr : servers.c_str(); gearman_return_t ret = gearman_worker_add_servers(&data->m_impl->worker, myServers); return ret == GEARMAN_SUCCESS; } static void* add_function_callback(gearman_job_st* job, void* context, size_t* result_size, gearman_return_t* ret) { Array params = Array::Create(); GearmanWorkerData::UserDefinedFunc* udf = (GearmanWorkerData::UserDefinedFunc*) context; is_callable(udf->func); //vm_call_user_func(udf->func, params); *result_size = 0; return NULL; } bool HHVM_METHOD(GearmanWorker, addFunction, const String& function_name, const Variant& function, const VRefParam& context, int64_t timeout /* = 0 */) { auto data = Native::data<GearmanWorkerData>(this_); if (function_name.empty()) { return false; } if (!is_callable(function)) { raise_warning("Not a valid callback function %s", function.toString().data()); return false; } auto udf = std::make_shared<GearmanWorkerData::UserDefinedFunc>(); if (gearman_worker_add_function(&data->m_impl->worker, function_name.data(), timeout, add_function_callback, (void*) udf.get()) == GEARMAN_SUCCESS) { udf->func = function; data->m_udfs.push_back(udf); return true; } return false; } bool HHVM_METHOD(GearmanWorker, setTimeout, int64_t timeout) { auto data = Native::data<GearmanWorkerData>(this_); gearman_worker_set_timeout(&data->m_impl->worker, timeout); return true; } bool HHVM_METHOD(GearmanWorker, work) { auto data = Native::data<GearmanWorkerData>(this_); gearman_return_t ret = gearman_worker_work(&data->m_impl->worker); return ret == GEARMAN_SUCCESS; } void HHVM_METHOD(GearmanJob, __construct) { auto data = Native::data<GearmanJobData>(this_); data->m_impl.reset(new GearmanJobData::Impl); } void HHVM_METHOD(GearmanTask, __construct) { auto data = Native::data<GearmanTaskData>(this_); data->m_impl.reset(new GearmanTaskData::Impl); } String HHVM_METHOD(GearmanTask, data) { auto data = Native::data<GearmanTaskData>(this_); char* result = (char*) gearman_task_data(&data->m_impl->task); size_t result_len = gearman_task_data_size(&data->m_impl->task); return String(result, result_len, CopyString); } int64_t HHVM_METHOD(GearmanTask, dataSize) { auto data = Native::data<GearmanTaskData>(this_); return gearman_task_data_size(&data->m_impl->task); } static class GearmanExtension : public Extension { public: GearmanExtension() : Extension("gearman") {} void moduleInit() override { HHVM_ME(GearmanClient, __construct); HHVM_ME(GearmanClient, doNormal); HHVM_ME(GearmanClient, doHigh); HHVM_ME(GearmanClient, doBackground); HHVM_ME(GearmanClient, doHighBackground); HHVM_ME(GearmanClient, ping); HHVM_ME(GearmanClient, addServer); HHVM_ME(GearmanClient, addServers); HHVM_ME(GearmanClient, setTimeout); HHVM_ME(GearmanClient, jobStatus); HHVM_ME(GearmanClient, setOptions); HHVM_ME(GearmanWorker, __construct); HHVM_ME(GearmanWorker, work); HHVM_ME(GearmanWorker, addServer); HHVM_ME(GearmanWorker, addServers); HHVM_ME(GearmanWorker, addFunction); HHVM_ME(GearmanWorker, setTimeout); HHVM_ME(GearmanJob, __construct); HHVM_ME(GearmanTask, __construct); HHVM_ME(GearmanTask, data); HHVM_ME(GearmanTask, dataSize); Native::registerNativeDataInfo<GearmanClientData>(s_GearmanClientData.get()); Native::registerNativeDataInfo<GearmanWorkerData>(s_GearmanWorkerData.get(), Native::NDIFlags::NO_SWEEP); Native::registerNativeDataInfo<GearmanJobData>(s_GearmanJobData.get()); Native::registerNativeDataInfo<GearmanTaskData>(s_GearmanTaskData.get()); loadSystemlib(); } } s_gearman_extension; HHVM_GET_MODULE(gearman) } // namespace HPHP <commit_msg>fix bug<commit_after>/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/extension.h" #include "hphp/runtime/ext/std/ext_std_function.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/vm/native-data.h" #include "hphp/runtime/base/array-init.h" #include "hphp/system/systemlib.h" #include <vector> #include <memory> #include <gearman.h> namespace HPHP { const StaticString s_GearmanClientData("GearmanClientData"); class GearmanClientData { public: class Impl { public: Impl() { gearman_client_create(&client); } ~Impl() { gearman_client_free(&client); } gearman_client_st client; }; GearmanClientData() {} ~GearmanClientData() {} typedef std::shared_ptr<Impl> ImplPtr; ImplPtr m_impl; }; const StaticString s_GearmanWorkerData("GearmanWorkerData"); class GearmanWorkerData { public: class Impl { public: Impl() { gearman_worker_create(&worker); } ~Impl() { gearman_worker_free(&worker); } gearman_worker_st worker; }; struct UserDefinedFunc { Variant func; }; GearmanWorkerData() {} ~GearmanWorkerData() {} typedef std::shared_ptr<Impl> ImplPtr; std::vector<std::shared_ptr<UserDefinedFunc>> m_udfs; ImplPtr m_impl; }; const StaticString s_GearmanJobData("GearmanJobData"); class GearmanJobData { public: class Impl { public: Impl() { } ~Impl() { } }; GearmanJobData() {} ~GearmanJobData() {} typedef std::shared_ptr<Impl> Implptr; Implptr m_impl; }; const StaticString s_GearmanTaskData("GearmanTaskData"); class GearmanTaskData { public: class Impl { public: Impl() { } ~Impl() { } gearman_task_st task; }; GearmanTaskData() {} ~GearmanTaskData() {} typedef std::shared_ptr<Impl> Implptr; Implptr m_impl; }; void HHVM_METHOD(GearmanClient, __construct) { auto data = Native::data<GearmanClientData>(this_); data->m_impl.reset(new GearmanClientData::Impl); } bool HHVM_METHOD(GearmanClient, addServer, const String& host, int64_t port) { auto data = Native::data<GearmanClientData>(this_); const char* myHost = host.empty() ? nullptr : host.c_str(); gearman_return_t ret = gearman_client_add_server(&data->m_impl->client, myHost, port); return ret == GEARMAN_SUCCESS; } bool HHVM_METHOD(GearmanClient, addServers, const String& servers) { auto data = Native::data<GearmanClientData>(this_); const char* myServers = servers.empty() ? nullptr : servers.c_str(); gearman_return_t ret = gearman_client_add_servers(&data->m_impl->client, myServers); return ret == GEARMAN_SUCCESS; } #define GEARMAN_CLIENT_DO(function_name, workload, unique) \ auto data = Native::data<GearmanClientData>(this_); \ const char* myFunctionName = function_name.empty() ? nullptr : function_name.c_str(); \ const char* myWorkload = workload.empty() ? nullptr : workload.c_str(); \ size_t workload_size = workload.length(); \ const char* myUnique = unique.empty() ? NULL : unique.c_str(); \ String HHVM_METHOD(GearmanClient, doNormal, const String& function_name, const String& workload, const String& unique /*= null*/) { GEARMAN_CLIENT_DO(function_name, workload, unique); size_t result_size; gearman_return_t ret; char* result = (char*) gearman_client_do(&data->m_impl->client, myFunctionName, myUnique, myWorkload, workload_size, &result_size, &ret); String myResult = String(result, result_size, CopyString); delete result; return myResult; } String HHVM_METHOD(GearmanClient, doHigh, const String& function_name, const String& workload, const String& unique /*= null*/) { GEARMAN_CLIENT_DO(function_name, workload, unique); size_t result_size; gearman_return_t ret; char* result = (char*) gearman_client_do_high(&data->m_impl->client, myFunctionName, myUnique, myWorkload, workload_size, &result_size, &ret); String myResult = String(result, result_size, CopyString); delete result; return myResult; } String HHVM_METHOD(GearmanClient, doBackground, const String& function_name, const String& workload, const String& unique /*= null*/) { GEARMAN_CLIENT_DO(function_name, workload, unique); gearman_job_handle_t handle; gearman_return_t ret = gearman_client_do_background(&data->m_impl->client, myFunctionName, myUnique, myWorkload, workload_size, handle); if (ret != GEARMAN_SUCCESS) { return String(); } return String(handle); } String HHVM_METHOD(GearmanClient, doHighBackground, const String& function_name, const String& workload, const String& unique /*= null*/) { GEARMAN_CLIENT_DO(function_name, workload, unique); gearman_job_handle_t handle; gearman_return_t ret = gearman_client_do_high_background(&data->m_impl->client, myFunctionName, myUnique, myWorkload, workload_size, handle); if (ret != GEARMAN_SUCCESS) { return String(); } return String(handle); } bool HHVM_METHOD(GearmanClient, ping, const String& workload) { auto data = Native::data<GearmanClientData>(this_); const char* myWorkload = workload.empty() ? nullptr : workload.c_str(); size_t workload_size = workload.length(); gearman_return_t ret = gearman_client_echo(&data->m_impl->client, myWorkload, workload_size); return ret == GEARMAN_SUCCESS; } bool HHVM_METHOD(GearmanClient, setTimeout, int64_t timeout) { auto data = Native::data<GearmanClientData>(this_); gearman_client_set_timeout(&data->m_impl->client, timeout); return true; } Array HHVM_METHOD(GearmanClient, jobStatus, const String& job_handle) { auto data = Native::data<GearmanClientData>(this_); bool is_known, is_running; uint32_t numerator, denominator; gearman_return_t ret = gearman_client_job_status(&data->m_impl->client, job_handle.c_str(), &is_known, &is_running, &numerator, &denominator); Array status; if (ret == GEARMAN_SUCCESS) { status.append(is_known); status.append(is_running); status.append((int64_t) numerator); status.append((int64_t) denominator); } return status; } bool HHVM_METHOD(GearmanClient, setOptions, int64_t options) { //auto data = Native::data<GearmanClientData>(this_); return true; } void HHVM_METHOD(GearmanWorker, __construct) { auto data = Native::data<GearmanWorkerData>(this_); data->m_impl.reset(new GearmanWorkerData::Impl); } bool HHVM_METHOD(GearmanWorker, addServer, const String& host, int64_t port) { auto data = Native::data<GearmanWorkerData>(this_); const char* myHost = host.empty() ? nullptr : host.c_str(); gearman_return_t ret = gearman_worker_add_server(&data->m_impl->worker, myHost, port); return ret == GEARMAN_SUCCESS; } bool HHVM_METHOD(GearmanWorker, addServers, const String& servers) { auto data = Native::data<GearmanWorkerData>(this_); const char* myServers = servers.empty() ? nullptr : servers.c_str(); gearman_return_t ret = gearman_worker_add_servers(&data->m_impl->worker, myServers); return ret == GEARMAN_SUCCESS; } static void* php_gearman_function_callback(gearman_job_st* job, void* context, size_t* result_size, gearman_return_t* ret) { Array params = Array::Create(); GearmanWorkerData::UserDefinedFunc* udf = (GearmanWorkerData::UserDefinedFunc*) context; is_callable(udf->func); //vm_call_user_func(udf->func, params); *result_size = 0; return NULL; } bool HHVM_METHOD(GearmanWorker, addFunction, const String& function_name, const Variant& function, const VRefParam& context, int64_t timeout /* = 0 */) { auto data = Native::data<GearmanWorkerData>(this_); if (function_name.empty()) { return false; } if (!is_callable(function)) { raise_warning("Not a valid callback function %s", function.toString().data()); return false; } auto udf = std::make_shared<GearmanWorkerData::UserDefinedFunc>(); if (gearman_worker_add_function(&data->m_impl->worker, function_name.data(), timeout, php_gearman_function_callback, udf.get()) == GEARMAN_SUCCESS) { udf->func = function; data->m_udfs.push_back(udf); return true; } return false; } bool HHVM_METHOD(GearmanWorker, setTimeout, int64_t timeout) { auto data = Native::data<GearmanWorkerData>(this_); gearman_worker_set_timeout(&data->m_impl->worker, timeout); return true; } bool HHVM_METHOD(GearmanWorker, work) { auto data = Native::data<GearmanWorkerData>(this_); gearman_return_t ret = gearman_worker_work(&data->m_impl->worker); return ret == GEARMAN_SUCCESS; } void HHVM_METHOD(GearmanJob, __construct) { auto data = Native::data<GearmanJobData>(this_); data->m_impl.reset(new GearmanJobData::Impl); } void HHVM_METHOD(GearmanTask, __construct) { auto data = Native::data<GearmanTaskData>(this_); data->m_impl.reset(new GearmanTaskData::Impl); } String HHVM_METHOD(GearmanTask, data) { auto data = Native::data<GearmanTaskData>(this_); char* result = (char*) gearman_task_data(&data->m_impl->task); size_t result_len = gearman_task_data_size(&data->m_impl->task); return String(result, result_len, CopyString); } int64_t HHVM_METHOD(GearmanTask, dataSize) { auto data = Native::data<GearmanTaskData>(this_); return gearman_task_data_size(&data->m_impl->task); } static class GearmanExtension : public Extension { public: GearmanExtension() : Extension("gearman") {} void moduleInit() override { HHVM_ME(GearmanClient, __construct); HHVM_ME(GearmanClient, doNormal); HHVM_ME(GearmanClient, doHigh); HHVM_ME(GearmanClient, doBackground); HHVM_ME(GearmanClient, doHighBackground); HHVM_ME(GearmanClient, ping); HHVM_ME(GearmanClient, addServer); HHVM_ME(GearmanClient, addServers); HHVM_ME(GearmanClient, setTimeout); HHVM_ME(GearmanClient, jobStatus); HHVM_ME(GearmanClient, setOptions); HHVM_ME(GearmanWorker, __construct); HHVM_ME(GearmanWorker, work); HHVM_ME(GearmanWorker, addServer); HHVM_ME(GearmanWorker, addServers); HHVM_ME(GearmanWorker, addFunction); HHVM_ME(GearmanWorker, setTimeout); HHVM_ME(GearmanJob, __construct); HHVM_ME(GearmanTask, __construct); HHVM_ME(GearmanTask, data); HHVM_ME(GearmanTask, dataSize); Native::registerNativeDataInfo<GearmanClientData>(s_GearmanClientData.get()); Native::registerNativeDataInfo<GearmanWorkerData>(s_GearmanWorkerData.get(), Native::NDIFlags::NO_SWEEP); Native::registerNativeDataInfo<GearmanJobData>(s_GearmanJobData.get()); Native::registerNativeDataInfo<GearmanTaskData>(s_GearmanTaskData.get()); loadSystemlib(); } } s_gearman_extension; HHVM_GET_MODULE(gearman) } // namespace HPHP <|endoftext|>
<commit_before>/// \file ROOT/TCanvas.hxx /// \ingroup Gpad ROOT7 /// \author Axel Naumann <axel@cern.ch> /// \date 2015-07-08 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_TCanvas #define ROOT7_TCanvas #include "ROOT/TColor.hxx" #include "ROOT/TPad.hxx" #include "ROOT/TVirtualCanvasPainter.hxx" #include <memory> #include <string> #include <vector> namespace ROOT { namespace Experimental { /** \class ROOT::Experimental::TCanvas A window's topmost `TPad`. Access is through TCanvasPtr. */ class TCanvas: public Internal::TPadBase { private: /// Title of the canvas. std::string fTitle; /// Size of the canvas in pixels, std::array<TPadCoord::Pixel, 2> fSize; /// Colors used by drawing options in the pad and any sub-pad. Internal::TOptsAttrTable<TColor> fColorTable; /// Integers used by drawing options in the pad and any sub-pad. Internal::TOptsAttrTable<long long> fIntAttrTable; /// Floating points used by drawing options in the pad and any sub-pad. Internal::TOptsAttrTable<double> fFPAttrTable; /// Modify counter, incremented every time canvas is changed uint64_t fModified; ///<! /// The painter of this canvas, bootstrapping the graphics connection. /// Unmapped canvases (those that never had `Draw()` invoked) might not have /// a painter. std::unique_ptr<Internal::TVirtualCanvasPainter> fPainter; ///<! /// Disable copy construction for now. TCanvas(const TCanvas &) = delete; /// Disable assignment for now. TCanvas &operator=(const TCanvas &) = delete; ///\{ ///\name Drawing options attribute handling /// Attribute table (non-const access). template <class PRIMITIVE> Internal::TOptsAttrTable<PRIMITIVE> &GetAttrTable(); // Available specializations: extern template Internal::TOptsAttrTable<TColor> &GetAttrTable<TColor>(); extern template Internal::TOptsAttrTable<long long> &GetAttrTable<long long>(); extern template Internal::TOptsAttrTable<double> &GetAttrTable<double>(); /// Attribute table (const access). template <class PRIMITIVE> const Internal::TOptsAttrTable<PRIMITIVE> &GetAttrTable() const; // Available specializations: extern template const Internal::TOptsAttrTable<TColor> &GetAttrTable<TColor>() const; extern template const Internal::TOptsAttrTable<long long> &GetAttrTable<long long>() const; extern template const Internal::TOptsAttrTable<double> &GetAttrTable<double>() const; friend class ROOT::Experimental::Internal::TDrawingOptsBase; ///\} public: static std::shared_ptr<TCanvas> Create(const std::string &title); /// Create a temporary TCanvas; for long-lived ones please use Create(). TCanvas() = default; /// Return canvas pixel size as array with two elements - width and height const std::array<TPadCoord::Pixel, 2> &GetSize() const { return fSize; } /// Set canvas pixel size as array with two elements - width and height void SetSize(const std::array<TPadCoord::Pixel, 2> &sz) { fSize = sz; } /// Set canvas pixel size - width and height void SetSize(const TPadCoord::Pixel &width, const TPadCoord::Pixel &height) { fSize[0] = width; fSize[1] = height; } /// Display the canvas. void Show(const std::string &where = ""); /// Close all canvas displays void Hide(); // Indicates that primitives list was changed or any primitive was modified void Modified() { fModified++; } // Return if canvas was modified and not yet updated bool IsModified() const; /// update drawing void Update(bool async = false, CanvasCallback_t callback = nullptr); /// Save canvas in image file void SaveAs(const std::string &filename, bool async = false, CanvasCallback_t callback = nullptr); /// Get the canvas's title. const std::string &GetTitle() const { return fTitle; } /// Set the canvas's title. void SetTitle(const std::string &title) { fTitle = title; } /// Convert a `Pixel` position to Canvas-normalized positions. std::array<TPadCoord::Normal, 2> PixelsToNormal(const std::array<TPadCoord::Pixel, 2> &pos) const final { return {{pos[0] / fSize[0], pos[1] / fSize[1]}}; } static const std::vector<std::shared_ptr<TCanvas>> &GetCanvases(); }; } // namespace Experimental } // namespace ROOT #endif <commit_msg>TPadBase is not Internal::.<commit_after>/// \file ROOT/TCanvas.hxx /// \ingroup Gpad ROOT7 /// \author Axel Naumann <axel@cern.ch> /// \date 2015-07-08 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_TCanvas #define ROOT7_TCanvas #include "ROOT/TColor.hxx" #include "ROOT/TPad.hxx" #include "ROOT/TVirtualCanvasPainter.hxx" #include <memory> #include <string> #include <vector> namespace ROOT { namespace Experimental { /** \class ROOT::Experimental::TCanvas A window's topmost `TPad`. Access is through TCanvasPtr. */ class TCanvas: public TPadBase { private: /// Title of the canvas. std::string fTitle; /// Size of the canvas in pixels, std::array<TPadCoord::Pixel, 2> fSize; /// Colors used by drawing options in the pad and any sub-pad. Internal::TOptsAttrTable<TColor> fColorTable; /// Integers used by drawing options in the pad and any sub-pad. Internal::TOptsAttrTable<long long> fIntAttrTable; /// Floating points used by drawing options in the pad and any sub-pad. Internal::TOptsAttrTable<double> fFPAttrTable; /// Modify counter, incremented every time canvas is changed uint64_t fModified; ///<! /// The painter of this canvas, bootstrapping the graphics connection. /// Unmapped canvases (those that never had `Draw()` invoked) might not have /// a painter. std::unique_ptr<Internal::TVirtualCanvasPainter> fPainter; ///<! /// Disable copy construction for now. TCanvas(const TCanvas &) = delete; /// Disable assignment for now. TCanvas &operator=(const TCanvas &) = delete; ///\{ ///\name Drawing options attribute handling /// Attribute table (non-const access). template <class PRIMITIVE> Internal::TOptsAttrTable<PRIMITIVE> &GetAttrTable(); // Available specializations: extern template Internal::TOptsAttrTable<TColor> &GetAttrTable<TColor>(); extern template Internal::TOptsAttrTable<long long> &GetAttrTable<long long>(); extern template Internal::TOptsAttrTable<double> &GetAttrTable<double>(); /// Attribute table (const access). template <class PRIMITIVE> const Internal::TOptsAttrTable<PRIMITIVE> &GetAttrTable() const; // Available specializations: extern template const Internal::TOptsAttrTable<TColor> &GetAttrTable<TColor>() const; extern template const Internal::TOptsAttrTable<long long> &GetAttrTable<long long>() const; extern template const Internal::TOptsAttrTable<double> &GetAttrTable<double>() const; friend class ROOT::Experimental::Internal::TDrawingOptsBase; ///\} public: static std::shared_ptr<TCanvas> Create(const std::string &title); /// Create a temporary TCanvas; for long-lived ones please use Create(). TCanvas() = default; /// Return canvas pixel size as array with two elements - width and height const std::array<TPadCoord::Pixel, 2> &GetSize() const { return fSize; } /// Set canvas pixel size as array with two elements - width and height void SetSize(const std::array<TPadCoord::Pixel, 2> &sz) { fSize = sz; } /// Set canvas pixel size - width and height void SetSize(const TPadCoord::Pixel &width, const TPadCoord::Pixel &height) { fSize[0] = width; fSize[1] = height; } /// Display the canvas. void Show(const std::string &where = ""); /// Close all canvas displays void Hide(); // Indicates that primitives list was changed or any primitive was modified void Modified() { fModified++; } // Return if canvas was modified and not yet updated bool IsModified() const; /// update drawing void Update(bool async = false, CanvasCallback_t callback = nullptr); /// Save canvas in image file void SaveAs(const std::string &filename, bool async = false, CanvasCallback_t callback = nullptr); /// Get the canvas's title. const std::string &GetTitle() const { return fTitle; } /// Set the canvas's title. void SetTitle(const std::string &title) { fTitle = title; } /// Convert a `Pixel` position to Canvas-normalized positions. std::array<TPadCoord::Normal, 2> PixelsToNormal(const std::array<TPadCoord::Pixel, 2> &pos) const final { return {{pos[0] / fSize[0], pos[1] / fSize[1]}}; } static const std::vector<std::shared_ptr<TCanvas>> &GetCanvases(); }; } // namespace Experimental } // namespace ROOT #endif <|endoftext|>
<commit_before>#include "UnitTest++/UnitTestPP.h" #include "UnitTest++/TestMacros.h" #include "UnitTest++/TestList.h" #include "UnitTest++/TestResults.h" #include "UnitTest++/TestReporter.h" #include "UnitTest++/ReportAssert.h" #include "RecordingReporter.h" #include "ScopedCurrentTest.h" using namespace UnitTest; using namespace std; namespace { TestList list1; TEST_EX(DummyTest, list1) { } TEST (TestsAreAddedToTheListThroughMacro) { CHECK(list1.GetHead() != 0); CHECK(list1.GetHead()->m_nextTest == 0); } #ifndef UNITTEST_NO_EXCEPTIONS struct ThrowingThingie { ThrowingThingie() : dummy(false) { if (!dummy) throw "Oops"; } bool dummy; }; TestList list2; TEST_FIXTURE_EX(ThrowingThingie, DummyTestName, list2) { } TEST (ExceptionsInFixtureAreReportedAsHappeningInTheFixture) { RecordingReporter reporter; TestResults result(&reporter); { ScopedCurrentTest scopedResults(result); list2.GetHead()->Run(); } CHECK(strstr(reporter.lastFailedMessage, "xception")); CHECK(strstr(reporter.lastFailedMessage, "fixture")); CHECK(strstr(reporter.lastFailedMessage, "ThrowingThingie")); } #endif struct DummyFixture { int x; }; // We're really testing the macros so we just want them to compile and link SUITE(TestSuite1) { TEST(SimilarlyNamedTestsInDifferentSuitesWork) { } TEST_FIXTURE(DummyFixture, SimilarlyNamedFixtureTestsInDifferentSuitesWork) { } } SUITE(TestSuite2) { TEST(SimilarlyNamedTestsInDifferentSuitesWork) { } TEST_FIXTURE(DummyFixture,SimilarlyNamedFixtureTestsInDifferentSuitesWork) { } } TestList macroTestList1; TEST_EX(MacroTestHelper1, macroTestList1) { } TEST(TestAddedWithTEST_EXMacroGetsDefaultSuite) { CHECK(macroTestList1.GetHead() != NULL); CHECK_EQUAL ("MacroTestHelper1", macroTestList1.GetHead()->m_details.testName); CHECK_EQUAL ("DefaultSuite", macroTestList1.GetHead()->m_details.suiteName); } TestList macroTestList2; TEST_FIXTURE_EX(DummyFixture, MacroTestHelper2, macroTestList2) { } TEST(TestAddedWithTEST_FIXTURE_EXMacroGetsDefaultSuite) { CHECK(macroTestList2.GetHead() != NULL); CHECK_EQUAL ("MacroTestHelper2", macroTestList2.GetHead()->m_details.testName); CHECK_EQUAL ("DefaultSuite", macroTestList2.GetHead()->m_details.suiteName); } #ifndef UNITTEST_NO_EXCEPTIONS struct FixtureCtorThrows { FixtureCtorThrows() { throw "exception"; } }; TestList throwingFixtureTestList1; TEST_FIXTURE_EX(FixtureCtorThrows, FixtureCtorThrowsTestName, throwingFixtureTestList1) { } TEST(FixturesWithThrowingCtorsAreFailures) { CHECK(throwingFixtureTestList1.GetHead() != NULL); RecordingReporter reporter; TestResults result(&reporter); { ScopedCurrentTest scopedResult(result); throwingFixtureTestList1.GetHead()->Run(); } int const failureCount = result.GetFailedTestCount(); CHECK_EQUAL(1, failureCount); CHECK(strstr(reporter.lastFailedMessage, "while constructing fixture")); } // Visual Studio 2015 in compliance with C++11 standard // implicitly adds a 'noexcept' to all user defined // destructors. Any exceptions thrown from destructors // cause abort() to be called on the process. #if(_MSC_VER < 1900) struct FixtureDtorThrows { ~FixtureDtorThrows() { throw "exception"; } }; TestList throwingFixtureTestList2; TEST_FIXTURE_EX(FixtureDtorThrows, FixtureDtorThrowsTestName, throwingFixtureTestList2) { } TEST(FixturesWithThrowingDtorsAreFailures) { CHECK(throwingFixtureTestList2.GetHead() != NULL); RecordingReporter reporter; TestResults result(&reporter); { ScopedCurrentTest scopedResult(result); throwingFixtureTestList2.GetHead()->Run(); } int const failureCount = result.GetFailedTestCount(); CHECK_EQUAL(1, failureCount); CHECK(strstr(reporter.lastFailedMessage, "while destroying fixture")); } #endif const int FailingLine = 123; struct FixtureCtorAsserts { FixtureCtorAsserts() { UnitTest::ReportAssert("assert failure", "file", FailingLine); } }; TestList ctorAssertFixtureTestList; TEST_FIXTURE_EX(FixtureCtorAsserts, CorrectlyReportsAssertFailureInCtor, ctorAssertFixtureTestList) { } TEST(CorrectlyReportsFixturesWithCtorsThatAssert) { RecordingReporter reporter; TestResults result(&reporter); { ScopedCurrentTest scopedResults(result); ctorAssertFixtureTestList.GetHead()->Run(); } const int failureCount = result.GetFailedTestCount(); CHECK_EQUAL(1, failureCount); CHECK_EQUAL(FailingLine, reporter.lastFailedLine); CHECK(strstr(reporter.lastFailedMessage, "assert failure")); } #endif } // We're really testing if it's possible to use the same suite in two files // to compile and link successfuly (TestTestSuite.cpp has suite with the same name) // Note: we are outside of the anonymous namespace SUITE(SameTestSuite) { TEST(DummyTest1) { } } #define CUR_TEST_NAME CurrentTestDetailsContainCurrentTestInfo #define INNER_STRINGIFY(X) #X #define STRINGIFY(X) INNER_STRINGIFY(X) TEST(CUR_TEST_NAME) { const UnitTest::TestDetails* details = CurrentTest::Details(); CHECK_EQUAL(STRINGIFY(CUR_TEST_NAME), details->testName); } #undef CUR_TEST_NAME #undef INNER_STRINGIFY #undef STRINGIFY <commit_msg>fixed a runtime error in Xcode 7.0<commit_after>#include "UnitTest++/UnitTestPP.h" #include "UnitTest++/TestMacros.h" #include "UnitTest++/TestList.h" #include "UnitTest++/TestResults.h" #include "UnitTest++/TestReporter.h" #include "UnitTest++/ReportAssert.h" #include "RecordingReporter.h" #include "ScopedCurrentTest.h" using namespace UnitTest; using namespace std; namespace { TestList list1; TEST_EX(DummyTest, list1) { } TEST (TestsAreAddedToTheListThroughMacro) { CHECK(list1.GetHead() != 0); CHECK(list1.GetHead()->m_nextTest == 0); } #ifndef UNITTEST_NO_EXCEPTIONS struct ThrowingThingie { ThrowingThingie() : dummy(false) { if (!dummy) throw "Oops"; } bool dummy; }; TestList list2; TEST_FIXTURE_EX(ThrowingThingie, DummyTestName, list2) { } TEST (ExceptionsInFixtureAreReportedAsHappeningInTheFixture) { RecordingReporter reporter; TestResults result(&reporter); { ScopedCurrentTest scopedResults(result); list2.GetHead()->Run(); } CHECK(strstr(reporter.lastFailedMessage, "xception")); CHECK(strstr(reporter.lastFailedMessage, "fixture")); CHECK(strstr(reporter.lastFailedMessage, "ThrowingThingie")); } #endif struct DummyFixture { int x; }; // We're really testing the macros so we just want them to compile and link SUITE(TestSuite1) { TEST(SimilarlyNamedTestsInDifferentSuitesWork) { } TEST_FIXTURE(DummyFixture, SimilarlyNamedFixtureTestsInDifferentSuitesWork) { } } SUITE(TestSuite2) { TEST(SimilarlyNamedTestsInDifferentSuitesWork) { } TEST_FIXTURE(DummyFixture,SimilarlyNamedFixtureTestsInDifferentSuitesWork) { } } TestList macroTestList1; TEST_EX(MacroTestHelper1, macroTestList1) { } TEST(TestAddedWithTEST_EXMacroGetsDefaultSuite) { CHECK(macroTestList1.GetHead() != NULL); CHECK_EQUAL ("MacroTestHelper1", macroTestList1.GetHead()->m_details.testName); CHECK_EQUAL ("DefaultSuite", macroTestList1.GetHead()->m_details.suiteName); } TestList macroTestList2; TEST_FIXTURE_EX(DummyFixture, MacroTestHelper2, macroTestList2) { } TEST(TestAddedWithTEST_FIXTURE_EXMacroGetsDefaultSuite) { CHECK(macroTestList2.GetHead() != NULL); CHECK_EQUAL ("MacroTestHelper2", macroTestList2.GetHead()->m_details.testName); CHECK_EQUAL ("DefaultSuite", macroTestList2.GetHead()->m_details.suiteName); } #ifndef UNITTEST_NO_EXCEPTIONS struct FixtureCtorThrows { FixtureCtorThrows() { throw "exception"; } }; TestList throwingFixtureTestList1; TEST_FIXTURE_EX(FixtureCtorThrows, FixtureCtorThrowsTestName, throwingFixtureTestList1) { } TEST(FixturesWithThrowingCtorsAreFailures) { CHECK(throwingFixtureTestList1.GetHead() != NULL); RecordingReporter reporter; TestResults result(&reporter); { ScopedCurrentTest scopedResult(result); throwingFixtureTestList1.GetHead()->Run(); } int const failureCount = result.GetFailedTestCount(); CHECK_EQUAL(1, failureCount); CHECK(strstr(reporter.lastFailedMessage, "while constructing fixture")); } // Visual Studio 2015 in compliance with C++11 standard // implicitly adds a 'noexcept' to all user defined // destructors. Any exceptions thrown from destructors // cause abort() to be called on the process. #if defined(_MSC_VER) && (_MSC_VER < 1900) struct FixtureDtorThrows { ~FixtureDtorThrows() { throw "exception"; } }; TestList throwingFixtureTestList2; TEST_FIXTURE_EX(FixtureDtorThrows, FixtureDtorThrowsTestName, throwingFixtureTestList2) { } TEST(FixturesWithThrowingDtorsAreFailures) { CHECK(throwingFixtureTestList2.GetHead() != NULL); RecordingReporter reporter; TestResults result(&reporter); { ScopedCurrentTest scopedResult(result); throwingFixtureTestList2.GetHead()->Run(); } int const failureCount = result.GetFailedTestCount(); CHECK_EQUAL(1, failureCount); CHECK(strstr(reporter.lastFailedMessage, "while destroying fixture")); } #endif const int FailingLine = 123; struct FixtureCtorAsserts { FixtureCtorAsserts() { UnitTest::ReportAssert("assert failure", "file", FailingLine); } }; TestList ctorAssertFixtureTestList; TEST_FIXTURE_EX(FixtureCtorAsserts, CorrectlyReportsAssertFailureInCtor, ctorAssertFixtureTestList) { } TEST(CorrectlyReportsFixturesWithCtorsThatAssert) { RecordingReporter reporter; TestResults result(&reporter); { ScopedCurrentTest scopedResults(result); ctorAssertFixtureTestList.GetHead()->Run(); } const int failureCount = result.GetFailedTestCount(); CHECK_EQUAL(1, failureCount); CHECK_EQUAL(FailingLine, reporter.lastFailedLine); CHECK(strstr(reporter.lastFailedMessage, "assert failure")); } #endif } // We're really testing if it's possible to use the same suite in two files // to compile and link successfuly (TestTestSuite.cpp has suite with the same name) // Note: we are outside of the anonymous namespace SUITE(SameTestSuite) { TEST(DummyTest1) { } } #define CUR_TEST_NAME CurrentTestDetailsContainCurrentTestInfo #define INNER_STRINGIFY(X) #X #define STRINGIFY(X) INNER_STRINGIFY(X) TEST(CUR_TEST_NAME) { const UnitTest::TestDetails* details = CurrentTest::Details(); CHECK_EQUAL(STRINGIFY(CUR_TEST_NAME), details->testName); } #undef CUR_TEST_NAME #undef INNER_STRINGIFY #undef STRINGIFY <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: SlsPageDescriptor.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2004-07-13 14:24:32 $ * * 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): _______________________________________ * * ************************************************************************/ #include "model/SlsPageDescriptor.hxx" #include "view/SlsPageObject.hxx" #include "view/SlsPageObjectViewObjectContact.hxx" #include "controller/SlsPageObjectFactory.hxx" #include "sdpage.hxx" #include "drawdoc.hxx" #include <svx/svdopage.hxx> #include <svx/svdpagv.hxx> #include <svx/sdr/contact/viewcontact.hxx> namespace sd { namespace slidesorter { namespace model { PageDescriptor::PageDescriptor ( SdPage& rPage, const controller::PageObjectFactory& rPageObjectFactory) : mrPage (rPage), mpPageObjectFactory(&rPageObjectFactory), mpPageObject (NULL), mbIsSelected (false), mbVisible (false), mbFocused (false), mpViewObjectContact (NULL), maModelBorder (0,0,0,0), maPageNumberAreaModelSize(0,0) { } PageDescriptor::~PageDescriptor (void) { } SdPage* PageDescriptor::GetPage (void) const { return &mrPage; } view::PageObject* PageDescriptor::GetPageObject (void) { if (mpPageObject==NULL && mpPageObjectFactory!=NULL) { mpPageObject = mpPageObjectFactory->CreatePageObject(&mrPage, *this); } return mpPageObject; } void PageDescriptor::ReleasePageObject (void) { mpPageObject = NULL; } bool PageDescriptor::IsVisible (void) const { return mbVisible; } void PageDescriptor::SetVisible (bool bVisible) { mbVisible = bVisible; } bool PageDescriptor::Select (void) { if ( ! IsSelected()) { mbIsSelected = true; // mrPage.SetSelected (TRUE); return true; } else return false; } bool PageDescriptor::Deselect (void) { if (IsSelected()) { mbIsSelected = false; // mrPage.SetSelected (FALSE); return true; } else return false; } bool PageDescriptor::IsSelected (void) const { return mbIsSelected;//mrPage.IsSelected(); } bool PageDescriptor::UpdateSelection (void) { if ((mrPage.IsSelected()==TRUE) != mbIsSelected) { mbIsSelected = ! mbIsSelected; return true; } else return false; } bool PageDescriptor::IsFocused (void) const { return mbFocused; } void PageDescriptor::SetFocus (void) { mbFocused = true; } void PageDescriptor::RemoveFocus (void) { mbFocused = false; } view::PageObjectViewObjectContact* PageDescriptor::GetViewObjectContact (void) { return mpViewObjectContact; } void PageDescriptor::SetViewObjectContact ( view::PageObjectViewObjectContact* pViewObjectContact) { mpViewObjectContact = pViewObjectContact; } const controller::PageObjectFactory& PageDescriptor::GetPageObjectFactory (void) const { return *mpPageObjectFactory; } void PageDescriptor::SetPageObjectFactory ( const controller::PageObjectFactory& rFactory) { mpPageObjectFactory = &rFactory; } void PageDescriptor::SetModelBorder (const SvBorder& rBorder) { maModelBorder = rBorder; } SvBorder PageDescriptor::GetModelBorder (void) const { return maModelBorder; } void PageDescriptor::SetPageNumberAreaModelSize (const Size& rSize) { maPageNumberAreaModelSize = rSize; } Size PageDescriptor::GetPageNumberAreaModelSize (void) const { return maPageNumberAreaModelSize; } } } } // end of namespace ::sd::slidesorter::model <commit_msg>INTEGRATION: CWS impress21ea (1.2.60); FILE MERGED 2004/09/17 11:29:09 af 1.2.60.1: #i33470# Made GetViewObjectContact() const.<commit_after>/************************************************************************* * * $RCSfile: SlsPageDescriptor.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-09-20 13:35:21 $ * * 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): _______________________________________ * * ************************************************************************/ #include "model/SlsPageDescriptor.hxx" #include "view/SlsPageObject.hxx" #include "view/SlsPageObjectViewObjectContact.hxx" #include "controller/SlsPageObjectFactory.hxx" #include "sdpage.hxx" #include "drawdoc.hxx" #include <svx/svdopage.hxx> #include <svx/svdpagv.hxx> #include <svx/sdr/contact/viewcontact.hxx> namespace sd { namespace slidesorter { namespace model { PageDescriptor::PageDescriptor ( SdPage& rPage, const controller::PageObjectFactory& rPageObjectFactory) : mrPage (rPage), mpPageObjectFactory(&rPageObjectFactory), mpPageObject (NULL), mbIsSelected (false), mbVisible (false), mbFocused (false), mpViewObjectContact (NULL), maModelBorder (0,0,0,0), maPageNumberAreaModelSize(0,0) { } PageDescriptor::~PageDescriptor (void) { } SdPage* PageDescriptor::GetPage (void) const { return &mrPage; } view::PageObject* PageDescriptor::GetPageObject (void) { if (mpPageObject==NULL && mpPageObjectFactory!=NULL) { mpPageObject = mpPageObjectFactory->CreatePageObject(&mrPage, *this); } return mpPageObject; } void PageDescriptor::ReleasePageObject (void) { mpPageObject = NULL; } bool PageDescriptor::IsVisible (void) const { return mbVisible; } void PageDescriptor::SetVisible (bool bVisible) { mbVisible = bVisible; } bool PageDescriptor::Select (void) { if ( ! IsSelected()) { mbIsSelected = true; // mrPage.SetSelected (TRUE); return true; } else return false; } bool PageDescriptor::Deselect (void) { if (IsSelected()) { mbIsSelected = false; // mrPage.SetSelected (FALSE); return true; } else return false; } bool PageDescriptor::IsSelected (void) const { return mbIsSelected;//mrPage.IsSelected(); } bool PageDescriptor::UpdateSelection (void) { if ((mrPage.IsSelected()==TRUE) != mbIsSelected) { mbIsSelected = ! mbIsSelected; return true; } else return false; } bool PageDescriptor::IsFocused (void) const { return mbFocused; } void PageDescriptor::SetFocus (void) { mbFocused = true; } void PageDescriptor::RemoveFocus (void) { mbFocused = false; } view::PageObjectViewObjectContact* PageDescriptor::GetViewObjectContact (void) const { return mpViewObjectContact; } void PageDescriptor::SetViewObjectContact ( view::PageObjectViewObjectContact* pViewObjectContact) { mpViewObjectContact = pViewObjectContact; } const controller::PageObjectFactory& PageDescriptor::GetPageObjectFactory (void) const { return *mpPageObjectFactory; } void PageDescriptor::SetPageObjectFactory ( const controller::PageObjectFactory& rFactory) { mpPageObjectFactory = &rFactory; } void PageDescriptor::SetModelBorder (const SvBorder& rBorder) { maModelBorder = rBorder; } SvBorder PageDescriptor::GetModelBorder (void) const { return maModelBorder; } void PageDescriptor::SetPageNumberAreaModelSize (const Size& rSize) { maPageNumberAreaModelSize = rSize; } Size PageDescriptor::GetPageNumberAreaModelSize (void) const { return maPageNumberAreaModelSize; } } } } // end of namespace ::sd::slidesorter::model <|endoftext|>
<commit_before>#include "Thread.hpp" #include "Exception.hpp" #ifdef ___INANITY_PLATFORM_POSIX #include <pthread.h> #include <time.h> #endif BEGIN_INANITY Thread::Thread(ptr<ThreadHandler> handler) : handler(handler) { try { #if defined(___INANITY_PLATFORM_WINDOWS) thread = NEW(Platform::Win32Handle(CreateThread(0, 0, ThreadRoutine, this, 0, 0))); if(!thread->IsValid()) THROW_SECONDARY("CreateThread failed", Exception::SystemError()); #elif defined(___INANITY_PLATFORM_POSIX) if(pthread_create(&thread, 0, ThreadRoutine, this)) THROW_SECONDARY("pthread_create failed", Exception::SystemError()); #else #error Unknown platform #endif Reference(); } catch(Exception* exception) { THROW_SECONDARY("Can't create thread", exception); } } #if defined(___INANITY_PLATFORM_WINDOWS) DWORD CALLBACK Thread::ThreadRoutine(void* self) { ((Thread*)self)->Run(); return 0; } #elif defined(___INANITY_PLATFORM_POSIX) void* Thread::ThreadRoutine(void* self) { ((Thread*)self)->Run(); return 0; } #else #error Unknown platform #endif void Thread::Run() { handler->FireData(this); Dereference(); } void Thread::WaitEnd() { #if defined(___INANITY_PLATFORM_WINDOWS) if(WaitForSingleObject(*thread, INFINITE) != WAIT_OBJECT_0) #elif defined(___INANITY_PLATFORM_POSIX) if(pthread_join(thread, 0)) #else #error Unknown platform #endif THROW_SECONDARY("Can't wait for thread end", Exception::SystemError()); } void Thread::Sleep(int milliseconds) { #if defined(___INANITY_PLATFORM_WINDOWS) ::Sleep(milliseconds); #elif defined(___INANITY_PLATFORM_POSIX) struct timespec t; t.tv_sec = (time_t)(milliseconds / 1000); t.tv_nsec = (long)((milliseconds % 1000) * 1000000); nanosleep(&t, 0); #else #error Unknown platform #endif } END_INANITY <commit_msg>code reformat<commit_after>#include "Thread.hpp" #include "Exception.hpp" #ifdef ___INANITY_PLATFORM_POSIX #include <pthread.h> #include <time.h> #endif BEGIN_INANITY Thread::Thread(ptr<ThreadHandler> handler) : handler(handler) { BEGIN_TRY(); #if defined(___INANITY_PLATFORM_WINDOWS) thread = NEW(Platform::Win32Handle(CreateThread(0, 0, ThreadRoutine, this, 0, 0))); if(!thread->IsValid()) THROW_SECONDARY("CreateThread failed", Exception::SystemError()); #elif defined(___INANITY_PLATFORM_POSIX) if(pthread_create(&thread, 0, ThreadRoutine, this)) THROW_SECONDARY("pthread_create failed", Exception::SystemError()); #else #error Unknown platform #endif Reference(); END_TRY("Can't create thread"); } #if defined(___INANITY_PLATFORM_WINDOWS) DWORD CALLBACK Thread::ThreadRoutine(void* self) { ((Thread*)self)->Run(); return 0; } #elif defined(___INANITY_PLATFORM_POSIX) void* Thread::ThreadRoutine(void* self) { ((Thread*)self)->Run(); return 0; } #else #error Unknown platform #endif void Thread::Run() { handler->FireData(this); Dereference(); } void Thread::WaitEnd() { #if defined(___INANITY_PLATFORM_WINDOWS) if(WaitForSingleObject(*thread, INFINITE) != WAIT_OBJECT_0) #elif defined(___INANITY_PLATFORM_POSIX) if(pthread_join(thread, 0)) #else #error Unknown platform #endif THROW_SECONDARY("Can't wait for thread end", Exception::SystemError()); } void Thread::Sleep(int milliseconds) { #if defined(___INANITY_PLATFORM_WINDOWS) ::Sleep(milliseconds); #elif defined(___INANITY_PLATFORM_POSIX) struct timespec t; t.tv_sec = (time_t)(milliseconds / 1000); t.tv_nsec = (long)((milliseconds % 1000) * 1000000); nanosleep(&t, 0); #else #error Unknown platform #endif } END_INANITY <|endoftext|>
<commit_before>//(c) 2016 by Authors //This file is a part of ABruijn program. //Released under the BSD license (see LICENSE file) #include <vector> #include <iostream> #include <unordered_set> #include <unordered_map> #include "chimera.h" #include "logger.h" void ChimeraDetector::detectChimeras() { Logger::get().debug() << "Overlap-estimated coverage: " << this->estimateOverlapCoverage(); for (auto& seqHash : _seqContainer.getIndex()) { if (this->testReadByCoverage(seqHash.first)) //if (this->testSelfOverlap(seqHash.first)) { _chimeras.insert(seqHash.first); } } Logger::get().debug() << _chimeras.size() / 2 << " sequences were marked as chimeric"; } int ChimeraDetector::estimateOverlapCoverage() { size_t total = 0; for (auto& seqHash : _seqContainer.getIndex()) { total += _ovlpDetector.getOverlapIndex().at(seqHash.first).size(); } return total / _seqContainer.getIndex().size(); } bool ChimeraDetector::testReadByCoverage(FastaRecord::Id readId) { static const int WINDOW = _maximumJump; const int FLANK = (_maximumJump + _maximumOverhang) / WINDOW; std::vector<int> coverage; int numWindows = _seqContainer.seqLen(readId) / WINDOW; if (numWindows - 2 * FLANK <= 0) return false; coverage.assign(numWindows - 2 * FLANK, 0); for (auto& ovlp : _ovlpDetector.getOverlapIndex().at(readId)) { if (ovlp.curId == ovlp.extId.rc()) continue; for (int pos = (ovlp.curBegin + _maximumJump) / WINDOW; pos < (ovlp.curEnd - _maximumJump) / WINDOW; ++pos) { if (pos - FLANK >= 0 && pos - FLANK < (int)coverage.size()) { ++coverage[pos - FLANK]; } } } Logger::get().debug() << _seqContainer.seqName(readId); std::string covStr; for (int cov : coverage) { covStr += std::to_string(cov) + " "; } Logger::get().debug() << covStr; bool zeroStrip = false; for (size_t i = 0; i < coverage.size() - 1; ++i) { if (!zeroStrip && coverage[i] != 0 && coverage[i + 1] == 0) { zeroStrip = true; } if (zeroStrip && coverage[i + 1] != 0) { Logger::get().debug() << "Chimeric!"; return true; } } return false; } bool ChimeraDetector::testSelfOverlap(FastaRecord::Id readId) { auto& overlaps = _ovlpDetector.getOverlapIndex().at(readId); for (auto& ovlp : overlaps) { if (ovlp.extId == readId.rc()) return true; } return false; } <commit_msg>self-overlaps<commit_after>//(c) 2016 by Authors //This file is a part of ABruijn program. //Released under the BSD license (see LICENSE file) #include <vector> #include <iostream> #include <unordered_set> #include <unordered_map> #include "chimera.h" #include "logger.h" void ChimeraDetector::detectChimeras() { Logger::get().debug() << "Overlap-estimated coverage: " << this->estimateOverlapCoverage(); for (auto& seqHash : _seqContainer.getIndex()) { if (this->testReadByCoverage(seqHash.first)) { _chimeras.insert(seqHash.first); } } Logger::get().debug() << _chimeras.size() / 2 << " sequences were marked as chimeric"; } int ChimeraDetector::estimateOverlapCoverage() { size_t total = 0; for (auto& seqHash : _seqContainer.getIndex()) { total += _ovlpDetector.getOverlapIndex().at(seqHash.first).size(); } return total / _seqContainer.getIndex().size(); } bool ChimeraDetector::testReadByCoverage(FastaRecord::Id readId) { static const int WINDOW = _maximumJump; const int FLANK = (_maximumJump + _maximumOverhang) / WINDOW; std::vector<int> coverage; int numWindows = _seqContainer.seqLen(readId) / WINDOW; if (numWindows - 2 * FLANK <= 0) return false; coverage.assign(numWindows - 2 * FLANK, 0); for (auto& ovlp : _ovlpDetector.getOverlapIndex().at(readId)) { if (ovlp.curId == ovlp.extId.rc()) return true; for (int pos = (ovlp.curBegin + _maximumJump) / WINDOW; pos < (ovlp.curEnd - _maximumJump) / WINDOW; ++pos) { if (pos - FLANK >= 0 && pos - FLANK < (int)coverage.size()) { ++coverage[pos - FLANK]; } } } Logger::get().debug() << _seqContainer.seqName(readId); std::string covStr; for (int cov : coverage) { covStr += std::to_string(cov) + " "; } Logger::get().debug() << covStr; bool zeroStrip = false; for (size_t i = 0; i < coverage.size() - 1; ++i) { if (!zeroStrip && coverage[i] != 0 && coverage[i + 1] == 0) { zeroStrip = true; } if (zeroStrip && coverage[i + 1] != 0) { Logger::get().debug() << "Chimeric!"; return true; } } return false; } <|endoftext|>
<commit_before>#pragma once #ifndef QI_OBJECTUID_HPP #define QI_OBJECTUID_HPP #include <boost/optional.hpp> #include <ka/typetraits.hpp> #include <ka/utility.hpp> #include <qi/ptruid.hpp> namespace qi { /// Unique identifier of an object being referred to by a qi::Object instance. /// /// @warning Users: your code SHALL NOT assume that ObjectUid will always /// be implemented as an alias to PtrUid. /// We only guarantee that it is Regular, i.e. it has value semantics. /// See ka/concept.hpp for a complete definition of Regular. /// The definition of ObjectUid may be changed in the future. using ObjectUid = PtrUid; /// Deserializes an ObjectUid from a range of bytes. /// @returns An ObjectUid or none if the range has the wrong size. /// /// Post-conditions (where empty(r) means begin(r) == end(r)): /// std::distance(begin(r), end(r)) == size(uid)) == !result.empty() /// /// Invariant: boost::range::equal(serializeObjectUid(*deserializeObjectUid(r)), r) /// /// ForwardRange<T> R, where T is implicitly convertible to uint8_t template<typename R> boost::optional<ObjectUid> deserializeObjectUid(const R& r) { using std::begin; using std::end; ObjectUid uid; using It = ka::Decay<decltype(begin(r))>; using DiffType = typename std::iterator_traits<It>::difference_type; if (std::distance(begin(r), end(r)) == static_cast<DiffType>(size(uid))) { std::copy(begin(r), end(r), begin(uid)); return uid; } return {}; } /// Serializes an ObjectUid into container (in a non human-readable way). /// @remark This is useful for storing an ObjectUid in an arbitrary container. /// Do not use this function with string for printing for human readers. /// To print an ObjectUid's content, use `operator<<` instead. /// /// Requires SequenceContainer<T> /// @returns A T object initialized with the ObjectUid's data. /// /// Invariant: *deserializeObjectUid(serializeObjectUid(x)) == x template<typename T> T serializeObjectUid(const ObjectUid& uid) { return T(begin(uid), end(uid)); } } // namespace qi #endif <commit_msg>qi.objectuid: Clarifies `deserializeObjectUid`'s specification.<commit_after>#pragma once #ifndef QI_OBJECTUID_HPP #define QI_OBJECTUID_HPP #include <boost/optional.hpp> #include <ka/typetraits.hpp> #include <ka/utility.hpp> #include <qi/ptruid.hpp> namespace qi { /// Unique identifier of an object being referred to by a qi::Object instance. /// /// @warning Users: your code SHALL NOT assume that ObjectUid will always /// be implemented as an alias to PtrUid. /// We only guarantee that it is Regular, i.e. it has value semantics. /// See ka/concept.hpp for a complete definition of Regular. /// The definition of ObjectUid may be changed in the future. using ObjectUid = PtrUid; /// Deserializes an ObjectUid from a range of bytes. /// @returns An ObjectUid or none if the range has the wrong size. /// /// Post-condition (where result == deserializeObjectUid(r)): /// (std::distance(begin(r), end(r)) == size(uid)) == result.has_value() /// /// Invariant: boost::range::equal(serializeObjectUid(*deserializeObjectUid(r)), r) /// provided deserializeObjectUid(r).has_value() /// /// Linearizable<T> R, where T is implicitly convertible to uint8_t template<typename R> boost::optional<ObjectUid> deserializeObjectUid(const R& r) { using std::begin; using std::end; ObjectUid uid; using It = ka::Decay<decltype(begin(r))>; using DiffType = typename std::iterator_traits<It>::difference_type; if (std::distance(begin(r), end(r)) == static_cast<DiffType>(size(uid))) { std::copy(begin(r), end(r), begin(uid)); return uid; } return {}; } /// Serializes an ObjectUid into container (in a non human-readable way). /// @remark This is useful for storing an ObjectUid in an arbitrary container. /// Do not use this function with string for printing for human readers. /// To print an ObjectUid's content, use `operator<<` instead. /// /// Requires SequenceContainer<T> /// @returns A T object initialized with the ObjectUid's data. /// /// Invariant: *deserializeObjectUid(serializeObjectUid(x)) == x template<typename T> T serializeObjectUid(const ObjectUid& uid) { return T(begin(uid), end(uid)); } } // namespace qi #endif <|endoftext|>
<commit_before>//===- YAML.cpp - YAMLIO utilities for object files -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines utility classes for handling the YAML representation of // object files. // //===----------------------------------------------------------------------===// #include "llvm/MC/YAML.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/raw_ostream.h" #include <cctype> using namespace llvm; void yaml::ScalarTraits<yaml::BinaryRef>::output( const yaml::BinaryRef &Val, void *, llvm::raw_ostream &Out) { Val.writeAsHex(Out); } StringRef yaml::ScalarTraits<yaml::BinaryRef>::input(StringRef Scalar, void *, yaml::BinaryRef &Val) { if (Scalar.size() % 2 != 0) return "BinaryRef hex string must contain an even number of nybbles."; // TODO: Can we improve YAMLIO to permit a more accurate diagnostic here? // (e.g. a caret pointing to the offending character). for (unsigned I = 0, N = Scalar.size(); I != N; ++I) if (!isxdigit(Scalar[I])) return "BinaryRef hex string must contain only hex digits."; Val = yaml::BinaryRef(Scalar); return StringRef(); } void yaml::BinaryRef::writeAsBinary(raw_ostream &OS) const { if (!DataIsHexString) { OS.write((const char *)Data.data(), Data.size()); return; } for (unsigned I = 0, N = Data.size(); I != N; I += 2) { uint8_t Byte; StringRef((const char *)&Data[I], 2).getAsInteger(16, Byte); OS.write(Byte); } } void yaml::BinaryRef::writeAsHex(raw_ostream &OS) const { if (binary_size() == 0) return; if (DataIsHexString) { OS.write((const char *)Data.data(), Data.size()); return; } for (ArrayRef<uint8_t>::iterator I = Data.begin(), E = Data.end(); I != E; ++I) { uint8_t Byte = *I; OS << hexdigit(Byte >> 4); OS << hexdigit(Byte & 0xf); } } <commit_msg>[MC][YAML] Rangify the loop. NFC<commit_after>//===- YAML.cpp - YAMLIO utilities for object files -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines utility classes for handling the YAML representation of // object files. // //===----------------------------------------------------------------------===// #include "llvm/MC/YAML.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/raw_ostream.h" #include <cctype> using namespace llvm; void yaml::ScalarTraits<yaml::BinaryRef>::output( const yaml::BinaryRef &Val, void *, llvm::raw_ostream &Out) { Val.writeAsHex(Out); } StringRef yaml::ScalarTraits<yaml::BinaryRef>::input(StringRef Scalar, void *, yaml::BinaryRef &Val) { if (Scalar.size() % 2 != 0) return "BinaryRef hex string must contain an even number of nybbles."; // TODO: Can we improve YAMLIO to permit a more accurate diagnostic here? // (e.g. a caret pointing to the offending character). for (unsigned I = 0, N = Scalar.size(); I != N; ++I) if (!isxdigit(Scalar[I])) return "BinaryRef hex string must contain only hex digits."; Val = yaml::BinaryRef(Scalar); return StringRef(); } void yaml::BinaryRef::writeAsBinary(raw_ostream &OS) const { if (!DataIsHexString) { OS.write((const char *)Data.data(), Data.size()); return; } for (unsigned I = 0, N = Data.size(); I != N; I += 2) { uint8_t Byte; StringRef((const char *)&Data[I], 2).getAsInteger(16, Byte); OS.write(Byte); } } void yaml::BinaryRef::writeAsHex(raw_ostream &OS) const { if (binary_size() == 0) return; if (DataIsHexString) { OS.write((const char *)Data.data(), Data.size()); return; } for (uint8_t Byte : Data) OS << hexdigit(Byte >> 4) << hexdigit(Byte & 0xf); } <|endoftext|>
<commit_before>#include "png.h" const unsigned char Png::header_magic[] = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }; size_t Png::Leanify(size_t size_leanified /*= 0*/) { char *p_read, *p_write; // header p_read = fp; p_write = p_read - size_leanified; if (size_leanified) { memmove(p_write, p_read, sizeof(header_magic)); } p_read += sizeof(header_magic); p_write += sizeof(header_magic); // chunk uint32_t chunk_type; do { // read chunk length // use bswap to convert Big-Endian to Little-Endian uint32_t chunk_lenth = bswap32(*(uint32_t *)p_read); // read chunk type chunk_type = *(uint32_t *)(p_read + 4); // judge the case of first letter // remove all ancillary chunks except tRNS and APNG chunks and npTc // tRNS has transparency information if (chunk_type & 0x20000000) { switch (chunk_type) { case 0x534E5274: // tRNS transparent case 0x4C546361: // acTL APNG case 0x4C546366: // fcTL APNG case 0x54416466: // fdAT APNG TODO: use zopfli to recompress fdAT case 0x6354706E: // npTc Android 9Patch images (*.9.png) // move this chunk if (p_write != p_read) { memmove(p_write, p_read, chunk_lenth + 12); } p_write += chunk_lenth + 12; break; default: // remove this chunk if (is_verbose) { // chunk name for (int i = 4; i < 8; i++) { std::cout << p_read[i]; } std::cout << " chunk removed." << std::endl; } break; } } else { // move this chunk if (p_write != p_read) { memmove(p_write, p_read, chunk_lenth + 12); } p_write += chunk_lenth + 12; } // skip whole chunk p_read += chunk_lenth + 12; } while (chunk_type != 0x444E4549); // IEND fp -= size_leanified; uint32_t png_size = p_write - fp; if (!is_fast) { ZopfliPNGOptions zopflipng_options; zopflipng_options.lossy_transparent = true; // see the switch above for information about these chunks zopflipng_options.keepchunks.push_back("acTL"); zopflipng_options.keepchunks.push_back("fcTL"); zopflipng_options.keepchunks.push_back("fdAT"); zopflipng_options.keepchunks.push_back("npTc"); zopflipng_options.num_iterations = iterations; zopflipng_options.num_iterations_large = iterations / 3 + 1; // trying both methods does not worth the time it spend // it's better to use the time for more iterations. // zopflipng_options.block_split_strategy = 3; const std::vector<unsigned char> origpng(fp, fp + png_size); std::vector<unsigned char> resultpng; if (ZopfliPNGOptimize(origpng, zopflipng_options, is_verbose, &resultpng)) { // error occurred return png_size; } // only use the result PNG if it is smaller // sometimes the original PNG is already highly optimized // then maybe ZopfliPNG will produce bigger file if (resultpng.size() < png_size) { memcpy(fp, resultpng.data(), resultpng.size()); return resultpng.size(); } } return png_size; } <commit_msg>PNG: use Initializer list instead of push_back<commit_after>#include "png.h" const unsigned char Png::header_magic[] = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }; size_t Png::Leanify(size_t size_leanified /*= 0*/) { char *p_read, *p_write; // header p_read = fp; p_write = p_read - size_leanified; if (size_leanified) { memmove(p_write, p_read, sizeof(header_magic)); } p_read += sizeof(header_magic); p_write += sizeof(header_magic); // chunk uint32_t chunk_type; do { // read chunk length // use bswap to convert Big-Endian to Little-Endian uint32_t chunk_lenth = bswap32(*(uint32_t *)p_read); // read chunk type chunk_type = *(uint32_t *)(p_read + 4); // judge the case of first letter // remove all ancillary chunks except tRNS and APNG chunks and npTc // tRNS has transparency information if (chunk_type & 0x20000000) { switch (chunk_type) { case 0x534E5274: // tRNS transparent case 0x4C546361: // acTL APNG case 0x4C546366: // fcTL APNG case 0x54416466: // fdAT APNG TODO: use zopfli to recompress fdAT case 0x6354706E: // npTc Android 9Patch images (*.9.png) // move this chunk if (p_write != p_read) { memmove(p_write, p_read, chunk_lenth + 12); } p_write += chunk_lenth + 12; break; default: // remove this chunk if (is_verbose) { // chunk name for (int i = 4; i < 8; i++) { std::cout << p_read[i]; } std::cout << " chunk removed." << std::endl; } break; } } else { // move this chunk if (p_write != p_read) { memmove(p_write, p_read, chunk_lenth + 12); } p_write += chunk_lenth + 12; } // skip whole chunk p_read += chunk_lenth + 12; } while (chunk_type != 0x444E4549); // IEND fp -= size_leanified; uint32_t png_size = p_write - fp; if (!is_fast) { ZopfliPNGOptions zopflipng_options; zopflipng_options.lossy_transparent = true; // see the switch above for information about these chunks zopflipng_options.keepchunks = { "acTL", "fcTL", "fdAT", "npTc" }; zopflipng_options.num_iterations = iterations; zopflipng_options.num_iterations_large = iterations / 3 + 1; // trying both methods does not worth the time it spend // it's better to use the time for more iterations. // zopflipng_options.block_split_strategy = 3; const std::vector<unsigned char> origpng(fp, fp + png_size); std::vector<unsigned char> resultpng; if (ZopfliPNGOptimize(origpng, zopflipng_options, is_verbose, &resultpng)) { // error occurred return png_size; } // only use the result PNG if it is smaller // sometimes the original PNG is already highly optimized // then maybe ZopfliPNG will produce bigger file if (resultpng.size() < png_size) { memcpy(fp, resultpng.data(), resultpng.size()); return resultpng.size(); } } return png_size; } <|endoftext|>
<commit_before>#include <stdio.h> ISSPACE(C) (C == (int)' ') ISALPHA(C) (('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z')) ISNUM(C) ('0' <= C && C <= '9') ISALNUM(C) (ISALPHA(C) || ISNUM(C)) enum Token { tok_eof = -1, // commands tok_def = -2, tok_extern = -3, // primary tok_identifier = -4, tok_number = -5, }; static std::string IdentifierStr; static double NumVal; static int gettok() { static int LastChar = ' '; // skip any whitespace. while (ISSPACE(LastChar)) LastChar = getchar(); if (ISALPHA(LastChar)) { IdentifierStr = LastChar; for (;;) { LastChar = getchar(); if (ISALNUM(LastChar)) { } else { break; } } } } <commit_msg>write lexer<commit_after>#include <stdio.h> ISSPACE(C) (C == (int)' ') ISALPHA(C) (('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z')) ISDIGIT(C) ('0' <= C && C <= '9') ISALNUM(C) (ISALPHA(C) || ISDIGIT(C)) enum Token { tok_eof = -1, // commands tok_def = -2, tok_extern = -3, // primary tok_identifier = -4, tok_number = -5, }; static std::string IdentifierStr; static double NumVal; static int gettok() { static int LastChar = ' '; // skip any whitespace. while (ISSPACE(LastChar)) LastChar = getchar(); if (ISALPHA(LastChar)) { IdentifierStr = LastChar; for (;;) { LastChar = getchar(); if (ISALNUM(LastChar)) { IdentifierStr += LastChar; } else { break; } } if (IdentifierStr == "def") return tok_def; if (IdentifierStr == "extern") return tok_extern; return tok_identifier; } if (ISDIGIT(LastChar) || LastChar == '.') { std::string NumStr; do { NumStr += LastChar; LastChar = getchar(); } while (ISDIGIT(LastChar) || LastChar == '.'); NumVal = strtod(NumStr.c_str(), 0); return tok_number; } if (LastChar =='#') { do { LastChar = getchar(); } while (LastChar != EOF && LastChar != '\n' && LastChar != '\r'); if (LastChar != EOF) return gettok(); } if (LastChar == EOF) return tok_eof; int ThisChar = LastChar; LastChar = getchar(); return ThisChar; } <|endoftext|>
<commit_before> CalibratePeriod(TString lPeriodName = "LHC10h"){ //Load ALICE stuff TString gLibs[] =   {"STEER", "ANALYSIS", "ANALYSISalice", "ANALYSIScalib","OADB"}; TString thislib = "lib"; for(Int_t ilib = 0; ilib<5; ilib++){ thislib="lib"; thislib.Append(gLibs[ilib].Data()); cout<<"Will load "<<thislib.Data()<<endl; gSystem->Load(thislib.Data()); } gSystem->SetIncludePath("-I$ROOTSYS/include -I$ALICE_ROOT/include -I$ALICE_PHYSICS/include"); cout<<"Alive! "<<endl; //All fine, let's try the calibrator AliMultSelectionCalibrator *lCalib = new AliMultSelectionCalibrator("lCalib"); //============================================================ // --- Definition of Boundaries --- //============================================================ //Set Adaptive Percentile Boundaries, adjust if finer selection desired Double_t lDesiredBoundaries[1000]; Long_t lNDesiredBoundaries=0; lDesiredBoundaries[0] = 100; //From Low To High Multiplicity for( Int_t ib = 1; ib < 91; ib++) { lNDesiredBoundaries++; lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] - 1.0; } for( Int_t ib = 1; ib < 91; ib++) { lNDesiredBoundaries++; lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] - 0.1; } for( Int_t ib = 1; ib < 91; ib++) { lNDesiredBoundaries++; lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] - 0.01; } for( Int_t ib = 1; ib < 101; ib++) { lNDesiredBoundaries++; lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] - 0.001; } lNDesiredBoundaries++; lDesiredBoundaries[lNDesiredBoundaries] = 0; lCalib->SetBoundaries( lNDesiredBoundaries, lDesiredBoundaries ); cout<<"Boundaries set. Will attempt calibration now... "<<endl; if ( lPeriodName.Contains("LHC10h") ){ cout<<"Setting event selection criteria for Pb-Pb..."<<endl; lCalib->GetEventCuts()->SetVzCut(10.0); lCalib->GetEventCuts()->SetTriggerCut (kTRUE ); lCalib->GetEventCuts()->SetINELgtZEROCut (kFALSE); lCalib->GetEventCuts()->SetTrackletsVsClustersCut (kFALSE); lCalib->GetEventCuts()->SetRejectPileupInMultBinsCut (kFALSE); lCalib->GetEventCuts()->SetVertexConsistencyCut (kFALSE); lCalib->GetEventCuts()->SetNonZeroNContribs (kTRUE); } if ( lPeriodName.Contains("LHC15m") ){ cout<<"Setting event selection criteria for Pb-Pb..."<<endl; lCalib->GetEventCuts()->SetVzCut(10.0); lCalib->GetEventCuts()->SetTriggerCut (kTRUE ); lCalib->GetEventCuts()->SetINELgtZEROCut (kFALSE); lCalib->GetEventCuts()->SetTrackletsVsClustersCut (kFALSE); lCalib->GetEventCuts()->SetRejectPileupInMultBinsCut (kFALSE); lCalib->GetEventCuts()->SetVertexConsistencyCut (kFALSE); lCalib->GetEventCuts()->SetNonZeroNContribs (kTRUE); } //============================================================ // --- Definition of Input Variables --- //============================================================ lCalib->SetupStandardInput(); //Changes in new version: create AliMultSelection here AliMultSelection *lMultSel = new AliMultSelection(); lCalib->SetMultSelection(lMultSel); //============================================================ // --- Definition of Estimators --- //============================================================ AliMultEstimator *fEstV0M = new AliMultEstimator("V0M", "", "(fAmplitude_V0A)+(fAmplitude_V0C)"); if( lPeriodName.Contains("LHC10h") ) { fEstV0M -> SetUseAnchor ( kTRUE ) ; fEstV0M -> SetAnchorPoint ( 81.0 ) ; fEstV0M -> SetAnchorPercentile ( 90.0 ) ; } if( lPeriodName.Contains("LHC15m") ) { fEstV0M -> SetUseAnchor ( kTRUE ) ; fEstV0M -> SetAnchorPoint ( 115.0 ) ; fEstV0M -> SetAnchorPercentile ( 87.5 ) ; AliMultEstimator *fEstnSPDClustersCorr = new AliMultEstimator("SPDClustersCorr", "", "(fnSPDClusters)/(1+((fEvSel_VtxZ)-1.83261)*(0.0057962-((fEvSel_VtxZ)-1.83261)*(-0.00307058)))"); fEstnSPDClustersCorr -> SetUseAnchor ( kTRUE ) ; fEstnSPDClustersCorr -> SetAnchorPoint ( 100.0 ) ; fEstnSPDClustersCorr -> SetAnchorPercentile ( 87.0 ) ; AliMultEstimator *fEstCL0 = new AliMultEstimator("CL0", "", "(fnSPDClusters0)/(1+((fEvSel_VtxZ)-1.84151)*(0.00759815-((fEvSel_VtxZ)-1.84151)*(-0.00340785)))"); fEstCL0 -> SetUseAnchor ( kTRUE ) ; fEstCL0 -> SetAnchorPoint ( 39.5 ) ; fEstCL0 -> SetAnchorPercentile ( 88.9 ) ; AliMultEstimator *fEstCL1 = new AliMultEstimator("CL1", "", "(fnSPDClusters1)/(1+((fEvSel_VtxZ)-1.8275)*(0.00389886-((fEvSel_VtxZ)-1.8275)*(-0.00283038)))"); fEstCL1 -> SetUseAnchor ( kTRUE ) ; fEstCL1 -> SetAnchorPoint ( 40.5 ) ; fEstCL1 -> SetAnchorPercentile ( 88.1 ) ; } AliMultEstimator *fEstV0A = new AliMultEstimator("V0A", "", "(fAmplitude_V0A)"); AliMultEstimator *fEstV0C = new AliMultEstimator("V0C", "", "(fAmplitude_V0C)"); AliMultEstimator *fEstOnlineV0M = new AliMultEstimator("OnlineV0M", "", "(fAmplitude_OnlineV0A)+(fAmplitude_OnlineV0C)"); AliMultEstimator *fEstOnlineV0A = new AliMultEstimator("OnlineV0A", "", "(fAmplitude_OnlineV0A)"); AliMultEstimator *fEstOnlineV0C = new AliMultEstimator("OnlineV0C", "", "(fAmplitude_OnlineV0C)"); AliMultEstimator *fEstADM = new AliMultEstimator("ADM", "", "(fMultiplicity_ADA)+(fMultiplicity_ADC)"); AliMultEstimator *fEstADA = new AliMultEstimator("ADA", "", "(fMultiplicity_ADA)"); AliMultEstimator *fEstADC = new AliMultEstimator("ADC", "", "(fMultiplicity_ADC)"); //Integer estimators AliMultEstimator *fEstnSPDClusters = new AliMultEstimator("SPDClusters", "", "(fnSPDClusters)"); fEstnSPDClusters->SetIsInteger(kTRUE); AliMultEstimator *fEstnSPDTracklets = new AliMultEstimator("SPDTracklets", "", "(fnTracklets)"); fEstnSPDTracklets->SetIsInteger(kTRUE); AliMultEstimator *fEstRefMultEta5 = new AliMultEstimator("RefMult05", "", "(fRefMultEta5)"); fEstRefMultEta5->SetIsInteger(kTRUE); AliMultEstimator *fEstRefMultEta8 = new AliMultEstimator("RefMult08", "", "(fRefMultEta8)"); fEstRefMultEta8->SetIsInteger(kTRUE); //Univeral: V0 lCalib->GetMultSelection() -> AddEstimator( fEstV0M ); lCalib->GetMultSelection() -> AddEstimator( fEstV0A ); lCalib->GetMultSelection() -> AddEstimator( fEstV0C ); //Testing! if( lPeriodName.Contains("LHC10h") ){ AliMultEstimator *fEstV0MNonAnchored = new AliMultEstimator("V0MNonAnchored", "", "(fAmplitude_V0A)+(fAmplitude_V0C)"); lCalib->GetMultSelection() -> AddEstimator( fEstV0MNonAnchored ); } //Anchoring test //Only do this in run 2, AD didn't exist in Run 1 //Will also save space in the OADB for old datasets! if( lPeriodName.Contains("LHC15") ){ lCalib->GetMultSelection() -> AddEstimator( fEstOnlineV0M ); lCalib->GetMultSelection() -> AddEstimator( fEstOnlineV0A ); lCalib->GetMultSelection() -> AddEstimator( fEstOnlineV0C ); lCalib->GetMultSelection() -> AddEstimator( fEstADM ); lCalib->GetMultSelection() -> AddEstimator( fEstADA ); lCalib->GetMultSelection() -> AddEstimator( fEstADC ); } //Universal: Tracking, etc lCalib->GetMultSelection() -> AddEstimator( fEstnSPDClusters ); lCalib->GetMultSelection() -> AddEstimator( fEstnSPDTracklets ); lCalib->GetMultSelection() -> AddEstimator( fEstRefMultEta5 ); lCalib->GetMultSelection() -> AddEstimator( fEstRefMultEta8 ); lCalib->GetMultSelection() -> AddEstimator( fEstnSPDClustersCorr ); lCalib->GetMultSelection() -> AddEstimator( fEstCL0 ); lCalib->GetMultSelection() -> AddEstimator( fEstCL1 ); //============================================================ // --- Definition of Input/Output --- //============================================================ if( !lPeriodName.Contains("test") ){ //Per Period calibration: standard locations... lCalib -> SetInputFile ( Form("~/work/calibs/Merged%s.root",lPeriodName.Data() ) ); lCalib -> SetBufferFile ( Form("~/work/fast/buffer-%s.root", lPeriodName.Data() ) ); //Local running please lCalib -> SetInputFile ( Form("~/Dropbox/MultSelCalib/%s/Merged%s.root",lPeriodName.Data(), lPeriodName.Data() ) ); lCalib -> SetBufferFile ( "buffer.root" ); lCalib -> SetOutputFile ( Form("OADB-%s.root", lPeriodName.Data() ) ); lCalib -> Calibrate (); }else{ lCalib -> SetInputFile ( "../MultSelCalib/LHC10h/files/AnalysisResults_137161.root"); lCalib -> SetBufferFile ( "buffer-test.root" ); lCalib -> SetOutputFile ( "OADB-testing.root" ); lCalib -> Calibrate (); } } <commit_msg>OADB update: minor adjustments; Calibrator macro update<commit_after> CalibratePeriod(TString lPeriodName = "LHC10h"){ //Load ALICE stuff TString gLibs[] =   {"STEER", "ANALYSIS", "ANALYSISalice", "ANALYSIScalib","OADB"}; TString thislib = "lib"; for(Int_t ilib = 0; ilib<5; ilib++){ thislib="lib"; thislib.Append(gLibs[ilib].Data()); cout<<"Will load "<<thislib.Data()<<endl; gSystem->Load(thislib.Data()); } gSystem->SetIncludePath("-I$ROOTSYS/include -I$ALICE_ROOT/include -I$ALICE_PHYSICS/include"); cout<<"Alive! "<<endl; //All fine, let's try the calibrator AliMultSelectionCalibrator *lCalib = new AliMultSelectionCalibrator("lCalib"); //============================================================ // --- Definition of Boundaries --- //============================================================ //Set Adaptive Percentile Boundaries, adjust if finer selection desired Double_t lDesiredBoundaries[1000]; Long_t lNDesiredBoundaries=0; lDesiredBoundaries[0] = 100; //From Low To High Multiplicity for( Int_t ib = 1; ib < 91; ib++) { lNDesiredBoundaries++; lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] - 1.0; } for( Int_t ib = 1; ib < 91; ib++) { lNDesiredBoundaries++; lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] - 0.1; } for( Int_t ib = 1; ib < 91; ib++) { lNDesiredBoundaries++; lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] - 0.01; } for( Int_t ib = 1; ib < 101; ib++) { lNDesiredBoundaries++; lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] - 0.001; } lNDesiredBoundaries++; lDesiredBoundaries[lNDesiredBoundaries] = 0; lCalib->SetBoundaries( lNDesiredBoundaries, lDesiredBoundaries ); cout<<"Boundaries set. Will attempt calibration now... "<<endl; if ( lPeriodName.Contains("LHC10h") ){ cout<<"Setting event selection criteria for Pb-Pb..."<<endl; lCalib->GetEventCuts()->SetVzCut(10.0); lCalib->GetEventCuts()->SetTriggerCut (kTRUE ); lCalib->GetEventCuts()->SetINELgtZEROCut (kFALSE); lCalib->GetEventCuts()->SetTrackletsVsClustersCut (kFALSE); lCalib->GetEventCuts()->SetRejectPileupInMultBinsCut (kFALSE); lCalib->GetEventCuts()->SetVertexConsistencyCut (kFALSE); lCalib->GetEventCuts()->SetNonZeroNContribs (kTRUE); } if ( lPeriodName.Contains("LHC15m") ){ cout<<"Setting event selection criteria for Pb-Pb..."<<endl; lCalib->GetEventCuts()->SetVzCut(10.0); lCalib->GetEventCuts()->SetTriggerCut (kTRUE ); lCalib->GetEventCuts()->SetINELgtZEROCut (kFALSE); lCalib->GetEventCuts()->SetTrackletsVsClustersCut (kFALSE); lCalib->GetEventCuts()->SetRejectPileupInMultBinsCut (kFALSE); lCalib->GetEventCuts()->SetVertexConsistencyCut (kFALSE); lCalib->GetEventCuts()->SetNonZeroNContribs (kTRUE); } //============================================================ // --- Definition of Input Variables --- //============================================================ lCalib->SetupStandardInput(); //Changes in new version: create AliMultSelection here AliMultSelection *lMultSel = new AliMultSelection(); lCalib->SetMultSelection(lMultSel); //============================================================ // --- Definition of Estimators --- //============================================================ AliMultEstimator *fEstV0M = new AliMultEstimator("V0M", "", "(fAmplitude_V0A)+(fAmplitude_V0C)"); if( lPeriodName.Contains("LHC10h") ) { fEstV0M -> SetUseAnchor ( kTRUE ) ; fEstV0M -> SetAnchorPoint ( 81.0 ) ; fEstV0M -> SetAnchorPercentile ( 90.0 ) ; } if( lPeriodName.Contains("LHC15m") ) { fEstV0M -> SetUseAnchor ( kTRUE ) ; fEstV0M -> SetAnchorPoint ( 115.0 ) ; fEstV0M -> SetAnchorPercentile ( 87.5 ) ; AliMultEstimator *fEstnSPDClustersCorr = new AliMultEstimator("SPDClustersCorr", "", "(fnSPDClusters)/(1+((fEvSel_VtxZ)-1.83261)*(0.0057962-((fEvSel_VtxZ)-1.83261)*(-0.00307058)))"); fEstnSPDClustersCorr -> SetUseAnchor ( kTRUE ) ; fEstnSPDClustersCorr -> SetAnchorPoint ( 100.0 ) ; fEstnSPDClustersCorr -> SetAnchorPercentile ( 87.0 ) ; AliMultEstimator *fEstCL0 = new AliMultEstimator("CL0", "", "(fnSPDClusters0)/(1+((fEvSel_VtxZ)-1.84151)*(0.00759815-((fEvSel_VtxZ)-1.84151)*(-0.00340785)))"); fEstCL0 -> SetUseAnchor ( kTRUE ) ; fEstCL0 -> SetAnchorPoint ( 39.5 ) ; fEstCL0 -> SetAnchorPercentile ( 88.9 ) ; AliMultEstimator *fEstCL1 = new AliMultEstimator("CL1", "", "(fnSPDClusters1)/(1+((fEvSel_VtxZ)-1.8275)*(0.00389886-((fEvSel_VtxZ)-1.8275)*(-0.00283038)))"); fEstCL1 -> SetUseAnchor ( kTRUE ) ; fEstCL1 -> SetAnchorPoint ( 40.5 ) ; fEstCL1 -> SetAnchorPercentile ( 88.1 ) ; } AliMultEstimator *fEstV0A = new AliMultEstimator("V0A", "", "(fAmplitude_V0A)"); AliMultEstimator *fEstV0C = new AliMultEstimator("V0C", "", "(fAmplitude_V0C)"); AliMultEstimator *fEstOnlineV0M = new AliMultEstimator("OnlineV0M", "", "(fAmplitude_OnlineV0A)+(fAmplitude_OnlineV0C)"); AliMultEstimator *fEstOnlineV0A = new AliMultEstimator("OnlineV0A", "", "(fAmplitude_OnlineV0A)"); AliMultEstimator *fEstOnlineV0C = new AliMultEstimator("OnlineV0C", "", "(fAmplitude_OnlineV0C)"); AliMultEstimator *fEstADM = new AliMultEstimator("ADM", "", "(fMultiplicity_ADA)+(fMultiplicity_ADC)"); AliMultEstimator *fEstADA = new AliMultEstimator("ADA", "", "(fMultiplicity_ADA)"); AliMultEstimator *fEstADC = new AliMultEstimator("ADC", "", "(fMultiplicity_ADC)"); //Integer estimators AliMultEstimator *fEstnSPDClusters = new AliMultEstimator("SPDClusters", "", "(fnSPDClusters)"); fEstnSPDClusters->SetIsInteger(kTRUE); AliMultEstimator *fEstnSPDTracklets = new AliMultEstimator("SPDTracklets", "", "(fnTracklets)"); fEstnSPDTracklets->SetIsInteger(kTRUE); AliMultEstimator *fEstRefMultEta5 = new AliMultEstimator("RefMult05", "", "(fRefMultEta5)"); fEstRefMultEta5->SetIsInteger(kTRUE); AliMultEstimator *fEstRefMultEta8 = new AliMultEstimator("RefMult08", "", "(fRefMultEta8)"); fEstRefMultEta8->SetIsInteger(kTRUE); //Univeral: V0 lCalib->GetMultSelection() -> AddEstimator( fEstV0M ); lCalib->GetMultSelection() -> AddEstimator( fEstV0A ); lCalib->GetMultSelection() -> AddEstimator( fEstV0C ); //Testing! if( lPeriodName.Contains("LHC10h") ){ AliMultEstimator *fEstV0MNonAnchored = new AliMultEstimator("V0MNonAnchored", "", "(fAmplitude_V0A)+(fAmplitude_V0C)"); lCalib->GetMultSelection() -> AddEstimator( fEstV0MNonAnchored ); } //Anchoring test //Only do this in run 2, AD didn't exist in Run 1 //Will also save space in the OADB for old datasets! if( lPeriodName.Contains("LHC15") ){ lCalib->GetMultSelection() -> AddEstimator( fEstOnlineV0M ); lCalib->GetMultSelection() -> AddEstimator( fEstOnlineV0A ); lCalib->GetMultSelection() -> AddEstimator( fEstOnlineV0C ); lCalib->GetMultSelection() -> AddEstimator( fEstADM ); lCalib->GetMultSelection() -> AddEstimator( fEstADA ); lCalib->GetMultSelection() -> AddEstimator( fEstADC ); } //Universal: Tracking, etc lCalib->GetMultSelection() -> AddEstimator( fEstnSPDClusters ); lCalib->GetMultSelection() -> AddEstimator( fEstnSPDTracklets ); lCalib->GetMultSelection() -> AddEstimator( fEstRefMultEta5 ); lCalib->GetMultSelection() -> AddEstimator( fEstRefMultEta8 ); if( lPeriodName.Contains("LHC15m") ) { lCalib->GetMultSelection() -> AddEstimator( fEstnSPDClustersCorr ); lCalib->GetMultSelection() -> AddEstimator( fEstCL0 ); lCalib->GetMultSelection() -> AddEstimator( fEstCL1 ); } //============================================================ // --- Definition of Input/Output --- //============================================================ if( !lPeriodName.Contains("test") ){ //Per Period calibration: standard locations... lCalib -> SetInputFile ( Form("~/work/calibs/Merged%s.root",lPeriodName.Data() ) ); lCalib -> SetBufferFile ( Form("~/work/fast/buffer-%s.root", lPeriodName.Data() ) ); //Local running please lCalib -> SetInputFile ( Form("~/Dropbox/MultSelCalib/%s/Merged%s.root",lPeriodName.Data(), lPeriodName.Data() ) ); lCalib -> SetBufferFile ( "buffer.root" ); lCalib -> SetOutputFile ( Form("OADB-%s.root", lPeriodName.Data() ) ); lCalib -> Calibrate (); }else{ lCalib -> SetInputFile ( "../MultSelCalib/LHC10h/files/AnalysisResults_137161.root"); lCalib -> SetBufferFile ( "buffer-test.root" ); lCalib -> SetOutputFile ( "OADB-testing.root" ); lCalib -> Calibrate (); } } <|endoftext|>
<commit_before>//===================================================== // Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr> //===================================================== // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // 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 General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // #ifndef BLAZE_INTERFACE_HH #define BLAZE_INTERFACE_HH #include <blaze/Math.h> #include <blaze/Blaze.h> // using namespace blaze; #include <vector> template<class real> class blaze_interface { public : typedef real real_type ; typedef std::vector<real> stl_vector; typedef std::vector<stl_vector > stl_matrix; typedef blaze::DynamicMatrix<real,blaze::columnMajor> gene_matrix; typedef blaze::DynamicVector<real> gene_vector; static inline std::string name() { return "blaze"; } static void free_matrix(gene_matrix & A, int N){ return ; } static void free_vector(gene_vector & B){ return ; } static inline void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){ A.resize(A_stl[0].size(), A_stl.size()); for (int j=0; j<A_stl.size() ; j++){ for (int i=0; i<A_stl[j].size() ; i++){ A(i,j) = A_stl[j][i]; } } } static inline void vector_from_stl(gene_vector & B, stl_vector & B_stl){ B.resize(B_stl.size()); for (int i=0; i<B_stl.size() ; i++){ B[i] = B_stl[i]; } } static inline void vector_to_stl(gene_vector & B, stl_vector & B_stl){ for (int i=0; i<B_stl.size() ; i++){ B_stl[i] = B[i]; } } static inline void matrix_to_stl(gene_matrix & A, stl_matrix & A_stl){ int N=A_stl.size(); for (int j=0;j<N;j++){ A_stl[j].resize(N); for (int i=0;i<N;i++){ A_stl[j][i] = A(i,j); } } } static inline void matrix_matrix_product(const gene_matrix & A, const gene_matrix & B, gene_matrix & X, int N){ X = (A*B); } static inline void transposed_matrix_matrix_product(const gene_matrix & A, const gene_matrix & B, gene_matrix & X, int N){ X = A.transpose()*B.transpose(); } static inline void ata_product(const gene_matrix & A, gene_matrix & X, int N){ X = (A.transpose()*A); } static inline void aat_product(const gene_matrix & A, gene_matrix & X, int N){ X = (A*A.transpose()); } static inline void matrix_vector_product(gene_matrix & A, gene_vector & B, gene_vector & X, int N){ X = (A*B); } static inline void atv_product(gene_matrix & A, gene_vector & B, gene_vector & X, int N){ X = (A.transpose()*B); } static inline void axpy(const real coef, const gene_vector & X, gene_vector & Y, int N){ Y += coef * X; } static inline void axpby(real a, const gene_vector & X, real b, gene_vector & Y, int N){ Y = a*X + b*Y; } // static inline void cholesky(const gene_matrix & X, gene_matrix & C, int N){ // C = X; // recursive_cholesky(C); // } // static inline void lu_decomp(const gene_matrix & X, gene_matrix & R, int N){ // R = X; // std::vector<int> ipvt(N); // lu_factor(R, ipvt); // } // static inline void trisolve_lower(const gene_matrix & L, const gene_vector& B, gene_vector & X, int N){ // X = lower_trisolve(L, B); // } static inline void copy_matrix(const gene_matrix & source, gene_matrix & cible, int N){ cible = source; } static inline void copy_vector(const gene_vector & source, gene_vector & cible, int N){ cible = source; } }; #endif <commit_msg>Use trans(X) instead of X.transpose() in Blaze Benchmark<commit_after>//===================================================== // Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr> //===================================================== // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // 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 General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // #ifndef BLAZE_INTERFACE_HH #define BLAZE_INTERFACE_HH #include <blaze/Math.h> #include <blaze/Blaze.h> // using namespace blaze; #include <vector> template<class real> class blaze_interface { public : typedef real real_type ; typedef std::vector<real> stl_vector; typedef std::vector<stl_vector > stl_matrix; typedef blaze::DynamicMatrix<real,blaze::columnMajor> gene_matrix; typedef blaze::DynamicVector<real> gene_vector; static inline std::string name() { return "blaze"; } static void free_matrix(gene_matrix & A, int N){ return ; } static void free_vector(gene_vector & B){ return ; } static inline void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){ A.resize(A_stl[0].size(), A_stl.size()); for (int j=0; j<A_stl.size() ; j++){ for (int i=0; i<A_stl[j].size() ; i++){ A(i,j) = A_stl[j][i]; } } } static inline void vector_from_stl(gene_vector & B, stl_vector & B_stl){ B.resize(B_stl.size()); for (int i=0; i<B_stl.size() ; i++){ B[i] = B_stl[i]; } } static inline void vector_to_stl(gene_vector & B, stl_vector & B_stl){ for (int i=0; i<B_stl.size() ; i++){ B_stl[i] = B[i]; } } static inline void matrix_to_stl(gene_matrix & A, stl_matrix & A_stl){ int N=A_stl.size(); for (int j=0;j<N;j++){ A_stl[j].resize(N); for (int i=0;i<N;i++){ A_stl[j][i] = A(i,j); } } } static inline void matrix_matrix_product(const gene_matrix & A, const gene_matrix & B, gene_matrix & X, int N){ X = (A*B); } static inline void transposed_matrix_matrix_product(const gene_matrix & A, const gene_matrix & B, gene_matrix & X, int N){ X = (trans(A)*trans(B)); } static inline void ata_product(const gene_matrix & A, gene_matrix & X, int N){ X = (trans(A)*A); } static inline void aat_product(const gene_matrix & A, gene_matrix & X, int N){ X = (A*trans(A)); } static inline void matrix_vector_product(gene_matrix & A, gene_vector & B, gene_vector & X, int N){ X = (A*B); } static inline void atv_product(gene_matrix & A, gene_vector & B, gene_vector & X, int N){ X = (trans(A)*B); } static inline void axpy(const real coef, const gene_vector & X, gene_vector & Y, int N){ Y += coef * X; } static inline void axpby(real a, const gene_vector & X, real b, gene_vector & Y, int N){ Y = a*X + b*Y; } // static inline void cholesky(const gene_matrix & X, gene_matrix & C, int N){ // C = X; // recursive_cholesky(C); // } // static inline void lu_decomp(const gene_matrix & X, gene_matrix & R, int N){ // R = X; // std::vector<int> ipvt(N); // lu_factor(R, ipvt); // } // static inline void trisolve_lower(const gene_matrix & L, const gene_vector& B, gene_vector & X, int N){ // X = lower_trisolve(L, B); // } static inline void copy_matrix(const gene_matrix & source, gene_matrix & cible, int N){ cible = source; } static inline void copy_vector(const gene_vector & source, gene_vector & cible, int N){ cible = source; } }; #endif <|endoftext|>
<commit_before>#include <seqan/sequence.h> #include <seqan/index.h> using namespace seqan; int main() { // One possible solution to the first sub assignment String<Dna> text = "ACGTTTGACAGCT"; Index<String<Dna>, IndexEsa<> > index(text); // One possible solution to the second sub assignment StringSet<String<Dna> > stringSet; appendValue(stringSet, "ACGTCATCAT"); appendValue(stringSet, "ACTTTG"); appendValue(stringSet, "CACCCCCCTATTT"); Index<StringSet<String<Dna> >, IndexEsa<> > indexSet(stringSet); return 0; } <commit_msg>[NOP] Fixing indentation in assignment solution.<commit_after>#include <seqan/sequence.h> #include <seqan/index.h> using namespace seqan; int main() { // One possible solution to the first sub assignment String<Dna> text = "ACGTTTGACAGCT"; Index<String<Dna>, IndexEsa<> > index(text); // One possible solution to the second sub assignment StringSet<String<Dna> > stringSet; appendValue(stringSet, "ACGTCATCAT"); appendValue(stringSet, "ACTTTG"); appendValue(stringSet, "CACCCCCCTATTT"); Index<StringSet<String<Dna> >, IndexEsa<> > indexSet(stringSet); return 0; } <|endoftext|>
<commit_before>#pragma once #ifndef _QI_SIGNALHELPER_HPP_ #define _QI_SIGNALHELPER_HPP_ #include <qi/actor.hpp> #include <qi/anyobject.hpp> #include <qi/clock.hpp> #include <qi/signal.hpp> namespace qi { /** * @brief A tool to track signal emissions, specialized for testing. * A signal spy can acknowledge every signal emission of a given signal, type-erased or not. * Every emission is recorded, so that they can be compared to expectations, or to produce a * history. * * It could also be used in production code for the timeout mechanism implemented in waitUntil. */ class SignalSpy: public qi::Actor { public: /// Constructor taking a signal instance. template<typename... Args> SignalSpy(SignalF<void(Args...)>& signal) : _records() { signal.connect(stranded([this](const Args&... args) { this->recordCallback(args...); })); } /// Constructor taking a type-erased signal. SignalSpy(qi::AnyObject& object, const std::string& signalOrPropertyName) : _records() { object.connect( signalOrPropertyName, qi::AnyFunction::fromDynamicFunction( stranded([this](qi::AnyReferenceVector anything) { return this->recordAnyCallback(anything); }))); } // Non-copyable SignalSpy(const SignalSpy&) = delete; SignalSpy& operator=(const SignalSpy&) = delete; ~SignalSpy() { joinTasks(); } /// A record data, corresponding to one signal emission. struct Record { /// Signal arguments are stored here, in a type-erased way for compatibility. std::vector<qi::AnyValue> args; /// Use this to access an argument in the type you expect it. template<typename T> const T& arg(int index) const { return args[index].asReference().as<T>(); } }; /// Retrieve all the records in one shot. std::vector<Record> allRecords() const { return async([this] { return _records; }).value(); } /// Direct access to a record, by order of arrival. Record record(size_t index) const { qiLogDebug("qi.signalspy") << "Getting record #" << index << " " << (strand()->isInThisContext() ? "from strand" : "from outside"); return async([this, index] { qiLogDebug("qi.signalspy") << "Getting record #" << index; return _records[index]; }).value(); } /// Direct access to last record. Record lastRecord() const { return async([this] { assert(!_records.empty()); return _records.back(); }).value(); } /// The number of records. size_t recordCount() const { qiLogDebug("qi.signalspy") << "Getting record count " << (strand()->isInThisContext() ? "from strand" : "from outside"); return async([this] { qiLogDebug("qi.signalspy") << "Getting record count"; return _records.size(); }).value(); } QI_API_DEPRECATED_MSG(Use 'recordCount' instead) unsigned int getCounter() const { return async([&]{ return static_cast<unsigned int>(_records.size()); }).value(); } /// Waits for the given number of records to be reached, before the given timeout. qi::FutureSync<bool> waitUntil(unsigned int nofRecords, const qi::Duration& timeout) const { qi::Promise<bool> waiting; async([this, waiting, nofRecords, timeout]() mutable { if(nofRecords <= _records.size()) { waiting.setValue(true); return; } qi::SignalLink recordedSubscription; // track timeout auto timingOut = asyncDelay([this, waiting, &recordedSubscription]() mutable { waiting.setValue(false); recorded.disconnect(recordedSubscription); }, timeout); // be called after signal emissions are recorded recordedSubscription = recorded.connect(stranded( [this, waiting, &recordedSubscription, timingOut, nofRecords]() mutable { assert(nofRecords >= _records.size()); if (nofRecords == _records.size()) { waiting.setValue(true); timingOut.cancel(); recorded.disconnect(recordedSubscription); } // no need for scheduling in the strand because it is a direct connection })).setCallType(qi::MetaCallType_Direct); }); return waiting.future(); } private: /// The signal records. std::vector<Record> _records; /// Emitted for internal synchronziation. mutable qi::Signal<void> recorded; /// Internal generic typed callback for signals. template <typename... Args> void recordCallback(const Args&... args) { assert(strand()->isInThisContext()); _records.emplace_back(Record{{qi::AnyValue::from<Args>(args)...}}); recorded(); } /// Internal type-erased callback for type-erased signals. AnyReference recordAnyCallback(const qi::AnyReferenceVector& args) { assert(strand()->isInThisContext()); Record record; for (const auto& arg: args) record.args.emplace_back(arg.to<qi::AnyValue>()); _records.emplace_back(std::move(record)); recorded(); return AnyReference(); } }; } #endif <commit_msg>Signal Spy: fix an abusive assertion<commit_after>#pragma once #ifndef _QI_SIGNALHELPER_HPP_ #define _QI_SIGNALHELPER_HPP_ #include <qi/actor.hpp> #include <qi/anyobject.hpp> #include <qi/clock.hpp> #include <qi/signal.hpp> namespace qi { /** * @brief A tool to track signal emissions, specialized for testing. * A signal spy can acknowledge every signal emission of a given signal, type-erased or not. * Every emission is recorded, so that they can be compared to expectations, or to produce a * history. * * It could also be used in production code for the timeout mechanism implemented in waitUntil. */ class SignalSpy: public qi::Actor { public: /// Constructor taking a signal instance. template<typename... Args> SignalSpy(SignalF<void(Args...)>& signal) : _records() { signal.connect(stranded([this](const Args&... args) { this->recordCallback(args...); })); } /// Constructor taking a type-erased signal. SignalSpy(qi::AnyObject& object, const std::string& signalOrPropertyName) : _records() { object.connect( signalOrPropertyName, qi::AnyFunction::fromDynamicFunction( stranded([this](qi::AnyReferenceVector anything) { return this->recordAnyCallback(anything); }))); } // Non-copyable SignalSpy(const SignalSpy&) = delete; SignalSpy& operator=(const SignalSpy&) = delete; ~SignalSpy() { joinTasks(); } /// A record data, corresponding to one signal emission. struct Record { /// Signal arguments are stored here, in a type-erased way for compatibility. std::vector<qi::AnyValue> args; /// Use this to access an argument in the type you expect it. template<typename T> const T& arg(int index) const { return args[index].asReference().as<T>(); } }; /// Retrieve all the records in one shot. std::vector<Record> allRecords() const { return async([this] { return _records; }).value(); } /// Direct access to a record, by order of arrival. Record record(size_t index) const { qiLogDebug("qi.signalspy") << "Getting record #" << index << " " << (strand()->isInThisContext() ? "from strand" : "from outside"); return async([this, index] { qiLogDebug("qi.signalspy") << "Getting record #" << index; return _records[index]; }).value(); } /// Direct access to last record. Record lastRecord() const { return async([this] { assert(!_records.empty()); return _records.back(); }).value(); } /// The number of records. size_t recordCount() const { qiLogDebug("qi.signalspy") << "Getting record count " << (strand()->isInThisContext() ? "from strand" : "from outside"); return async([this] { qiLogDebug("qi.signalspy") << "Getting record count"; return _records.size(); }).value(); } QI_API_DEPRECATED_MSG(Use 'recordCount' instead) unsigned int getCounter() const { return async([&]{ return static_cast<unsigned int>(_records.size()); }).value(); } /// Waits for the given number of records to be reached, before the given timeout. qi::FutureSync<bool> waitUntil(unsigned int nofRecords, const qi::Duration& timeout) const { qi::Promise<bool> waiting; async([this, waiting, nofRecords, timeout]() mutable { if(nofRecords <= _records.size()) { waiting.setValue(true); return; } qi::SignalLink recordedSubscription; // track timeout auto timingOut = asyncDelay([this, waiting, &recordedSubscription]() mutable { waiting.setValue(false); recorded.disconnect(recordedSubscription); }, timeout); // be called after signal emissions are recorded recordedSubscription = recorded.connect(stranded( [this, waiting, &recordedSubscription, timingOut, nofRecords]() mutable { if (nofRecords <= _records.size()) { waiting.setValue(true); timingOut.cancel(); recorded.disconnect(recordedSubscription); } // no need for scheduling in the strand because it is a direct connection })).setCallType(qi::MetaCallType_Direct); }); return waiting.future(); } private: /// The signal records. std::vector<Record> _records; /// Emitted for internal synchronziation. mutable qi::Signal<void> recorded; /// Internal generic typed callback for signals. template <typename... Args> void recordCallback(const Args&... args) { assert(strand()->isInThisContext()); _records.emplace_back(Record{{qi::AnyValue::from<Args>(args)...}}); recorded(); } /// Internal type-erased callback for type-erased signals. AnyReference recordAnyCallback(const qi::AnyReferenceVector& args) { assert(strand()->isInThisContext()); Record record; for (const auto& arg: args) record.args.emplace_back(arg.to<qi::AnyValue>()); _records.emplace_back(std::move(record)); recorded(); return AnyReference(); } }; } #endif <|endoftext|>
<commit_before>#include "swf.h" const unsigned char Swf::header_magic[] = { 'F', 'W', 'S' }; const unsigned char Swf::header_magic_deflate[] = { 'C', 'W', 'S' }; const unsigned char Swf::header_magic_lzma[] = { 'Z', 'W', 'S' }; size_t Swf::Leanify(size_t size_leanified /*= 0*/) { if (is_fast && *fp != 'F') { return Format::Leanify(size_leanified); } unsigned char *in_buffer = (unsigned char *)fp + 8; uint32_t in_len = *(uint32_t *)(fp + 4) - 8; // if SWF is compressed, decompress it first if (*fp == 'C') { // deflate if (is_verbose) { std::cout << "SWF is compressed with deflate." << std::endl; } size_t s = 0; in_buffer = (unsigned char *)tinfl_decompress_mem_to_heap(in_buffer, size - 8, &s, TINFL_FLAG_PARSE_ZLIB_HEADER); if (!in_buffer || s != in_len) { std::cerr << "SWF file corrupted!" << std::endl; mz_free(in_buffer); return Format::Leanify(size_leanified); } } else if (*fp == 'Z') { // LZMA if (is_verbose) { std::cout << "SWF is compressed with LZMA." << std::endl; } // | 4 bytes | 4 bytes | 4 bytes | 5 bytes | n bytes | 6 bytes | // | 'ZWS' + version | scriptLen | compressedLen | LZMA props | LZMA data | LZMA end marker | unsigned char *dst_buffer = new unsigned char[in_len]; size_t s = in_len, len = size - 12 - LZMA_PROPS_SIZE; // check compressed length if (*(uint32_t *)in_buffer != len || LzmaUncompress(dst_buffer, &s, in_buffer + 4 + LZMA_PROPS_SIZE, &len, in_buffer + 4, LZMA_PROPS_SIZE) || s != in_len) { std::cerr << "SWF file corrupted!" << std::endl; delete[] dst_buffer; return Format::Leanify(size_leanified); } in_buffer = dst_buffer; } else if (is_verbose) { std::cout << "SWF is not compressed." << std::endl; } // parsing SWF tags unsigned char *p = in_buffer + 13; // skip FrameSize(9B) + FrameRate(2B) + FrameCount(2B) = 13B size_t tag_size_leanified = 0; do { uint16_t tag_type = *(uint16_t *)p >> 6; uint32_t tag_length = *p & 0x3F; size_t tag_header_length = 2; if (tag_length == 0x3F) { tag_length = *(uint32_t *)(p + 2); tag_header_length += 4; } if (tag_size_leanified) { memmove(p - tag_size_leanified, p, tag_header_length); } p += tag_header_length; switch (tag_type) { case 20: // DefineBitsLossless case 36: // DefineBitsLossless2 { size_t header_size = 7 + (p[3] == 3); if (is_verbose) { std::cout << "DefineBitsLossless tag found." << std::endl; } if (tag_size_leanified) { memmove(p - tag_size_leanified, p, header_size); } // recompress Zlib bitmap data size_t new_data_size = ZlibRecompress(p + header_size, tag_length - header_size, tag_size_leanified); UpdateTagLength(p - tag_size_leanified, tag_header_length, header_size + new_data_size); tag_size_leanified += tag_length - header_size - new_data_size; break; } case 21: // DefineBitsJPEG2 { if (is_verbose) { std::cout << "DefineBitsJPEG2 tag found." << std::endl; } // copy id *(uint16_t *)(p - tag_size_leanified) = *(uint16_t *)p; // Leanify embedded image size_t new_size = LeanifyFile(p + 2, tag_length - 2, tag_size_leanified); UpdateTagLength(p - tag_size_leanified, tag_header_length, 2 + new_size); tag_size_leanified += tag_length - 2 - new_size; break; } case 35: // DefineBitsJPEG3 case 90: // DefineBitsJPEG4 { // copy id *(uint16_t *)(p - tag_size_leanified) = *(uint16_t *)p; uint32_t img_size = *(uint32_t *)(p + 2); size_t header_size = tag_type == 90 ? 8 : 6; if (is_verbose) { std::cout << "DefineBitsJPEG" << header_size / 2 << " tag found." << std::endl; } // Leanify embedded image size_t new_img_size = LeanifyFile(p + header_size, img_size, tag_size_leanified); *(uint32_t *)(p + 2 - tag_size_leanified) = new_img_size; // recompress alpha data size_t new_alpha_data_size = ZlibRecompress(p + header_size + img_size, tag_length - img_size - header_size, tag_size_leanified + img_size - new_img_size); size_t new_tag_size = new_img_size + new_alpha_data_size + header_size; UpdateTagLength(p - tag_size_leanified, tag_header_length, new_tag_size); tag_size_leanified += tag_length - new_tag_size; break; } case 77: // Metadata if (is_verbose) { std::cout << "Metadata removed." << std::endl; } tag_size_leanified += tag_length + tag_header_length; break; case 69: // FileAttributes *p &= ~(1 << 4); // set HasMetadata bit to 0 default: if (tag_size_leanified) { memmove(p - tag_size_leanified, p, tag_length); } } p += tag_length; } while (p < in_buffer + in_len); in_len -= tag_size_leanified; if (is_fast) { // write header fp -= size_leanified; // decompressed size (including header) *(uint32_t *)(fp + 4) = size = in_len + 8; if (size_leanified) { memmove(fp, fp + size_leanified, 4); memmove(fp + 8, fp + 8 + size_leanified, in_len); } return size; } // compress with LZMA size_t s = in_len, props = LZMA_PROPS_SIZE; unsigned char *dst = new unsigned char[in_len + LZMA_PROPS_SIZE]; // have to set writeEndMark to true if (LzmaCompress(dst + LZMA_PROPS_SIZE, &s, in_buffer, in_len, dst, &props, iterations < 9 ? iterations : 9, 1 << 24, -1, -1, -1, 128, -1)) { std::cerr << "LZMA compression failed." << std::endl; s = size; } // free decompressed data if (*fp == 'C') { mz_free(in_buffer); } else if (*fp == 'Z') { delete[] in_buffer; } fp -= size_leanified; s += LZMA_PROPS_SIZE; if (s + 12 < size) { size = s + 12; // write header memcpy(fp, header_magic_lzma, sizeof(header_magic_lzma)); // write SWF version, at least 13 to support LZMA if (fp[3 + size_leanified] < 13) { fp[3] = 13; } else { fp[3] = fp[3 + size_leanified]; } // decompressed size (including header) *(uint32_t *)(fp + 4) = in_len + 8; // compressed size: LZMA data + end mark *(uint32_t *)(fp + 8) = s - LZMA_PROPS_SIZE; memcpy(fp + 12, dst, s); } else if (size_leanified) { memmove(fp, fp + size_leanified, size); } delete[] dst; return size; } void Swf::UpdateTagLength(unsigned char *tag_content, size_t header_length, size_t new_length) { if (header_length == 6) { *(uint32_t *)(tag_content - 4) = new_length; } else { *(tag_content - 2) += (new_length & 0x3F) - (*(tag_content - 2) & 0x3F); } } <commit_msg>SWF: increase LZMA buffer size<commit_after>#include "swf.h" const unsigned char Swf::header_magic[] = { 'F', 'W', 'S' }; const unsigned char Swf::header_magic_deflate[] = { 'C', 'W', 'S' }; const unsigned char Swf::header_magic_lzma[] = { 'Z', 'W', 'S' }; size_t Swf::Leanify(size_t size_leanified /*= 0*/) { if (is_fast && *fp != 'F') { return Format::Leanify(size_leanified); } unsigned char *in_buffer = (unsigned char *)fp + 8; uint32_t in_len = *(uint32_t *)(fp + 4) - 8; // if SWF is compressed, decompress it first if (*fp == 'C') { // deflate if (is_verbose) { std::cout << "SWF is compressed with deflate." << std::endl; } size_t s = 0; in_buffer = (unsigned char *)tinfl_decompress_mem_to_heap(in_buffer, size - 8, &s, TINFL_FLAG_PARSE_ZLIB_HEADER); if (!in_buffer || s != in_len) { std::cerr << "SWF file corrupted!" << std::endl; mz_free(in_buffer); return Format::Leanify(size_leanified); } } else if (*fp == 'Z') { // LZMA if (is_verbose) { std::cout << "SWF is compressed with LZMA." << std::endl; } // | 4 bytes | 4 bytes | 4 bytes | 5 bytes | n bytes | 6 bytes | // | 'ZWS' + version | scriptLen | compressedLen | LZMA props | LZMA data | LZMA end marker | unsigned char *dst_buffer = new unsigned char[in_len]; size_t s = in_len, len = size - 12 - LZMA_PROPS_SIZE; // check compressed length if (*(uint32_t *)in_buffer != len || LzmaUncompress(dst_buffer, &s, in_buffer + 4 + LZMA_PROPS_SIZE, &len, in_buffer + 4, LZMA_PROPS_SIZE) || s != in_len) { std::cerr << "SWF file corrupted!" << std::endl; delete[] dst_buffer; return Format::Leanify(size_leanified); } in_buffer = dst_buffer; } else if (is_verbose) { std::cout << "SWF is not compressed." << std::endl; } // parsing SWF tags unsigned char *p = in_buffer + 13; // skip FrameSize(9B) + FrameRate(2B) + FrameCount(2B) = 13B size_t tag_size_leanified = 0; do { uint16_t tag_type = *(uint16_t *)p >> 6; uint32_t tag_length = *p & 0x3F; size_t tag_header_length = 2; if (tag_length == 0x3F) { tag_length = *(uint32_t *)(p + 2); tag_header_length += 4; } if (tag_size_leanified) { memmove(p - tag_size_leanified, p, tag_header_length); } p += tag_header_length; switch (tag_type) { case 20: // DefineBitsLossless case 36: // DefineBitsLossless2 { size_t header_size = 7 + (p[3] == 3); if (is_verbose) { std::cout << "DefineBitsLossless tag found." << std::endl; } if (tag_size_leanified) { memmove(p - tag_size_leanified, p, header_size); } // recompress Zlib bitmap data size_t new_data_size = ZlibRecompress(p + header_size, tag_length - header_size, tag_size_leanified); UpdateTagLength(p - tag_size_leanified, tag_header_length, header_size + new_data_size); tag_size_leanified += tag_length - header_size - new_data_size; break; } case 21: // DefineBitsJPEG2 { if (is_verbose) { std::cout << "DefineBitsJPEG2 tag found." << std::endl; } // copy id *(uint16_t *)(p - tag_size_leanified) = *(uint16_t *)p; // Leanify embedded image size_t new_size = LeanifyFile(p + 2, tag_length - 2, tag_size_leanified); UpdateTagLength(p - tag_size_leanified, tag_header_length, 2 + new_size); tag_size_leanified += tag_length - 2 - new_size; break; } case 35: // DefineBitsJPEG3 case 90: // DefineBitsJPEG4 { // copy id *(uint16_t *)(p - tag_size_leanified) = *(uint16_t *)p; uint32_t img_size = *(uint32_t *)(p + 2); size_t header_size = tag_type == 90 ? 8 : 6; if (is_verbose) { std::cout << "DefineBitsJPEG" << header_size / 2 << " tag found." << std::endl; } // Leanify embedded image size_t new_img_size = LeanifyFile(p + header_size, img_size, tag_size_leanified); *(uint32_t *)(p + 2 - tag_size_leanified) = new_img_size; // recompress alpha data size_t new_alpha_data_size = ZlibRecompress(p + header_size + img_size, tag_length - img_size - header_size, tag_size_leanified + img_size - new_img_size); size_t new_tag_size = new_img_size + new_alpha_data_size + header_size; UpdateTagLength(p - tag_size_leanified, tag_header_length, new_tag_size); tag_size_leanified += tag_length - new_tag_size; break; } case 77: // Metadata if (is_verbose) { std::cout << "Metadata removed." << std::endl; } tag_size_leanified += tag_length + tag_header_length; break; case 69: // FileAttributes *p &= ~(1 << 4); // set HasMetadata bit to 0 default: if (tag_size_leanified) { memmove(p - tag_size_leanified, p, tag_length); } } p += tag_length; } while (p < in_buffer + in_len); in_len -= tag_size_leanified; if (is_fast) { // write header fp -= size_leanified; // decompressed size (including header) *(uint32_t *)(fp + 4) = size = in_len + 8; if (size_leanified) { memmove(fp, fp + size_leanified, 4); memmove(fp + 8, fp + 8 + size_leanified, in_len); } return size; } // compress with LZMA size_t s = in_len + in_len / 4, props = LZMA_PROPS_SIZE; unsigned char *dst = new unsigned char[s + LZMA_PROPS_SIZE]; // have to set writeEndMark to true if (LzmaCompress(dst + LZMA_PROPS_SIZE, &s, in_buffer, in_len, dst, &props, iterations < 9 ? iterations : 9, 1 << 24, -1, -1, -1, 128, -1)) { std::cerr << "LZMA compression failed." << std::endl; s = size; } // free decompressed data if (*fp == 'C') { mz_free(in_buffer); } else if (*fp == 'Z') { delete[] in_buffer; } fp -= size_leanified; s += LZMA_PROPS_SIZE; if (s + 12 < size) { size = s + 12; // write header memcpy(fp, header_magic_lzma, sizeof(header_magic_lzma)); // write SWF version, at least 13 to support LZMA if (fp[3 + size_leanified] < 13) { fp[3] = 13; } else { fp[3] = fp[3 + size_leanified]; } // decompressed size (including header) *(uint32_t *)(fp + 4) = in_len + 8; // compressed size: LZMA data + end mark *(uint32_t *)(fp + 8) = s - LZMA_PROPS_SIZE; memcpy(fp + 12, dst, s); } else if (size_leanified) { memmove(fp, fp + size_leanified, size); } delete[] dst; return size; } void Swf::UpdateTagLength(unsigned char *tag_content, size_t header_length, size_t new_length) { if (header_length == 6) { *(uint32_t *)(tag_content - 4) = new_length; } else { *(tag_content - 2) += (new_length & 0x3F) - (*(tag_content - 2) & 0x3F); } } <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/api/atom_bindings.h" #include <algorithm> #include <iostream> #include <memory> #include <string> #include "atom/common/atom_version.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/node_includes.h" #include "base/logging.h" #include "base/process/process_metrics.h" #include "chrome/common/chrome_version.h" #include "native_mate/dictionary.h" namespace atom { namespace { // Dummy class type that used for crashing the program. struct DummyClass { bool crash; }; void Crash() { static_cast<DummyClass*>(nullptr)->crash = true; } void Hang() { for (;;) base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1)); } v8::Local<v8::Value> GetProcessMemoryInfo(v8::Isolate* isolate) { std::unique_ptr<base::ProcessMetrics> metrics( base::ProcessMetrics::CreateCurrentProcessMetrics()); mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); dict.Set("workingSetSize", static_cast<double>(metrics->GetWorkingSetSize() >> 10)); dict.Set("peakWorkingSetSize", static_cast<double>(metrics->GetPeakWorkingSetSize() >> 10)); size_t private_bytes, shared_bytes; if (metrics->GetMemoryBytes(&private_bytes, &shared_bytes)) { dict.Set("privateBytes", static_cast<double>(private_bytes >> 10)); dict.Set("sharedBytes", static_cast<double>(shared_bytes >> 10)); } return dict.GetHandle(); } v8::Local<v8::Value> GetSystemMemoryInfo(v8::Isolate* isolate, mate::Arguments* args) { base::SystemMemoryInfoKB mem_info; if (!base::GetSystemMemoryInfo(&mem_info)) { args->ThrowError("Unable to retrieve system memory information"); return v8::Undefined(isolate); } mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); dict.Set("total", mem_info.total); dict.Set("free", mem_info.free); // NB: These return bogus values on macOS #if !defined(OS_MACOSX) dict.Set("swapTotal", mem_info.swap_total); dict.Set("swapFree", mem_info.swap_free); #endif return dict.GetHandle(); } // Called when there is a fatal error in V8, we just crash the process here so // we can get the stack trace. void FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; Crash(); } void Log(const base::string16& message) { std::cout << message << std::flush; } } // namespace AtomBindings::AtomBindings() { uv_async_init(uv_default_loop(), &call_next_tick_async_, OnCallNextTick); call_next_tick_async_.data = this; } AtomBindings::~AtomBindings() { } void AtomBindings::BindTo(v8::Isolate* isolate, v8::Local<v8::Object> process) { v8::V8::SetFatalErrorHandler(FatalErrorCallback); mate::Dictionary dict(isolate, process); dict.SetMethod("crash", &Crash); dict.SetMethod("hang", &Hang); dict.SetMethod("log", &Log); dict.SetMethod("getProcessMemoryInfo", &GetProcessMemoryInfo); dict.SetMethod("getSystemMemoryInfo", &GetSystemMemoryInfo); #if defined(OS_POSIX) dict.SetMethod("setFdLimit", &base::SetFdLimit); #endif dict.SetMethod("activateUvLoop", base::Bind(&AtomBindings::ActivateUVLoop, base::Unretained(this))); #if defined(MAS_BUILD) dict.Set("mas", true); #endif mate::Dictionary versions; if (dict.Get("versions", &versions)) { versions.Set(PRODUCT_FULLNAME_STRING, ATOM_VERSION_STRING); versions.Set("atom-shell", ATOM_VERSION_STRING); // For compatibility. versions.Set("chrome", CHROME_VERSION_STRING); } } void AtomBindings::ActivateUVLoop(v8::Isolate* isolate) { node::Environment* env = node::Environment::GetCurrent(isolate); if (std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env) != pending_next_ticks_.end()) return; pending_next_ticks_.push_back(env); uv_async_send(&call_next_tick_async_); } // static void AtomBindings::OnCallNextTick(uv_async_t* handle) { AtomBindings* self = static_cast<AtomBindings*>(handle->data); for (std::list<node::Environment*>::const_iterator it = self->pending_next_ticks_.begin(); it != self->pending_next_ticks_.end(); ++it) { node::Environment* env = *it; // KickNextTick, copied from node.cc: node::Environment::AsyncCallbackScope callback_scope(env); if (callback_scope.in_makecallback()) continue; node::Environment::TickInfo* tick_info = env->tick_info(); if (tick_info->length() == 0) env->isolate()->RunMicrotasks(); v8::Local<v8::Object> process = env->process_object(); if (tick_info->length() == 0) tick_info->set_index(0); env->tick_callback_function()->Call(process, 0, nullptr).IsEmpty(); } self->pending_next_ticks_.clear(); } } // namespace atom <commit_msg>Fix free memory calculation. https://chromium.googlesource.com/chromium/src/+/01ac10b7938701bc9f9f2c05faf18229f9573b4c<commit_after>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/api/atom_bindings.h" #include <algorithm> #include <iostream> #include <memory> #include <string> #include "atom/common/atom_version.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/node_includes.h" #include "base/logging.h" #include "base/process/process_metrics.h" #include "chrome/common/chrome_version.h" #include "native_mate/dictionary.h" namespace atom { namespace { // Dummy class type that used for crashing the program. struct DummyClass { bool crash; }; void Crash() { static_cast<DummyClass*>(nullptr)->crash = true; } void Hang() { for (;;) base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1)); } v8::Local<v8::Value> GetProcessMemoryInfo(v8::Isolate* isolate) { std::unique_ptr<base::ProcessMetrics> metrics( base::ProcessMetrics::CreateCurrentProcessMetrics()); mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); dict.Set("workingSetSize", static_cast<double>(metrics->GetWorkingSetSize() >> 10)); dict.Set("peakWorkingSetSize", static_cast<double>(metrics->GetPeakWorkingSetSize() >> 10)); size_t private_bytes, shared_bytes; if (metrics->GetMemoryBytes(&private_bytes, &shared_bytes)) { dict.Set("privateBytes", static_cast<double>(private_bytes >> 10)); dict.Set("sharedBytes", static_cast<double>(shared_bytes >> 10)); } return dict.GetHandle(); } v8::Local<v8::Value> GetSystemMemoryInfo(v8::Isolate* isolate, mate::Arguments* args) { base::SystemMemoryInfoKB mem_info; if (!base::GetSystemMemoryInfo(&mem_info)) { args->ThrowError("Unable to retrieve system memory information"); return v8::Undefined(isolate); } mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); dict.Set("total", mem_info.total); #if !defined(OS_WIN) dict.Set("free", mem_info.free); #endif #if defined(OS_WIN) dict.Set("availPhys", mem_info.avail_phys); #endif // NB: These return bogus values on macOS #if !defined(OS_MACOSX) dict.Set("swapTotal", mem_info.swap_total); dict.Set("swapFree", mem_info.swap_free); #endif return dict.GetHandle(); } // Called when there is a fatal error in V8, we just crash the process here so // we can get the stack trace. void FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; Crash(); } void Log(const base::string16& message) { std::cout << message << std::flush; } } // namespace AtomBindings::AtomBindings() { uv_async_init(uv_default_loop(), &call_next_tick_async_, OnCallNextTick); call_next_tick_async_.data = this; } AtomBindings::~AtomBindings() { } void AtomBindings::BindTo(v8::Isolate* isolate, v8::Local<v8::Object> process) { v8::V8::SetFatalErrorHandler(FatalErrorCallback); mate::Dictionary dict(isolate, process); dict.SetMethod("crash", &Crash); dict.SetMethod("hang", &Hang); dict.SetMethod("log", &Log); dict.SetMethod("getProcessMemoryInfo", &GetProcessMemoryInfo); dict.SetMethod("getSystemMemoryInfo", &GetSystemMemoryInfo); #if defined(OS_POSIX) dict.SetMethod("setFdLimit", &base::SetFdLimit); #endif dict.SetMethod("activateUvLoop", base::Bind(&AtomBindings::ActivateUVLoop, base::Unretained(this))); #if defined(MAS_BUILD) dict.Set("mas", true); #endif mate::Dictionary versions; if (dict.Get("versions", &versions)) { versions.Set(PRODUCT_FULLNAME_STRING, ATOM_VERSION_STRING); versions.Set("atom-shell", ATOM_VERSION_STRING); // For compatibility. versions.Set("chrome", CHROME_VERSION_STRING); } } void AtomBindings::ActivateUVLoop(v8::Isolate* isolate) { node::Environment* env = node::Environment::GetCurrent(isolate); if (std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env) != pending_next_ticks_.end()) return; pending_next_ticks_.push_back(env); uv_async_send(&call_next_tick_async_); } // static void AtomBindings::OnCallNextTick(uv_async_t* handle) { AtomBindings* self = static_cast<AtomBindings*>(handle->data); for (std::list<node::Environment*>::const_iterator it = self->pending_next_ticks_.begin(); it != self->pending_next_ticks_.end(); ++it) { node::Environment* env = *it; // KickNextTick, copied from node.cc: node::Environment::AsyncCallbackScope callback_scope(env); if (callback_scope.in_makecallback()) continue; node::Environment::TickInfo* tick_info = env->tick_info(); if (tick_info->length() == 0) env->isolate()->RunMicrotasks(); v8::Local<v8::Object> process = env->process_object(); if (tick_info->length() == 0) tick_info->set_index(0); env->tick_callback_function()->Call(process, 0, nullptr).IsEmpty(); } self->pending_next_ticks_.clear(); } } // namespace atom <|endoftext|>
<commit_before>// Copyright (c) 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 "chrome/browser/extensions/user_script_master.h" #include <vector> #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/pickle.h" #include "base/stl_util-inl.h" #include "base/string_util.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/notification_service.h" #include "chrome/common/url_constants.h" #include "net/base/net_util.h" // Helper function to parse greasesmonkey headers static bool GetDeclarationValue(const StringPiece& line, const StringPiece& prefix, std::string* value) { if (!line.starts_with(prefix)) return false; std::string temp(line.data() + prefix.length(), line.length() - prefix.length()); TrimWhitespace(temp, TRIM_ALL, value); return true; } UserScriptMaster::ScriptReloader::ScriptReloader(UserScriptMaster* master) : master_(master), master_message_loop_(MessageLoop::current()) { } // static bool UserScriptMaster::ScriptReloader::ParseMetadataHeader( const StringPiece& script_text, UserScript* script) { // http://wiki.greasespot.net/Metadata_block StringPiece line; size_t line_start = 0; size_t line_end = 0; bool in_metadata = false; static const StringPiece kUserScriptBegin("// ==UserScript=="); static const StringPiece kUserScriptEng("// ==/UserScript=="); static const StringPiece kIncludeDeclaration("// @include "); static const StringPiece kMatchDeclaration("// @match "); static const StringPiece kRunAtDeclaration("// @run-at "); static const StringPiece kRunAtDocumentStartValue("document-start"); static const StringPiece kRunAtDocumentEndValue("document-end"); while (line_start < script_text.length()) { line_end = script_text.find('\n', line_start); // Handle the case where there is no trailing newline in the file. if (line_end == std::string::npos) { line_end = script_text.length() - 1; } line.set(script_text.data() + line_start, line_end - line_start); if (!in_metadata) { if (line.starts_with(kUserScriptBegin)) { in_metadata = true; } } else { if (line.starts_with(kUserScriptEng)) { break; } std::string value; if (GetDeclarationValue(line, kIncludeDeclaration, &value)) { // We escape some characters that MatchPattern() considers special. ReplaceSubstringsAfterOffset(&value, 0, "\\", "\\\\"); ReplaceSubstringsAfterOffset(&value, 0, "?", "\\?"); script->add_glob(value); } else if (GetDeclarationValue(line, kMatchDeclaration, &value)) { URLPattern pattern; if (!pattern.Parse(value)) return false; script->add_url_pattern(pattern); } else if (GetDeclarationValue(line, kRunAtDeclaration, &value)) { if (value == kRunAtDocumentStartValue) script->set_run_location(UserScript::DOCUMENT_START); else if (value != kRunAtDocumentEndValue) return false; } // TODO(aa): Handle more types of metadata. } line_start = line_end + 1; } // It is probably a mistake to declare both @include and @match rules. if (script->globs().size() > 0 && script->url_patterns().size() > 0) return false; // If no patterns were specified, default to @include *. This is what // Greasemonkey does. if (script->globs().size() == 0 && script->url_patterns().size() == 0) script->add_glob("*"); return true; } void UserScriptMaster::ScriptReloader::StartScan( MessageLoop* work_loop, const FilePath& script_dir, const UserScriptList& lone_scripts) { // Add a reference to ourselves to keep ourselves alive while we're running. // Balanced by NotifyMaster(). AddRef(); work_loop->PostTask(FROM_HERE, NewRunnableMethod(this, &UserScriptMaster::ScriptReloader::RunScan, script_dir, lone_scripts)); } void UserScriptMaster::ScriptReloader::NotifyMaster( base::SharedMemory* memory) { if (!master_) { // The master went away, so these new scripts aren't useful anymore. delete memory; } else { master_->NewScriptsAvailable(memory); } // Drop our self-reference. // Balances StartScan(). Release(); } static void LoadScriptContent(UserScript::File* script_file) { std::string content; file_util::ReadFileToString(script_file->path(), &content); script_file->set_content(content); LOG(INFO) << "Loaded user script file: " << script_file->path().value(); } void UserScriptMaster::ScriptReloader::LoadScriptsFromDirectory( const FilePath script_dir, UserScriptList* result) { // Clear the list. We will populate it with the scrips found in script_dir. result->clear(); // Find all the scripts in |script_dir|. if (!script_dir.value().empty()) { // Create the "<Profile>/User Scripts" directory if it doesn't exist if (!file_util::DirectoryExists(script_dir)) file_util::CreateDirectory(script_dir); file_util::FileEnumerator enumerator(script_dir, false, file_util::FileEnumerator::FILES, FILE_PATH_LITERAL("*.user.js")); for (FilePath file = enumerator.Next(); !file.value().empty(); file = enumerator.Next()) { result->push_back(UserScript()); UserScript& user_script = result->back(); // Push single js file in this UserScript. GURL url(std::string(chrome::kUserScriptScheme) + ":/" + net::FilePathToFileURL(file).ExtractFileName()); user_script.js_scripts().push_back(UserScript::File(file, url)); UserScript::File& script_file = user_script.js_scripts().back(); LoadScriptContent(&script_file); ParseMetadataHeader(script_file.GetContent(), &user_script); } } } static void LoadLoneScripts(UserScriptList* lone_scripts) { for (size_t i = 0; i < lone_scripts->size(); ++i) { UserScript& script = lone_scripts->at(i); for (size_t k = 0; k < script.js_scripts().size(); ++k) { UserScript::File& script_file = script.js_scripts()[k]; if (script_file.GetContent().empty()) { LoadScriptContent(&script_file); } } for (size_t k = 0; k < script.css_scripts().size(); ++k) { UserScript::File& script_file = script.css_scripts()[k]; if (script_file.GetContent().empty()) { LoadScriptContent(&script_file); } } } } // Pickle user scripts and return pointer to the shared memory. static base::SharedMemory* Serialize(UserScriptList& scripts) { Pickle pickle; pickle.WriteSize(scripts.size()); for (size_t i = 0; i < scripts.size(); i++) { UserScript& script = scripts[i]; script.Pickle(&pickle); // Write scripts as 'data' so that we can read it out in the slave without // allocating a new string. for (size_t j = 0; j < script.js_scripts().size(); j++) { StringPiece contents = script.js_scripts()[j].GetContent(); pickle.WriteData(contents.data(), contents.length()); } for (size_t j = 0; j < script.css_scripts().size(); j++) { StringPiece contents = script.css_scripts()[j].GetContent(); pickle.WriteData(contents.data(), contents.length()); } } // Create the shared memory object. scoped_ptr<base::SharedMemory> shared_memory(new base::SharedMemory()); if (!shared_memory->Create(std::wstring(), // anonymous false, // read-only false, // open existing pickle.size())) { return NULL; } // Map into our process. if (!shared_memory->Map(pickle.size())) return NULL; // Copy the pickle to shared memory. memcpy(shared_memory->memory(), pickle.data(), pickle.size()); return shared_memory.release(); } // This method will be called from the file thread void UserScriptMaster::ScriptReloader::RunScan( const FilePath script_dir, UserScriptList lone_script) { UserScriptList scripts; // Get list of user scripts. if (!script_dir.empty()) LoadScriptsFromDirectory(script_dir, &scripts); LoadLoneScripts(&lone_script); // Merge with the explicit scripts scripts.reserve(scripts.size() + lone_script.size()); scripts.insert(scripts.end(), lone_script.begin(), lone_script.end()); // Scripts now contains list of up-to-date scripts. Load the content in the // shared memory and let the master know it's ready. We need to post the task // back even if no scripts ware found to balance the AddRef/Release calls master_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(this, &ScriptReloader::NotifyMaster, Serialize(scripts))); } UserScriptMaster::UserScriptMaster(MessageLoop* worker_loop, const FilePath& script_dir) : user_script_dir_(script_dir), worker_loop_(worker_loop), extensions_service_ready_(false), pending_scan_(false) { if (!user_script_dir_.value().empty()) AddWatchedPath(script_dir); registrar_.Add(this, NotificationType::EXTENSIONS_READY, NotificationService::AllSources()); registrar_.Add(this, NotificationType::EXTENSIONS_LOADED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::EXTENSION_UNLOADED, NotificationService::AllSources()); } UserScriptMaster::~UserScriptMaster() { if (script_reloader_) script_reloader_->DisownMaster(); // TODO(aa): Enable this when DirectoryWatcher is implemented for linux. #if defined(OS_WIN) || defined(OS_MACOSX) STLDeleteElements(&dir_watchers_); #endif } void UserScriptMaster::AddWatchedPath(const FilePath& path) { // TODO(aa): Enable this when DirectoryWatcher is implemented for linux. #if defined(OS_WIN) || defined(OS_MACOSX) DirectoryWatcher* watcher = new DirectoryWatcher(); base::Thread* file_thread = g_browser_process->file_thread(); watcher->Watch(path, this, file_thread ? file_thread->message_loop() : NULL, true); dir_watchers_.push_back(watcher); #endif } void UserScriptMaster::NewScriptsAvailable(base::SharedMemory* handle) { // Ensure handle is deleted or released. scoped_ptr<base::SharedMemory> handle_deleter(handle); if (pending_scan_) { // While we were scanning, there were further changes. Don't bother // notifying about these scripts and instead just immediately rescan. pending_scan_ = false; StartScan(); } else { // We're no longer scanning. script_reloader_ = NULL; // We've got scripts ready to go. shared_memory_.swap(handle_deleter); NotificationService::current()->Notify( NotificationType::USER_SCRIPTS_UPDATED, NotificationService::AllSources(), Details<base::SharedMemory>(handle)); } } void UserScriptMaster::OnDirectoryChanged(const FilePath& path) { if (script_reloader_.get()) { // We're already scanning for scripts. We note that we should rescan when // we get the chance. pending_scan_ = true; return; } StartScan(); } void UserScriptMaster::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::EXTENSIONS_READY: extensions_service_ready_ = true; StartScan(); break; case NotificationType::EXTENSIONS_LOADED: { // TODO(aa): Fix race here. A page could need a content script on startup, // before the extension has loaded. We need to freeze the renderer in // that case. // See: http://code.google.com/p/chromium/issues/detail?id=11547. // Add any content scripts inside the extension. ExtensionList* extensions = Details<ExtensionList>(details).ptr(); for (ExtensionList::iterator extension_iterator = extensions->begin(); extension_iterator != extensions->end(); ++extension_iterator) { Extension* extension = *extension_iterator; const UserScriptList& scripts = extension->content_scripts(); for (UserScriptList::const_iterator iter = scripts.begin(); iter != scripts.end(); ++iter) { lone_scripts_.push_back(*iter); } } if (!extensions_service_ready_) StartScan(); break; } case NotificationType::EXTENSION_UNLOADED: { // Remove any content scripts. Extension* extension = Details<Extension>(details).ptr(); UserScriptList new_lone_scripts; for (UserScriptList::iterator iter = lone_scripts_.begin(); iter != lone_scripts_.end(); ++iter) { if (iter->extension_id() != extension->id()) { new_lone_scripts.push_back(*iter); } } lone_scripts_ = new_lone_scripts; StartScan(); // TODO(aa): Do we want to do something smarter for the scripts that have // already been injected? break; } default: DCHECK(false); } } void UserScriptMaster::StartScan() { if (!script_reloader_) script_reloader_ = new ScriptReloader(this); script_reloader_->StartScan(worker_loop_, user_script_dir_, lone_scripts_); } <commit_msg>Fix bug where content scripts are not run if they are in extensions that are loaded after EXTENSIONS_READY.<commit_after>// Copyright (c) 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 "chrome/browser/extensions/user_script_master.h" #include <vector> #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/pickle.h" #include "base/stl_util-inl.h" #include "base/string_util.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/notification_service.h" #include "chrome/common/url_constants.h" #include "net/base/net_util.h" // Helper function to parse greasesmonkey headers static bool GetDeclarationValue(const StringPiece& line, const StringPiece& prefix, std::string* value) { if (!line.starts_with(prefix)) return false; std::string temp(line.data() + prefix.length(), line.length() - prefix.length()); TrimWhitespace(temp, TRIM_ALL, value); return true; } UserScriptMaster::ScriptReloader::ScriptReloader(UserScriptMaster* master) : master_(master), master_message_loop_(MessageLoop::current()) { } // static bool UserScriptMaster::ScriptReloader::ParseMetadataHeader( const StringPiece& script_text, UserScript* script) { // http://wiki.greasespot.net/Metadata_block StringPiece line; size_t line_start = 0; size_t line_end = 0; bool in_metadata = false; static const StringPiece kUserScriptBegin("// ==UserScript=="); static const StringPiece kUserScriptEng("// ==/UserScript=="); static const StringPiece kIncludeDeclaration("// @include "); static const StringPiece kMatchDeclaration("// @match "); static const StringPiece kRunAtDeclaration("// @run-at "); static const StringPiece kRunAtDocumentStartValue("document-start"); static const StringPiece kRunAtDocumentEndValue("document-end"); while (line_start < script_text.length()) { line_end = script_text.find('\n', line_start); // Handle the case where there is no trailing newline in the file. if (line_end == std::string::npos) { line_end = script_text.length() - 1; } line.set(script_text.data() + line_start, line_end - line_start); if (!in_metadata) { if (line.starts_with(kUserScriptBegin)) { in_metadata = true; } } else { if (line.starts_with(kUserScriptEng)) { break; } std::string value; if (GetDeclarationValue(line, kIncludeDeclaration, &value)) { // We escape some characters that MatchPattern() considers special. ReplaceSubstringsAfterOffset(&value, 0, "\\", "\\\\"); ReplaceSubstringsAfterOffset(&value, 0, "?", "\\?"); script->add_glob(value); } else if (GetDeclarationValue(line, kMatchDeclaration, &value)) { URLPattern pattern; if (!pattern.Parse(value)) return false; script->add_url_pattern(pattern); } else if (GetDeclarationValue(line, kRunAtDeclaration, &value)) { if (value == kRunAtDocumentStartValue) script->set_run_location(UserScript::DOCUMENT_START); else if (value != kRunAtDocumentEndValue) return false; } // TODO(aa): Handle more types of metadata. } line_start = line_end + 1; } // It is probably a mistake to declare both @include and @match rules. if (script->globs().size() > 0 && script->url_patterns().size() > 0) return false; // If no patterns were specified, default to @include *. This is what // Greasemonkey does. if (script->globs().size() == 0 && script->url_patterns().size() == 0) script->add_glob("*"); return true; } void UserScriptMaster::ScriptReloader::StartScan( MessageLoop* work_loop, const FilePath& script_dir, const UserScriptList& lone_scripts) { // Add a reference to ourselves to keep ourselves alive while we're running. // Balanced by NotifyMaster(). AddRef(); work_loop->PostTask(FROM_HERE, NewRunnableMethod(this, &UserScriptMaster::ScriptReloader::RunScan, script_dir, lone_scripts)); } void UserScriptMaster::ScriptReloader::NotifyMaster( base::SharedMemory* memory) { if (!master_) { // The master went away, so these new scripts aren't useful anymore. delete memory; } else { master_->NewScriptsAvailable(memory); } // Drop our self-reference. // Balances StartScan(). Release(); } static void LoadScriptContent(UserScript::File* script_file) { std::string content; file_util::ReadFileToString(script_file->path(), &content); script_file->set_content(content); LOG(INFO) << "Loaded user script file: " << script_file->path().value(); } void UserScriptMaster::ScriptReloader::LoadScriptsFromDirectory( const FilePath script_dir, UserScriptList* result) { // Clear the list. We will populate it with the scrips found in script_dir. result->clear(); // Find all the scripts in |script_dir|. if (!script_dir.value().empty()) { // Create the "<Profile>/User Scripts" directory if it doesn't exist if (!file_util::DirectoryExists(script_dir)) file_util::CreateDirectory(script_dir); file_util::FileEnumerator enumerator(script_dir, false, file_util::FileEnumerator::FILES, FILE_PATH_LITERAL("*.user.js")); for (FilePath file = enumerator.Next(); !file.value().empty(); file = enumerator.Next()) { result->push_back(UserScript()); UserScript& user_script = result->back(); // Push single js file in this UserScript. GURL url(std::string(chrome::kUserScriptScheme) + ":/" + net::FilePathToFileURL(file).ExtractFileName()); user_script.js_scripts().push_back(UserScript::File(file, url)); UserScript::File& script_file = user_script.js_scripts().back(); LoadScriptContent(&script_file); ParseMetadataHeader(script_file.GetContent(), &user_script); } } } static void LoadLoneScripts(UserScriptList* lone_scripts) { for (size_t i = 0; i < lone_scripts->size(); ++i) { UserScript& script = lone_scripts->at(i); for (size_t k = 0; k < script.js_scripts().size(); ++k) { UserScript::File& script_file = script.js_scripts()[k]; if (script_file.GetContent().empty()) { LoadScriptContent(&script_file); } } for (size_t k = 0; k < script.css_scripts().size(); ++k) { UserScript::File& script_file = script.css_scripts()[k]; if (script_file.GetContent().empty()) { LoadScriptContent(&script_file); } } } } // Pickle user scripts and return pointer to the shared memory. static base::SharedMemory* Serialize(UserScriptList& scripts) { Pickle pickle; pickle.WriteSize(scripts.size()); for (size_t i = 0; i < scripts.size(); i++) { UserScript& script = scripts[i]; script.Pickle(&pickle); // Write scripts as 'data' so that we can read it out in the slave without // allocating a new string. for (size_t j = 0; j < script.js_scripts().size(); j++) { StringPiece contents = script.js_scripts()[j].GetContent(); pickle.WriteData(contents.data(), contents.length()); } for (size_t j = 0; j < script.css_scripts().size(); j++) { StringPiece contents = script.css_scripts()[j].GetContent(); pickle.WriteData(contents.data(), contents.length()); } } // Create the shared memory object. scoped_ptr<base::SharedMemory> shared_memory(new base::SharedMemory()); if (!shared_memory->Create(std::wstring(), // anonymous false, // read-only false, // open existing pickle.size())) { return NULL; } // Map into our process. if (!shared_memory->Map(pickle.size())) return NULL; // Copy the pickle to shared memory. memcpy(shared_memory->memory(), pickle.data(), pickle.size()); return shared_memory.release(); } // This method will be called from the file thread void UserScriptMaster::ScriptReloader::RunScan( const FilePath script_dir, UserScriptList lone_script) { UserScriptList scripts; // Get list of user scripts. if (!script_dir.empty()) LoadScriptsFromDirectory(script_dir, &scripts); LoadLoneScripts(&lone_script); // Merge with the explicit scripts scripts.reserve(scripts.size() + lone_script.size()); scripts.insert(scripts.end(), lone_script.begin(), lone_script.end()); // Scripts now contains list of up-to-date scripts. Load the content in the // shared memory and let the master know it's ready. We need to post the task // back even if no scripts ware found to balance the AddRef/Release calls master_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(this, &ScriptReloader::NotifyMaster, Serialize(scripts))); } UserScriptMaster::UserScriptMaster(MessageLoop* worker_loop, const FilePath& script_dir) : user_script_dir_(script_dir), worker_loop_(worker_loop), extensions_service_ready_(false), pending_scan_(false) { if (!user_script_dir_.value().empty()) AddWatchedPath(script_dir); registrar_.Add(this, NotificationType::EXTENSIONS_READY, NotificationService::AllSources()); registrar_.Add(this, NotificationType::EXTENSIONS_LOADED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::EXTENSION_UNLOADED, NotificationService::AllSources()); } UserScriptMaster::~UserScriptMaster() { if (script_reloader_) script_reloader_->DisownMaster(); // TODO(aa): Enable this when DirectoryWatcher is implemented for linux. #if defined(OS_WIN) || defined(OS_MACOSX) STLDeleteElements(&dir_watchers_); #endif } void UserScriptMaster::AddWatchedPath(const FilePath& path) { // TODO(aa): Enable this when DirectoryWatcher is implemented for linux. #if defined(OS_WIN) || defined(OS_MACOSX) DirectoryWatcher* watcher = new DirectoryWatcher(); base::Thread* file_thread = g_browser_process->file_thread(); watcher->Watch(path, this, file_thread ? file_thread->message_loop() : NULL, true); dir_watchers_.push_back(watcher); #endif } void UserScriptMaster::NewScriptsAvailable(base::SharedMemory* handle) { // Ensure handle is deleted or released. scoped_ptr<base::SharedMemory> handle_deleter(handle); if (pending_scan_) { // While we were scanning, there were further changes. Don't bother // notifying about these scripts and instead just immediately rescan. pending_scan_ = false; StartScan(); } else { // We're no longer scanning. script_reloader_ = NULL; // We've got scripts ready to go. shared_memory_.swap(handle_deleter); NotificationService::current()->Notify( NotificationType::USER_SCRIPTS_UPDATED, NotificationService::AllSources(), Details<base::SharedMemory>(handle)); } } void UserScriptMaster::OnDirectoryChanged(const FilePath& path) { if (script_reloader_.get()) { // We're already scanning for scripts. We note that we should rescan when // we get the chance. pending_scan_ = true; return; } StartScan(); } void UserScriptMaster::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::EXTENSIONS_READY: extensions_service_ready_ = true; StartScan(); break; case NotificationType::EXTENSIONS_LOADED: { // TODO(aa): Fix race here. A page could need a content script on startup, // before the extension has loaded. We need to freeze the renderer in // that case. // See: http://code.google.com/p/chromium/issues/detail?id=11547. // Add any content scripts inside the extension. ExtensionList* extensions = Details<ExtensionList>(details).ptr(); for (ExtensionList::iterator extension_iterator = extensions->begin(); extension_iterator != extensions->end(); ++extension_iterator) { Extension* extension = *extension_iterator; const UserScriptList& scripts = extension->content_scripts(); for (UserScriptList::const_iterator iter = scripts.begin(); iter != scripts.end(); ++iter) { lone_scripts_.push_back(*iter); } } if (extensions_service_ready_) StartScan(); break; } case NotificationType::EXTENSION_UNLOADED: { // Remove any content scripts. Extension* extension = Details<Extension>(details).ptr(); UserScriptList new_lone_scripts; for (UserScriptList::iterator iter = lone_scripts_.begin(); iter != lone_scripts_.end(); ++iter) { if (iter->extension_id() != extension->id()) { new_lone_scripts.push_back(*iter); } } lone_scripts_ = new_lone_scripts; StartScan(); // TODO(aa): Do we want to do something smarter for the scripts that have // already been injected? break; } default: DCHECK(false); } } void UserScriptMaster::StartScan() { if (!script_reloader_) script_reloader_ = new ScriptReloader(this); script_reloader_->StartScan(worker_loop_, user_script_dir_, lone_scripts_); } <|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/extensions/webstore_installer.h" #include "base/string_util.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/crx_installer.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "content/browser/tab_contents/navigation_controller.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "googleurl/src/gurl.h" #include "net/base/escape.h" namespace { const char kInvalidIdError[] = "Invalid id"; const char kNoBrowserError[] = "No browser found"; const char kInlineInstallSource[] = "inline"; const char kDefaultInstallSource[] = ""; GURL GetWebstoreInstallUrl( const std::string& extension_id, const std::string& install_source) { std::vector<std::string> params; params.push_back("id=" + extension_id); if (!install_source.empty()) { params.push_back("installsource=" + install_source); } params.push_back("lang=" + g_browser_process->GetApplicationLocale()); params.push_back("uc"); std::string url_string = extension_urls::GetWebstoreUpdateUrl(true).spec(); GURL url(url_string + "?response=redirect&x=" + net::EscapeQueryParamValue(JoinString(params, '&'), true)); DCHECK(url.is_valid()); return url; } } // namespace WebstoreInstaller::WebstoreInstaller(Profile* profile, Delegate* delegate, NavigationController* controller, const std::string& id, int flags) : profile_(profile), delegate_(delegate), controller_(controller), id_(id), flags_(flags) { download_url_ = GetWebstoreInstallUrl(id, flags & FLAG_INLINE_INSTALL ? kInlineInstallSource : kDefaultInstallSource); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_INSTALLED, content::Source<Profile>(profile)); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_INSTALL_ERROR, content::Source<CrxInstaller>(NULL)); } WebstoreInstaller::~WebstoreInstaller() {} void WebstoreInstaller::Start() { AddRef(); // Balanced in ReportSuccess and ReportFailure. if (!Extension::IdIsValid(id_)) { ReportFailure(kInvalidIdError); return; } // TODO(mihaip): For inline installs, we pretend like the referrer is the // gallery, even though this could be an inline install, in order to pass the // checks in ExtensionService::IsDownloadFromGallery. We should instead pass // the real referrer, track if this is an inline install in the whitelist // entry and look that up when checking that this is a valid download. GURL referrer = controller_->GetActiveEntry()->url(); if (flags_ & FLAG_INLINE_INSTALL) referrer = GURL(extension_urls::GetWebstoreItemDetailURLPrefix() + id_); // The download url for the given extension is contained in |download_url_|. // We will navigate the current tab to this url to start the download. The // download system will then pass the crx to the CrxInstaller. controller_->LoadURL(download_url_, referrer, content::PAGE_TRANSITION_LINK, std::string()); } void WebstoreInstaller::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_EXTENSION_INSTALLED: { CHECK(profile_->IsSameProfile(content::Source<Profile>(source).ptr())); const Extension* extension = content::Details<const Extension>(details).ptr(); if (id_ == extension->id()) ReportSuccess(); break; } case chrome::NOTIFICATION_EXTENSION_INSTALL_ERROR: { CrxInstaller* crx_installer = content::Source<CrxInstaller>(source).ptr(); CHECK(crx_installer); if (!profile_->IsSameProfile(crx_installer->profile())) return; const std::string* error = content::Details<const std::string>(details).ptr(); if (download_url_ == crx_installer->original_download_url()) ReportFailure(*error); break; } default: NOTREACHED(); } } void WebstoreInstaller::ReportFailure(const std::string& error) { if (delegate_) delegate_->OnExtensionInstallFailure(id_, error); Release(); // Balanced in Start(). } void WebstoreInstaller::ReportSuccess() { if (delegate_) delegate_->OnExtensionInstallSuccess(id_); Release(); // Balanced in Start(). } <commit_msg>Rename GetWebstoreInstallerUrl in WebstoreInstaller.<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/extensions/webstore_installer.h" #include "base/string_util.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/crx_installer.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "content/browser/tab_contents/navigation_controller.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "googleurl/src/gurl.h" #include "net/base/escape.h" namespace { const char kInvalidIdError[] = "Invalid id"; const char kNoBrowserError[] = "No browser found"; const char kInlineInstallSource[] = "inline"; const char kDefaultInstallSource[] = ""; GURL GetWebstoreInstallURL( const std::string& extension_id, const std::string& install_source) { std::vector<std::string> params; params.push_back("id=" + extension_id); if (!install_source.empty()) { params.push_back("installsource=" + install_source); } params.push_back("lang=" + g_browser_process->GetApplicationLocale()); params.push_back("uc"); std::string url_string = extension_urls::GetWebstoreUpdateUrl(true).spec(); GURL url(url_string + "?response=redirect&x=" + net::EscapeQueryParamValue(JoinString(params, '&'), true)); DCHECK(url.is_valid()); return url; } } // namespace WebstoreInstaller::WebstoreInstaller(Profile* profile, Delegate* delegate, NavigationController* controller, const std::string& id, int flags) : profile_(profile), delegate_(delegate), controller_(controller), id_(id), flags_(flags) { download_url_ = GetWebstoreInstallURL(id, flags & FLAG_INLINE_INSTALL ? kInlineInstallSource : kDefaultInstallSource); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_INSTALLED, content::Source<Profile>(profile)); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_INSTALL_ERROR, content::Source<CrxInstaller>(NULL)); } WebstoreInstaller::~WebstoreInstaller() {} void WebstoreInstaller::Start() { AddRef(); // Balanced in ReportSuccess and ReportFailure. if (!Extension::IdIsValid(id_)) { ReportFailure(kInvalidIdError); return; } // TODO(mihaip): For inline installs, we pretend like the referrer is the // gallery, even though this could be an inline install, in order to pass the // checks in ExtensionService::IsDownloadFromGallery. We should instead pass // the real referrer, track if this is an inline install in the whitelist // entry and look that up when checking that this is a valid download. GURL referrer = controller_->GetActiveEntry()->url(); if (flags_ & FLAG_INLINE_INSTALL) referrer = GURL(extension_urls::GetWebstoreItemDetailURLPrefix() + id_); // The download url for the given extension is contained in |download_url_|. // We will navigate the current tab to this url to start the download. The // download system will then pass the crx to the CrxInstaller. controller_->LoadURL(download_url_, referrer, content::PAGE_TRANSITION_LINK, std::string()); } void WebstoreInstaller::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_EXTENSION_INSTALLED: { CHECK(profile_->IsSameProfile(content::Source<Profile>(source).ptr())); const Extension* extension = content::Details<const Extension>(details).ptr(); if (id_ == extension->id()) ReportSuccess(); break; } case chrome::NOTIFICATION_EXTENSION_INSTALL_ERROR: { CrxInstaller* crx_installer = content::Source<CrxInstaller>(source).ptr(); CHECK(crx_installer); if (!profile_->IsSameProfile(crx_installer->profile())) return; const std::string* error = content::Details<const std::string>(details).ptr(); if (download_url_ == crx_installer->original_download_url()) ReportFailure(*error); break; } default: NOTREACHED(); } } void WebstoreInstaller::ReportFailure(const std::string& error) { if (delegate_) delegate_->OnExtensionInstallFailure(id_, error); Release(); // Balanced in Start(). } void WebstoreInstaller::ReportSuccess() { if (delegate_) delegate_->OnExtensionInstallSuccess(id_); Release(); // Balanced in Start(). } <|endoftext|>
<commit_before>#include "SharedCommandData.h" #include <gtest\gtest.h><commit_msg>Adding shared command data tests<commit_after>#include "SharedCommandData.h" #include <gtest\gtest.h> TEST(SharedCommandDataTest1, extractBadCommand) { SharedCommandData scd; filterDataMap scdInput; scdInput[COMMAND_INPUT] = 5; // Invalid type scd.setInput(scdInput); scd.process(); ASSERT_EQ(filterError::INVALID_INPUT, scd.getFilterError()); ASSERT_EQ(filterStatus::FILTER_ERROR, scd.getFilterStatus()); } TEST(SharedCommandDataTest2, extractCommand) { SharedCommandData scd; filterDataMap scdInput; commandData dat; dat.type = MOUSE_COMMAND; dat.mouse = LEFT_CLICK; scdInput[COMMAND_INPUT] = dat; scd.setInput(scdInput); scd.process(); ASSERT_EQ(filterError::NO_FILTER_ERROR, scd.getFilterError()); ASSERT_EQ(filterStatus::END_CHAIN, scd.getFilterStatus()); commandData outputDat; scd.consumeCommand(outputDat); ASSERT_EQ(MOUSE_COMMAND, outputDat.type); ASSERT_EQ(LEFT_CLICK, outputDat.mouse); } TEST(SharedCommandDataTest3, extractVelocity) { SharedCommandData scd; filterDataMap scdInput; point dat; dat.x = 50; dat.y = 100; scdInput[VELOCITY_INPUT] = dat; scd.setInput(scdInput); scd.process(); ASSERT_EQ(filterError::NO_FILTER_ERROR, scd.getFilterError()); ASSERT_EQ(filterStatus::END_CHAIN, scd.getFilterStatus()); point outputDat; outputDat = scd.getVelocity(); ASSERT_EQ(50, outputDat.x); ASSERT_EQ(100, outputDat.y); } TEST(SharedCommandDataTest4, extractBadVelocity) { SharedCommandData scd; filterDataMap scdInput; scdInput[VELOCITY_INPUT] = 5; // Bad type scd.setInput(scdInput); scd.process(); ASSERT_EQ(filterError::INVALID_INPUT, scd.getFilterError()); ASSERT_EQ(filterStatus::FILTER_ERROR, scd.getFilterStatus()); }<|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// @brief upload request handler /// /// @file /// /// DISCLAIMER /// /// Copyright 2014 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany /// @author Copyright 2012-2014, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "RestUploadHandler.h" #include "Basics/FileUtils.h" #include "Basics/files.h" #include "Basics/logging.h" #include "Basics/StringUtils.h" #include "HttpServer/HttpServer.h" #include "Rest/HttpRequest.h" using namespace std; using namespace triagens::basics; using namespace triagens::rest; using namespace triagens::arango; // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief constructor //////////////////////////////////////////////////////////////////////////////// RestUploadHandler::RestUploadHandler (HttpRequest* request) : RestVocbaseBaseHandler(request) { } //////////////////////////////////////////////////////////////////////////////// /// @brief destructor //////////////////////////////////////////////////////////////////////////////// RestUploadHandler::~RestUploadHandler () { } // ----------------------------------------------------------------------------- // --SECTION-- Handler methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// Handler::status_t RestUploadHandler::execute () { // extract the request type const HttpRequest::HttpRequestType type = _request->requestType(); if (type != HttpRequest::HTTP_REQUEST_POST) { generateError(HttpResponse::METHOD_NOT_ALLOWED, TRI_ERROR_HTTP_METHOD_NOT_ALLOWED); return status_t(Handler::HANDLER_DONE); } char* filename = nullptr; if (TRI_GetTempName("uploads", &filename, false) != TRI_ERROR_NO_ERROR) { generateError(HttpResponse::SERVER_ERROR, TRI_ERROR_INTERNAL, "could not generate temp file"); return status_t(Handler::HANDLER_FAILED); } char* relative = TRI_GetFilename(filename); LOG_TRACE("saving uploaded file of length %llu in file '%s', relative '%s'", (unsigned long long) _request->bodySize(), filename, relative); char const* body = _request->body(); size_t bodySize = _request->bodySize(); bool found; char const* value = _request->value("multipart", found); bool multiPart = false; if (found) { multiPart = triagens::basics::StringUtils::boolean(value); if (multiPart) { if (! parseMultiPart(body, bodySize)) { TRI_Free(TRI_CORE_MEM_ZONE, relative); TRI_Free(TRI_CORE_MEM_ZONE, filename); generateError(HttpResponse::SERVER_ERROR, TRI_ERROR_INTERNAL, "invalid multipart request"); return status_t(Handler::HANDLER_FAILED); } } } try { FileUtils::spit(string(filename), body, bodySize); TRI_Free(TRI_CORE_MEM_ZONE, filename); } catch (...) { TRI_Free(TRI_CORE_MEM_ZONE, relative); TRI_Free(TRI_CORE_MEM_ZONE, filename); generateError(HttpResponse::SERVER_ERROR, TRI_ERROR_INTERNAL, "could not save file"); return status_t(Handler::HANDLER_FAILED); } char* fullName = TRI_Concatenate2File("uploads", relative); TRI_Free(TRI_CORE_MEM_ZONE, relative); // create the response _response = createResponse(HttpResponse::CREATED); _response->setContentType("application/json; charset=utf-8"); TRI_json_t json; TRI_InitObjectJson(TRI_UNKNOWN_MEM_ZONE, &json); TRI_Insert3ObjectJson(TRI_UNKNOWN_MEM_ZONE, &json, "filename", TRI_CreateStringCopyJson(TRI_UNKNOWN_MEM_ZONE, fullName, strlen(fullName))); TRI_Free(TRI_CORE_MEM_ZONE, filename); generateResult(HttpResponse::CREATED, &json); TRI_DestroyJson(TRI_UNKNOWN_MEM_ZONE, &json); // success return status_t(Handler::HANDLER_DONE); } //////////////////////////////////////////////////////////////////////////////// /// @brief parses a multi-part request body and determines the boundaries of /// its first element //////////////////////////////////////////////////////////////////////////////// bool RestUploadHandler::parseMultiPart (char const*& body, size_t& length) { char const* beg = _request->body(); char const* end = beg + _request->bodySize(); while (beg < end && (*beg == '\r' || *beg == '\n' || *beg == ' ')) { ++beg; } // find delimiter char const* ptr = beg; while (ptr < end && *ptr == '-') { ++ptr; } while (ptr < end && *ptr != '\r' && *ptr != '\n') { ++ptr; } if (ptr == beg) { // oops return false; } std::string const delimiter(beg, ptr - beg); if (ptr < end && *ptr == '\r') { ++ptr; } if (ptr < end && *ptr == '\n') { ++ptr; } std::vector<std::pair<char const*, size_t>> parts; while (ptr < end) { char const* p = TRI_IsContainedMemory(ptr, end - ptr, delimiter.c_str(), delimiter.size()); if (p == nullptr || p + delimiter.size() + 2 >= end || p - 2 <= ptr) { return false; } char const* q = p; if (*(q - 1) == '\n') { --q; } if (*(q - 1) == '\r') { --q; } parts.push_back(std::make_pair(ptr, q - ptr)); ptr = p + delimiter.size(); if (*ptr == '-' && *(ptr + 1) == '-') { // eom break; } if (*ptr == '\r') { ++ptr; } if (ptr < end && *ptr == '\n') { ++ptr; } } for (auto& part : parts) { auto ptr = part.first; auto end = part.first + part.second; char const* data = nullptr; while (ptr < end) { while (ptr < end && *ptr == ' ') { ++ptr; } if (ptr < end && (*ptr == '\r' || *ptr == '\n')) { // end of headers if (*ptr == '\r') { ++ptr; } if (ptr < end && *ptr == '\n') { ++ptr; } data = ptr; break; } // header line char const* eol = TRI_IsContainedMemory(ptr, end - ptr, "\r\n", 2); if (eol == nullptr) { eol = TRI_IsContainedMemory(ptr, end - ptr, "\n", 1); } if (eol == nullptr) { return false; } char const* colon = TRI_IsContainedMemory(ptr, end - ptr, ":", 1); if (colon == nullptr) { return false; } char const* p = colon; while (p > ptr && *(p - 1) == ' ') { --p; } ++colon; while (colon < eol && *colon == ' ') { ++colon; } char const* q = eol; while (q > ptr && *(q - 1) == ' ') { --q; } ptr = eol; if (*ptr == '\r') { ++ptr; } if (ptr < end && *ptr == '\n') { ++ptr; } } if (data == nullptr) { return false; } body = data; length = static_cast<size_t>(end - data); // stop after the first found element break; } return true; } // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}" // End: <commit_msg>fixed leak<commit_after>//////////////////////////////////////////////////////////////////////////////// /// @brief upload request handler /// /// @file /// /// DISCLAIMER /// /// Copyright 2014 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany /// @author Copyright 2012-2014, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "RestUploadHandler.h" #include "Basics/FileUtils.h" #include "Basics/files.h" #include "Basics/logging.h" #include "Basics/StringUtils.h" #include "HttpServer/HttpServer.h" #include "Rest/HttpRequest.h" using namespace std; using namespace triagens::basics; using namespace triagens::rest; using namespace triagens::arango; // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief constructor //////////////////////////////////////////////////////////////////////////////// RestUploadHandler::RestUploadHandler (HttpRequest* request) : RestVocbaseBaseHandler(request) { } //////////////////////////////////////////////////////////////////////////////// /// @brief destructor //////////////////////////////////////////////////////////////////////////////// RestUploadHandler::~RestUploadHandler () { } // ----------------------------------------------------------------------------- // --SECTION-- Handler methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// Handler::status_t RestUploadHandler::execute () { // extract the request type const HttpRequest::HttpRequestType type = _request->requestType(); if (type != HttpRequest::HTTP_REQUEST_POST) { generateError(HttpResponse::METHOD_NOT_ALLOWED, TRI_ERROR_HTTP_METHOD_NOT_ALLOWED); return status_t(Handler::HANDLER_DONE); } char* filename = nullptr; if (TRI_GetTempName("uploads", &filename, false) != TRI_ERROR_NO_ERROR) { generateError(HttpResponse::SERVER_ERROR, TRI_ERROR_INTERNAL, "could not generate temp file"); return status_t(Handler::HANDLER_FAILED); } char* relative = TRI_GetFilename(filename); LOG_TRACE("saving uploaded file of length %llu in file '%s', relative '%s'", (unsigned long long) _request->bodySize(), filename, relative); char const* body = _request->body(); size_t bodySize = _request->bodySize(); bool found; char const* value = _request->value("multipart", found); bool multiPart = false; if (found) { multiPart = triagens::basics::StringUtils::boolean(value); if (multiPart) { if (! parseMultiPart(body, bodySize)) { TRI_Free(TRI_CORE_MEM_ZONE, relative); TRI_Free(TRI_CORE_MEM_ZONE, filename); generateError(HttpResponse::SERVER_ERROR, TRI_ERROR_INTERNAL, "invalid multipart request"); return status_t(Handler::HANDLER_FAILED); } } } try { FileUtils::spit(string(filename), body, bodySize); TRI_Free(TRI_CORE_MEM_ZONE, filename); } catch (...) { TRI_Free(TRI_CORE_MEM_ZONE, relative); TRI_Free(TRI_CORE_MEM_ZONE, filename); generateError(HttpResponse::SERVER_ERROR, TRI_ERROR_INTERNAL, "could not save file"); return status_t(Handler::HANDLER_FAILED); } char* fullName = TRI_Concatenate2File("uploads", relative); TRI_Free(TRI_CORE_MEM_ZONE, relative); // create the response _response = createResponse(HttpResponse::CREATED); _response->setContentType("application/json; charset=utf-8"); TRI_json_t json; TRI_InitObjectJson(TRI_UNKNOWN_MEM_ZONE, &json); TRI_Insert3ObjectJson(TRI_UNKNOWN_MEM_ZONE, &json, "filename", TRI_CreateStringCopyJson(TRI_UNKNOWN_MEM_ZONE, fullName, strlen(fullName))); TRI_Free(TRI_CORE_MEM_ZONE, fullName); generateResult(HttpResponse::CREATED, &json); TRI_DestroyJson(TRI_UNKNOWN_MEM_ZONE, &json); // success return status_t(Handler::HANDLER_DONE); } //////////////////////////////////////////////////////////////////////////////// /// @brief parses a multi-part request body and determines the boundaries of /// its first element //////////////////////////////////////////////////////////////////////////////// bool RestUploadHandler::parseMultiPart (char const*& body, size_t& length) { char const* beg = _request->body(); char const* end = beg + _request->bodySize(); while (beg < end && (*beg == '\r' || *beg == '\n' || *beg == ' ')) { ++beg; } // find delimiter char const* ptr = beg; while (ptr < end && *ptr == '-') { ++ptr; } while (ptr < end && *ptr != '\r' && *ptr != '\n') { ++ptr; } if (ptr == beg) { // oops return false; } std::string const delimiter(beg, ptr - beg); if (ptr < end && *ptr == '\r') { ++ptr; } if (ptr < end && *ptr == '\n') { ++ptr; } std::vector<std::pair<char const*, size_t>> parts; while (ptr < end) { char const* p = TRI_IsContainedMemory(ptr, end - ptr, delimiter.c_str(), delimiter.size()); if (p == nullptr || p + delimiter.size() + 2 >= end || p - 2 <= ptr) { return false; } char const* q = p; if (*(q - 1) == '\n') { --q; } if (*(q - 1) == '\r') { --q; } parts.push_back(std::make_pair(ptr, q - ptr)); ptr = p + delimiter.size(); if (*ptr == '-' && *(ptr + 1) == '-') { // eom break; } if (*ptr == '\r') { ++ptr; } if (ptr < end && *ptr == '\n') { ++ptr; } } for (auto& part : parts) { auto ptr = part.first; auto end = part.first + part.second; char const* data = nullptr; while (ptr < end) { while (ptr < end && *ptr == ' ') { ++ptr; } if (ptr < end && (*ptr == '\r' || *ptr == '\n')) { // end of headers if (*ptr == '\r') { ++ptr; } if (ptr < end && *ptr == '\n') { ++ptr; } data = ptr; break; } // header line char const* eol = TRI_IsContainedMemory(ptr, end - ptr, "\r\n", 2); if (eol == nullptr) { eol = TRI_IsContainedMemory(ptr, end - ptr, "\n", 1); } if (eol == nullptr) { return false; } char const* colon = TRI_IsContainedMemory(ptr, end - ptr, ":", 1); if (colon == nullptr) { return false; } char const* p = colon; while (p > ptr && *(p - 1) == ' ') { --p; } ++colon; while (colon < eol && *colon == ' ') { ++colon; } char const* q = eol; while (q > ptr && *(q - 1) == ' ') { --q; } ptr = eol; if (*ptr == '\r') { ++ptr; } if (ptr < end && *ptr == '\n') { ++ptr; } } if (data == nullptr) { return false; } body = data; length = static_cast<size_t>(end - data); // stop after the first found element break; } return true; } // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}" // End: <|endoftext|>
<commit_before>// Copyright (c) 2009 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 entry. // // Implement the storage of service tokens in memory. #include "chrome/browser/sync/util/user_settings.h" namespace browser_sync { void UserSettings::ClearAllServiceTokens() { service_tokens_.clear(); } void UserSettings::SetAuthTokenForService( const std::string& email, const std::string& service_name, const std::string& long_lived_service_token) { service_tokens_[service_name] = long_lived_service_token; } bool UserSettings::GetLastUserAndServiceToken(const std::string& service_name, std::string* username, std::string* service_token) { ServiceTokenMap::const_iterator iter = service_tokens_.find(service_name); if (iter != service_tokens_.end()) { *username = email_; *service_token = iter->second; return true; } return false; } } // namespace browser_sync <commit_msg>Use the password_manager encryptor to encrypt the sync credentials under Linux and OSX.<commit_after>// Copyright (c) 2009 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 entry. // // Implement the storage of service tokens in memory. #include "chrome/browser/sync/util/user_settings.h" #include "chrome/browser/password_manager/encryptor.h" #include "chrome/browser/sync/util/query_helpers.h" namespace browser_sync { void UserSettings::SetAuthTokenForService( const std::string& email, const std::string& service_name, const std::string& long_lived_service_token) { std::string encrypted_service_token; if (!Encryptor::EncryptString(long_lived_service_token, &encrypted_service_token)) { LOG(ERROR) << "Encrytion failed: " << long_lived_service_token; return; } ScopedDBHandle dbhandle(this); ExecOrDie(dbhandle.get(), "INSERT INTO cookies " "(email, service_name, service_token) " "values (?, ?, ?)", email, service_name, encrypted_service_token); } void UserSettings::ClearAllServiceTokens() { ScopedDBHandle dbhandle(this); ExecOrDie(dbhandle.get(), "DELETE FROM cookies"); } bool UserSettings::GetLastUser(std::string* username) { ScopedDBHandle dbhandle(this); ScopedStatement query(PrepareQuery(dbhandle.get(), "SELECT email FROM cookies")); if (SQLITE_ROW == sqlite3_step(query.get())) { GetColumn(query.get(), 0, username); return true; } else { return false; } } bool UserSettings::GetLastUserAndServiceToken(const std::string& service_name, std::string* username, std::string* service_token) { ScopedDBHandle dbhandle(this); ScopedStatement query(PrepareQuery( dbhandle.get(), "SELECT email, service_token FROM cookies WHERE service_name = ?", service_name)); if (SQLITE_ROW == sqlite3_step(query.get())) { std::string encrypted_service_token; GetColumn(query.get(), 1, &encrypted_service_token); if (!Encryptor::DecryptString(encrypted_service_token, service_token)) { LOG(ERROR) << "Decryption failed: " << encrypted_service_token; return false; } GetColumn(query.get(), 0, username); return true; } return false; } } // namespace browser_sync <|endoftext|>
<commit_before>#define SASS_NODE_INCLUDED #include <string> #include <vector> namespace Sass { using namespace std; enum Node_Type { none, flags, comment, root, ruleset, propset, selector_group, selector, selector_combinator, simple_selector_sequence, backref, simple_selector, type_selector, class_selector, id_selector, pseudo, pseudo_negation, functional_pseudo, attribute_selector, block, rule, property, nil, comma_list, space_list, disjunction, conjunction, relation, eq, neq, gt, gte, lt, lte, expression, add, sub, term, mul, div, factor, unary_plus, unary_minus, values, value, identifier, uri, textual_percentage, textual_dimension, textual_number, textual_hex, color_name, string_constant, number, numeric_percentage, numeric_dimension, numeric_color, boolean, important, value_schema, string_schema, css_import, function_call, mixin, parameters, expansion, arguments, variable, assignment }; struct Node_Impl; class Node { private: friend class Node_Factory; Node_Impl* ip_; // private constructors; must use a Node_Factory Node(); Node(Node_Impl* ip); // : ip_(ip) { } public: Node_Type type(); // { return ip_->type; } bool has_children(); // { return ip_->has_children; } bool has_statements(); // { return ip_->has_statements; } bool has_blocks(); // { return ip_->has_blocks; } bool has_expansions(); // { return ip_->has_expansions; } bool has_backref(); // { return ip_->has_backref; } bool from_variable(); // { return ip_->from_variable; } bool eval_me(); // { return ip_->eval_me; } bool is_unquoted(); // { return ip_->is_unquoted; } bool is_numeric(); // { return ip_->is_numeric(); } string file_name() const; // { return *(ip_->file_name); } size_t line_number() const; // { return ip_->line_number; } size_t size() const; // { return ip_->size(); } Node& at(size_t i) const; // { return ip_->at(i); } Node& operator[](size_t i) const; // { return at(i); } void pop_back(); // { return ip_->pop_back(); } Node& push_back(Node n); // { ip_->push_back(n); return *this; } Node& operator<<(Node n); // { return push_back(n); } Node& operator+=(Node n); // { // for (size_t i = 0, L = n.size(); i < L; ++i) push_back(n[i]); // return *this; // } bool boolean_value(); // { return ip_->boolean_value(); } double numeric_value(); // { return ip_->numeric_value(); } }; struct Token { const char* begin; const char* end; // Need Token::make(...) because tokens are union members, and hence they // can't have non-trivial constructors. static Token make() { Token t; t.begin = 0; t.end = 0; return t; } static Token make(const char* s) { Token t; t.begin = s; t.end = s + std::strlen(s); return t; } static Token make(const char* b, const char* e) { Token t; t.begin = b; t.end = e; return t; } size_t length() const { return end - begin; } string to_string() const { return string(begin, end - begin); } string unquote() const; void unquote_to_stream(std::stringstream& buf) const; operator bool() { return begin && end && begin >= end; } bool operator<(const Token& rhs) const; bool operator==(const Token& rhs) const; }; struct Dimension { double numeric; Token unit; }; struct Node_Impl { union { bool boolean; double numeric; Token token; Dimension dimension; } value; vector<Node> children; string* file_name; size_t line_number; Node_Type type; bool has_children; bool has_statements; bool has_blocks; bool has_expansions; bool has_backref; bool from_variable; bool eval_me; bool is_unquoted; // bool is_numeric(); // // size_t size(); // Node& at(size_t i); // Node& back(); // Node& pop_back(); // void push_back(const Node& n); // // bool boolean_value(); bool is_numeric() { return type >= number && type <= numeric_dimension; } size_t size() { return children.size(); } Node& at(size_t i) { return children.at(i); } Node& back() { return children.back(); } void push_back(const Node& n) { children.push_back(n); } Node& pop_back() { children.pop_back(); } bool boolean_value() { return value.boolean; } double numeric_value(); string unit(); }; // ------------------------------------------------------------------------ // Node method implementations -- in the header so they can be inlined // ------------------------------------------------------------------------ inline Node::Node(Node_Impl* ip) : ip_(ip) { } inline Node_Type Node::type() { return ip_->type; } inline bool Node::has_children() { return ip_->has_children; } inline bool Node::has_statements() { return ip_->has_statements; } inline bool Node::has_blocks() { return ip_->has_blocks; } inline bool Node::has_expansions() { return ip_->has_expansions; } inline bool Node::has_backref() { return ip_->has_backref; } inline bool Node::from_variable() { return ip_->from_variable; } inline bool Node::eval_me() { return ip_->eval_me; } inline bool Node::is_unquoted() { return ip_->is_unquoted; } inline bool Node::is_numeric() { return ip_->is_numeric(); } inline string Node::file_name() const { return *(ip_->file_name); } inline size_t Node::line_number() const { return ip_->line_number; } inline size_t Node::size() const { return ip_->size(); } inline Node& Node::at(size_t i) const { return ip_->at(i); } inline Node& Node::operator[](size_t i) const { return at(i); } inline void Node::pop_back() { ip_->pop_back(); } inline Node& Node::push_back(Node n) { ip_->push_back(n); return *this; } inline Node& Node::operator<<(Node n) { return push_back(n); } inline Node& Node::operator+=(Node n) { for (size_t i = 0, L = n.size(); i < L; ++i) push_back(n[i]); return *this; } inline bool Node::boolean_value() { return ip_->boolean_value(); } inline double Node::numeric_value() { return ip_->numeric_value(); } }<commit_msg>Added a comment explaining the slightly unorthodox organization.<commit_after>#define SASS_NODE_INCLUDED #include <string> #include <vector> namespace Sass { using namespace std; enum Node_Type { none, flags, comment, root, ruleset, propset, selector_group, selector, selector_combinator, simple_selector_sequence, backref, simple_selector, type_selector, class_selector, id_selector, pseudo, pseudo_negation, functional_pseudo, attribute_selector, block, rule, property, nil, comma_list, space_list, disjunction, conjunction, relation, eq, neq, gt, gte, lt, lte, expression, add, sub, term, mul, div, factor, unary_plus, unary_minus, values, value, identifier, uri, textual_percentage, textual_dimension, textual_number, textual_hex, color_name, string_constant, number, numeric_percentage, numeric_dimension, numeric_color, boolean, important, value_schema, string_schema, css_import, function_call, mixin, parameters, expansion, arguments, variable, assignment }; struct Node_Impl; class Node { private: friend class Node_Factory; Node_Impl* ip_; // private constructors; must use a Node_Factory Node(); Node(Node_Impl* ip); // : ip_(ip) { } public: Node_Type type(); // { return ip_->type; } bool has_children(); // { return ip_->has_children; } bool has_statements(); // { return ip_->has_statements; } bool has_blocks(); // { return ip_->has_blocks; } bool has_expansions(); // { return ip_->has_expansions; } bool has_backref(); // { return ip_->has_backref; } bool from_variable(); // { return ip_->from_variable; } bool eval_me(); // { return ip_->eval_me; } bool is_unquoted(); // { return ip_->is_unquoted; } bool is_numeric(); // { return ip_->is_numeric(); } string file_name() const; // { return *(ip_->file_name); } size_t line_number() const; // { return ip_->line_number; } size_t size() const; // { return ip_->size(); } Node& at(size_t i) const; // { return ip_->at(i); } Node& operator[](size_t i) const; // { return at(i); } void pop_back(); // { return ip_->pop_back(); } Node& push_back(Node n); // { ip_->push_back(n); return *this; } Node& operator<<(Node n); // { return push_back(n); } Node& operator+=(Node n); // { // for (size_t i = 0, L = n.size(); i < L; ++i) push_back(n[i]); // return *this; // } bool boolean_value(); // { return ip_->boolean_value(); } double numeric_value(); // { return ip_->numeric_value(); } }; struct Token { const char* begin; const char* end; // Need Token::make(...) because tokens are union members, and hence they // can't have non-trivial constructors. static Token make() { Token t; t.begin = 0; t.end = 0; return t; } static Token make(const char* s) { Token t; t.begin = s; t.end = s + std::strlen(s); return t; } static Token make(const char* b, const char* e) { Token t; t.begin = b; t.end = e; return t; } size_t length() const { return end - begin; } string to_string() const { return string(begin, end - begin); } string unquote() const; void unquote_to_stream(std::stringstream& buf) const; operator bool() { return begin && end && begin >= end; } bool operator<(const Token& rhs) const; bool operator==(const Token& rhs) const; }; struct Dimension { double numeric; Token unit; }; struct Node_Impl { union { bool boolean; double numeric; Token token; Dimension dimension; } value; vector<Node> children; string* file_name; size_t line_number; Node_Type type; bool has_children; bool has_statements; bool has_blocks; bool has_expansions; bool has_backref; bool from_variable; bool eval_me; bool is_unquoted; // bool is_numeric(); // // size_t size(); // Node& at(size_t i); // Node& back(); // Node& pop_back(); // void push_back(const Node& n); // // bool boolean_value(); bool is_numeric() { return type >= number && type <= numeric_dimension; } size_t size() { return children.size(); } Node& at(size_t i) { return children.at(i); } Node& back() { return children.back(); } void push_back(const Node& n) { children.push_back(n); } Node& pop_back() { children.pop_back(); } bool boolean_value() { return value.boolean; } double numeric_value(); string unit(); }; // ------------------------------------------------------------------------ // Node method implementations // -- in the header so they can be easily declared inline // -- outside of their class definition to get the right declaration order // ------------------------------------------------------------------------ inline Node::Node(Node_Impl* ip) : ip_(ip) { } inline Node_Type Node::type() { return ip_->type; } inline bool Node::has_children() { return ip_->has_children; } inline bool Node::has_statements() { return ip_->has_statements; } inline bool Node::has_blocks() { return ip_->has_blocks; } inline bool Node::has_expansions() { return ip_->has_expansions; } inline bool Node::has_backref() { return ip_->has_backref; } inline bool Node::from_variable() { return ip_->from_variable; } inline bool Node::eval_me() { return ip_->eval_me; } inline bool Node::is_unquoted() { return ip_->is_unquoted; } inline bool Node::is_numeric() { return ip_->is_numeric(); } inline string Node::file_name() const { return *(ip_->file_name); } inline size_t Node::line_number() const { return ip_->line_number; } inline size_t Node::size() const { return ip_->size(); } inline Node& Node::at(size_t i) const { return ip_->at(i); } inline Node& Node::operator[](size_t i) const { return at(i); } inline void Node::pop_back() { ip_->pop_back(); } inline Node& Node::push_back(Node n) { ip_->push_back(n); return *this; } inline Node& Node::operator<<(Node n) { return push_back(n); } inline Node& Node::operator+=(Node n) { for (size_t i = 0, L = n.size(); i < L; ++i) push_back(n[i]); return *this; } inline bool Node::boolean_value() { return ip_->boolean_value(); } inline double Node::numeric_value() { return ip_->numeric_value(); } }<|endoftext|>
<commit_before>/* * File: strings.cpp * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS) */ #include "common/sedna.h" #include "tr/strings/utf8.h" #include "tr/pstr/pstr.h" #include "tr/pstr/pstr_long.h" #include "tr/executor/fo/casting_operations.h" #include "common/errdbg/d_printf.h" CharsetHandler *charset_handler = NULL; #define T_STR_MEMBUF_SIZE 100 void str_buf_base::move_to_mem_buf() { if (m_flags & f_text_in_buf) return; if (m_buf_size <= m_len) { if (m_buf_size > 0) free(m_buf); m_buf_size = m_len + 1; if (m_buf_size < T_STR_MEMBUF_SIZE) m_buf_size = T_STR_MEMBUF_SIZE; m_buf = (char*)malloc(m_buf_size); } switch (m_ttype) { case text_mem: strcpy(m_buf, m_str_ptr.get()); m_flags |= f_text_in_buf; m_ttype = text_mem; return; case text_estr: estr_copy_to_buffer(m_buf, m_ptr, m_len); m_buf[m_len] = 0; m_flags |= f_text_in_buf; m_ttype = text_mem; return; case text_doc: if (m_len < PSTRMAXSIZE) estr_copy_to_buffer(m_buf, m_ptr, m_len); else pstr_long_copy_to_buffer(m_buf, m_ptr, m_len); m_buf[m_len] = 0; m_flags |= f_text_in_buf; m_ttype = text_mem; return; } throw USER_EXCEPTION2(SE1003, "Impossible case in str_buf_base::move_to_mem_buf()"); } //pre: text is not in estr buf void str_buf_base::move_to_estr() { U_ASSERT(!mem_only()); if (m_flags & f_text_in_buf) { m_ptr = m_estr.append_mstr(m_buf); m_flags |= f_text_in_estr_buf; return; } switch (m_ttype) { case text_mem: m_ptr = m_estr.append_mstr(m_str_ptr.get()); m_ttype = text_estr; m_flags |= f_text_in_estr_buf; return; case text_estr: m_ptr = m_estr.append_estr(m_ptr, m_len); m_flags |= f_text_in_estr_buf; return; case text_doc: if (m_len < PSTRMAXSIZE) m_ptr = m_estr.append_estr(m_ptr, m_len); else m_ptr = m_estr.append_pstr_long(m_ptr); m_ttype = text_estr; m_flags |= f_text_in_estr_buf; return; } throw USER_EXCEPTION2(SE1003, "Impossible case in op_str_buf::move_to_estr()"); } void str_buf_base::clear() { m_len = 0; if (m_flags & f_text_in_estr_buf) clear_estr_buf(); m_flags = 0; m_ttype = text_mem; } void str_buf_base::append(const tuple_cell &tc) { if (m_len == 0) { m_flags = 0; if (tc.is_light_atomic()) { m_str_ptr = tc.get_str_ptr(); m_len = tc.get_strlen_mem(); m_flags = 0; m_ttype = text_mem; } else { m_len = tc.get_strlen_vmm(); m_ptr = tc.get_str_vmm(); if (tc.get_type() == tc_heavy_atomic_estr) m_ttype = text_estr; else m_ttype = text_doc; } } else { if (tc.is_light_atomic()) { append(tc.get_str_mem()); } else { const int add_len = tc.get_strlen_vmm(); const int new_len = m_len + add_len; if (new_len < T_STR_MEMBUF_SIZE || mem_only()) { if (m_buf_size == 0) { m_buf_size = T_STR_MEMBUF_SIZE; while (m_buf_size <= new_len) m_buf_size *= 2; m_buf = (char *)malloc(m_buf_size); } else if (m_buf_size <= new_len) { while (m_buf_size <= new_len) m_buf_size *= 2; m_buf = (char*)realloc(m_buf, m_buf_size); } move_to_mem_buf(); if (m_flags & f_text_in_estr_buf) { m_flags = f_text_in_buf; //clear f_text_in_estr_buf clear_estr_buf(); } tc.copy_string(m_buf + m_len); m_buf[new_len] = 0; m_len = new_len; } else { if (!(m_flags & f_text_in_estr_buf)) move_to_estr(); m_flags = f_text_in_estr_buf; //clear f_text_in_buf m_estr.append(tc); m_len = new_len; } } } } void str_buf_base::append(const char *str, int add_len) { const int new_len = m_len + add_len; if (new_len < T_STR_MEMBUF_SIZE || mem_only()) { if (m_buf_size == 0) { m_buf_size = T_STR_MEMBUF_SIZE; while (m_buf_size <= new_len) m_buf_size *= 2; U_ASSERT(m_buf == NULL); m_buf = (char *)malloc(m_buf_size); } else if (m_buf_size <= new_len) { while (m_buf_size <= new_len) m_buf_size *= 2; m_buf = (char*)realloc(m_buf, m_buf_size); } if (m_len > 0) { move_to_mem_buf(); if (m_flags & f_text_in_estr_buf) clear_estr_buf(); } m_flags = f_text_in_buf; //clear f_text_in_estr_buf m_ttype = text_mem; strncpy(m_buf + m_len, str, add_len); m_len = new_len; U_ASSERT(m_len < m_buf_size); m_buf[m_len] = 0; } else { if (!(m_flags & f_text_in_estr_buf)) move_to_estr(); m_estr.append_mstr(str, add_len); m_len = new_len; m_ttype = text_estr; m_flags = f_text_in_estr_buf; //clear f_text_in_buf } } void str_buf_base::append(const char *str) { const int add_len = strlen(str); this->append(str, add_len); } char * str_buf_base::c_str() { if (m_flags & f_text_in_buf) return m_buf; if (m_ttype == text_mem) return m_str_ptr.get(); move_to_mem_buf(); return m_buf; } char * str_buf_base::get_str() { U_ASSERT(mem_only()); move_to_mem_buf(); char *res = m_buf; m_buf = NULL; m_buf_size = 0; U_ASSERT(!(m_flags & f_text_in_estr_buf)); m_flags = 0; m_ptr = XNULL; m_len = 0; m_ttype = text_mem; return res; } str_buf_base::~str_buf_base() { if (m_buf_size > 0) free(m_buf); } stmt_str_buf_impl stmt_str_buf::buf_impl; bool stmt_str_buf::used = false; void feed_tuple_cell(string_consumer_fn fn, void *p, const tuple_cell& tc) { tuple_cell cell = cast(tc, xs_string); switch (tc.get_type()) { case tc_light_atomic_var_size: fn(tc.get_str_mem(), tc.get_strlen_mem(), p); return; case tc_heavy_atomic_estr: case tc_heavy_atomic_pstr_short: estr_feed(fn, p, tc.get_str_vmm(), tc.get_strlen_vmm()); return; case tc_heavy_atomic_pstr_long: pstr_long_feed(tc.get_str_vmm(), fn, p); return; } } void print_tuple_cell_dummy(se_ostream& crmout,const tuple_cell& tc) { feed_tuple_cell(writextext_cb, &crmout, tc); } CollationHandler *CollationManager::get_collation_handler(const char *uri) { if (strcmp(uri, "http://www.w3.org/2005/xpath-functions/collation/codepoint") == 0) return utf8_charset_handler.get_unicode_codepoint_collation(); else return NULL; } CollationHandler *CollationManager::get_default_collation_handler() { return utf8_charset_handler.get_unicode_codepoint_collation(); } <commit_msg>stm_str_buf mem only empty string bug fixed<commit_after>/* * File: strings.cpp * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS) */ #include "common/sedna.h" #include "tr/strings/utf8.h" #include "tr/pstr/pstr.h" #include "tr/pstr/pstr_long.h" #include "tr/executor/fo/casting_operations.h" #include "common/errdbg/d_printf.h" CharsetHandler *charset_handler = NULL; #define T_STR_MEMBUF_SIZE 100 void str_buf_base::move_to_mem_buf() { if (m_flags & f_text_in_buf) return; if (m_buf_size <= m_len) { if (m_buf_size > 0) free(m_buf); m_buf_size = m_len + 1; if (m_buf_size < T_STR_MEMBUF_SIZE) m_buf_size = T_STR_MEMBUF_SIZE; m_buf = (char*)malloc(m_buf_size); } if (m_len == 0) { m_buf[0] = 0; return; } switch (m_ttype) { case text_mem: strcpy(m_buf, m_str_ptr.get()); m_flags |= f_text_in_buf; m_ttype = text_mem; return; case text_estr: estr_copy_to_buffer(m_buf, m_ptr, m_len); m_buf[m_len] = 0; m_flags |= f_text_in_buf; m_ttype = text_mem; return; case text_doc: if (m_len < PSTRMAXSIZE) estr_copy_to_buffer(m_buf, m_ptr, m_len); else pstr_long_copy_to_buffer(m_buf, m_ptr, m_len); m_buf[m_len] = 0; m_flags |= f_text_in_buf; m_ttype = text_mem; return; } throw USER_EXCEPTION2(SE1003, "Impossible case in str_buf_base::move_to_mem_buf()"); } //pre: text is not in estr buf void str_buf_base::move_to_estr() { U_ASSERT(!mem_only()); if (m_flags & f_text_in_buf) { m_ptr = m_estr.append_mstr(m_buf); m_flags |= f_text_in_estr_buf; return; } switch (m_ttype) { case text_mem: m_ptr = m_estr.append_mstr(m_str_ptr.get()); m_ttype = text_estr; m_flags |= f_text_in_estr_buf; return; case text_estr: m_ptr = m_estr.append_estr(m_ptr, m_len); m_flags |= f_text_in_estr_buf; return; case text_doc: if (m_len < PSTRMAXSIZE) m_ptr = m_estr.append_estr(m_ptr, m_len); else m_ptr = m_estr.append_pstr_long(m_ptr); m_ttype = text_estr; m_flags |= f_text_in_estr_buf; return; } throw USER_EXCEPTION2(SE1003, "Impossible case in op_str_buf::move_to_estr()"); } void str_buf_base::clear() { m_len = 0; if (m_flags & f_text_in_estr_buf) clear_estr_buf(); m_flags = 0; m_ttype = text_mem; } void str_buf_base::append(const tuple_cell &tc) { if (m_len == 0) { m_flags = 0; if (tc.is_light_atomic()) { m_str_ptr = tc.get_str_ptr(); m_len = tc.get_strlen_mem(); m_flags = 0; m_ttype = text_mem; } else { m_len = tc.get_strlen_vmm(); m_ptr = tc.get_str_vmm(); if (tc.get_type() == tc_heavy_atomic_estr) m_ttype = text_estr; else m_ttype = text_doc; } } else { if (tc.is_light_atomic()) { append(tc.get_str_mem()); } else { const int add_len = tc.get_strlen_vmm(); const int new_len = m_len + add_len; if (new_len < T_STR_MEMBUF_SIZE || mem_only()) { if (m_buf_size == 0) { m_buf_size = T_STR_MEMBUF_SIZE; while (m_buf_size <= new_len) m_buf_size *= 2; m_buf = (char *)malloc(m_buf_size); } else if (m_buf_size <= new_len) { while (m_buf_size <= new_len) m_buf_size *= 2; m_buf = (char*)realloc(m_buf, m_buf_size); } move_to_mem_buf(); if (m_flags & f_text_in_estr_buf) { m_flags = f_text_in_buf; //clear f_text_in_estr_buf clear_estr_buf(); } tc.copy_string(m_buf + m_len); m_buf[new_len] = 0; m_len = new_len; } else { if (!(m_flags & f_text_in_estr_buf)) move_to_estr(); m_flags = f_text_in_estr_buf; //clear f_text_in_buf m_estr.append(tc); m_len = new_len; } } } } void str_buf_base::append(const char *str, int add_len) { const int new_len = m_len + add_len; if (new_len < T_STR_MEMBUF_SIZE || mem_only()) { if (m_buf_size == 0) { m_buf_size = T_STR_MEMBUF_SIZE; while (m_buf_size <= new_len) m_buf_size *= 2; U_ASSERT(m_buf == NULL); m_buf = (char *)malloc(m_buf_size); } else if (m_buf_size <= new_len) { while (m_buf_size <= new_len) m_buf_size *= 2; m_buf = (char*)realloc(m_buf, m_buf_size); } if (m_len > 0) { move_to_mem_buf(); if (m_flags & f_text_in_estr_buf) clear_estr_buf(); } m_flags = f_text_in_buf; //clear f_text_in_estr_buf m_ttype = text_mem; strncpy(m_buf + m_len, str, add_len); m_len = new_len; U_ASSERT(m_len < m_buf_size); m_buf[m_len] = 0; } else { if (!(m_flags & f_text_in_estr_buf)) move_to_estr(); m_estr.append_mstr(str, add_len); m_len = new_len; m_ttype = text_estr; m_flags = f_text_in_estr_buf; //clear f_text_in_buf } } void str_buf_base::append(const char *str) { const int add_len = strlen(str); this->append(str, add_len); } char * str_buf_base::c_str() { if (m_flags & f_text_in_buf) return m_buf; if (m_ttype == text_mem) return m_str_ptr.get(); move_to_mem_buf(); return m_buf; } char * str_buf_base::get_str() { U_ASSERT(mem_only()); move_to_mem_buf(); char *res = m_buf; m_buf = NULL; m_buf_size = 0; U_ASSERT(!(m_flags & f_text_in_estr_buf)); m_flags = 0; m_ptr = XNULL; m_len = 0; m_ttype = text_mem; return res; } str_buf_base::~str_buf_base() { if (m_buf_size > 0) free(m_buf); } stmt_str_buf_impl stmt_str_buf::buf_impl; bool stmt_str_buf::used = false; void feed_tuple_cell(string_consumer_fn fn, void *p, const tuple_cell& tc) { tuple_cell cell = cast(tc, xs_string); switch (tc.get_type()) { case tc_light_atomic_var_size: fn(tc.get_str_mem(), tc.get_strlen_mem(), p); return; case tc_heavy_atomic_estr: case tc_heavy_atomic_pstr_short: estr_feed(fn, p, tc.get_str_vmm(), tc.get_strlen_vmm()); return; case tc_heavy_atomic_pstr_long: pstr_long_feed(tc.get_str_vmm(), fn, p); return; } } void print_tuple_cell_dummy(se_ostream& crmout,const tuple_cell& tc) { feed_tuple_cell(writextext_cb, &crmout, tc); } CollationHandler *CollationManager::get_collation_handler(const char *uri) { if (strcmp(uri, "http://www.w3.org/2005/xpath-functions/collation/codepoint") == 0) return utf8_charset_handler.get_unicode_codepoint_collation(); else return NULL; } CollationHandler *CollationManager::get_default_collation_handler() { return utf8_charset_handler.get_unicode_codepoint_collation(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: corframe.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: np $ $Date: 2002-11-14 18:01:54 $ * * 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): _______________________________________ * * ************************************************************************/ #ifndef ADC_CORFRAME_HXX #define ADC_CORFRAME_HXX // USED SERVICES // BASE CLASSES // COMPONENTS // PARAMETERS class Html_Image; namespace display { class CorporateFrame { public: // LIFECYCLE virtual ~CorporateFrame() {} // INQUIRY virtual DYN Html_Image * LogoSrc() const = 0; virtual const char * LogoLink() const = 0; virtual const char * CopyrightText() const = 0; virtual const char * CssStyle() const = 0; virtual const char * DevelopersGuideHtmlRoot() const = 0; virtual bool SimpleLinks() const = 0; // ACCESS virtual void Set_DevelopersGuideHtmlRoot( const String & i_directory ) = 0; virtual void Set_SimpleLinks() = 0; }; // IMPLEMENTATION } // namespace display #endif <commit_msg>INTEGRATION: CWS adc11 (1.2.122); FILE MERGED 2005/02/18 18:28:45 np 1.2.122.1: #i39458#<commit_after>/************************************************************************* * * $RCSfile: corframe.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2005-03-23 08:52: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): _______________________________________ * * ************************************************************************/ #ifndef ADC_CORFRAME_HXX #define ADC_CORFRAME_HXX // USED SERVICES // BASE CLASSES // COMPONENTS // PARAMETERS class Html_Image; namespace display { class CorporateFrame { public: // LIFECYCLE virtual ~CorporateFrame() {} // INQUIRY virtual DYN Html_Image * LogoSrc() const = 0; virtual const char * LogoLink() const = 0; virtual const char * CopyrightText() const = 0; virtual const char * CssStyle() const = 0; virtual const char * CssStylesExplanation() const = 0; virtual const char * DevelopersGuideHtmlRoot() const = 0; virtual bool SimpleLinks() const = 0; // ACCESS virtual void Set_DevelopersGuideHtmlRoot( const String & i_directory ) = 0; virtual void Set_SimpleLinks() = 0; }; // IMPLEMENTATION } // namespace display #endif <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "ConstantEnvironment.h" int64_t SignedConstantDomain::max_element() const { if (constant_domain().is_value()) { return *constant_domain().get_constant(); } switch (interval()) { case sign_domain::Interval::EMPTY: not_reached_log("Empty interval does not have a max element"); case sign_domain::Interval::EQZ: case sign_domain::Interval::LEZ: return 0; case sign_domain::Interval::LTZ: return -1; case sign_domain::Interval::GEZ: case sign_domain::Interval::GTZ: case sign_domain::Interval::ALL: case sign_domain::Interval::NEZ: return std::numeric_limits<int64_t>::max(); case sign_domain::Interval::SIZE: not_reached(); } } int64_t SignedConstantDomain::min_element() const { if (constant_domain().is_value()) { return *constant_domain().get_constant(); } switch (interval()) { case sign_domain::Interval::EMPTY: not_reached_log("Empty interval does not have a min element"); case sign_domain::Interval::EQZ: case sign_domain::Interval::GEZ: return 0; case sign_domain::Interval::GTZ: return 1; case sign_domain::Interval::LEZ: case sign_domain::Interval::LTZ: case sign_domain::Interval::ALL: case sign_domain::Interval::NEZ: return std::numeric_limits<int64_t>::min(); case sign_domain::Interval::SIZE: not_reached(); } } // TODO: Instead of this custom meet function, the ConstantValue should get a // custom meet AND JOIN that knows about the relationship of NEZ and certain // non-null custom object domains. ConstantValue meet(const ConstantValue& left, const ConstantValue& right) { auto is_nez = [](const ConstantValue& value) { auto signed_value = value.maybe_get<SignedConstantDomain>(); return signed_value && signed_value->interval() == sign_domain::Interval::NEZ; }; auto is_not_null = [](const ConstantValue& value) { return !value.is_top() && !value.is_bottom() && !value.maybe_get<SignedConstantDomain>(); }; // Non-null objects of custom object domains are compatible with NEZ, and // more specific. if (is_nez(left) && is_not_null(right)) { return right; } if (is_nez(right) && is_not_null(left)) { return left; } // Non-null objects of different custom object domains can never alias, so // they meet at bottom, which is the default meet implementation for // disjoint domains. return left.meet(right); } <commit_msg>Fix meet operator for object references<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "ConstantEnvironment.h" int64_t SignedConstantDomain::max_element() const { if (constant_domain().is_value()) { return *constant_domain().get_constant(); } switch (interval()) { case sign_domain::Interval::EMPTY: not_reached_log("Empty interval does not have a max element"); case sign_domain::Interval::EQZ: case sign_domain::Interval::LEZ: return 0; case sign_domain::Interval::LTZ: return -1; case sign_domain::Interval::GEZ: case sign_domain::Interval::GTZ: case sign_domain::Interval::ALL: case sign_domain::Interval::NEZ: return std::numeric_limits<int64_t>::max(); case sign_domain::Interval::SIZE: not_reached(); } } int64_t SignedConstantDomain::min_element() const { if (constant_domain().is_value()) { return *constant_domain().get_constant(); } switch (interval()) { case sign_domain::Interval::EMPTY: not_reached_log("Empty interval does not have a min element"); case sign_domain::Interval::EQZ: case sign_domain::Interval::GEZ: return 0; case sign_domain::Interval::GTZ: return 1; case sign_domain::Interval::LEZ: case sign_domain::Interval::LTZ: case sign_domain::Interval::ALL: case sign_domain::Interval::NEZ: return std::numeric_limits<int64_t>::min(); case sign_domain::Interval::SIZE: not_reached(); } } // TODO: Instead of this custom meet function, the ConstantValue should get a // custom meet AND JOIN that knows about the relationship of NEZ and certain // non-null custom object domains. ConstantValue meet(const ConstantValue& left, const ConstantValue& right) { auto is_nez = [](const ConstantValue& value) { auto signed_value = value.maybe_get<SignedConstantDomain>(); return signed_value && signed_value->interval() == sign_domain::Interval::NEZ; }; auto is_not_null = [](const ConstantValue& value) { return !value.is_top() && !value.is_bottom() && !value.maybe_get<SignedConstantDomain>(); }; // Non-null objects of custom object domains are compatible with NEZ, and // more specific. if (is_nez(left) && is_not_null(right)) { return right; } if (is_nez(right) && is_not_null(left)) { return left; } // SingletonObjectDomain and ObjectWithImmutAttrDomain both represent object // references and they have intersection. // Handle their meet operator specially. auto is_singleton_obj = [](const ConstantValue& value) { auto obj = value.maybe_get<SingletonObjectDomain>(); return obj; }; auto is_obj_with_immutable_attr = [](const ConstantValue& value) { auto obj = value.maybe_get<ObjectWithImmutAttrDomain>(); return obj; }; if (is_singleton_obj(left) && is_obj_with_immutable_attr(right)) { return right; } if (is_singleton_obj(right) && is_obj_with_immutable_attr(left)) { return left; } // Non-null objects of different custom object domains can never alias, so // they meet at bottom, which is the default meet implementation for // disjoint domains. return left.meet(right); } <|endoftext|>
<commit_before>/* keyview.cpp * * Author: Austin Voecks * * Usage: * sudo keyview (input_device_name) [output_log_file] */ #include "keyview.h" int main(int argc, char **argv) { // variables int num_keys, fd, key_counter = 0; struct input_event ev; bool is_modifier_key, shift_state, alt_state, ctrl_state, buffer; char *program_name, *device_name, *output_name; STATE state; std::string key, shift_key; std::ofstream output_file; // initialize shift_state = false; alt_state = false; ctrl_state = false; buffer = false; program_name = argv[0]; device_name = argv[1]; output_name = argv[2]; num_keys = sizeof(keys) / sizeof(*keys); // arguments if (argc < 2) { std::cerr << "usage: " << program_name << " (device) [log_file]" << std::endl; return 1; } // open the /dev/input/event device fd = open(device_name, O_RDONLY); if (fd < 0) { std::cerr << "could not open device '" << device_name << "'" << std::endl; return 1; } // open output file in append mode, buffer output if (argc == 3) { output_file.open(output_name, std::ios::out | std::ofstream::app); buffer = true; } // set output to stdout or log file std::ostream & output = (argc == 3 ? output_file : std::cout); while (true) { // read the new key read(fd, &ev, sizeof(struct input_event)); if (ev.type == 1) { key = ""; shift_key = ""; state = S_NONE; is_modifier_key = false; // get key value if (ev.code < num_keys and keys[ev.code] != _U_) { key = keys[ev.code]; shift_key = shift_keys[ev.code]; } // get key state switch (ev.value) { case 0: state = S_OFF ; break; case 1: state = S_ON ; break; case 2: state = S_HOLD; break; } if (not key.empty() and state != S_NONE) { if (state == S_ON or state == S_HOLD) { // on, hold if (key == rsh or key == lsh) // shift is_modifier_key = shift_state = true; else if (key == ral or key == lal) // alt is_modifier_key = alt_state = true; else if (key == rct or key == lct) // ctrl is_modifier_key = ctrl_state = true; } else { // off if (key == rsh or key == lsh) // shift shift_state = false; else if (key == ral or key == lal) // alt alt_state = false; else if (key == rct or key == lct) // ctrl ctrl_state = false; } // output if (not is_modifier_key and state == S_ON) { if (shift_state) { if (shift_key != key) key = shift_key; else output << "shf_"; } if (ctrl_state) output << "ctl_"; if (alt_state) output << "alt_"; output << key << " " << std::endl; if (key_counter++ % 50 == 0 or not buffer) output.flush(); } } else { printf("key %i state %i\n", ev.code, ev.value); } } } } <commit_msg>Remove file buffering<commit_after>/* keyview.cpp * * Author: Austin Voecks * * Usage: * sudo keyview (input_device_name) [output_log_file] */ #include "keyview.h" int main(int argc, char **argv) { // variables int num_keys, fd; struct input_event ev; bool is_modifier_key, shift_state, alt_state, ctrl_state; char *program_name, *device_name, *output_name; STATE state; std::string key, shift_key; std::ofstream output_file; // initialize shift_state = false; alt_state = false; ctrl_state = false; program_name = argv[0]; device_name = argv[1]; output_name = argv[2]; num_keys = sizeof(keys) / sizeof(*keys); // arguments if (argc < 2) { std::cerr << "usage: " << program_name << " (device) [log_file]" << std::endl; return 1; } // open the /dev/input/event device fd = open(device_name, O_RDONLY); if (fd < 0) { std::cerr << "could not open device '" << device_name << "'" << std::endl; return 1; } // open output file in append mode if (argc == 3) { output_file.open(output_name, std::ios::out | std::ofstream::app); } // set output to stdout or log file std::ostream & output = (argc == 3 ? output_file : std::cout); while (true) { // read the new key read(fd, &ev, sizeof(struct input_event)); if (ev.type == 1) { key = ""; shift_key = ""; state = S_NONE; is_modifier_key = false; // get key value if (ev.code < num_keys and keys[ev.code] != _U_) { key = keys[ev.code]; shift_key = shift_keys[ev.code]; } // get key state switch (ev.value) { case 0: state = S_OFF ; break; case 1: state = S_ON ; break; case 2: state = S_HOLD; break; } if (not key.empty() and state != S_NONE) { if (state == S_ON or state == S_HOLD) { // on, hold if (key == rsh or key == lsh) // shift is_modifier_key = shift_state = true; else if (key == ral or key == lal) // alt is_modifier_key = alt_state = true; else if (key == rct or key == lct) // ctrl is_modifier_key = ctrl_state = true; } else { // off if (key == rsh or key == lsh) // shift shift_state = false; else if (key == ral or key == lal) // alt alt_state = false; else if (key == rct or key == lct) // ctrl ctrl_state = false; } // output if (not is_modifier_key and state == S_ON) { if (shift_state) { if (shift_key != key) key = shift_key; else output << "shf_"; } if (ctrl_state) output << "ctl_"; if (alt_state) output << "alt_"; output << key << std::endl; } } else { printf("key %i state %i\n", ev.code, ev.value); } } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2014 David Wicks, sansumbrella.com * 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. * * 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 * HOLDER 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. */ #pragma once namespace choreograph { // A motion describes a one-dimensional change through time. // These can be ease equations, always return the same value, or sample some data. Whatever you want. // For classic motion, EaseFn( 0 ) = 0, EaseFn( 1 ) = 1. // set( 0.0f ).move( ) // then again, might just make a curve struct that is callable and have a way to set its initial and final derivatives. typedef std::function<float (float)> EaseFn; struct Hold { float operator() ( float t ) const { return 0.0f; } }; struct LinearRamp { float operator() ( float t ) const { return t; } }; //! A Position describes a point in time. template<typename T> struct Position { T value; float time; }; //! The default templated lerp function. template<typename T> T lerpT( const T &a, const T &b, float t ) { return a + (b - a) * t; } /** A Phrase is a part of a Sequence. It describes the motion between two positions. This is the essence of a Tween, with all values held internally. */ template<typename T> struct Phrase { Position<T> start; Position<T> end; EaseFn motion; std::function<T (const T&, const T&, float)> lerpFn = &lerpT<T>; T getValue( float atTime ) const { float t = (atTime - start.time) / (end.time - start.time); return lerpFn( start.value, end.value, motion( t ) ); } }; /** Phrase with separately-interpolated components. Allows for the use of separate ease functions per component. */ template<typename T> struct Phrase2 { Position<T> start; Position<T> end; using ComponentT = decltype( std::declval<T>().x ); std::function<ComponentT (const ComponentT&, const ComponentT&, float)> lerpFn = &lerpT<ComponentT>; EaseFn motion1; EaseFn motion2; T getValue( float atTime ) const { float t = (atTime - start.time) / (end.time - start.time); return T( lerpFn( start.value.x, end.value.x, motion1( t ) ), lerpFn( start.value.y, end.value.y, motion2( t ) ) ); } }; /** A Sequence of motions. Our essential compositional tool, describing all the transformations to one element. A kind of platonic idea of an animation sequence; this describes a motion without giving it an output. */ template<typename T> class Sequence { public: Sequence() = delete; //! Construct a Sequence with \a value initial value. explicit Sequence( const T &value ): _initial_value( value ) {} T getValue( float atTime ); //! Set current value. An instantaneous hold. Sequence<T>& set( const T &value ) { if( _segments.empty() ) { _initial_value = value; } else { hold( value, 0.0f ); } return *this; } //! Returns a copy of this sequence. Useful if you want to make a base animation and modify that. std::shared_ptr<Sequence<T>> copy() const { return std::make_shared<Sequence<T>>( *this ); } //! Hold on current end value for \a duration seconds. Sequence<T>& wait( float duration ) { return hold( duration ); } //! Hold on current end value for \a duration seconds. Sequence<T>& hold( float duration ) { return hold( endValue(), duration ); } //! Hold on \a value for \a duration seconds. Sequence<T>& hold( const T &value, float duration ) { Phrase<T> s; s.start = Position<T>{ value, _duration }; s.end = Position<T>{ value, _duration + duration }; s.motion = Hold(); _segments.push_back( s ); _duration += duration; return *this; } //! Animate to \a value over \a duration seconds using \a ease easing. Sequence<T>& rampTo( const T &value, float duration, const EaseFn &ease = LinearRamp() ) { Phrase<T> s; s.start = Position<T>{ endValue(), _duration }; s.end = Position<T>{ value, _duration + duration }; s.motion = ease; _segments.push_back( s ); _duration += duration; return *this; } //! Sets the ease function of the last Phrase in the Sequence. Sequence<T>& ease( const EaseFn &easeFn ) { if( ! _segments.empty() ) { _segments.back().motion = easeFn; } return *this; } //! Returns the number of seconds required to move through all Phrases. float getDuration() const { return _duration; } //! Returns the value at the end of the Sequence. T endValue() const { return _segments.empty() ? _initial_value : _segments.back().end.value; } //! Returns the value at the beginning of the Sequence. T initialValue() const { return _initial_value; } private: std::vector<Phrase<T>> _segments; T _initial_value; float _duration = 0.0f; friend class Timeline; }; //! Returns the value of this sequence for a given point in time. // Would be nice to have a constant-time check (without a while loop). template<typename T> T Sequence<T>::getValue( float atTime ) { if( atTime < 0.0f ) { return _initial_value; } else if ( atTime >= _duration ) { return endValue(); } auto iter = _segments.begin(); while( iter < _segments.end() ) { if( (*iter).end.time > atTime ) { return (*iter).getValue( atTime ); } ++iter; } // past the end, get the final value // this should be unreachable, given that we return early if time >= duration return endValue(); } template<typename T> using SequenceRef = std::shared_ptr<Sequence<T>>; } // namespace choreograph <commit_msg>Note on what decltype( declval ) does.<commit_after>/* * Copyright (c) 2014 David Wicks, sansumbrella.com * 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. * * 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 * HOLDER 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. */ #pragma once namespace choreograph { // A motion describes a one-dimensional change through time. // These can be ease equations, always return the same value, or sample some data. Whatever you want. // For classic motion, EaseFn( 0 ) = 0, EaseFn( 1 ) = 1. // set( 0.0f ).move( ) // then again, might just make a curve struct that is callable and have a way to set its initial and final derivatives. typedef std::function<float (float)> EaseFn; struct Hold { float operator() ( float t ) const { return 0.0f; } }; struct LinearRamp { float operator() ( float t ) const { return t; } }; //! A Position describes a point in time. template<typename T> struct Position { T value; float time; }; //! The default templated lerp function. template<typename T> T lerpT( const T &a, const T &b, float t ) { return a + (b - a) * t; } /** A Phrase is a part of a Sequence. It describes the motion between two positions. This is the essence of a Tween, with all values held internally. */ template<typename T> struct Phrase { Position<T> start; Position<T> end; EaseFn motion; std::function<T (const T&, const T&, float)> lerpFn = &lerpT<T>; T getValue( float atTime ) const { float t = (atTime - start.time) / (end.time - start.time); return lerpFn( start.value, end.value, motion( t ) ); } }; /** Phrase with separately-interpolated components. Allows for the use of separate ease functions per component. */ template<typename T> struct Phrase2 { Position<T> start; Position<T> end; using ComponentT = decltype( std::declval<T>().x ); // get the type of T thing.x; std::function<ComponentT (const ComponentT&, const ComponentT&, float)> lerpFn = &lerpT<ComponentT>; EaseFn motion1; EaseFn motion2; T getValue( float atTime ) const { float t = (atTime - start.time) / (end.time - start.time); return T( lerpFn( start.value.x, end.value.x, motion1( t ) ), lerpFn( start.value.y, end.value.y, motion2( t ) ) ); } }; /** A Sequence of motions. Our essential compositional tool, describing all the transformations to one element. A kind of platonic idea of an animation sequence; this describes a motion without giving it an output. */ template<typename T> class Sequence { public: Sequence() = delete; //! Construct a Sequence with \a value initial value. explicit Sequence( const T &value ): _initial_value( value ) {} T getValue( float atTime ); //! Set current value. An instantaneous hold. Sequence<T>& set( const T &value ) { if( _segments.empty() ) { _initial_value = value; } else { hold( value, 0.0f ); } return *this; } //! Returns a copy of this sequence. Useful if you want to make a base animation and modify that. std::shared_ptr<Sequence<T>> copy() const { return std::make_shared<Sequence<T>>( *this ); } //! Hold on current end value for \a duration seconds. Sequence<T>& wait( float duration ) { return hold( duration ); } //! Hold on current end value for \a duration seconds. Sequence<T>& hold( float duration ) { return hold( endValue(), duration ); } //! Hold on \a value for \a duration seconds. Sequence<T>& hold( const T &value, float duration ) { Phrase<T> s; s.start = Position<T>{ value, _duration }; s.end = Position<T>{ value, _duration + duration }; s.motion = Hold(); _segments.push_back( s ); _duration += duration; return *this; } //! Animate to \a value over \a duration seconds using \a ease easing. Sequence<T>& rampTo( const T &value, float duration, const EaseFn &ease = LinearRamp() ) { Phrase<T> s; s.start = Position<T>{ endValue(), _duration }; s.end = Position<T>{ value, _duration + duration }; s.motion = ease; _segments.push_back( s ); _duration += duration; return *this; } //! Sets the ease function of the last Phrase in the Sequence. Sequence<T>& ease( const EaseFn &easeFn ) { if( ! _segments.empty() ) { _segments.back().motion = easeFn; } return *this; } //! Returns the number of seconds required to move through all Phrases. float getDuration() const { return _duration; } //! Returns the value at the end of the Sequence. T endValue() const { return _segments.empty() ? _initial_value : _segments.back().end.value; } //! Returns the value at the beginning of the Sequence. T initialValue() const { return _initial_value; } private: std::vector<Phrase<T>> _segments; T _initial_value; float _duration = 0.0f; friend class Timeline; }; //! Returns the value of this sequence for a given point in time. // Would be nice to have a constant-time check (without a while loop). template<typename T> T Sequence<T>::getValue( float atTime ) { if( atTime < 0.0f ) { return _initial_value; } else if ( atTime >= _duration ) { return endValue(); } auto iter = _segments.begin(); while( iter < _segments.end() ) { if( (*iter).end.time > atTime ) { return (*iter).getValue( atTime ); } ++iter; } // past the end, get the final value // this should be unreachable, given that we return early if time >= duration return endValue(); } template<typename T> using SequenceRef = std::shared_ptr<Sequence<T>>; } // namespace choreograph <|endoftext|>
<commit_before>// // Copyright (C) 2006-2015 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Scott Zuk // szuk AT telusplanet DOT net ////////////////////////////////////////////////////////////////////////////// #include <sipxunittests.h> #include <os/OsDefs.h> #include <os/OsTimerTask.h> #include <os/OsProcess.h> #include <os/OsNatAgentTask.h> #include <net/SipMessage.h> #include <net/SipUserAgent.h> #include <net/SipLineMgr.h> #include <net/SipRefreshMgr.h> #include <net/SipMessageEvent.h> #define SHUTDOWN_TEST_ITERATIONS 3 /** * Unittest for SipUserAgent */ class SipUserAgentTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(SipUserAgentTest); CPPUNIT_TEST(testRefreshMgrTimeouts); CPPUNIT_TEST(testShutdownBlocking); CPPUNIT_TEST(testShutdownNonBlocking); CPPUNIT_TEST_SUITE_END(); public: // OsProcess doesn't provide any thread info so this method returns // the number of threads running under the process given by PID. // FIXME: Only implemented for linux, always returns 1 otherwise. int getNumThreads( int PID ) { int numThreads = 1; #ifdef __linux__ // /proc parsing stolen from OsProcessIteratorLinux.cpp OsStatus retval = OS_FAILED; char pidString[20]; snprintf(pidString, 20, "%d", PID); OsPath fullProcName = "/proc/"; fullProcName += pidString; fullProcName += "/status"; OsFileLinux procFile(fullProcName); if (procFile.open(OsFile::READ_ONLY) == OS_SUCCESS) { long len = 5000; //since the length is always 0 for these files, lets try to read 5k char *buffer = new char[len+1]; if (buffer) { unsigned long bytesRead; procFile.read((void *)buffer,(unsigned long)len,bytesRead); if (bytesRead) { procFile.close(); //null-terminate the string buffer[bytesRead] = 0; //now parse the info we need char *ptr = strtok(buffer,"\n"); while(ptr) { if (memcmp(ptr,"Threads:",8) == 0) { numThreads = atoi(ptr+8); } ptr = strtok(NULL,"\n"); } //say we are successful retval = OS_SUCCESS; } else osPrintf("Couldn't read bytes in readProcFile\n"); delete [] buffer; } procFile.close(); } #endif return numThreads; } void testRefreshMgrTimeouts() { int myPID = OsProcess::getCurrentPID(); int startingThreads; // Stop TimerTask and NatAgentTask before counting threads. // Some tests do not bother stopping them, so they may come started. OsTimerTask::destroyTimerTask(); OsNatAgentTask::releaseInstance(); // Count number of threads now. startingThreads = getNumThreads(myPID); for(int i = 0; i < 1; ++i) { // Limit life time of lineMgr and refreshMgr. They should be freed // before releasing OsNatAgentTask instance, or we will crash. { SipLineMgr regLineMgr; regLineMgr.StartLineMgr(); SipUserAgent sipRegistrar( 5099 ,5099 ,5098 ,NULL // default publicAddress ,NULL // default defaultUser ,"127.0.0.1" // default defaultSipAddress ,NULL // default sipProxyServers ,NULL // default sipDirectoryServers ,NULL // default sipRegistryServers ,NULL // default authenticationScheme ,NULL // default authenicateRealm ,NULL // default authenticateDb ,NULL // default authorizeUserIds ,NULL // default authorizePasswords ,&regLineMgr // No lineMgr needed for registrar ); sipRegistrar.start(); OsMsgQ messageQueue; sipRegistrar.addMessageObserver(messageQueue); SipLineMgr lineMgr; SipRefreshMgr refreshMgr; lineMgr.StartLineMgr(); lineMgr.initializeRefreshMgr( &refreshMgr ); SipUserAgent sipUA( 5090 ,5090 ,5091 ,NULL // default publicAddress ,NULL // default defaultUser ,"127.0.0.1" // default defaultSipAddress ,NULL // default sipProxyServers ,NULL // default sipDirectoryServers ,NULL // default sipRegistryServers ,NULL // default authenticationScheme ,NULL // default authenicateRealm ,NULL // default authenticateDb ,NULL // default authorizeUserIds ,NULL // default authorizePasswords ,&lineMgr ); sipUA.start(); refreshMgr.init(&sipUA); // Wait and give time for SIP UA and other tasks to start refreshMgr.StartRefreshMgr(); // Set a short refresh period so we can run the test faster refreshMgr.setRegistryPeriod(15); // seconds // Add a line and have it register const char* realm = "sipXtackUnitTest"; const char* userId = "foo"; const char* uriString = "sip:foo@127.0.0.1:5099"; SipLine line(uriString, uriString, userId); line.addCredentials(realm, userId, "password", HTTP_DIGEST_AUTHENTICATION); lineMgr.addLine(line, FALSE); // add disabled lineMgr.setStateForLine(uriString, SipLine::LINE_STATE_PROVISIONED); lineMgr.enableLine(uriString); // Wait for the first registration OsTime regTimeout(5, 0); OsMsg* appMessagePtr = NULL; printf("waiting for initial reg\n"); OsStatus messageStatus = messageQueue.receive(appMessagePtr, regTimeout); printf("got reg\n"); CPPUNIT_ASSERT_EQUAL(messageStatus, OS_SUCCESS); CPPUNIT_ASSERT(messageStatus); CPPUNIT_ASSERT_EQUAL(appMessagePtr->getMsgType(), OsMsg::PHONE_APP); SipMessage* sipMessage = (SipMessage*)((SipMessageEvent*)appMessagePtr)->getMessage(); CPPUNIT_ASSERT(sipMessage); CPPUNIT_ASSERT(!sipMessage->isResponse()); { SipMessage response; response.setRequestUnauthorized(sipMessage, HTTP_DIGEST_AUTHENTICATION, // scheme realm, "111wwwsipx", // nonce ""); // opaque sipRegistrar.send(response); printf("sent reg\n"); } printf("waiting for reg with auth\n"); messageStatus = messageQueue.receive(appMessagePtr, regTimeout); printf("got re-reg\n"); CPPUNIT_ASSERT_EQUAL(messageStatus, OS_SUCCESS); CPPUNIT_ASSERT(messageStatus); CPPUNIT_ASSERT_EQUAL(appMessagePtr->getMsgType(), OsMsg::PHONE_APP); sipMessage = (SipMessage*)((SipMessageEvent*)appMessagePtr)->getMessage(); CPPUNIT_ASSERT(sipMessage); CPPUNIT_ASSERT(!sipMessage->isResponse()); { SipMessage response; response.setOkResponseData(sipMessage); sipRegistrar.send(response); printf("sent reg\n"); } // Wait a bit to be sure response was sent OsTask::delay(200); // Now shutdown so the rest of the REGISTER refreshes don't get received. printf("shutting down reg\n"); sipRegistrar.removeMessageObserver(messageQueue); sipRegistrar.shutdown(TRUE); regLineMgr.requestShutdown(); printf("reg shutdown\n"); // Wait long enough for several REGISTER timeouts/retansmits and refreshes to occur OsTask::delay(100000); // 100 seconds // Shut down the tasks in reverse order. refreshMgr.requestShutdown(); sipUA.shutdown(TRUE); lineMgr.requestShutdown(); CPPUNIT_ASSERT(sipUA.isShutdownDone()); CPPUNIT_ASSERT(sipRegistrar.isShutdownDone()); } // Stop TimerTask and NatAgentTask again before counting threads. // They were started while testing. OsTimerTask::destroyTimerTask(); OsNatAgentTask::releaseInstance(); // Test to see that all the threads created by the above operations // get properly shut down. // Since the threads do not shut down synchronously with the above // calls, we have to wait before we know they will be cleared. OsTask::delay(1000); // 1 second int numThreads = getNumThreads(myPID); CPPUNIT_ASSERT_EQUAL(startingThreads,numThreads); } }; void testShutdownBlocking() { int myPID = OsProcess::getCurrentPID(); int startingThreads; // Stop TimerTask and NatAgentTask before counting threads. // Some tests do not bother stopping them, so they may come started. OsTimerTask::destroyTimerTask(); OsNatAgentTask::releaseInstance(); // Count number of threads now. startingThreads = getNumThreads(myPID); // Simple invite message from siptest/src/siptest/invite.txt const char* SimpleMessage = "INVITE sip:1@192.168.0.6 SIP/2.0\r\n" "Route: <sip:foo@192.168.0.4:5064;lr>\r\n" "From: <sip:888@10.1.1.144;user=phone>;tag=bbb\r\n" "To: <sip:3000@192.168.0.3:3000;user=phone>\r\n" "Call-Id: 8\r\n" "Cseq: 1 INVITE\r\n" "Content-Length: 0\r\n" "\r\n"; SipMessage testMsg( SimpleMessage, strlen( SimpleMessage ) ); for(int i = 0; i < SHUTDOWN_TEST_ITERATIONS; ++i) { // Limit life time of lineMgr and refreshMgr. They should be freed // before releasing OsNatAgentTask instance, or we will crash. { SipLineMgr lineMgr; SipRefreshMgr refreshMgr; lineMgr.StartLineMgr(); lineMgr.initializeRefreshMgr( &refreshMgr ); SipUserAgent sipUA( 5090 ,5090 ,5091 ,NULL // default publicAddress ,NULL // default defaultUser ,"127.0.0.1" // default defaultSipAddress ,NULL // default sipProxyServers ,NULL // default sipDirectoryServers ,NULL // default sipRegistryServers ,NULL // default authenticationScheme ,NULL // default authenicateRealm ,NULL // default authenticateDb ,NULL // default authorizeUserIds ,NULL // default authorizePasswords ,&lineMgr ); sipUA.start(); refreshMgr.init(&sipUA); sipUA.send(testMsg); // Wait long enough for some stack timeouts/retansmits to occur OsTask::delay(10000); // 10 seconds // Shut down the tasks in reverse order. refreshMgr.requestShutdown(); sipUA.shutdown(TRUE); lineMgr.requestShutdown(); CPPUNIT_ASSERT(sipUA.isShutdownDone()); } // Stop TimerTask and NatAgentTask again before counting threads. // They were started while testing. OsTimerTask::destroyTimerTask(); OsNatAgentTask::releaseInstance(); // Test to see that all the threads created by the above operations // get properly shut down. // Since the threads do not shut down synchronously with the above // calls, we have to wait before we know they will be cleared. OsTask::delay(1000); // 1 second int numThreads = getNumThreads(myPID); CPPUNIT_ASSERT_EQUAL(startingThreads,numThreads); } }; void testShutdownNonBlocking() { int myPID = OsProcess::getCurrentPID(); int startingThreads; // Stop TimerTask and NatAgentTask before counting threads. // Some tests do not bother stopping them, so they may come started. OsTimerTask::destroyTimerTask(); OsNatAgentTask::releaseInstance(); // Count number of threads now. startingThreads = getNumThreads(myPID); // Simple invite message from siptest/src/siptest/invite.txt const char* SimpleMessage = "INVITE sip:1@192.168.0.6 SIP/2.0\r\n" "Route: <sip:foo@192.168.0.4:5064;lr>\r\n" "From: <sip:888@10.1.1.144;user=phone>;tag=bbb\r\n" "To: <sip:3000@192.168.0.3:3000;user=phone>\r\n" "Call-Id: 8\r\n" "Cseq: 1 INVITE\r\n" "Content-Length: 0\r\n" "\r\n"; SipMessage testMsg( SimpleMessage, strlen( SimpleMessage ) ); for(int i = 0; i < SHUTDOWN_TEST_ITERATIONS; ++i) { // Limit life time of lineMgr and refreshMgr. They should be freed // before releasing OsNatAgentTask instance, or we will crash. { SipLineMgr lineMgr; SipRefreshMgr refreshMgr; lineMgr.StartLineMgr(); lineMgr.initializeRefreshMgr( &refreshMgr ); SipUserAgent sipUA( 5090 ,5090 ,5091 ,NULL // default publicAddress ,NULL // default defaultUser ,"127.0.0.1" // default defaultSipAddress ,NULL // default sipProxyServers ,NULL // default sipDirectoryServers ,NULL // default sipRegistryServers ,NULL // default authenticationScheme ,NULL // default authenicateRealm ,NULL // default authenticateDb ,NULL // default authorizeUserIds ,NULL // default authorizePasswords ,&lineMgr ); sipUA.start(); refreshMgr.init(&sipUA); sipUA.send(testMsg); // Wait long enough for some stack timeouts/retransmits to occur OsTask::delay(10000); // 10 seconds sipUA.shutdown(FALSE); lineMgr.requestShutdown(); refreshMgr.requestShutdown(); while(!sipUA.isShutdownDone()) { ; } CPPUNIT_ASSERT(sipUA.isShutdownDone()); } // Stop TimerTask and NatAgentTask again before counting threads. // They were started while testing. OsTimerTask::destroyTimerTask(); OsNatAgentTask::releaseInstance(); // Test to see that all the threads created by the above operations // get properly shut down. // Since the threads do not shut down synchronously with the above // calls, we have to wait before we know they will be cleared. OsTask::delay(1000); // 1 second int numThreads = getNumThreads(myPID); CPPUNIT_ASSERT_EQUAL(startingThreads,numThreads); } }; }; CPPUNIT_TEST_SUITE_REGISTRATION(SipUserAgentTest); <commit_msg>Removed unused var in SipUserAgentTest<commit_after>// // Copyright (C) 2006-2017 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Scott Zuk // szuk AT telusplanet DOT net ////////////////////////////////////////////////////////////////////////////// #include <sipxunittests.h> #include <os/OsDefs.h> #include <os/OsTimerTask.h> #include <os/OsProcess.h> #include <os/OsNatAgentTask.h> #include <net/SipMessage.h> #include <net/SipUserAgent.h> #include <net/SipLineMgr.h> #include <net/SipRefreshMgr.h> #include <net/SipMessageEvent.h> #define SHUTDOWN_TEST_ITERATIONS 3 /** * Unittest for SipUserAgent */ class SipUserAgentTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(SipUserAgentTest); CPPUNIT_TEST(testRefreshMgrTimeouts); CPPUNIT_TEST(testShutdownBlocking); CPPUNIT_TEST(testShutdownNonBlocking); CPPUNIT_TEST_SUITE_END(); public: // OsProcess doesn't provide any thread info so this method returns // the number of threads running under the process given by PID. // FIXME: Only implemented for linux, always returns 1 otherwise. int getNumThreads( int PID ) { int numThreads = 1; #ifdef __linux__ // /proc parsing stolen from OsProcessIteratorLinux.cpp char pidString[20]; snprintf(pidString, 20, "%d", PID); OsPath fullProcName = "/proc/"; fullProcName += pidString; fullProcName += "/status"; OsFileLinux procFile(fullProcName); if (procFile.open(OsFile::READ_ONLY) == OS_SUCCESS) { long len = 5000; //since the length is always 0 for these files, lets try to read 5k char *buffer = new char[len+1]; if (buffer) { unsigned long bytesRead; procFile.read((void *)buffer,(unsigned long)len,bytesRead); if (bytesRead) { procFile.close(); //null-terminate the string buffer[bytesRead] = 0; //now parse the info we need char *ptr = strtok(buffer,"\n"); while(ptr) { if (memcmp(ptr,"Threads:",8) == 0) { numThreads = atoi(ptr+8); } ptr = strtok(NULL,"\n"); } } else osPrintf("Couldn't read bytes in readProcFile\n"); delete [] buffer; } procFile.close(); } #endif return numThreads; } void testRefreshMgrTimeouts() { int myPID = OsProcess::getCurrentPID(); int startingThreads; // Stop TimerTask and NatAgentTask before counting threads. // Some tests do not bother stopping them, so they may come started. OsTimerTask::destroyTimerTask(); OsNatAgentTask::releaseInstance(); // Count number of threads now. startingThreads = getNumThreads(myPID); for(int i = 0; i < 1; ++i) { // Limit life time of lineMgr and refreshMgr. They should be freed // before releasing OsNatAgentTask instance, or we will crash. { SipLineMgr regLineMgr; regLineMgr.StartLineMgr(); SipUserAgent sipRegistrar( 5099 ,5099 ,5098 ,NULL // default publicAddress ,NULL // default defaultUser ,"127.0.0.1" // default defaultSipAddress ,NULL // default sipProxyServers ,NULL // default sipDirectoryServers ,NULL // default sipRegistryServers ,NULL // default authenticationScheme ,NULL // default authenicateRealm ,NULL // default authenticateDb ,NULL // default authorizeUserIds ,NULL // default authorizePasswords ,&regLineMgr // No lineMgr needed for registrar ); sipRegistrar.start(); OsMsgQ messageQueue; sipRegistrar.addMessageObserver(messageQueue); SipLineMgr lineMgr; SipRefreshMgr refreshMgr; lineMgr.StartLineMgr(); lineMgr.initializeRefreshMgr( &refreshMgr ); SipUserAgent sipUA( 5090 ,5090 ,5091 ,NULL // default publicAddress ,NULL // default defaultUser ,"127.0.0.1" // default defaultSipAddress ,NULL // default sipProxyServers ,NULL // default sipDirectoryServers ,NULL // default sipRegistryServers ,NULL // default authenticationScheme ,NULL // default authenicateRealm ,NULL // default authenticateDb ,NULL // default authorizeUserIds ,NULL // default authorizePasswords ,&lineMgr ); sipUA.start(); refreshMgr.init(&sipUA); // Wait and give time for SIP UA and other tasks to start refreshMgr.StartRefreshMgr(); // Set a short refresh period so we can run the test faster refreshMgr.setRegistryPeriod(15); // seconds // Add a line and have it register const char* realm = "sipXtackUnitTest"; const char* userId = "foo"; const char* uriString = "sip:foo@127.0.0.1:5099"; SipLine line(uriString, uriString, userId); line.addCredentials(realm, userId, "password", HTTP_DIGEST_AUTHENTICATION); lineMgr.addLine(line, FALSE); // add disabled lineMgr.setStateForLine(uriString, SipLine::LINE_STATE_PROVISIONED); lineMgr.enableLine(uriString); // Wait for the first registration OsTime regTimeout(5, 0); OsMsg* appMessagePtr = NULL; printf("waiting for initial reg\n"); OsStatus messageStatus = messageQueue.receive(appMessagePtr, regTimeout); printf("got reg\n"); CPPUNIT_ASSERT_EQUAL(messageStatus, OS_SUCCESS); CPPUNIT_ASSERT(messageStatus); CPPUNIT_ASSERT_EQUAL(appMessagePtr->getMsgType(), OsMsg::PHONE_APP); SipMessage* sipMessage = (SipMessage*)((SipMessageEvent*)appMessagePtr)->getMessage(); CPPUNIT_ASSERT(sipMessage); CPPUNIT_ASSERT(!sipMessage->isResponse()); { SipMessage response; response.setRequestUnauthorized(sipMessage, HTTP_DIGEST_AUTHENTICATION, // scheme realm, "111wwwsipx", // nonce ""); // opaque sipRegistrar.send(response); printf("sent reg\n"); } printf("waiting for reg with auth\n"); messageStatus = messageQueue.receive(appMessagePtr, regTimeout); printf("got re-reg\n"); CPPUNIT_ASSERT_EQUAL(messageStatus, OS_SUCCESS); CPPUNIT_ASSERT(messageStatus); CPPUNIT_ASSERT_EQUAL(appMessagePtr->getMsgType(), OsMsg::PHONE_APP); sipMessage = (SipMessage*)((SipMessageEvent*)appMessagePtr)->getMessage(); CPPUNIT_ASSERT(sipMessage); CPPUNIT_ASSERT(!sipMessage->isResponse()); { SipMessage response; response.setOkResponseData(sipMessage); sipRegistrar.send(response); printf("sent reg\n"); } // Wait a bit to be sure response was sent OsTask::delay(200); // Now shutdown so the rest of the REGISTER refreshes don't get received. printf("shutting down reg\n"); sipRegistrar.removeMessageObserver(messageQueue); sipRegistrar.shutdown(TRUE); regLineMgr.requestShutdown(); printf("reg shutdown\n"); // Wait long enough for several REGISTER timeouts/retansmits and refreshes to occur OsTask::delay(100000); // 100 seconds // Shut down the tasks in reverse order. refreshMgr.requestShutdown(); sipUA.shutdown(TRUE); lineMgr.requestShutdown(); CPPUNIT_ASSERT(sipUA.isShutdownDone()); CPPUNIT_ASSERT(sipRegistrar.isShutdownDone()); } // Stop TimerTask and NatAgentTask again before counting threads. // They were started while testing. OsTimerTask::destroyTimerTask(); OsNatAgentTask::releaseInstance(); // Test to see that all the threads created by the above operations // get properly shut down. // Since the threads do not shut down synchronously with the above // calls, we have to wait before we know they will be cleared. OsTask::delay(1000); // 1 second int numThreads = getNumThreads(myPID); CPPUNIT_ASSERT_EQUAL(startingThreads,numThreads); } }; void testShutdownBlocking() { int myPID = OsProcess::getCurrentPID(); int startingThreads; // Stop TimerTask and NatAgentTask before counting threads. // Some tests do not bother stopping them, so they may come started. OsTimerTask::destroyTimerTask(); OsNatAgentTask::releaseInstance(); // Count number of threads now. startingThreads = getNumThreads(myPID); // Simple invite message from siptest/src/siptest/invite.txt const char* SimpleMessage = "INVITE sip:1@192.168.0.6 SIP/2.0\r\n" "Route: <sip:foo@192.168.0.4:5064;lr>\r\n" "From: <sip:888@10.1.1.144;user=phone>;tag=bbb\r\n" "To: <sip:3000@192.168.0.3:3000;user=phone>\r\n" "Call-Id: 8\r\n" "Cseq: 1 INVITE\r\n" "Content-Length: 0\r\n" "\r\n"; SipMessage testMsg( SimpleMessage, strlen( SimpleMessage ) ); for(int i = 0; i < SHUTDOWN_TEST_ITERATIONS; ++i) { // Limit life time of lineMgr and refreshMgr. They should be freed // before releasing OsNatAgentTask instance, or we will crash. { SipLineMgr lineMgr; SipRefreshMgr refreshMgr; lineMgr.StartLineMgr(); lineMgr.initializeRefreshMgr( &refreshMgr ); SipUserAgent sipUA( 5090 ,5090 ,5091 ,NULL // default publicAddress ,NULL // default defaultUser ,"127.0.0.1" // default defaultSipAddress ,NULL // default sipProxyServers ,NULL // default sipDirectoryServers ,NULL // default sipRegistryServers ,NULL // default authenticationScheme ,NULL // default authenicateRealm ,NULL // default authenticateDb ,NULL // default authorizeUserIds ,NULL // default authorizePasswords ,&lineMgr ); sipUA.start(); refreshMgr.init(&sipUA); sipUA.send(testMsg); // Wait long enough for some stack timeouts/retansmits to occur OsTask::delay(10000); // 10 seconds // Shut down the tasks in reverse order. refreshMgr.requestShutdown(); sipUA.shutdown(TRUE); lineMgr.requestShutdown(); CPPUNIT_ASSERT(sipUA.isShutdownDone()); } // Stop TimerTask and NatAgentTask again before counting threads. // They were started while testing. OsTimerTask::destroyTimerTask(); OsNatAgentTask::releaseInstance(); // Test to see that all the threads created by the above operations // get properly shut down. // Since the threads do not shut down synchronously with the above // calls, we have to wait before we know they will be cleared. OsTask::delay(1000); // 1 second int numThreads = getNumThreads(myPID); CPPUNIT_ASSERT_EQUAL(startingThreads,numThreads); } }; void testShutdownNonBlocking() { int myPID = OsProcess::getCurrentPID(); int startingThreads; // Stop TimerTask and NatAgentTask before counting threads. // Some tests do not bother stopping them, so they may come started. OsTimerTask::destroyTimerTask(); OsNatAgentTask::releaseInstance(); // Count number of threads now. startingThreads = getNumThreads(myPID); // Simple invite message from siptest/src/siptest/invite.txt const char* SimpleMessage = "INVITE sip:1@192.168.0.6 SIP/2.0\r\n" "Route: <sip:foo@192.168.0.4:5064;lr>\r\n" "From: <sip:888@10.1.1.144;user=phone>;tag=bbb\r\n" "To: <sip:3000@192.168.0.3:3000;user=phone>\r\n" "Call-Id: 8\r\n" "Cseq: 1 INVITE\r\n" "Content-Length: 0\r\n" "\r\n"; SipMessage testMsg( SimpleMessage, strlen( SimpleMessage ) ); for(int i = 0; i < SHUTDOWN_TEST_ITERATIONS; ++i) { // Limit life time of lineMgr and refreshMgr. They should be freed // before releasing OsNatAgentTask instance, or we will crash. { SipLineMgr lineMgr; SipRefreshMgr refreshMgr; lineMgr.StartLineMgr(); lineMgr.initializeRefreshMgr( &refreshMgr ); SipUserAgent sipUA( 5090 ,5090 ,5091 ,NULL // default publicAddress ,NULL // default defaultUser ,"127.0.0.1" // default defaultSipAddress ,NULL // default sipProxyServers ,NULL // default sipDirectoryServers ,NULL // default sipRegistryServers ,NULL // default authenticationScheme ,NULL // default authenicateRealm ,NULL // default authenticateDb ,NULL // default authorizeUserIds ,NULL // default authorizePasswords ,&lineMgr ); sipUA.start(); refreshMgr.init(&sipUA); sipUA.send(testMsg); // Wait long enough for some stack timeouts/retransmits to occur OsTask::delay(10000); // 10 seconds sipUA.shutdown(FALSE); lineMgr.requestShutdown(); refreshMgr.requestShutdown(); while(!sipUA.isShutdownDone()) { ; } CPPUNIT_ASSERT(sipUA.isShutdownDone()); } // Stop TimerTask and NatAgentTask again before counting threads. // They were started while testing. OsTimerTask::destroyTimerTask(); OsNatAgentTask::releaseInstance(); // Test to see that all the threads created by the above operations // get properly shut down. // Since the threads do not shut down synchronously with the above // calls, we have to wait before we know they will be cleared. OsTask::delay(1000); // 1 second int numThreads = getNumThreads(myPID); CPPUNIT_ASSERT_EQUAL(startingThreads,numThreads); } }; }; CPPUNIT_TEST_SUITE_REGISTRATION(SipUserAgentTest); <|endoftext|>
<commit_before>#include <QtGui/QPainter> #include <QtWidgets/QStyle> #include <QtWidgets/QStyleOptionGraphicsItem> #include <qrkernel/settingsManager.h> #include "lineItem.h" #include "wallItem.h" using namespace twoDModel::items; using namespace qReal; using namespace graphicsUtils; LineItem::LineItem(QPointF const &begin, QPointF const &end, int cornerRadius) : mLineImpl() , mCornerRadius(cornerRadius) , mCellNumbX1(0) , mCellNumbY1(0) , mCellNumbX2(0) , mCellNumbY2(0) { mX1 = begin.x(); mY1 = begin.y(); mX2 = end.x(); mY2 = end.y(); setFlags(ItemIsSelectable | ItemIsMovable); setPrivateData(); } void LineItem::setPrivateData() { mPen.setColor(Qt::green); mPen.setStyle(Qt::SolidLine); mSerializeName = "line"; } QRectF LineItem::boundingRect() const { return mLineImpl.boundingRect(mX1, mY1, mX2, mY2, mPen.width(), drift); } void LineItem::drawItem(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { Q_UNUSED(option); Q_UNUSED(widget); mLineImpl.drawItem(painter, mX1, mY1, mX2, mY2); } void LineItem::drawExtractionForItem(QPainter* painter) { mLineImpl.drawPointExtractionForItem(painter, mX1, mY1, mX2, mY2); setPenBrushDriftRect(painter); mLineImpl.drawExtractionForItem(painter, mX1, mY1, mX2, mY2, drift); mLineImpl.drawFieldForResizeItem(painter, resizeDrift, mX1, mY1, mX2, mY2); painter->setPen(QPen(Qt::red)); painter->setBrush(QBrush(Qt::SolidPattern)); } QPainterPath LineItem::shape() const { return mLineImpl.shape(drift, mX1, mY1, mX2, mY2); } void LineItem::resizeItem(QGraphicsSceneMouseEvent *event) { if (event->modifiers() & Qt::ShiftModifier) { mX2=event->scenePos().x(); mY2=event->scenePos().y(); reshapeRectWithShift(); } else { if (SettingsManager::value("2dShowGrid").toBool() && (mDragState == TopLeft || mDragState == BottomRight) && dynamic_cast<WallItem *>(this)) { calcResizeItem(event, SettingsManager::value("2dGridCellSize").toInt()); } else { if (mDragState == TopLeft || mDragState == BottomRight) { AbstractItem::resizeItem(event); } else { setFlag(QGraphicsItem::ItemIsMovable, true); } } } } void LineItem::calcResizeItem(QGraphicsSceneMouseEvent *event, int indexGrid) { qreal const x = mapFromScene(event->scenePos()).x(); qreal const y = mapFromScene(event->scenePos()).y(); if (mDragState != None) { setFlag(QGraphicsItem::ItemIsMovable, false); } if (mDragState == TopLeft) { mX1 = x; mY1 = y; resizeBeginWithGrid(indexGrid); } else if (mDragState == BottomRight) { mX2 = x; mY2 = y; reshapeEndWithGrid(indexGrid); } } void LineItem::reshapeRectWithShift() { qreal differenceX = abs(mX2 - mX1); qreal differenceY = abs(mY2 - mY1); qreal differenceXY = abs(differenceX - differenceY); qreal size = qMax(differenceX, differenceY); const int delta = size / 2; if (differenceXY > delta) { QPair<qreal, qreal> res = mLineImpl.reshapeRectWithShiftForLine(mX1, mY1, mX2, mY2, differenceX, differenceY, size); setX2andY2(res.first, res.second); } else AbstractItem::reshapeRectWithShift(); } void LineItem::resizeBeginWithGrid(int indexGrid) { int const coefX = static_cast<int>(mX1) / indexGrid; int const coefY = static_cast<int>(mY1) / indexGrid; if (qAbs(mY2 - mY1) > qAbs(mX2 - mX1)) { setX1andY1(mX2, alignedCoordinate(mY1, coefY, indexGrid)); } else { setX1andY1(alignedCoordinate(mX1, coefX, indexGrid), mY2); } mCellNumbX1 = mX1 / indexGrid; mCellNumbY1 = mY1 / indexGrid; } void LineItem::reshapeEndWithGrid(int indexGrid) { int const coefX = static_cast<int>(mX2) / indexGrid; int const coefY = static_cast<int>(mY2) / indexGrid; if (qAbs(mY2 - mY1) > qAbs(mX2 - mX1)) { setX2andY2(mX1, alignedCoordinate(mY2, coefY, indexGrid)); } else { setX2andY2(alignedCoordinate(mX2, coefX, indexGrid), mY1); } mCellNumbX2 = mX2 / indexGrid; mCellNumbY2 = mY2 / indexGrid; } void LineItem::reshapeBeginWithGrid(int indexGrid) { int const coefX = static_cast<int> (mX1) / indexGrid; int const coefY = static_cast<int> (mY1) / indexGrid; setX1andY1(alignedCoordinate(mX1, coefX, indexGrid), alignedCoordinate(mY1, coefY, indexGrid)); mCellNumbX1 = mX1 / indexGrid; mCellNumbY1 = mY1 / indexGrid; } void LineItem::alignTheWall(int indexGrid) { countCellNumbCoordinates(indexGrid); setBeginCoordinatesWithGrid(indexGrid); setEndCoordinatesWithGrid(indexGrid); } void LineItem::countCellNumbCoordinates(int indexGrid) { mCellNumbX1 = mX1 / indexGrid; mCellNumbY1 = mY1 / indexGrid; if (qAbs(mY2 - mY1) > qAbs(mX2 - mX1)) { mCellNumbX2 = mCellNumbX1; mCellNumbY2 = mY2 / indexGrid; } else { mCellNumbX2 = mX2 / indexGrid; mCellNumbY2 = mCellNumbY1; } } void LineItem::setBeginCoordinatesWithGrid(int indexGrid) { setX1andY1(mCellNumbX1 * indexGrid, mCellNumbY1 * indexGrid); } void LineItem::setEndCoordinatesWithGrid(int indexGrid) { setX2andY2(mCellNumbX2 * indexGrid, mCellNumbY2 * indexGrid); } void LineItem::setDraggedEnd(qreal x, qreal y) { setX2andY2(mX1 - x, mY1 - y); } qreal LineItem::alignedCoordinate(qreal coord, int coef, int const indexGrid) const { int const coefSign = coef ? coef / qAbs(coef) : 0; if (qAbs(qAbs(coord) - qAbs(coef) * indexGrid) <= indexGrid / 2) { return coef * indexGrid; } else if (qAbs(qAbs(coord) - (qAbs(coef) + 1) * indexGrid) <= indexGrid / 2) { return (coef + coefSign) * indexGrid; } return coord; } QDomElement LineItem::serialize(QDomDocument &document, QPoint const &topLeftPicture) { QDomElement lineNode = setPenBrushToDoc(document, mSerializeName); lineNode.setAttribute("begin", QString::number(mX1 + scenePos().x() - topLeftPicture.x()) + ":" + QString::number(mY1 + scenePos().y() - topLeftPicture.y())); lineNode.setAttribute("end", QString::number(mX2 + scenePos().x() - topLeftPicture.x()) + ":" + QString::number(mY2 + scenePos().y() - topLeftPicture.y())); return lineNode; } void LineItem::deserialize(QDomElement const &element) { QString const beginStr = element.attribute("begin", "0:0"); QStringList splittedStr = beginStr.split(":"); int x = splittedStr[0].toInt(); int y = splittedStr[1].toInt(); QPointF const begin = QPointF(x, y); QString const endStr = element.attribute("end", "0:0"); splittedStr = endStr.split(":"); x = splittedStr[0].toInt(); y = splittedStr[1].toInt(); QPointF const end = QPointF(x, y); mX1 = begin.x(); mY1 = begin.y(); mX2 = end.x(); mY2 = end.y(); deserializePenBrush(element); } void LineItem::deserializePenBrush(QDomElement const &element) { readPenBrush(element); } void LineItem::setSerializeName(QString const &name) { mSerializeName = name; } <commit_msg>diagonal walls<commit_after>#include <QtGui/QPainter> #include <QtWidgets/QStyle> #include <QtWidgets/QStyleOptionGraphicsItem> #include <qrkernel/settingsManager.h> #include "lineItem.h" #include "wallItem.h" using namespace twoDModel::items; using namespace qReal; using namespace graphicsUtils; LineItem::LineItem(QPointF const &begin, QPointF const &end, int cornerRadius) : mLineImpl() , mCornerRadius(cornerRadius) , mCellNumbX1(0) , mCellNumbY1(0) , mCellNumbX2(0) , mCellNumbY2(0) { mX1 = begin.x(); mY1 = begin.y(); mX2 = end.x(); mY2 = end.y(); setFlags(ItemIsSelectable | ItemIsMovable); setPrivateData(); } void LineItem::setPrivateData() { mPen.setColor(Qt::green); mPen.setStyle(Qt::SolidLine); mSerializeName = "line"; } QRectF LineItem::boundingRect() const { return mLineImpl.boundingRect(mX1, mY1, mX2, mY2, mPen.width(), drift); } void LineItem::drawItem(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { Q_UNUSED(option); Q_UNUSED(widget); mLineImpl.drawItem(painter, mX1, mY1, mX2, mY2); } void LineItem::drawExtractionForItem(QPainter* painter) { mLineImpl.drawPointExtractionForItem(painter, mX1, mY1, mX2, mY2); setPenBrushDriftRect(painter); mLineImpl.drawExtractionForItem(painter, mX1, mY1, mX2, mY2, drift); mLineImpl.drawFieldForResizeItem(painter, resizeDrift, mX1, mY1, mX2, mY2); painter->setPen(QPen(Qt::red)); painter->setBrush(QBrush(Qt::SolidPattern)); } QPainterPath LineItem::shape() const { return mLineImpl.shape(drift, mX1, mY1, mX2, mY2); } void LineItem::resizeItem(QGraphicsSceneMouseEvent *event) { if (event->modifiers() & Qt::ShiftModifier) { mX2=event->scenePos().x(); mY2=event->scenePos().y(); reshapeRectWithShift(); } else { if (SettingsManager::value("2dShowGrid").toBool() && (mDragState == TopLeft || mDragState == BottomRight) && dynamic_cast<WallItem *>(this)) { calcResizeItem(event, SettingsManager::value("2dGridCellSize").toInt()); } else { if (mDragState == TopLeft || mDragState == BottomRight) { AbstractItem::resizeItem(event); } else { setFlag(QGraphicsItem::ItemIsMovable, true); } } } } void LineItem::calcResizeItem(QGraphicsSceneMouseEvent *event, int indexGrid) { qreal const x = mapFromScene(event->scenePos()).x(); qreal const y = mapFromScene(event->scenePos()).y(); if (mDragState != None) { setFlag(QGraphicsItem::ItemIsMovable, false); } if (mDragState == TopLeft) { mX1 = x; mY1 = y; resizeBeginWithGrid(indexGrid); } else if (mDragState == BottomRight) { mX2 = x; mY2 = y; reshapeEndWithGrid(indexGrid); } } void LineItem::reshapeRectWithShift() { qreal differenceX = abs(mX2 - mX1); qreal differenceY = abs(mY2 - mY1); qreal differenceXY = abs(differenceX - differenceY); qreal size = qMax(differenceX, differenceY); const int delta = size / 2; if (differenceXY > delta) { QPair<qreal, qreal> res = mLineImpl.reshapeRectWithShiftForLine(mX1, mY1, mX2, mY2, differenceX, differenceY, size); setX2andY2(res.first, res.second); } else AbstractItem::reshapeRectWithShift(); } void LineItem::resizeBeginWithGrid(int indexGrid) { int const coefX = static_cast<int>(mX1) / indexGrid; int const coefY = static_cast<int>(mY1) / indexGrid; if (qAbs(mY2 - mY1) > 2 * qAbs(mX2 - mX1)) { setX1andY1(mX2, alignedCoordinate(mY1, coefY, indexGrid)); } else if (qAbs(mY2 - mY1) < qAbs(mX2 - mX1) / 2) { setX1andY1(alignedCoordinate(mX1, coefX, indexGrid), mY2); } else { setX2andY2(alignedCoordinate(mX1, coefX, indexGrid), alignedCoordinate(mY1, coefY, indexGrid)); } mCellNumbX1 = mX1 / indexGrid; mCellNumbY1 = mY1 / indexGrid; } void LineItem::reshapeEndWithGrid(int indexGrid) { int const coefX = static_cast<int>(mX2) / indexGrid; int const coefY = static_cast<int>(mY2) / indexGrid; if (qAbs(mY2 - mY1) > 2 * qAbs(mX2 - mX1)) { setX2andY2(mX1, alignedCoordinate(mY2, coefY, indexGrid)); } else if (qAbs(mY2 - mY1) < qAbs(mX2 - mX1) / 2) { setX2andY2(alignedCoordinate(mX2, coefX, indexGrid), mY1); } else { setX2andY2(alignedCoordinate(mX2, coefX, indexGrid), alignedCoordinate(mY2, coefY, indexGrid)); } mCellNumbX2 = mX2 / indexGrid; mCellNumbY2 = mY2 / indexGrid; } void LineItem::reshapeBeginWithGrid(int indexGrid) { int const coefX = static_cast<int> (mX1) / indexGrid; int const coefY = static_cast<int> (mY1) / indexGrid; setX1andY1(alignedCoordinate(mX1, coefX, indexGrid), alignedCoordinate(mY1, coefY, indexGrid)); mCellNumbX1 = mX1 / indexGrid; mCellNumbY1 = mY1 / indexGrid; } void LineItem::alignTheWall(int indexGrid) { countCellNumbCoordinates(indexGrid); setBeginCoordinatesWithGrid(indexGrid); setEndCoordinatesWithGrid(indexGrid); } void LineItem::countCellNumbCoordinates(int indexGrid) { mCellNumbX1 = mX1 / indexGrid; mCellNumbY1 = mY1 / indexGrid; if (qAbs(mY2 - mY1) > qAbs(mX2 - mX1)) { mCellNumbX2 = mCellNumbX1; mCellNumbY2 = mY2 / indexGrid; } else { mCellNumbX2 = mX2 / indexGrid; mCellNumbY2 = mCellNumbY1; } } void LineItem::setBeginCoordinatesWithGrid(int indexGrid) { setX1andY1(mCellNumbX1 * indexGrid, mCellNumbY1 * indexGrid); } void LineItem::setEndCoordinatesWithGrid(int indexGrid) { setX2andY2(mCellNumbX2 * indexGrid, mCellNumbY2 * indexGrid); } void LineItem::setDraggedEnd(qreal x, qreal y) { setX2andY2(mX1 - x, mY1 - y); } qreal LineItem::alignedCoordinate(qreal coord, int coef, int const indexGrid) const { int const coefSign = coef ? coef / qAbs(coef) : 0; if (qAbs(qAbs(coord) - qAbs(coef) * indexGrid) <= indexGrid / 2) { return coef * indexGrid; } else if (qAbs(qAbs(coord) - (qAbs(coef) + 1) * indexGrid) <= indexGrid / 2) { return (coef + coefSign) * indexGrid; } return coord; } QDomElement LineItem::serialize(QDomDocument &document, QPoint const &topLeftPicture) { QDomElement lineNode = setPenBrushToDoc(document, mSerializeName); lineNode.setAttribute("begin", QString::number(mX1 + scenePos().x() - topLeftPicture.x()) + ":" + QString::number(mY1 + scenePos().y() - topLeftPicture.y())); lineNode.setAttribute("end", QString::number(mX2 + scenePos().x() - topLeftPicture.x()) + ":" + QString::number(mY2 + scenePos().y() - topLeftPicture.y())); return lineNode; } void LineItem::deserialize(QDomElement const &element) { QString const beginStr = element.attribute("begin", "0:0"); QStringList splittedStr = beginStr.split(":"); int x = splittedStr[0].toInt(); int y = splittedStr[1].toInt(); QPointF const begin = QPointF(x, y); QString const endStr = element.attribute("end", "0:0"); splittedStr = endStr.split(":"); x = splittedStr[0].toInt(); y = splittedStr[1].toInt(); QPointF const end = QPointF(x, y); mX1 = begin.x(); mY1 = begin.y(); mX2 = end.x(); mY2 = end.y(); deserializePenBrush(element); } void LineItem::deserializePenBrush(QDomElement const &element) { readPenBrush(element); } void LineItem::setSerializeName(QString const &name) { mSerializeName = name; } <|endoftext|>
<commit_before>#include <catch2/catch.hpp> #include <optional> #include <vector> struct Block { size_t offset; size_t size; operator bool() { return size != 0; } }; class TLSFAllocator { struct TLSFSizeClass { size_t sizeClass; uint64_t slBitmap; std::vector<std::vector<Block>> freeBlocks; }; struct TLSFControl { uint64_t flBitmap; std::vector<TLSFSizeClass> sizeclasses; }; unsigned fli; // first level index unsigned sli; // second level index, typically 5 unsigned sli_count; // second level index, typically 5 unsigned mbs; // minimum block size TLSFControl control; size_t m_size; int fls(uint64_t size) { unsigned long index; return _BitScanReverse64(&index, size) ? index : -1; } int ffs(uint64_t size) { unsigned long index; return _BitScanForward64(&index, size) ? index : -1; } void mapping(size_t size, unsigned& fl, unsigned& sl) { fl = fls(size); sl = ((size ^ (1 << fl)) >> (fl - sli)); // printf("%zu -> fl %u sl %u\n", size, fl, sl); } void initialize() { fli = ffs(m_size); sli = 5; sli_count = 1 << sli; mbs = 16; control.flBitmap = 0; for (int i = 0; i <= fli; ++i) { size_t sizeClass = 1 << i; std::vector<std::vector<Block>> vectors; for (int k = 0; k < sli; ++k) { vectors.push_back(std::vector<Block>()); } control.sizeclasses.push_back(TLSFSizeClass{sizeClass, 0, vectors}); } } void remove_bit(uint64_t& value, int index) { value = value & (~(1 << index)); } void set_bit(uint64_t& value, int index) { value |= (1 << index); } void insert(Block block, unsigned fl, unsigned sl) { auto& sizeClass = control.sizeclasses[fl]; auto& secondLv = sizeClass.freeBlocks[sl]; secondLv.push_back(block); set_bit(sizeClass.slBitmap, sl); set_bit(control.flBitmap, fl); } Block search_suitable_block(size_t size, unsigned fl, unsigned sl) { // first step, assume we got something at fl / sl location auto& sizeClass = control.sizeclasses[fl]; auto& secondLv = sizeClass.freeBlocks[sl]; if (!secondLv.empty() && sizeClass.sizeClass >= size) { auto block = secondLv.back(); secondLv.pop_back(); // remove bitmap bit if (secondLv.empty()) remove_bit(sizeClass.slBitmap, sl); if (sizeClass.slBitmap == 0) remove_bit(control.flBitmap, fl); return block; } else { // second step, scan bitmaps for empty slots auto mask = ~((1 << (fl + 1)) - 1); // create mask to ignore first bits, could be wrong auto fl2 = ffs(control.flBitmap & mask); if (fl2 >= 0) { auto& sizeClass2 = control.sizeclasses[fl2]; auto sl2 = ffs(sizeClass2.slBitmap); if (sl2 >= 0 && sizeClass2.sizeClass >= size) { assert(!sizeClass2.freeBlocks[sl2].empty()); auto block = sizeClass2.freeBlocks[sl2].back(); sizeClass2.freeBlocks[sl2].pop_back(); // remove bitmap bit if (sizeClass2.freeBlocks[sl2].empty()) remove_bit(sizeClass2.slBitmap, sl2); if (sizeClass2.slBitmap == 0) remove_bit(control.flBitmap, fl2); return block; } } } return {}; } Block split(Block& block) { auto new_size = block.size / 2; Block new_block = {block.offset + new_size, new_size}; block.size = new_size; return new_block; } Block merge(Block block) { // try to merge with some existing block??????????????? auto otf = block.offset; auto otf2 = block.offset + block.size; // BRUTEFORCE, we got not boundary tagging possible auto fl = 0; for (auto&& firstLevel : control.sizeclasses) { auto sl = 0; for (auto&& secondLevel : firstLevel.freeBlocks) { auto iter = std::find_if( secondLevel.begin(), secondLevel.end(), [otf, otf2](Block b) { return (b.offset + b.size == otf) || (b.offset == otf2); }); if (iter != secondLevel.end()) { auto rb = *iter; secondLevel.erase(iter); if (secondLevel.empty()) remove_bit(firstLevel.slBitmap, sl); if (firstLevel.slBitmap == 0) remove_bit(control.flBitmap, fl); if (rb.offset + rb.size == otf) { rb.size += block.size; return rb; } else if (rb.offset == otf2) { block.size += rb.size; return block; } } sl++; } fl++; } return block; } public: TLSFAllocator(size_t size) : m_size(size) { initialize(); unsigned fl, sl; mapping(size, fl, sl); insert({0, size}, fl, sl); } std::optional<Block> allocate(size_t size) { unsigned fl, sl, fl2, sl2; mapping(size, fl, sl); auto found_block = search_suitable_block(size, fl, sl); if (found_block) { while (found_block.size >= size * 2) { // oh no auto remaining_block = split(found_block); mapping(remaining_block.size, fl2, sl2); insert(remaining_block, fl2, sl2); // O(1) } return found_block; } return {}; } void free(Block block) { // immediately merge with existing free blocks. unsigned fl, sl; auto size = block.size; auto big_free_block = merge(block); while (big_free_block.size != size) { // Oh no, shitty thing size = big_free_block.size; big_free_block = merge(big_free_block); } mapping(big_free_block.size, fl, sl); insert(big_free_block, fl, sl); } }; TEST_CASE("some basic allocation tests") { TLSFAllocator tlsf(4); auto block = tlsf.allocate(5); REQUIRE_FALSE(block); block = tlsf.allocate(2); REQUIRE(block); if (block) { REQUIRE(block.value().size == 2); } tlsf.free(block.value()); block = tlsf.allocate(4); REQUIRE(block); if (block) { REQUIRE(block.value().size == 4); } tlsf.free(block.value()); block = tlsf.allocate(3); REQUIRE(block); if (block) { REQUIRE(block.value().size == 4); } tlsf.free(block.value()); block = tlsf.allocate(2); auto block2 = tlsf.allocate(2); REQUIRE(block); REQUIRE(block2); if (block && block2) { REQUIRE(block.value().size == 2); REQUIRE(block2.value().size == 2); } tlsf.free(block.value()); tlsf.free(block2.value()); block = tlsf.allocate(2); block2 = tlsf.allocate(1); REQUIRE(block); REQUIRE(block2); if (block && block2) { REQUIRE(block.value().size == 2); REQUIRE(block2.value().size == 1); } tlsf.free(block.value()); tlsf.free(block2.value()); auto block3 = tlsf.allocate(1); block = tlsf.allocate(2); block2 = tlsf.allocate(1); REQUIRE(block); REQUIRE(block2); REQUIRE(block3); if (block && block2 && block3) { REQUIRE(block.value().size == 2); REQUIRE(block2.value().size == 1); REQUIRE(block3.value().size == 1); } tlsf.free(block.value()); tlsf.free(block2.value()); tlsf.free(block3.value()); auto block4 = tlsf.allocate(1); block = tlsf.allocate(1); block2 = tlsf.allocate(1); block3 = tlsf.allocate(1); REQUIRE(block); REQUIRE(block2); REQUIRE(block3); REQUIRE(block4); if (block && block2 && block3 && block4) { REQUIRE(block.value().size == 1); REQUIRE(block2.value().size == 1); REQUIRE(block3.value().size == 1); REQUIRE(block4.value().size == 1); } tlsf.free(block.value()); tlsf.free(block2.value()); tlsf.free(block3.value()); tlsf.free(block4.value()); block = tlsf.allocate(4); REQUIRE(block); if (block) { REQUIRE(block.value().size == 4); } }<commit_msg>Cleaned up naming.<commit_after>#include <catch2/catch.hpp> #include <optional> #include <vector> struct Block { size_t offset; size_t size; operator bool() { return size != 0; } }; class TLSFAllocator { struct TLSFSizeClass { size_t sizeClass; uint64_t slBitmap; std::vector<std::vector<Block>> freeBlocks; }; struct TLSFControl { uint64_t flBitmap; std::vector<TLSFSizeClass> sizeclasses; }; unsigned fli; // first level index unsigned sli; // second level index, typically 5 unsigned sli_count; // second level index, typically 5 unsigned mbs; // minimum block size TLSFControl control; size_t m_size; int fls(uint64_t size) { unsigned long index; return _BitScanReverse64(&index, size) ? index : -1; } int ffs(uint64_t size) { unsigned long index; return _BitScanForward64(&index, size) ? index : -1; } void mapping(size_t size, unsigned& fl, unsigned& sl) { fl = fls(size); sl = ((size ^ (1 << fl)) >> (fl - sli)); // printf("%zu -> fl %u sl %u\n", size, fl, sl); } void initialize() { fli = ffs(m_size); sli = 5; sli_count = 1 << sli; mbs = 16; control.flBitmap = 0; for (int i = 0; i <= fli; ++i) { size_t sizeClass = 1 << i; std::vector<std::vector<Block>> vectors; for (int k = 0; k < sli; ++k) { vectors.push_back(std::vector<Block>()); } control.sizeclasses.push_back(TLSFSizeClass{sizeClass, 0, vectors}); } } void remove_bit(uint64_t& value, int index) { value = value & (~(1 << index)); } void set_bit(uint64_t& value, int index) { value |= (1 << index); } void insert(Block block, unsigned fl, unsigned sl) { auto& sizeClass = control.sizeclasses[fl]; auto& secondLv = sizeClass.freeBlocks[sl]; secondLv.push_back(block); set_bit(sizeClass.slBitmap, sl); set_bit(control.flBitmap, fl); } Block search_suitable_block(size_t size, unsigned fl, unsigned sl) { // first step, assume we got something at fl / sl location auto& secondLevel = control.sizeclasses[fl]; auto& freeblocks = secondLevel.freeBlocks[sl]; if (!freeblocks.empty() && secondLevel.sizeClass >= size) { auto block = freeblocks.back(); freeblocks.pop_back(); // remove bitmap bit if (freeblocks.empty()) remove_bit(secondLevel.slBitmap, sl); if (secondLevel.slBitmap == 0) remove_bit(control.flBitmap, fl); return block; } else { // second step, scan bitmaps for empty slots // create mask to ignore first bits, could be wrong auto mask = ~((1 << (fl + 1)) - 1); auto fl2 = ffs(control.flBitmap & mask); if (fl2 >= 0) { auto& secondLevel2 = control.sizeclasses[fl2]; auto sl2 = ffs(secondLevel2.slBitmap); if (sl2 >= 0 && secondLevel2.sizeClass >= size) { assert(!secondLevel2.freeBlocks[sl2].empty()); auto block = secondLevel2.freeBlocks[sl2].back(); secondLevel2.freeBlocks[sl2].pop_back(); // remove bitmap bit if (secondLevel2.freeBlocks[sl2].empty()) remove_bit(secondLevel2.slBitmap, sl2); if (secondLevel2.slBitmap == 0) remove_bit(control.flBitmap, fl2); return block; } } } return {}; } Block split(Block& block) { auto new_size = block.size / 2; Block new_block = {block.offset + new_size, new_size}; block.size = new_size; return new_block; } Block merge(Block block) { auto otf = block.offset; auto otf2 = block.offset + block.size; // oh no, nail in the coffin. BRUTEFORCE, we got not boundary tagging possible auto fl = 0; for (auto&& secondLevel : control.sizeclasses) { auto sl = 0; for (auto&& freeBlocks : secondLevel.freeBlocks) { auto iter = std::find_if( freeBlocks.begin(), freeBlocks.end(), [otf, otf2](Block b) { return (b.offset + b.size == otf) || (b.offset == otf2); }); if (iter != freeBlocks.end()) { auto rb = *iter; freeBlocks.erase(iter); if (freeBlocks.empty()) remove_bit(secondLevel.slBitmap, sl); if (secondLevel.slBitmap == 0) remove_bit(control.flBitmap, fl); if (rb.offset + rb.size == otf) { rb.size += block.size; return rb; } else if (rb.offset == otf2) { block.size += rb.size; return block; } } sl++; } fl++; } return block; } public: TLSFAllocator(size_t size) : m_size(size) { initialize(); unsigned fl, sl; mapping(size, fl, sl); insert({0, size}, fl, sl); } std::optional<Block> allocate(size_t size) { unsigned fl, sl, fl2, sl2; mapping(size, fl, sl); auto found_block = search_suitable_block(size, fl, sl); if (found_block) { while (found_block.size >= size * 2) { // oh no, while loop auto remaining_block = split(found_block); mapping(remaining_block.size, fl2, sl2); insert(remaining_block, fl2, sl2); } return found_block; } return {}; } void free(Block block) { // immediately merge with existing free blocks. unsigned fl, sl; auto size = block.size; auto big_free_block = merge(block); while (big_free_block.size != size) { // Oh no, another while loop size = big_free_block.size; big_free_block = merge(big_free_block); } mapping(big_free_block.size, fl, sl); insert(big_free_block, fl, sl); } }; TEST_CASE("some basic allocation tests") { TLSFAllocator tlsf(4); auto block = tlsf.allocate(5); REQUIRE_FALSE(block); block = tlsf.allocate(2); REQUIRE(block); if (block) { REQUIRE(block.value().size == 2); } tlsf.free(block.value()); block = tlsf.allocate(4); REQUIRE(block); if (block) { REQUIRE(block.value().size == 4); } tlsf.free(block.value()); block = tlsf.allocate(3); REQUIRE(block); if (block) { REQUIRE(block.value().size == 4); } tlsf.free(block.value()); block = tlsf.allocate(2); auto block2 = tlsf.allocate(2); REQUIRE(block); REQUIRE(block2); if (block && block2) { REQUIRE(block.value().size == 2); REQUIRE(block2.value().size == 2); } tlsf.free(block.value()); tlsf.free(block2.value()); block = tlsf.allocate(2); block2 = tlsf.allocate(1); REQUIRE(block); REQUIRE(block2); if (block && block2) { REQUIRE(block.value().size == 2); REQUIRE(block2.value().size == 1); } tlsf.free(block.value()); tlsf.free(block2.value()); auto block3 = tlsf.allocate(1); block = tlsf.allocate(2); block2 = tlsf.allocate(1); REQUIRE(block); REQUIRE(block2); REQUIRE(block3); if (block && block2 && block3) { REQUIRE(block.value().size == 2); REQUIRE(block2.value().size == 1); REQUIRE(block3.value().size == 1); } tlsf.free(block.value()); tlsf.free(block2.value()); tlsf.free(block3.value()); auto block4 = tlsf.allocate(1); block = tlsf.allocate(1); block2 = tlsf.allocate(1); block3 = tlsf.allocate(1); REQUIRE(block); REQUIRE(block2); REQUIRE(block3); REQUIRE(block4); if (block && block2 && block3 && block4) { REQUIRE(block.value().size == 1); REQUIRE(block2.value().size == 1); REQUIRE(block3.value().size == 1); REQUIRE(block4.value().size == 1); } tlsf.free(block.value()); tlsf.free(block2.value()); tlsf.free(block3.value()); tlsf.free(block4.value()); block = tlsf.allocate(4); REQUIRE(block); if (block) { REQUIRE(block.value().size == 4); } }<|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "architectures.h" #include <QMap> #include <QMapIterator> #include <QStringList> namespace qbs { QString canonicalArchitecture(const QString &architecture) { QMap<QString, QStringList> archMap; archMap.insert(QLatin1String("x86"), QStringList() << QLatin1String("i386") << QLatin1String("i486") << QLatin1String("i586") << QLatin1String("i686") << QLatin1String("ia32") << QLatin1String("ia-32") << QLatin1String("x86_32") << QLatin1String("x86-32") << QLatin1String("intel32") << QLatin1String("mingw32")); archMap.insert(QLatin1String("x86_64"), QStringList() << QLatin1String("x86-64") << QLatin1String("x64") << QLatin1String("amd64") << QLatin1String("ia32e") << QLatin1String("em64t") << QLatin1String("intel64") << QLatin1String("mingw64")); archMap.insert(QLatin1String("ia64"), QStringList() << QLatin1String("ia-64") << QLatin1String("itanium")); archMap.insert(QLatin1String("ppc"), QStringList() << QLatin1String("powerpc")); archMap.insert(QLatin1String("ppc64"), QStringList() << QLatin1String("powerpc64")); QMapIterator<QString, QStringList> i(archMap); while (i.hasNext()) { i.next(); if (i.value().contains(architecture.toLower())) return i.key(); } return architecture; } QString defaultEndianness(const QString &architecture) { const QString canonicalArch = canonicalArchitecture(architecture); QStringList little = QStringList() << QLatin1String("x86") << QLatin1String("x86_64") << QLatin1String("arm") << QLatin1String("arm64"); if (little.contains(canonicalArch)) return QLatin1String("little"); QStringList big = QStringList() << QLatin1String("ppc") << QLatin1String("ppc64"); if (big.contains(canonicalArch)) return QLatin1String("big"); return QString(); } } // namespace qbs <commit_msg>Add missing copyright notice.<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Copyright (C) 2014 Petroules Corporation. ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "architectures.h" #include <QMap> #include <QMapIterator> #include <QStringList> namespace qbs { QString canonicalArchitecture(const QString &architecture) { QMap<QString, QStringList> archMap; archMap.insert(QLatin1String("x86"), QStringList() << QLatin1String("i386") << QLatin1String("i486") << QLatin1String("i586") << QLatin1String("i686") << QLatin1String("ia32") << QLatin1String("ia-32") << QLatin1String("x86_32") << QLatin1String("x86-32") << QLatin1String("intel32") << QLatin1String("mingw32")); archMap.insert(QLatin1String("x86_64"), QStringList() << QLatin1String("x86-64") << QLatin1String("x64") << QLatin1String("amd64") << QLatin1String("ia32e") << QLatin1String("em64t") << QLatin1String("intel64") << QLatin1String("mingw64")); archMap.insert(QLatin1String("ia64"), QStringList() << QLatin1String("ia-64") << QLatin1String("itanium")); archMap.insert(QLatin1String("ppc"), QStringList() << QLatin1String("powerpc")); archMap.insert(QLatin1String("ppc64"), QStringList() << QLatin1String("powerpc64")); QMapIterator<QString, QStringList> i(archMap); while (i.hasNext()) { i.next(); if (i.value().contains(architecture.toLower())) return i.key(); } return architecture; } QString defaultEndianness(const QString &architecture) { const QString canonicalArch = canonicalArchitecture(architecture); QStringList little = QStringList() << QLatin1String("x86") << QLatin1String("x86_64") << QLatin1String("arm") << QLatin1String("arm64"); if (little.contains(canonicalArch)) return QLatin1String("little"); QStringList big = QStringList() << QLatin1String("ppc") << QLatin1String("ppc64"); if (big.contains(canonicalArch)) return QLatin1String("big"); return QString(); } } // namespace qbs <|endoftext|>
<commit_before>#include <catch2/catch.hpp> #include <optional> #include <vector> #include <algorithm> struct Block { size_t offset; size_t size; operator bool() { return size != 0; } }; class TLSFAllocator { struct TLSFSizeClass { size_t sizeClass; uint64_t slBitmap; std::vector<std::vector<Block>> freeBlocks; }; struct TLSFControl { uint64_t flBitmap; std::vector<TLSFSizeClass> sizeclasses; }; unsigned fli; // first level index unsigned sli; // second level index, typically 5 unsigned sli_count; // second level index, typically 5 unsigned mbs; // minimum block size unsigned min_fli; TLSFControl control; size_t m_size; int fls(uint64_t size) { unsigned long index; return _BitScanReverse64(&index, size) ? index : -1; } int ffs(uint64_t size) { unsigned long index; return _BitScanForward64(&index, size) ? index : -1; } void mapping(size_t size, unsigned& fl, unsigned& sl) { fl = fls(size); sl = ((size ^ (1 << fl)) >> (fl - sli)); fl = first_level_index(fl); // printf("%zu -> fl %u sl %u\n", size, fl, sl); } int first_level_index(unsigned fli) { if (fli < min_fli) return 0; return fli - min_fli; } void initialize() { fli = fls(m_size); sli = 5; sli_count = 1 << sli; mbs = std::min(int(m_size), 16); min_fli = fls(mbs); control.flBitmap = 0; for (int i = min_fli; i <= fli; ++i) { size_t sizeClass = 1 << i; std::vector<std::vector<Block>> vectors; for (int k = 0; k < sli_count; ++k) { vectors.push_back(std::vector<Block>()); } control.sizeclasses.push_back(TLSFSizeClass{sizeClass, 0, vectors}); } } void remove_bit(uint64_t& value, int index) { value = value ^ (1 << index); } void set_bit(uint64_t& value, int index) { value |= (1 << index); } void insert(Block block, unsigned fl, unsigned sl) { auto& sizeClass = control.sizeclasses[fl]; auto& secondLv = sizeClass.freeBlocks[sl]; secondLv.push_back(block); set_bit(sizeClass.slBitmap, sl); set_bit(control.flBitmap, fl); } Block search_suitable_block(size_t size, unsigned fl, unsigned sl) { // first step, assume we got something at fl / sl location auto& secondLevel = control.sizeclasses[fl]; auto& freeblocks = secondLevel.freeBlocks[sl]; if (!freeblocks.empty() && freeblocks.back().size >= size) { auto block = freeblocks.back(); freeblocks.pop_back(); // remove bitmap bit if (freeblocks.empty()) remove_bit(secondLevel.slBitmap, sl); if (secondLevel.slBitmap == 0) remove_bit(control.flBitmap, fl); return block; } else { // second step, scan bitmaps for empty slots // create mask to ignore first bits, could be wrong auto mask = ~((1 << (fl + 1)) - 1); auto fl2 = ffs(control.flBitmap & mask); if (fl2 >= 0) { auto& secondLevel2 = control.sizeclasses[fl2]; auto sl2 = ffs(secondLevel2.slBitmap); assert(!secondLevel2.freeBlocks[sl2].empty()); if (sl2 >= 0 && secondLevel2.freeBlocks[sl2].back().size >= size) { auto block = secondLevel2.freeBlocks[sl2].back(); secondLevel2.freeBlocks[sl2].pop_back(); // remove bitmap bit if (secondLevel2.freeBlocks[sl2].empty()) remove_bit(secondLevel2.slBitmap, sl2); if (secondLevel2.slBitmap == 0) remove_bit(control.flBitmap, fl2); return block; } } } return {}; } Block split(Block& block, size_t size) { auto new_size = block.size - size; Block new_block = {block.offset + size, new_size}; block.size = size; return new_block; } Block merge(Block block) { auto otf = block.offset; auto otf2 = block.offset + block.size; // oh no, nail in the coffin. BRUTEFORCE, we got not boundary tagging // possible sped up by using bitmaps to avoid checking empty vectors auto fl = 0; // scan through only the memory where blocks reside using bitfields auto flBM = control.flBitmap; while (flBM != 0) { auto fl = ffs(flBM); remove_bit(flBM, fl); auto& secondLevel = control.sizeclasses[fl]; // use the bitmap to only check relevant vectors auto slBM = secondLevel.slBitmap; while (slBM != 0) { auto sl = ffs(slBM); remove_bit(slBM, sl); auto& freeBlocks = secondLevel.freeBlocks[sl]; auto iter = std::find_if( freeBlocks.begin(), freeBlocks.end(), [otf, otf2](Block b) { return (b.offset + b.size == otf) || (b.offset == otf2); }); if (iter != freeBlocks.end()) { auto rb = *iter; freeBlocks.erase(iter); if (freeBlocks.empty()) remove_bit(secondLevel.slBitmap, sl); if (secondLevel.slBitmap == 0) remove_bit(control.flBitmap, fl); if (rb.offset + rb.size == otf) { rb.size += block.size; return rb; } else if (rb.offset == otf2) { block.size += rb.size; return block; } } } } return block; } public: TLSFAllocator(size_t size) : m_size(size) { initialize(); unsigned fl, sl; mapping(size, fl, sl); insert({0, size}, fl, sl); } std::optional<Block> allocate(size_t size) { unsigned fl, sl, fl2, sl2; mapping(size, fl, sl); auto found_block = search_suitable_block(size, fl, sl); if (found_block) { if (found_block.size > size) { auto remaining_block = split(found_block, size); mapping(remaining_block.size, fl2, sl2); insert(remaining_block, fl2, sl2); } return found_block; } return {}; } void free(Block block) { // immediately merge with existing free blocks. unsigned fl, sl; auto size = block.size; auto big_free_block = merge(block); while (big_free_block.size != size) // while loop here { size = big_free_block.size; big_free_block = merge(big_free_block); } mapping(big_free_block.size, fl, sl); insert(big_free_block, fl, sl); } }; TEST_CASE("some basic allocation tests") { TLSFAllocator tlsf(4); auto block = tlsf.allocate(5); REQUIRE_FALSE(block); block = tlsf.allocate(2); REQUIRE(block); if (block) { REQUIRE(block.value().size == 2); } tlsf.free(block.value()); block = tlsf.allocate(4); REQUIRE(block); if (block) { REQUIRE(block.value().size == 4); } tlsf.free(block.value()); block = tlsf.allocate(3); REQUIRE(block); if (block) { REQUIRE(block.value().size == 3); } tlsf.free(block.value()); block = tlsf.allocate(2); auto block2 = tlsf.allocate(2); REQUIRE(block); REQUIRE(block2); if (block && block2) { REQUIRE(block.value().size == 2); REQUIRE(block2.value().size == 2); } tlsf.free(block.value()); tlsf.free(block2.value()); block = tlsf.allocate(2); block2 = tlsf.allocate(1); REQUIRE(block); REQUIRE(block2); if (block && block2) { REQUIRE(block.value().size == 2); REQUIRE(block2.value().size == 1); } tlsf.free(block.value()); tlsf.free(block2.value()); auto block3 = tlsf.allocate(1); block = tlsf.allocate(2); block2 = tlsf.allocate(1); REQUIRE(block); REQUIRE(block2); REQUIRE(block3); if (block && block2 && block3) { REQUIRE(block.value().size == 2); REQUIRE(block2.value().size == 1); REQUIRE(block3.value().size == 1); } tlsf.free(block.value()); tlsf.free(block2.value()); tlsf.free(block3.value()); auto block4 = tlsf.allocate(1); block = tlsf.allocate(1); block2 = tlsf.allocate(1); block3 = tlsf.allocate(1); REQUIRE(block); REQUIRE(block2); REQUIRE(block3); REQUIRE(block4); if (block && block2 && block3 && block4) { REQUIRE(block.value().size == 1); REQUIRE(block2.value().size == 1); REQUIRE(block3.value().size == 1); REQUIRE(block4.value().size == 1); } tlsf.free(block.value()); tlsf.free(block2.value()); tlsf.free(block3.value()); tlsf.free(block4.value()); block = tlsf.allocate(4); REQUIRE(block); if (block) { REQUIRE(block.value().size == 4); } } TEST_CASE("some basic allocation tests 2") { TLSFAllocator tlsf(70000); auto block = tlsf.allocate(50000); auto block2 = tlsf.allocate(20000); REQUIRE(block); REQUIRE(block2); } TEST_CASE("stranger tests") { auto count = 100; auto sum = (count * (count + 1)) / 2; TLSFAllocator tlsf(sum); std::vector<Block> blocks; for (int i = 1; i <= count; ++i) { auto block = tlsf.allocate(i); REQUIRE(block); blocks.push_back(block.value()); } auto block = tlsf.allocate(1); REQUIRE_FALSE(block); tlsf.free(blocks.back()); block = tlsf.allocate(1); REQUIRE(block); }<commit_msg>Improved TLSF to handle alignments itself. Waxed the outlook and wrote few more tests. Next I think I'll try to integrate the allocator to my backends. Tests aren't really covering all cases and don't test for fragmentation. But better than nothing tbh. Still wondering how to quickly merge these kind of "blocks"...<commit_after>#include <catch2/catch.hpp> #include <optional> #include <vector> #include <algorithm> struct Block { uint64_t offset; uint64_t size; operator bool() { return size != 0; } }; class TLSFAllocator { struct TLSFSizeClass { size_t sizeClass; uint64_t slBitmap; std::vector<std::vector<Block>> freeBlocks; }; struct TLSFControl { uint64_t flBitmap; std::vector<TLSFSizeClass> sizeclasses; }; Block m_baseBlock; uint64_t fli; // first level index uint64_t sli; // second level index, typically 5 unsigned sli_count; // second level index, typically 5 int mbs; // minimum block size uint64_t min_fli; TLSFControl control; size_t m_usedSize; int fls(uint64_t size) noexcept { unsigned long index; return _BitScanReverse64(&index, size) ? index : -1; } int ffs(uint64_t size) noexcept { unsigned long index; return _BitScanForward64(&index, size) ? index : -1; } void mapping(size_t size, uint64_t& fl, uint64_t& sl) noexcept { fl = fls(size); sl = ((size ^ (1 << fl)) >> (fl - sli)); fl = first_level_index(fl); // printf("%zu -> fl %u sl %u\n", size, fl, sl); } int first_level_index(int fli) noexcept { if (fli < min_fli ) return 0; return fli - min_fli; } void initialize() noexcept { fli = fls(m_baseBlock.size); mbs = std::min(int(m_baseBlock.size), mbs); min_fli = fls(mbs); control.flBitmap = 0; if (0) { size_t sizeClass = 1; std::vector<std::vector<Block>> vectors; for (int k = 0; k < sli_count; ++k) { vectors.push_back(std::vector<Block>()); } control.sizeclasses.push_back(TLSFSizeClass{sizeClass, 0, vectors}); } for (int i = min_fli; i <= fli; ++i) { size_t sizeClass = 1 << i; std::vector<std::vector<Block>> vectors; for (int k = 0; k < sli_count; ++k) { vectors.push_back(std::vector<Block>()); } control.sizeclasses.push_back(TLSFSizeClass{sizeClass, 0, vectors}); } } void remove_bit(uint64_t& value, int index) noexcept { value = value ^ (1 << index); } void set_bit(uint64_t& value, int index) noexcept { value |= (1 << index); } void insert(Block block, unsigned fl, unsigned sl) noexcept { auto& sizeClass = control.sizeclasses[fl]; auto& secondLv = sizeClass.freeBlocks[sl]; secondLv.push_back(block); set_bit(sizeClass.slBitmap, sl); set_bit(control.flBitmap, fl); } Block search_suitable_block(size_t size, unsigned fl, unsigned sl) noexcept { // first step, assume we got something at fl / sl location auto& secondLevel = control.sizeclasses[fl]; auto& freeblocks = secondLevel.freeBlocks[sl]; if (!freeblocks.empty() && freeblocks.back().size >= size) { auto block = freeblocks.back(); freeblocks.pop_back(); // remove bitmap bit if (freeblocks.empty()) remove_bit(secondLevel.slBitmap, sl); if (secondLevel.slBitmap == 0) remove_bit(control.flBitmap, fl); return block; } else { // second step, scan bitmaps for empty slots // create mask to ignore first bits, could be wrong auto mask = ~((1 << (fl+1)) - 1); auto fl2 = ffs(control.flBitmap & mask); if (fl2 >= 0) { auto& secondLevel2 = control.sizeclasses[fl2]; assert(secondLevel2.sizeClass >= size && secondLevel2.slBitmap != 0); auto sl2 = ffs(secondLevel2.slBitmap); assert(!secondLevel2.freeBlocks[sl2].empty()); if (sl2 >= 0 && secondLevel2.freeBlocks[sl2].back().size >= size) { auto block = secondLevel2.freeBlocks[sl2].back(); secondLevel2.freeBlocks[sl2].pop_back(); // remove bitmap bit if (secondLevel2.freeBlocks[sl2].empty()) remove_bit(secondLevel2.slBitmap, sl2); if (secondLevel2.slBitmap == 0) remove_bit(control.flBitmap, fl2); return block; } } } return {}; } Block split(Block& block, size_t size) noexcept { auto new_size = block.size - size; Block new_block = {block.offset + size, new_size}; block.size = size; return new_block; } Block merge(Block block) noexcept { auto otf = block.offset; auto otf2 = block.offset + block.size; // oh no, nail in the coffin. BRUTEFORCE, we got not boundary tagging // possible sped up by using bitmaps to avoid checking empty vectors auto fl = 0; // scan through only the memory where blocks reside using bitfields auto flBM = control.flBitmap; while (flBM != 0) { auto fl = ffs(flBM); remove_bit(flBM, fl); auto& secondLevel = control.sizeclasses[fl]; // use the bitmap to only check relevant vectors auto slBM = secondLevel.slBitmap; while (slBM != 0) { auto sl = ffs(slBM); remove_bit(slBM, sl); auto& freeBlocks = secondLevel.freeBlocks[sl]; auto iter = std::find_if( freeBlocks.begin(), freeBlocks.end(), [otf, otf2](Block b) { return (b.offset + b.size == otf) || (b.offset == otf2); }); if (iter != freeBlocks.end()) { auto rb = *iter; freeBlocks.erase(iter); if (freeBlocks.empty()) remove_bit(secondLevel.slBitmap, sl); if (secondLevel.slBitmap == 0) remove_bit(control.flBitmap, fl); if (rb.offset + rb.size == otf) { rb.size += block.size; return rb; } else if (rb.offset == otf2) { block.size += rb.size; return block; } } } } return block; } public: TLSFAllocator(Block initialBlock, size_t minimumBlockSize = 16, int sli = 3) : m_baseBlock(initialBlock), mbs(minimumBlockSize), sli(sli), sli_count(1 << sli) { initialize(); uint64_t fl, sl; mapping(m_baseBlock.size, fl, sl); insert(initialBlock, fl, sl); } TLSFAllocator(size_t size, size_t minimumBlockSize = 16, int sli = 3) : m_baseBlock({0,size}), mbs(minimumBlockSize), sli(sli), sli_count(1 << sli) { initialize(); uint64_t fl, sl; mapping(m_baseBlock.size, fl, sl); insert(m_baseBlock, fl, sl); } std::optional<Block> allocate(size_t size, size_t alignment = 1) noexcept { size = std::max(size, size_t(mbs)); uint64_t fl, sl, fl2, sl2; mapping(size, fl, sl); auto found_block = search_suitable_block(size, fl, sl); if (found_block) { auto overAlign = found_block.offset % alignment; if (overAlign != 0 && found_block.size > size + alignment) { // fix alignment auto overAlignmentFix = alignment - overAlign; auto smallFixBlock = Block{found_block.offset, overAlign}; found_block.offset += overAlignmentFix; assert(found_block.offset % alignment == 0); // guaranteed that nothing will merge with this block. mapping(smallFixBlock.size, fl2, sl2); insert(smallFixBlock, fl2, sl2); } if (found_block.size > size) { auto remaining_block = split(found_block, size); mapping(remaining_block.size, fl2, sl2); insert(remaining_block, fl2, sl2); } m_usedSize += found_block.size; return found_block; } return {}; } void free(Block block) noexcept { // immediately merge with existing free blocks. m_usedSize -= block.size; uint64_t fl, sl; auto size = block.size; auto big_free_block = merge(block); while (big_free_block.size != size) // while loop here { size = big_free_block.size; big_free_block = merge(big_free_block); } mapping(big_free_block.size, fl, sl); insert(big_free_block, fl, sl); } size_t size() const noexcept { return m_baseBlock.size - m_usedSize; } size_t max_size() const noexcept { return m_baseBlock.size; } size_t size_allocated() const noexcept { return m_usedSize; } }; TEST_CASE("some basic allocation tests") { TLSFAllocator tlsf(4, 1); auto block = tlsf.allocate(5); REQUIRE_FALSE(block); block = tlsf.allocate(2); REQUIRE(block); if (block) { REQUIRE(block.value().size == 2); } tlsf.free(block.value()); block = tlsf.allocate(4); REQUIRE(block); if (block) { REQUIRE(block.value().size == 4); } tlsf.free(block.value()); block = tlsf.allocate(3); REQUIRE(block); if (block) { REQUIRE(block.value().size == 3); } tlsf.free(block.value()); block = tlsf.allocate(2); auto block2 = tlsf.allocate(2); REQUIRE(block); REQUIRE(block2); if (block && block2) { REQUIRE(block.value().size == 2); REQUIRE(block2.value().size == 2); } tlsf.free(block.value()); tlsf.free(block2.value()); block = tlsf.allocate(2); block2 = tlsf.allocate(1); REQUIRE(block); REQUIRE(block2); if (block && block2) { REQUIRE(block.value().size == 2); REQUIRE(block2.value().size == 1); } tlsf.free(block.value()); tlsf.free(block2.value()); auto block3 = tlsf.allocate(1); block = tlsf.allocate(2); block2 = tlsf.allocate(1); REQUIRE(block); REQUIRE(block2); REQUIRE(block3); if (block && block2 && block3) { REQUIRE(block.value().size == 2); REQUIRE(block2.value().size == 1); REQUIRE(block3.value().size == 1); } tlsf.free(block.value()); tlsf.free(block2.value()); tlsf.free(block3.value()); auto block4 = tlsf.allocate(1); block = tlsf.allocate(1); block2 = tlsf.allocate(1); block3 = tlsf.allocate(1); REQUIRE(block); REQUIRE(block2); REQUIRE(block3); REQUIRE(block4); if (block && block2 && block3 && block4) { REQUIRE(block.value().size == 1); REQUIRE(block2.value().size == 1); REQUIRE(block3.value().size == 1); REQUIRE(block4.value().size == 1); } tlsf.free(block.value()); tlsf.free(block2.value()); tlsf.free(block3.value()); tlsf.free(block4.value()); block = tlsf.allocate(4); REQUIRE(block); if (block) { REQUIRE(block.value().size == 4); } } TEST_CASE("some basic allocation tests 2") { TLSFAllocator tlsf(70000); auto block = tlsf.allocate(50000); auto block2 = tlsf.allocate(20000); REQUIRE(block); REQUIRE(block2); } TEST_CASE("stranger tests") { auto count = 100; auto sum = (count * (count + 1)) / 2; TLSFAllocator tlsf(sum, 1); std::vector<Block> blocks; for (int i = 1; i <= count; ++i) { auto block = tlsf.allocate(i); REQUIRE(block); blocks.push_back(block.value()); } auto block = tlsf.allocate(1); REQUIRE_FALSE(block); tlsf.free(blocks.back()); block = tlsf.allocate(1); REQUIRE(block); } TEST_CASE("alignment tests") { TLSFAllocator tlsf(50, 1); auto block = tlsf.allocate(3, 1); auto block2 = tlsf.allocate(3*3*3, 9); REQUIRE(block); REQUIRE(block.value().offset % 1 == 0); REQUIRE(block.value().size == 3); REQUIRE(block2); REQUIRE(block2.value().offset % 9 == 0); REQUIRE(block2.value().size == 3*3*3); auto block4 = tlsf.allocate(10, 2); REQUIRE(block4); REQUIRE(block4.value().size == 10); auto block3 = tlsf.allocate(3, 1); REQUIRE(block3); REQUIRE(block3.value().size == 3); auto block5 = tlsf.allocate(10, 1); REQUIRE(block5); REQUIRE(block5.value().size == 10); tlsf.free(block2.value()); block2 = tlsf.allocate(3*3, 1); REQUIRE(block2); REQUIRE(block2.value().offset % 1 == 0); REQUIRE(block2.value().size == 3*3); } TEST_CASE("alignment tests with minimum block size") { TLSFAllocator tlsf(100, 16); auto block = tlsf.allocate(3, 1); auto block2 = tlsf.allocate(3*3*3, 9); REQUIRE(block); REQUIRE(block.value().offset % 1 == 0); REQUIRE(block.value().size == 16); REQUIRE(block2); REQUIRE(block2.value().offset % 9 == 0); REQUIRE(block2.value().size == 3*3*3); auto block4 = tlsf.allocate(10, 2); REQUIRE(block4); REQUIRE(block4.value().size == 16); auto block3 = tlsf.allocate(3, 1); REQUIRE(block3); REQUIRE(block3.value().size == 16); }<|endoftext|>
<commit_before>/* * * Copyright 2016 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker 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. * * Orion Context Broker 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 Affero * General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * iot_support at tid dot es * * Author: Ken Zangelin */ #include "rapidjson/document.h" #include "alarmMgr/alarmMgr.h" #include "rest/ConnectionInfo.h" #include "ngsi/ParseData.h" #include "ngsi/Request.h" #include "jsonParseV2/jsonParseTypeNames.h" #include "jsonParseV2/parseEntityVector.h" #include "jsonParseV2/parseAttributeList.h" #include "jsonParseV2/parseScopeVector.h" using namespace rapidjson; /* **************************************************************************** * * parseBatchQuery - */ std::string parseBatchQuery(ConnectionInfo* ciP, BatchQuery* bqrP) { Document document; document.Parse(ciP->payload); if (document.HasParseError()) { ErrorCode ec; alarmMgr.badInput(clientIp, "JSON Parse Error"); ec.fill(ERROR_STRING_PARSERROR, "Errors found in incoming JSON buffer"); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } if (!document.IsObject()) { ErrorCode ec; alarmMgr.badInput(clientIp, "JSON Parse Error"); ec.fill("BadRequest", "JSON Parse Error"); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } else if (document.ObjectEmpty()) { ErrorCode ec; alarmMgr.badInput(clientIp, "Empty JSON payload"); ec.fill("BadRequest", "empty payload"); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } else if (!document.HasMember("entities") && !document.HasMember("attributes") && !document.HasMember("scopes")) { ErrorCode ec; alarmMgr.badInput(clientIp, "Invalid JSON payload, no relevant fields found"); ec.fill("BadRequest", "Invalid JSON payload, no relevant fields found"); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } for (Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter) { std::string name = iter->name.GetString(); std::string type = jsonParseTypeNames[iter->value.GetType()]; if (name == "entities") { std::string r = parseEntityVector(ciP, iter, &bqrP->entities, false); // param 4: attributes are NOT allowed in payload if (r != "OK") { ErrorCode ec("BadRequest", r); alarmMgr.badInput(clientIp, r); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } } else if (name == "attributes") { std::string r = parseAttributeList(ciP, iter, &bqrP->attributeV); if (r != "OK") { ErrorCode ec("BadRequest", r); alarmMgr.badInput(clientIp, r); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } } else if (name == "scopes") { std::string r = parseScopeVector(ciP, iter, &bqrP->scopeV); if (r != "OK") { ErrorCode ec("BadRequest", r); alarmMgr.badInput(clientIp, r); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } } else { std::string description = std::string("Unrecognizedfield in JSON payload: /") + name + "/"; ErrorCode ec("BadRequest", description); alarmMgr.badInput(clientIp, description); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } } return "OK"; } <commit_msg>Fixed an error in an error decsription in parseBatchQuery<commit_after>/* * * Copyright 2016 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker 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. * * Orion Context Broker 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 Affero * General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * iot_support at tid dot es * * Author: Ken Zangelin */ #include "rapidjson/document.h" #include "alarmMgr/alarmMgr.h" #include "rest/ConnectionInfo.h" #include "ngsi/ParseData.h" #include "ngsi/Request.h" #include "jsonParseV2/jsonParseTypeNames.h" #include "jsonParseV2/parseEntityVector.h" #include "jsonParseV2/parseAttributeList.h" #include "jsonParseV2/parseScopeVector.h" using namespace rapidjson; /* **************************************************************************** * * parseBatchQuery - */ std::string parseBatchQuery(ConnectionInfo* ciP, BatchQuery* bqrP) { Document document; document.Parse(ciP->payload); if (document.HasParseError()) { ErrorCode ec; alarmMgr.badInput(clientIp, "JSON Parse Error"); ec.fill(ERROR_STRING_PARSERROR, "Errors found in incoming JSON buffer"); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } if (!document.IsObject()) { ErrorCode ec; alarmMgr.badInput(clientIp, "JSON Parse Error"); ec.fill("BadRequest", "JSON Parse Error"); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } else if (document.ObjectEmpty()) { ErrorCode ec; alarmMgr.badInput(clientIp, "Empty JSON payload"); ec.fill("BadRequest", "empty payload"); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } else if (!document.HasMember("entities") && !document.HasMember("attributes") && !document.HasMember("scopes")) { ErrorCode ec; alarmMgr.badInput(clientIp, "Invalid JSON payload, no relevant fields found"); ec.fill("BadRequest", "Invalid JSON payload, no relevant fields found"); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } for (Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter) { std::string name = iter->name.GetString(); std::string type = jsonParseTypeNames[iter->value.GetType()]; if (name == "entities") { std::string r = parseEntityVector(ciP, iter, &bqrP->entities, false); // param 4: attributes are NOT allowed in payload if (r != "OK") { ErrorCode ec("BadRequest", r); alarmMgr.badInput(clientIp, r); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } } else if (name == "attributes") { std::string r = parseAttributeList(ciP, iter, &bqrP->attributeV); if (r != "OK") { ErrorCode ec("BadRequest", r); alarmMgr.badInput(clientIp, r); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } } else if (name == "scopes") { std::string r = parseScopeVector(ciP, iter, &bqrP->scopeV); if (r != "OK") { ErrorCode ec("BadRequest", r); alarmMgr.badInput(clientIp, r); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } } else { std::string description = std::string("Unrecognized field in JSON payload: /") + name + "/"; ErrorCode ec("BadRequest", description); alarmMgr.badInput(clientIp, description); ciP->httpStatusCode = SccBadRequest; return ec.toJson(true); } } return "OK"; } <|endoftext|>
<commit_before>// // Copyright (C) 2006-2010 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006-2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// #include <os/OsIntTypes.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <mp/MpCodecFactory.h> #include <os/OsTime.h> #include <os/OsDateTime.h> #include <sipxunittests.h> /// Duration of one frame in milliseconds #define FRAME_MS 20 /// Maximum length of audio data we expect from decoder (in samples). #define DECODED_FRAME_MAX_SIZE 1600 /// Maximum size of encoded frame (in bytes). #define ENCODED_FRAME_MAX_SIZE 1480 /// Number of RTP packets to encode/decode. #define NUM_PACKETS_TO_TEST 3 /// Maximum number of milliseconds in packet. #define MAX_PACKET_TIME 20 // Setup codec paths.. static UtlString sCodecPaths[] = { #ifdef WIN32 "bin", "..\\bin", #elif defined(__pingtel_on_posix__) "../../../../bin", "../../../bin", "../../bin", #else # error "Unknown platform" #endif "." }; static size_t sNumCodecPaths = sizeof(sCodecPaths)/sizeof(sCodecPaths[0]); /// Unit test for testing performance of supported codecs. class MpCodecsPerformanceTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(MpCodecsPerformanceTest); CPPUNIT_TEST(testCodecsPreformance); CPPUNIT_TEST_SUITE_END(); public: void setUp() { // Create pool for data buffers mpPool = new MpBufPool(ENCODED_FRAME_MAX_SIZE + MpArrayBuf::getHeaderSize(), 1); CPPUNIT_ASSERT(mpPool != NULL); // Create pool for buffer headers mpHeadersPool = new MpBufPool(sizeof(MpRtpBuf), 1); CPPUNIT_ASSERT(mpHeadersPool != NULL); // Set mpHeadersPool as default pool for audio and data pools. MpRtpBuf::smpDefaultPool = mpHeadersPool; } void tearDown() { if (mpPool != NULL) { delete mpPool; } if (mpHeadersPool != NULL) { delete mpHeadersPool; } } void testCodecsPreformance() { MpCodecFactory *pCodecFactory; const MppCodecInfoV1_1 **pCodecInfo; unsigned codecInfoNum; // Get/create codec factory pCodecFactory = MpCodecFactory::getMpCodecFactory(); CPPUNIT_ASSERT(pCodecFactory != NULL); // Load all available codecs size_t i; for(i = 0; i < sNumCodecPaths; i++) { printf("MpCodecsPerformanceTest loading codecs from: %s\n", sCodecPaths[i].data()); pCodecFactory->loadAllDynCodecs(sCodecPaths[i], CODEC_PLUGINS_FILTER); } // Get list of loaded codecs pCodecFactory->getCodecInfoArray(codecInfoNum, pCodecInfo); CPPUNIT_ASSERT(codecInfoNum>0); unsigned j; for (j=0; j<codecInfoNum; j++) { const char **pCodecFmtps; unsigned codecFmtpsNum; codecFmtpsNum = pCodecInfo[j]->fmtpsNum; pCodecFmtps = pCodecInfo[j]->fmtps; if (codecFmtpsNum == 0) { testOneCodecPreformance(pCodecFactory, pCodecInfo[j]->mimeSubtype, "", pCodecInfo[j]->sampleRate, pCodecInfo[j]->numChannels); } else { for (unsigned fmtpNum=0; fmtpNum<codecFmtpsNum; fmtpNum++) { testOneCodecPreformance(pCodecFactory, pCodecInfo[j]->mimeSubtype, pCodecFmtps[fmtpNum], pCodecInfo[j]->sampleRate, pCodecInfo[j]->numChannels); } } } // Free codec factory MpCodecFactory::freeSingletonHandle(); } protected: MpBufPool *mpPool; ///< Pool for data buffers MpBufPool *mpHeadersPool; ///< Pool for buffers headers void testOneCodecPreformance(MpCodecFactory *pCodecFactory, const UtlString &codecMime, const UtlString &codecFmtp, int sampleRate, int numChannels) { MpDecoderBase *pDecoder; MpEncoderBase *pEncoder; MpAudioSample *pOriginal; MpAudioSample pDecoded[DECODED_FRAME_MAX_SIZE]; int encodeFrameNum = 0; int maxPacketSamples = (MAX_PACKET_TIME*sampleRate)/1000; int frameSize = (sampleRate*FRAME_MS)/1000; int codecFrameSamples; // Allocate buffer for raw audio data pOriginal = new MpAudioSample[frameSize]; srand(time(NULL)); for (int k=0; k<frameSize; k++) { pOriginal[k] = rand()%32000 - 16000; } // Create and initialize decoder and encoder //printf("creating decoder: %s/%d/%d fmpt=\"%s\"\n", // codecMime.data(), sampleRate, numChannels, codecFmtp.data()); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pCodecFactory->createDecoder(codecMime, codecFmtp, sampleRate, numChannels, 0, pDecoder)); CPPUNIT_ASSERT(pDecoder); OsStatus initDecodeStatus = pDecoder->initDecode(); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, initDecodeStatus); // Could not test speed of signaling codec if (pDecoder->getInfo() == NULL || pDecoder->getInfo()->isSignalingCodec()) { pDecoder->freeDecode(); delete pDecoder; return; } CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pCodecFactory->createEncoder(codecMime, codecFmtp, sampleRate, numChannels, 0, pEncoder)); CPPUNIT_ASSERT(pEncoder); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pEncoder->initEncode()); // Get number of samples we'll pack to get one packet if (pEncoder->getInfo()->getCodecType() == CODEC_TYPE_FRAME_BASED) { codecFrameSamples = pEncoder->getInfo()->getNumSamplesPerFrame(); } else if (pEncoder->getInfo()->getCodecType() == CODEC_TYPE_SAMPLE_BASED) { codecFrameSamples = frameSize; } else { assert(!"Unknown codec type!"); } for (int i=0; i<NUM_PACKETS_TO_TEST; i++) { int tmpSamplesConsumed; int tmpEncodedSize; UtlBoolean tmpIsPacketReady; UtlBoolean tmpIsPacketSilent; MpRtpBufPtr pRtpPacket = mpPool->getBuffer(); unsigned char *pRtpPayloadPtr = (unsigned char *)pRtpPacket->getDataWritePtr(); int payloadSize = 0; int samplesInPacket = 0; OsTime start; OsTime stop; OsTime diff; // Encode frames until we get tmpSendNow set or reach packet size limit. do { // Encode one frame and measure time it took. OsStatus result; OsDateTime::getCurTime(start); result = pEncoder->encode(pOriginal, frameSize, tmpSamplesConsumed, pRtpPayloadPtr, ENCODED_FRAME_MAX_SIZE-payloadSize, tmpEncodedSize, tmpIsPacketReady, tmpIsPacketSilent); OsDateTime::getCurTime(stop); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, result); // Print timing in CSV format diff = stop - start; printf("encode %s/%d/%d %s;%d;%ld.%06ld;%ld.%06ld\n", codecMime.data(), sampleRate, numChannels, codecFmtp.data(), encodeFrameNum, start.seconds(), start.usecs(), diff.seconds(), diff.usecs()); // Adjust encoding state payloadSize += tmpEncodedSize; pRtpPayloadPtr += tmpEncodedSize; samplesInPacket += tmpSamplesConsumed; CPPUNIT_ASSERT(payloadSize <= ENCODED_FRAME_MAX_SIZE); encodeFrameNum++; } while( (payloadSize == 0) ||( (tmpIsPacketReady != TRUE) && (samplesInPacket+codecFrameSamples <= maxPacketSamples))); pRtpPacket->setPayloadSize(payloadSize); // Decode frame, measure time and verify, that we decoded same number of samples. OsDateTime::getCurTime(start); tmpSamplesConsumed = pDecoder->decode(pRtpPacket, DECODED_FRAME_MAX_SIZE, pDecoded); OsDateTime::getCurTime(stop); CPPUNIT_ASSERT_EQUAL(samplesInPacket, tmpSamplesConsumed); // Print timing in TSV format diff = stop - start; printf("decode %s/%d/%d %s;%d;%ld.%06ld;%ld.%06ld\n", codecMime.data(), sampleRate, numChannels, codecFmtp.data(), i, start.seconds(), start.usecs(), diff.seconds(), diff.usecs()); } // Free encoder and decoder CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pDecoder->freeDecode()); delete pDecoder; CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pEncoder->freeEncode()); delete pEncoder; // Free buffer used for raw audio data delete[] pOriginal; } }; CPPUNIT_TEST_SUITE_REGISTRATION(MpCodecsPerformanceTest); <commit_msg>Fixed arg change on encoder in MpCodecsPerformanceTest<commit_after>// // Copyright (C) 2006-2010 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2006-2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// #include <os/OsIntTypes.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <mp/MpCodecFactory.h> #include <os/OsTime.h> #include <os/OsDateTime.h> #include <sipxunittests.h> /// Duration of one frame in milliseconds #define FRAME_MS 20 /// Maximum length of audio data we expect from decoder (in samples). #define DECODED_FRAME_MAX_SIZE 1600 /// Maximum size of encoded frame (in bytes). #define ENCODED_FRAME_MAX_SIZE 1480 /// Number of RTP packets to encode/decode. #define NUM_PACKETS_TO_TEST 3 /// Maximum number of milliseconds in packet. #define MAX_PACKET_TIME 20 // Setup codec paths.. static UtlString sCodecPaths[] = { #ifdef WIN32 "bin", "..\\bin", #elif defined(__pingtel_on_posix__) "../../../../bin", "../../../bin", "../../bin", #else # error "Unknown platform" #endif "." }; static size_t sNumCodecPaths = sizeof(sCodecPaths)/sizeof(sCodecPaths[0]); /// Unit test for testing performance of supported codecs. class MpCodecsPerformanceTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(MpCodecsPerformanceTest); CPPUNIT_TEST(testCodecsPreformance); CPPUNIT_TEST_SUITE_END(); public: void setUp() { // Create pool for data buffers mpPool = new MpBufPool(ENCODED_FRAME_MAX_SIZE + MpArrayBuf::getHeaderSize(), 1); CPPUNIT_ASSERT(mpPool != NULL); // Create pool for buffer headers mpHeadersPool = new MpBufPool(sizeof(MpRtpBuf), 1); CPPUNIT_ASSERT(mpHeadersPool != NULL); // Set mpHeadersPool as default pool for audio and data pools. MpRtpBuf::smpDefaultPool = mpHeadersPool; } void tearDown() { if (mpPool != NULL) { delete mpPool; } if (mpHeadersPool != NULL) { delete mpHeadersPool; } } void testCodecsPreformance() { MpCodecFactory *pCodecFactory; const MppCodecInfoV1_1 **pCodecInfo; unsigned codecInfoNum; // Get/create codec factory pCodecFactory = MpCodecFactory::getMpCodecFactory(); CPPUNIT_ASSERT(pCodecFactory != NULL); // Load all available codecs size_t i; for(i = 0; i < sNumCodecPaths; i++) { printf("MpCodecsPerformanceTest loading codecs from: %s\n", sCodecPaths[i].data()); pCodecFactory->loadAllDynCodecs(sCodecPaths[i], CODEC_PLUGINS_FILTER); } // Get list of loaded codecs pCodecFactory->getCodecInfoArray(codecInfoNum, pCodecInfo); CPPUNIT_ASSERT(codecInfoNum>0); unsigned j; for (j=0; j<codecInfoNum; j++) { const char **pCodecFmtps; unsigned codecFmtpsNum; codecFmtpsNum = pCodecInfo[j]->fmtpsNum; pCodecFmtps = pCodecInfo[j]->fmtps; if (codecFmtpsNum == 0) { testOneCodecPreformance(pCodecFactory, pCodecInfo[j]->mimeSubtype, "", pCodecInfo[j]->sampleRate, pCodecInfo[j]->numChannels); } else { for (unsigned fmtpNum=0; fmtpNum<codecFmtpsNum; fmtpNum++) { testOneCodecPreformance(pCodecFactory, pCodecInfo[j]->mimeSubtype, pCodecFmtps[fmtpNum], pCodecInfo[j]->sampleRate, pCodecInfo[j]->numChannels); } } } // Free codec factory MpCodecFactory::freeSingletonHandle(); } protected: MpBufPool *mpPool; ///< Pool for data buffers MpBufPool *mpHeadersPool; ///< Pool for buffers headers void testOneCodecPreformance(MpCodecFactory *pCodecFactory, const UtlString &codecMime, const UtlString &codecFmtp, int sampleRate, int numChannels) { MpDecoderBase *pDecoder; MpEncoderBase *pEncoder; MpAudioSample *pOriginal; MpAudioSample pDecoded[DECODED_FRAME_MAX_SIZE]; int encodeFrameNum = 0; int maxPacketSamples = (MAX_PACKET_TIME*sampleRate)/1000; int frameSize = (sampleRate*FRAME_MS)/1000; int codecFrameSamples; // Allocate buffer for raw audio data pOriginal = new MpAudioSample[frameSize]; srand(time(NULL)); for (int k=0; k<frameSize; k++) { pOriginal[k] = rand()%32000 - 16000; } // Create and initialize decoder and encoder //printf("creating decoder: %s/%d/%d fmpt=\"%s\"\n", // codecMime.data(), sampleRate, numChannels, codecFmtp.data()); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pCodecFactory->createDecoder(codecMime, codecFmtp, sampleRate, numChannels, 0, pDecoder)); CPPUNIT_ASSERT(pDecoder); OsStatus initDecodeStatus = pDecoder->initDecode(); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, initDecodeStatus); // Could not test speed of signaling codec if (pDecoder->getInfo() == NULL || pDecoder->getInfo()->isSignalingCodec()) { pDecoder->freeDecode(); delete pDecoder; return; } CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pCodecFactory->createEncoder(codecMime, codecFmtp, sampleRate, numChannels, 0, pEncoder)); CPPUNIT_ASSERT(pEncoder); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pEncoder->initEncode()); // Get number of samples we'll pack to get one packet if (pEncoder->getInfo()->getCodecType() == CODEC_TYPE_FRAME_BASED) { codecFrameSamples = pEncoder->getInfo()->getNumSamplesPerFrame(); } else if (pEncoder->getInfo()->getCodecType() == CODEC_TYPE_SAMPLE_BASED) { codecFrameSamples = frameSize; } else { assert(!"Unknown codec type!"); } for (int i=0; i<NUM_PACKETS_TO_TEST; i++) { int tmpSamplesConsumed; int tmpEncodedSize; UtlBoolean tmpIsPacketReady; UtlBoolean tmpIsPacketSilent; MpRtpBufPtr pRtpPacket = mpPool->getBuffer(); unsigned char *pRtpPayloadPtr = (unsigned char *)pRtpPacket->getDataWritePtr(); int payloadSize = 0; int samplesInPacket = 0; OsTime start; OsTime stop; OsTime diff; // Encode frames until we get tmpSendNow set or reach packet size limit. do { // Encode one frame and measure time it took. UtlBoolean setMarkerBit; OsStatus result; OsDateTime::getCurTime(start); result = pEncoder->encode(pOriginal, frameSize, tmpSamplesConsumed, pRtpPayloadPtr, ENCODED_FRAME_MAX_SIZE-payloadSize, tmpEncodedSize, tmpIsPacketReady, tmpIsPacketSilent, setMarkerBit); OsDateTime::getCurTime(stop); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, result); // Print timing in CSV format diff = stop - start; printf("encode %s/%d/%d %s;%d;%ld.%06ld;%ld.%06ld\n", codecMime.data(), sampleRate, numChannels, codecFmtp.data(), encodeFrameNum, start.seconds(), start.usecs(), diff.seconds(), diff.usecs()); // Adjust encoding state payloadSize += tmpEncodedSize; pRtpPayloadPtr += tmpEncodedSize; samplesInPacket += tmpSamplesConsumed; CPPUNIT_ASSERT(payloadSize <= ENCODED_FRAME_MAX_SIZE); encodeFrameNum++; } while( (payloadSize == 0) ||( (tmpIsPacketReady != TRUE) && (samplesInPacket+codecFrameSamples <= maxPacketSamples))); pRtpPacket->setPayloadSize(payloadSize); // Decode frame, measure time and verify, that we decoded same number of samples. OsDateTime::getCurTime(start); tmpSamplesConsumed = pDecoder->decode(pRtpPacket, DECODED_FRAME_MAX_SIZE, pDecoded); OsDateTime::getCurTime(stop); CPPUNIT_ASSERT_EQUAL(samplesInPacket, tmpSamplesConsumed); // Print timing in TSV format diff = stop - start; printf("decode %s/%d/%d %s;%d;%ld.%06ld;%ld.%06ld\n", codecMime.data(), sampleRate, numChannels, codecFmtp.data(), i, start.seconds(), start.usecs(), diff.seconds(), diff.usecs()); } // Free encoder and decoder CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pDecoder->freeDecode()); delete pDecoder; CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pEncoder->freeEncode()); delete pEncoder; // Free buffer used for raw audio data delete[] pOriginal; } }; CPPUNIT_TEST_SUITE_REGISTRATION(MpCodecsPerformanceTest); <|endoftext|>
<commit_before>// coding: utf-8 #ifndef TASK_MECHANICS_HPP # error "Don't include this file directly, use 'task_mechanics.hpp' instead!" #endif task::Mechanics::Mechanics(Leds &leds, Buttons &buttons) : leds(leds), buttons(buttons), isCalibratedX(false), isCalibratedZ(false), correctionX(-40), correctionZ(15), xMotor(&OCR1AL, &TCCR1B, t1_steps), zMotor(&OCR0A, &TCCR0B, t0_steps), motorTimeout(30000) { } void task::Mechanics::initialize() { // setup CTC mode for Z axis TCCR0A = (1 << COM0A0) | (1 << WGM01); TCCR0B = 0; OCR0A = 0; TIMSK0 = (1 << OCIE0A); // setup CTC mode for X axis TCCR1A = (1 << COM1A0); TCCR1B = (1 << WGM12); OCR1A = 0; TIMSK1 = (1 << OCIE1A); XZ_Enable::setOutput(xpcc::Gpio::Low); releaseMotors(); xMotor.initialize(); zMotor.initialize(); } xpcc::co::Result<bool> task::Mechanics::calibrateX(void *ctx) { CO_BEGIN(ctx); startMotors(); if (buttons.isX_AxisLimitPressed()) { xMotor.rotateBy(100, 500); CO_WAIT_WHILE(xMotor.isRunning()); } xMotor.setSpeed(-100); timeout.restart(18000); CO_WAIT_UNTIL(buttons.isX_AxisLimitPressed() || timeout.isExpired()); xMotor.stop(); if ( (isCalibratedX = !timeout.isExpired()) ) { xMotor.rotateBy(correctionX, 200); CO_WAIT_WHILE(xMotor.isRunning()); leds.resetMechanicalError(); leds.resetBusy(); CO_RETURN(true); } leds.setMechanicalError(); leds.resetBusy(); CO_RETURN(false); CO_END(); } xpcc::co::Result<bool> task::Mechanics::calibrateZ(void *ctx) { CO_BEGIN(ctx); startMotors(); zMotor.stop(); if (buttons.isZ_AxisLimitPressed()) { zMotor.rotateBy(100, 500); CO_WAIT_WHILE(zMotor.isRunning()); zMotor.stop(); } zMotor.setSpeed(-100); timeout.restart(18000); CO_WAIT_UNTIL(buttons.isZ_AxisLimitPressed() || timeout.isExpired()); zMotor.stop(); if ( (isCalibratedZ = !timeout.isExpired()) ) { zMotor.rotateBy(correctionZ, 300); CO_WAIT_WHILE(zMotor.isRunning()); leds.resetMechanicalError(); leds.resetBusy(); CO_RETURN(true); } leds.setMechanicalError(); leds.resetBusy(); CO_RETURN(false); CO_END(); } xpcc::co::Result<bool> task::Mechanics::rotateForward(void *ctx) { CO_BEGIN(ctx); if (!isCalibrated()) CO_RETURN(false); startMotors(); xMotor.rotateBy(3600, 10000); CO_WAIT_WHILE(xMotor.isRunning()); zMotor.rotateBy(3600, 10000); CO_WAIT_WHILE(zMotor.isRunning()); leds.resetBusy(); isCalibratedX = false; isCalibratedZ = false; CO_RETURN(true); CO_END(); } xpcc::co::Result<bool> task::Mechanics::rotateBackward(void *ctx) { CO_BEGIN(ctx); startMotors(); zMotor.rotateBy(-3600, 5000); CO_WAIT_WHILE(zMotor.isRunning()); xMotor.rotateBy(-3600, 5000); CO_WAIT_WHILE(xMotor.isRunning()); releaseMotors(); CO_RETURN(true); CO_END(); } void task::Mechanics::startMotors() { leds.setBusy(); XZ_Enable::set(); motorTimeout.restart(30000); } void task::Mechanics::stopMotors() { xMotor.stop(); zMotor.stop(); stopCoroutine(); isCalibratedX = false; isCalibratedZ = false; leds.resetBusy(); } void task::Mechanics::releaseMotors() { stopMotors(); XZ_Enable::reset(); leds.resetMechanicalError(); } void task::Mechanics::update() { xMotor.update(); zMotor.update(); this->run(); } bool task::Mechanics::run() { PT_BEGIN(); while(true) { if (!xMotor.isRunning() && !zMotor.isRunning() && motorTimeout.isExpired()) { stopMotors(); XZ_Enable::reset(); } PT_YIELD(); } PT_END(); } <commit_msg>Make mechanics a little faster.<commit_after>// coding: utf-8 #ifndef TASK_MECHANICS_HPP # error "Don't include this file directly, use 'task_mechanics.hpp' instead!" #endif task::Mechanics::Mechanics(Leds &leds, Buttons &buttons) : leds(leds), buttons(buttons), isCalibratedX(false), isCalibratedZ(false), correctionX(-40), correctionZ(15), xMotor(&OCR1AL, &TCCR1B, t1_steps), zMotor(&OCR0A, &TCCR0B, t0_steps), motorTimeout(30000) { } void task::Mechanics::initialize() { // setup CTC mode for Z axis TCCR0A = (1 << COM0A0) | (1 << WGM01); TCCR0B = 0; OCR0A = 0; TIMSK0 = (1 << OCIE0A); // setup CTC mode for X axis TCCR1A = (1 << COM1A0); TCCR1B = (1 << WGM12); OCR1A = 0; TIMSK1 = (1 << OCIE1A); XZ_Enable::setOutput(xpcc::Gpio::Low); releaseMotors(); xMotor.initialize(); zMotor.initialize(); } xpcc::co::Result<bool> task::Mechanics::calibrateX(void *ctx) { CO_BEGIN(ctx); startMotors(); if (buttons.isX_AxisLimitPressed()) { xMotor.rotateBy(100, 500); CO_WAIT_WHILE(xMotor.isRunning()); } xMotor.setSpeed(-200); timeout.restart(18000); CO_WAIT_UNTIL(buttons.isX_AxisLimitPressed() || timeout.isExpired()); xMotor.stop(); if ( (isCalibratedX = !timeout.isExpired()) ) { xMotor.rotateBy(correctionX, 200); CO_WAIT_WHILE(xMotor.isRunning()); leds.resetMechanicalError(); leds.resetBusy(); CO_RETURN(true); } leds.setMechanicalError(); leds.resetBusy(); CO_RETURN(false); CO_END(); } xpcc::co::Result<bool> task::Mechanics::calibrateZ(void *ctx) { CO_BEGIN(ctx); startMotors(); zMotor.stop(); if (buttons.isZ_AxisLimitPressed()) { zMotor.rotateBy(100, 500); CO_WAIT_WHILE(zMotor.isRunning()); zMotor.stop(); } zMotor.setSpeed(-200); timeout.restart(18000); CO_WAIT_UNTIL(buttons.isZ_AxisLimitPressed() || timeout.isExpired()); zMotor.stop(); if ( (isCalibratedZ = !timeout.isExpired()) ) { zMotor.rotateBy(correctionZ, 300); CO_WAIT_WHILE(zMotor.isRunning()); leds.resetMechanicalError(); leds.resetBusy(); CO_RETURN(true); } leds.setMechanicalError(); leds.resetBusy(); CO_RETURN(false); CO_END(); } xpcc::co::Result<bool> task::Mechanics::rotateForward(void *ctx) { CO_BEGIN(ctx); if (!isCalibrated()) CO_RETURN(false); startMotors(); xMotor.rotateBy(3600, 10000); CO_WAIT_WHILE(xMotor.isRunning()); zMotor.rotateBy(3600, 10000); CO_WAIT_WHILE(zMotor.isRunning()); leds.resetBusy(); isCalibratedX = false; isCalibratedZ = false; CO_RETURN(true); CO_END(); } xpcc::co::Result<bool> task::Mechanics::rotateBackward(void *ctx) { CO_BEGIN(ctx); startMotors(); zMotor.rotateBy(-3600, 5000); CO_WAIT_WHILE(zMotor.isRunning()); xMotor.rotateBy(-3600, 5000); CO_WAIT_WHILE(xMotor.isRunning()); releaseMotors(); CO_RETURN(true); CO_END(); } void task::Mechanics::startMotors() { leds.setBusy(); XZ_Enable::set(); motorTimeout.restart(30000); } void task::Mechanics::stopMotors() { xMotor.stop(); zMotor.stop(); stopCoroutine(); isCalibratedX = false; isCalibratedZ = false; leds.resetBusy(); } void task::Mechanics::releaseMotors() { stopMotors(); XZ_Enable::reset(); leds.resetMechanicalError(); } void task::Mechanics::update() { xMotor.update(); zMotor.update(); this->run(); } bool task::Mechanics::run() { PT_BEGIN(); while(true) { if (!xMotor.isRunning() && !zMotor.isRunning() && motorTimeout.isExpired()) { stopMotors(); XZ_Enable::reset(); } PT_YIELD(); } PT_END(); } <|endoftext|>
<commit_before>/*************************************************/ /* regex.cpp */ /*************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /*************************************************/ /* Source code within this file is: */ /* (c) 2007-2010 Juan Linietsky, Ariel Manzur */ /* All Rights Reserved. */ /*************************************************/ #include "regex.h" #include "nrex.hpp" #include "core/os/memory.h" void RegEx::_bind_methods() { ObjectTypeDB::bind_method(_MD("compile","pattern"),&RegEx::compile); ObjectTypeDB::bind_method(_MD("find","text","start","end"),&RegEx::find, DEFVAL(0), DEFVAL(-1)); ObjectTypeDB::bind_method(_MD("clear"),&RegEx::clear); ObjectTypeDB::bind_method(_MD("is_valid"),&RegEx::is_valid); ObjectTypeDB::bind_method(_MD("get_capture_count"),&RegEx::get_capture_count); ObjectTypeDB::bind_method(_MD("get_capture","capture"),&RegEx::get_capture); ObjectTypeDB::bind_method(_MD("get_captures"),&RegEx::_bind_get_captures); }; StringArray RegEx::_bind_get_captures() const { StringArray ret; int count = get_capture_count(); for (int i=0; i<count; i++) { String c = get_capture(i); ret.push_back(c); }; return ret; }; void RegEx::clear() { text.clear(); captures.clear(); exp.reset(); }; bool RegEx::is_valid() const { return exp.valid(); }; int RegEx::get_capture_count() const { return exp.capture_size(); } String RegEx::get_capture(int capture) const { ERR_FAIL_COND_V( get_capture_count() <= capture, String() ); return text.substr(captures[capture].start, captures[capture].length); } Error RegEx::compile(const String& p_pattern) { clear(); exp.compile(p_pattern.c_str()); ERR_FAIL_COND_V( !exp.valid(), FAILED ); captures.resize(exp.capture_size()); return OK; }; int RegEx::find(const String& p_text, int p_start, int p_end) const { ERR_FAIL_COND_V( !exp.valid(), false ); ERR_FAIL_COND_V( p_text.length() < p_start, false ); ERR_FAIL_COND_V( p_text.length() < p_end, false ); bool res = exp.match(p_text.c_str(), &captures[0], p_start, p_end); if (res) { text = p_text; return captures[0].start; } text.clear(); return -1; }; RegEx::RegEx(const String& p_pattern) { compile(p_pattern); }; RegEx::RegEx() { }; RegEx::~RegEx() { clear(); }; <commit_msg>Fixed incorrect failsafe return values<commit_after>/*************************************************/ /* regex.cpp */ /*************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /*************************************************/ /* Source code within this file is: */ /* (c) 2007-2010 Juan Linietsky, Ariel Manzur */ /* All Rights Reserved. */ /*************************************************/ #include "regex.h" #include "nrex.hpp" #include "core/os/memory.h" void RegEx::_bind_methods() { ObjectTypeDB::bind_method(_MD("compile","pattern"),&RegEx::compile); ObjectTypeDB::bind_method(_MD("find","text","start","end"),&RegEx::find, DEFVAL(0), DEFVAL(-1)); ObjectTypeDB::bind_method(_MD("clear"),&RegEx::clear); ObjectTypeDB::bind_method(_MD("is_valid"),&RegEx::is_valid); ObjectTypeDB::bind_method(_MD("get_capture_count"),&RegEx::get_capture_count); ObjectTypeDB::bind_method(_MD("get_capture","capture"),&RegEx::get_capture); ObjectTypeDB::bind_method(_MD("get_captures"),&RegEx::_bind_get_captures); }; StringArray RegEx::_bind_get_captures() const { StringArray ret; int count = get_capture_count(); for (int i=0; i<count; i++) { String c = get_capture(i); ret.push_back(c); }; return ret; }; void RegEx::clear() { text.clear(); captures.clear(); exp.reset(); }; bool RegEx::is_valid() const { return exp.valid(); }; int RegEx::get_capture_count() const { return exp.capture_size(); } String RegEx::get_capture(int capture) const { ERR_FAIL_COND_V( get_capture_count() <= capture, String() ); return text.substr(captures[capture].start, captures[capture].length); } Error RegEx::compile(const String& p_pattern) { clear(); exp.compile(p_pattern.c_str()); ERR_FAIL_COND_V( !exp.valid(), FAILED ); captures.resize(exp.capture_size()); return OK; }; int RegEx::find(const String& p_text, int p_start, int p_end) const { ERR_FAIL_COND_V( !exp.valid(), -1 ); ERR_FAIL_COND_V( p_text.length() < p_start, -1 ); ERR_FAIL_COND_V( p_text.length() < p_end, -1 ); bool res = exp.match(p_text.c_str(), &captures[0], p_start, p_end); if (res) { text = p_text; return captures[0].start; } text.clear(); return -1; }; RegEx::RegEx(const String& p_pattern) { compile(p_pattern); }; RegEx::RegEx() { }; RegEx::~RegEx() { clear(); }; <|endoftext|>
<commit_before> #include <iostream> #include <unordered_map> #include <boost/algorithm/string.hpp> #include <vector> #include <Galois/Galois.h> #include <Galois/Graph/Graph.h> #include <cstring> #include <string> #include <fstream> using namespace std; using namespace boost; typedef enum{pi,po,nd} node_type; struct Node { string label_type;//a0,b0... node_type type;// pi,po,nd int fanins; bool fanout; int level; }; int main() { unordered_map <string, int> map; //unordered_map<string, int> map; int node_index = 0; typedef Galois::Graph::FirstGraph<Node,int,true> Graph; Graph g; //vector<Node> nodes; vector<Graph::GraphNode> gnodes; vector<string> fields; ifstream fin; fin.open("/home/alex/Downloads/test.v"); // open a file if (!fin.good()){ cout << "file not found\n"; return 1; // exit if file not found } // read each line of the file while (!fin.eof()) { // read an entire line into memory string line; getline(fin,line); trim(line); split(fields, line, is_any_of(" ")); Node n; if(fields[0].compare("input") == 0 || fields[0].compare("output") == 0||fields[0].compare("wire") == 0) { for(unsigned i =1;i<fields.size();i++){ //add to hash map to index to corresponding node in array if(fields[i].size()>1) { //Add data to each node for level and type of input if(fields[0].compare("input") == 0) { n.type = pi; n.level = 0; n.label_type = fields[i].substr(0,fields[i].length()-1); //nodes[node_index].type = pi; //nodes[node_index].level = 0; //nodes[node_index].label_type = fields[i].substr(0,fields[i].length()-1); } if(fields[0].compare("output") == 0) { n.type = po; n.label_type = fields[i].substr(0,fields[i].length()-1); //nodes[node_index].type = po; //nodes[node_index].label_type = fields[i].substr(0,fields[i].length()-1); } if(fields[0].compare("wire") == 0) { n.type = nd; n.label_type = fields[i].substr(0,fields[i].length()-1); //nodes[node_index].type = nd; //nodes[node_index].label_type = fields[i].substr(0,fields[i].length()-1); } //remove last char b/c its ',' or ';' map[fields[i].substr(0,fields[i].length()-1)] = node_index; //gnodes[node_index] = g.createNode(nodes[node_index]); gnodes.push_back(g.createNode(n)); g.addNode(gnodes[gnodes.size()-1]); //cout << "node index: "<< node_index<<endl; node_index++; } } } //cout <<"compare assign"<<endl; if(fields[0].compare("assign") == 0) { if(fields[4].compare("|") == 0) { //Edge weight: 2- Negative 1 - Positive g.getEdgeData(g.addEdge(gnodes[map[fields[3].substr(0,fields[3].length())]]//src ,gnodes[map[fields[1]]])) = 2;//dest g.getEdgeData(g.addEdge(gnodes[map[fields[5].substr(0,fields[5].length()-1)]] ,gnodes[map[fields[1]]])) = 2; //needs to be inproved doesnt work i think -alex //nodes[map[fields[1]]].fanout = 0;// TO DO: Negated output: Try using getData() } else { size_t invert = fields[3].find_first_of("~"); if (invert != string::npos){ //addEdge(src,dest) //remove the '~' from the start of string //map[string] returns node index to find which node g.getEdgeData(g.addEdge(gnodes[map[fields[3].substr(1,fields[3].length())]],gnodes[map[fields[1]]])) = 2;// } else{ g.getEdgeData(g.addEdge(gnodes[map[fields[3].substr(0,fields[3].length())]],gnodes[map[fields[1]]])) = 1; } invert = fields[5].find_first_of("~"); if (invert != string::npos){ //remove first and last char b/c '~' to start and ';' at th //cout <<fields[5] << " substr"<<fields[5].substr(1,fields[5].length()-1)<<" "<<map[fields[5].substr(1,fields[5].length()-1)]<< " "<< nodes[map[fields[5].substr(1,fields[5].length()-1)]].label_type <<endl; g.getEdgeData(g.addEdge(gnodes[map[fields[5].substr(1,fields[5].length()-2)]],gnodes[map[fields[1]]])) = 2; } else{ g.getEdgeData(g.addEdge(gnodes[map[fields[5].substr(0,fields[5].length()-1)]],gnodes[map[fields[1]]])) = 1; } } } } //cout << g.getData(gnodes[0]).label_type << endl; // Traverse graph for (Graph::iterator ii = g.begin(), ei = g.end(); ii != ei; ++ii) { Graph::GraphNode src = *ii; cout <<"src: "<< g.getData(src).label_type ; for (Graph::edge_iterator edge : g.out_edges(src)) { Graph::GraphNode dst = g.getEdgeDst(edge); cout <<" dest: "<< g.getData(dst).label_type; int edgeData = g.getEdgeData(edge); cout << " edge data " << edgeData; //assert(edgeData == 5); } cout <<endl; } return 0; } <commit_msg>Changing levels by fetching levels from the primary inputs and constructing it for intermediate nodes<commit_after> #include <iostream> #include <unordered_map> #include <boost/algorithm/string.hpp> #include <vector> #include <Galois/Galois.h> #include <Galois/Graph/Graph.h> #include <cstring> #include <string> #include <fstream> using namespace std; using namespace boost; typedef enum{pi,po,nd} node_type; struct Node { string label_type;//a0,b0... node_type type;// pi,po,nd int fanins; // Not required as of now bool fanout; //Not required as of now int level; }; int main() { unordered_map <string, int> map; //unordered_map<string, int> map; int node_index = 0; typedef Galois::Graph::FirstGraph<Node,int,true> Graph; Graph g; //vector<Node> nodes; vector<Graph::GraphNode> gnodes; vector<string> fields; ifstream fin; fin.open("/home/aditya/CS_220/alan-abc/examples/sk"); // open a file if (!fin.good()){ cout << "file not found\n"; return 1; // exit if file not found } // read each line of the file while (!fin.eof()) { // read an entire line into memory string line; getline(fin,line); trim(line); split(fields, line, is_any_of(" ")); Node n; if(fields[0].compare("input") == 0 || fields[0].compare("output") == 0||fields[0].compare("wire") == 0) { for(unsigned i =1;i<fields.size();i++){ //add to hash map to index to corresponding node in array if(fields[i].size()>1) { //Add data to each node for level and type of input if(fields[0].compare("input") == 0) { n.type = pi; n.level = 0; n.label_type = fields[i].substr(0,fields[i].length()-1); //nodes[node_index].type = pi; //nodes[node_index].level = 0; //nodes[node_index].label_type = fields[i].substr(0,fields[i].length()-1); } if(fields[0].compare("output") == 0) { n.type = po; n.level = -1; n.label_type = fields[i].substr(0,fields[i].length()-1); //nodes[node_index].type = po; //nodes[node_index].label_type = fields[i].substr(0,fields[i].length()-1); } if(fields[0].compare("wire") == 0) { n.type = nd; n.level = -2; n.label_type = fields[i].substr(0,fields[i].length()-1); //nodes[node_index].type = nd; //nodes[node_index].label_type = fields[i].substr(0,fields[i].length()-1); } //remove last char b/c its ',' or ';' map[fields[i].substr(0,fields[i].length()-1)] = node_index; //gnodes[node_index] = g.createNode(nodes[node_index]); gnodes.push_back(g.createNode(n)); g.addNode(gnodes[gnodes.size()-1]); //cout << "node index: "<< node_index<<endl; node_index++; } } } //cout <<"compare assign"<<endl; if(fields[0].compare("assign") == 0) { int level1,level2; if(fields[4].compare("|") == 0) { //Edge weight: 2- Negative 1 - Positive g.getEdgeData(g.addEdge(gnodes[map[fields[3].substr(0,fields[3].length())]]//src ,gnodes[map[fields[1]]])) = 2;//dest g.getEdgeData(g.addEdge(gnodes[map[fields[5].substr(0,fields[5].length()-1)]] ,gnodes[map[fields[1]]])) = 2; level1 = g.getData(gnodes[map[fields[3].substr(0,fields[3].length())]]).level; level2 = g.getData(gnodes[map[fields[5].substr(0,fields[5].length()-1)]]).level; g.getEdgeData(g.addEdge(gnodes[map[fields[1]]], gnodes[map[fields[3].substr(0,fields[3].length())]])) = 3;//back edges to determine fanins -> wt. = 3 g.getEdgeData(g.addEdge(gnodes[map[fields[1]]], gnodes[map[fields[5].substr(0,fields[5].length())]])) = 3;//back edges to determins fanins -> wt. = 3 } else { size_t invert = fields[3].find_first_of("~"); if (invert != string::npos){ //addEdge(src,dest) //remove the '~' from the start of string //map[string] returns node index to find which node g.getEdgeData(g.addEdge(gnodes[map[fields[3].substr(1,fields[3].length())]],gnodes[map[fields[1]]])) = 2;// level1 = g.getData(gnodes[map[fields[3].substr(1,fields[3].length())]]).level; g.getEdgeData(g.addEdge(gnodes[map[fields[1]]], gnodes[map[fields[3].substr(1,fields[3].length())]])) = 3;// Back edges to determine fanins -> wt. = 3 } else{ g.getEdgeData(g.addEdge(gnodes[map[fields[3].substr(0,fields[3].length())]],gnodes[map[fields[1]]])) = 1; level1 = g.getData(gnodes[map[fields[3].substr(0,fields[3].length())]]).level; g.getEdgeData(g.addEdge(gnodes[map[fields[1]]], gnodes[map[fields[3].substr(0,fields[3].length())]])) = 3;// Back edges to determine fanins -> wt. = 3 } invert = fields[5].find_first_of("~"); if (invert != string::npos){ //remove first and last char b/c '~' to start and ';' at th //cout <<fields[5] << " substr"<<fields[5].substr(1,fields[5].length()-1)<<" "<<map[fields[5].substr(1,fields[5].length()-1)]<< " "<< nodes[map[fields[5].substr(1,fields[5].length()-1)]].label_type <<endl; g.getEdgeData(g.addEdge(gnodes[map[fields[5].substr(1,fields[5].length()-2)]],gnodes[map[fields[1]]])) = 2; level2 = g.getData(gnodes[map[fields[5].substr(1,fields[5].length()-2)]]).level; g.getEdgeData(g.addEdge(gnodes[map[fields[1]]], gnodes[map[fields[5].substr(1,fields[5].length()-2)]])) = 3;// Back edges to determine fanins -> wt. = 3 } else{ g.getEdgeData(g.addEdge(gnodes[map[fields[5].substr(0,fields[5].length()-1)]],gnodes[map[fields[1]]])) = 1; level2 = g.getData(gnodes[map[fields[5].substr(0,fields[5].length()-1)]]).level; g.getEdgeData(g.addEdge(gnodes[map[fields[1]]], gnodes[map[fields[5].substr(0,fields[5].length()-1)]])) = 3;// Back edges to determine fanins -> wt. = 3 } } if(level1>=level2) g.getData(gnodes[map[fields[1]]]).level= level1+1; else g.getData(gnodes[map[fields[1]]]).level= level2+1; } } //cout << g.getData(gnodes[0]).label_type << endl; // Traverse graph for (Graph::iterator ii = g.begin(), ei = g.end(); ii != ei; ++ii) { Graph::GraphNode src = *ii; cout <<"src: "<< g.getData(src).label_type; cout <<"src: level"<<g.getData(src).level; for (Graph::edge_iterator edge : g.out_edges(src)) { Graph::GraphNode dst = g.getEdgeDst(edge); cout <<" dest: "<< g.getData(dst).label_type; int edgeData = g.getEdgeData(edge); cout << " edge data " << edgeData; //assert(edgeData == 5); } cout <<endl; } return 0; } <|endoftext|>
<commit_before>#include <stdio.h> #include <iostream> #include <QString> #include <QVariant> #include <QMessageBox> #include <QDebug> int line_no = 1; int file_eof = 0; int last_op = 0; const int cmd_invalid = 0; const int cmd_assign = 1; // var = 12 const int cmd_assign_plus = 2; // var = 12 + 44 const int cmd_assign_new = 3; // var = new ... enum SymbolType_ { NoError, Undefined, NumberError, EndOfText }; SymbolType_ SymbolType; // ------------------- // our AST struct ... // ------------------- typedef struct _MyNode { public: SymbolType_ command; std::string id; QChar op; double value; _MyNode * parent; _MyNode * lhs; _MyNode * rhs; _MyNode() { parent = nullptr; lhs = nullptr; rhs = nullptr; } ~_MyNode() { delete lhs; delete rhs; } } MyNode; MyNode *eval_ast = nullptr; void print_ast() { MyNode * tmp = new MyNode; tmp = eval_ast; while (tmp != nullptr) { printf("res: %f\n",tmp->value); tmp = tmp->rhs; } } void add_astnode(char op, double val1, double val2) { MyNode * tmp = new MyNode; MyNode * new_node; tmp = eval_ast; new_node = new MyNode; if (op == '+') new_node->op = '+'; if (val1 < val2) { new_node->lhs = new MyNode; new_node->lhs->value = val2; tmp = new_node->lhs; } else { std::cout << "A: " << val1; std::cout << "B: " << val2; new_node->rhs = new MyNode; new_node->rhs->value = val1; tmp = new_node->rhs; } tmp->parent = new MyNode; tmp->parent->id = std::string("assign"); eval_ast = tmp; std::cout << "C:> " << tmp->value << std::endl; } // ------------------------------------------------------ // namespace to avoid conflicts with other frameworks ... // ------------------------------------------------------ namespace kallup { QString number, ident; int m_pos = 0; // buffer position char * m_TextBuffer; // the source code buffer // ------------------------------------ // cut spaces, and return next char ... // ------------------------------------ int SkipWhiteSpaces() { int c = 0; while (1) { c = m_TextBuffer[m_pos++]; if (isspace(c)) continue; break; } return c; } QString GetIdent() { int c = 0; while (1) { c = m_TextBuffer[m_pos++]; if (isalpha(c)) { ident += c; continue; } break; } return ident; } #if 0 int Match(char *buffer, char expected) { if (SkipWhitespaces() == expected) return expected; throw QString("Expected token '%1' at position: %2") .arg(expected) .arg(pos); } #endif QString GetNumber(void) { int c = SkipWhiteSpaces(); if ((c >= '0') && (c <= '9')) number += c; else throw QString("number expected, but found other chars.\n" "or Syntax Error."); while (1) { c = m_TextBuffer[m_pos]; if (isdigit(c)) { number += c; ++m_pos; continue; } else if (c == '.') { number += '.'; ++m_pos; continue; } else if (c == EOF || c == 0) { if (number.size() > 0) return number; else throw QString("wrong token as excpected."); } else if (isspace(c)) { if (number.size() > 0) return number; continue; } else { throw QString("number expected, wrong type: >>%1<<").arg(c); break; } } return number; } template <typename T> struct Token { Token() { qDebug() << "new token"; } }; template < typename T > struct Token<T*> { Token(){ std::cout << "A< T* >" << std::endl; } }; struct bool_ { }; struct int_ { }; struct char_ { }; template <> struct Token<bool> { public: Token() { name = QString("bool"); value = static_cast<bool>(false); } QVariant value; QString name; }; template <> struct Token<int> { public: Token() { name = QString("int"); value = static_cast<int>(0); } bool parse() { qDebug() << "parse int"; qDebug() << GetNumber(); return true; } QVariant value; QString name; }; template <> struct Token<char> { public: Token() { name = QString("char"); value = QString(""); } bool parse() { qDebug() << "parse char"; qDebug() << GetIdent(); return true; } QVariant value; QString name; }; Token<bool> bool_; Token<int> int_; Token<char> char_; class ParserCommon { public: ParserCommon(QString src) { m_TextBuffer = new char[src.size()+1]; strcpy(m_TextBuffer,src.toLatin1().data()); } ~ParserCommon() { delete m_TextBuffer; } }; // ------------------------------------ // wrapper class for token scanning ... // ------------------------------------ class grammar { public: grammar() { } grammar & operator << (Token<int> t) { qDebug() << "a token: " << t.name; t.parse(); return *this; } grammar & operator + (Token<char> t) { qDebug() << "a token: " << t.name; t.parse(); return *this; } }; // ----------------------------------- // parser oode for an dBase parser ... // ----------------------------------- class dBase { public: dBase() { qDebug() << "handle dbase grammar..."; } void start(QString src) { ParserCommon pc(src); grammar go; // grammar: go +char_ << int_ << int_ << int_; // --------------------------------- // sanity check, if all token read ? // --------------------------------- if (m_pos < strlen(m_TextBuffer)) throw QString("not all input are proceed."); } }; template <typename T> class Parser: public T { public: Parser() { qDebug() << "parser init."; line_no = 1; m_pos = 0; ident .clear(); number.clear(); eval_ast = new MyNode; eval_ast->parent = new MyNode; eval_ast->parent->id = "root"; eval_ast->op = '+'; } }; } bool parseText(QString src) { try { using namespace kallup; Parser<dBase> p; p.start(src); QMessageBox::information(0,"Info","SUCCESS"); return true; } catch (QString &e) { QMessageBox::critical(0,"Error", QString("Error in line: %1\n%2") .arg(line_no) .arg(e)); } return false; } <commit_msg>update<commit_after>#include <stdio.h> #include <iostream> #include <string> #include <boost/variant/recursive_variant.hpp> #include <boost/variant/apply_visitor.hpp> #include <boost/variant/get.hpp> #include <QString> #include <QVariant> #include <QMessageBox> #include <QDebug> int line_no = 1; int file_eof = 0; int last_op = 0; const int cmd_invalid = 0; const int cmd_assign = 1; // var = 12 const int cmd_assign_plus = 2; // var = 12 + 44 const int cmd_assign_new = 3; // var = new ... enum SymbolType_ { NoError, Undefined, NumberError, EndOfText }; SymbolType_ SymbolType; // ------------------- // our AST struct ... // ------------------- typedef struct _MyNode { public: SymbolType_ command; std::string id; QChar op; double value; _MyNode * parent; _MyNode * lhs; _MyNode * rhs; _MyNode() { parent = nullptr; lhs = nullptr; rhs = nullptr; } ~_MyNode() { delete lhs; delete rhs; } } MyNode; MyNode *eval_ast = nullptr; void print_ast() { MyNode * tmp = new MyNode; tmp = eval_ast; while (tmp != nullptr) { printf("res: %f\n",tmp->value); tmp = tmp->rhs; } } void add_astnode(char op, double val1, double val2) { MyNode * tmp = new MyNode; MyNode * new_node; tmp = eval_ast; new_node = new MyNode; if (op == '+') new_node->op = '+'; if (val1 < val2) { new_node->lhs = new MyNode; new_node->lhs->value = val2; tmp = new_node->lhs; } else { std::cout << "A: " << val1; std::cout << "B: " << val2; new_node->rhs = new MyNode; new_node->rhs->value = val1; tmp = new_node->rhs; } tmp->parent = new MyNode; tmp->parent->id = std::string("assign"); eval_ast = tmp; std::cout << "C:> " << tmp->value << std::endl; } // ------------------------------------------------------ // namespace to avoid conflicts with other frameworks ... // ------------------------------------------------------ namespace kallup { QString number, ident; int m_pos = 0; // buffer position char * m_TextBuffer; // the source code buffer struct add { }; struct sub { }; struct mul { }; struct div { }; template <typename OpTag> struct binary_op; typedef boost::variant< double , boost::recursive_wrapper< binary_op<add> > , boost::recursive_wrapper< binary_op<sub> > , boost::recursive_wrapper< binary_op<mul> > , boost::recursive_wrapper< binary_op<div> > > expression; template <typename OpTag> struct binary_op { expression left; // variant instantiated here... expression right; binary_op( const expression & lhs, const expression & rhs ) : left(lhs), right(rhs) { } double get(binary_op<sub> *bo) { std::cout << "getter\n"; ///left = bo->left ; //right = bo->right; //double res = boost::get<double>(left) // - boost::get<double>(right); return 2.0; } binary_op(binary_op<mul> *mul, double val) { std::cout << "mexter" << std::endl; left = mul; right = val; } binary_op(binary_op<sub> *bo) { std::cout << "-----------------\n"; std::cout << bo->left << std::endl; std::cout << bo->right << std::endl; if (typeid(bo) == typeid(binary_op<sub>)) { std::cout << " ok = left" << std::endl; double res2 = get(&bo); std::cout << "==>> " << res2 << std::endl; } else { std::cout << (boost::get<double>(bo->left ) - boost::get<double>(bo->right)) << std::endl; } } binary_op(const binary_op<add> &bo) { //std::cout << bo.left << std::endl; //std::cout << bo.right << std::endl; std::cout << (boost::get<double>(bo.left ) + boost::get<double>(bo.right)) << std::endl; } binary_op(const binary_op<mul> &bo) { std::cout << "mopser" << std::endl; //std::cout << bo.left << std::endl; //std::cout << bo.right << std::endl; left = bo.left ; right = bo.right; std::cout << (boost::get<double>(bo.left ) * boost::get<double>(bo.right)) << std::endl; } binary_op(const binary_op<div> &bo) { //std::cout << bo.left << std::endl; //std::cout << bo.right << std::endl; std::cout << (boost::get<double>(bo.left ) / boost::get<double>(bo.right)) << std::endl; } }; class calculator: public boost::static_visitor<double> { public: double operator()(double value) const { std::cout << "getter value: " << value << std::endl; return value; } double operator()(const binary_op<add> & binary) const { return boost::apply_visitor( calculator(), binary.left ) + boost::apply_visitor( calculator(), binary.right ); } double operator()(const binary_op<sub> & binary) const { std::cout << "double subserle" << std::endl; std::cout << binary.left << std::endl; std::cout << binary.right << std::endl; return boost::apply_visitor( calculator(), binary.left ) - boost::apply_visitor( calculator(), binary.right ); } double operator()(const binary_op<mul> & binary) const { std::cout << "double:" << std::endl; std::cout << binary.left << std::endl; std::cout << binary.right << std::endl; return boost::apply_visitor( calculator(), binary.left ) * boost::apply_visitor( calculator(), binary.right ); } double operator()(const binary_op<div> & binary) const { return boost::apply_visitor( calculator(), binary.left ) / boost::apply_visitor( calculator(), binary.right ); } }; expression& operator - (expression& exp, const binary_op<sub> &v) { exp = boost::get<double>(v.left) - boost::get<double>(v.right); return exp; } std::ostream& operator << (std::ostream& os, const binary_op<add> &val) { qDebug() << "adder"; double res = boost::get<double>(val.left) + boost::get<double>(val.right); os << val.left << std::endl; os << val.right << std::endl; os << "A------" << std::endl; os << res << std::endl; return os; } std::ostream& operator<< (std::ostream& os, const binary_op<sub> &val) { qDebug() << "subser"; return os; } std::ostream& operator<< (std::ostream& os, const binary_op<mul> &val) { qDebug() << "muller"; return os; } std::ostream& operator<< (std::ostream& os, const binary_op<div> &val) { qDebug() << "diver"; return os; } void test() { expression res1 = binary_op<mul>(2.0 ,4.0); expression res2 = binary_op<sub>(res1,3.0); expression result = ( res2 ); std::cout << boost::apply_visitor(calculator(),result) << std::endl; } #if 0 class expression_ast { public: typedef boost::variant< nil , int , double , boost::recursive_wrapper<expression_ast> , boost::recursive_wrapper<binary_op> > type_expr; type_expr expr; expression_ast() {} expression_ast & operator += (int rhs); //expression_ast & operator -= (expression_ast * rhs); //expression_ast & operator *= (expression_ast * rhs); //expression_ast & operator /= (expression_ast * rhs); }; expression_ast expr_ast; std::ostream& operator<< (std::ostream& os, const expression_ast &ast) { qDebug() << "blaxter: "; os << ast.expr; return os; } std::ostream& operator<< (std::ostream& os, const nil &sn) { qDebug() << "nullscher"; return os; } struct binary_op { binary_op( char op , expression_ast & left , expression_ast & right) : op(op) , left(left) , right(right) { std::cout << "Math2: " << std::endl; } //binary_op(char op, expression_ast::type_expr &left, expression_ast *right) binary_op(char op, expression_ast::type_expr &left, int right) { qDebug() << "lefter"; expr_ast.expr = right; } binary_op & operator << (binary_op bop) { left = bop.left; right = bop.right; return *this; } char op; expression_ast left; expression_ast right; }; expression_ast& expression_ast::operator += (int rhs) { qDebug() << "inter: " << rhs; expr = binary_op('+', expr, rhs); return *this; } /* expression_ast& expression_ast::operator -= (expression_ast * rhs) { expr = binary_op('-', expr, rhs); return *this; } expression_ast& expression_ast::operator *= (expression_ast * rhs) { expr = binary_op('*', expr, rhs); return *this; } expression_ast& expression_ast::operator /= (expression_ast * rhs) { expr = binary_op('/', expr, rhs); return *this; }*/ QDebug & operator << (QDebug dbg, const expression_ast ast) { dbg << "hallo"; return dbg; } std::ostream& operator<< (std::ostream& os, const binary_op &bipo) { qDebug() << "bipo"; //qDebug() << boost::get<double>(bipo); os << bipo.left; os << bipo.right; return os; } // ------------------------------- // print/handle our AST - exec ... // ------------------------------- struct ast_print { typedef void result_type; void operator()(nil const & dv) const { qDebug() << "NILer"; } void operator()(int const & dv) const { std::cout << "int: " << dv << std::endl; } void operator()(double const & dv) const { std::cout << "dbl: " << dv << std::endl; } void operator()(expression_ast const& ast) const { qDebug() << "aster"; qDebug() << typeid(ast.expr).name(); if (expr_ast.expr.type() == typeid(binary_op)) { std::cout << boost::get<binary_op>(ast.expr) << std::endl; } qDebug() << "-------"; //binary_op *bop = boost::get<binary_op>; //if (!(ast.expr.type().name() == std::string("N11dBaseParser3nilE"))) boost::apply_visitor(*this, ast.expr); } void operator()(binary_op const& expr) const { std::cout << "op:" << expr.op << "("; boost::apply_visitor(*this, expr.left.expr); std::cout << ", "; boost::apply_visitor(*this, expr.right.expr); std::cout << ')'; } }; // ------------------------------------ // cut spaces, and return next char ... // ------------------------------------ int SkipWhiteSpaces() { int c = 0; while (1) { c = m_TextBuffer[m_pos++]; if (isspace(c)) continue; break; } return c; } QString GetIdent() { int c = 0; while (1) { c = m_TextBuffer[m_pos++]; if (isalpha(c)) { ident += c; continue; } break; } return ident; } #if 0 int Match(char *buffer, char expected) { if (SkipWhitespaces() == expected) return expected; throw QString("Expected token '%1' at position: %2") .arg(expected) .arg(pos); } #endif QString GetNumber(void) { int c = SkipWhiteSpaces(); if ((c >= '0') && (c <= '9')) number += c; else throw QString("number expected, but found other chars.\n" "or Syntax Error."); while (1) { c = m_TextBuffer[m_pos]; if (isdigit(c)) { number += c; ++m_pos; continue; } else if (c == '.') { number += '.'; ++m_pos; continue; } else if (c == EOF || c == 0) { if (number.size() > 0) return number; else throw QString("wrong token as excpected."); } else if (isspace(c)) { if (number.size() > 0) return number; continue; } else { throw QString("number expected, wrong type: >>%1<<").arg(c); break; } } return number; } template <typename T> struct Token { Token() { qDebug() << "new token"; } }; template < typename T > struct Token<T*> { Token(){ std::cout << "A< T* >" << std::endl; } }; struct bool_ { }; struct int_ { }; struct char_ { }; template <> struct Token<bool> { public: Token() { name = QString("bool"); value = static_cast<bool>(false); } QVariant value; QString name; }; template <> struct Token<int> { public: Token() { name = QString("int"); value = static_cast<int>(0); } bool parse() { qDebug() << "parse int"; qDebug() << GetNumber(); return true; } QVariant value; QString name; }; template <> struct Token<char> { public: Token() { name = QString("char"); value = QString(""); } bool parse() { qDebug() << "parse char"; qDebug() << GetIdent(); return true; } QVariant value; QString name; }; Token<bool> bool_; Token<int> int_; Token<char> char_; class ParserCommon { public: ParserCommon(QString src) { m_TextBuffer = new char[src.size()+1]; strcpy(m_TextBuffer,src.toLatin1().data()); } ~ParserCommon() { delete m_TextBuffer; } }; // ------------------------------------ // wrapper class for token scanning ... // ------------------------------------ class grammar { public: grammar() { } grammar & operator << (Token<int> t) { qDebug() << "a token: " << t.name; t.parse(); return *this; } grammar & operator + (Token<char> t) { qDebug() << "a token: " << t.name; t.parse(); return *this; } }; // ----------------------------------- // parser oode for an dBase parser ... // ----------------------------------- class dBase { public: dBase() { qDebug() << "handle dbase grammar..."; } void start(QString src) { ParserCommon pc(src); grammar go; // grammar: go +char_ << int_ << int_ << int_; // --------------------------------- // sanity check, if all token read ? // --------------------------------- if (m_pos < strlen(m_TextBuffer)) throw QString("not all input are proceed."); } }; template <typename T> class Parser: public T { public: Parser() { qDebug() << "parser init."; line_no = 1; m_pos = 0; ident .clear(); number.clear(); eval_ast = new MyNode; eval_ast->parent = new MyNode; eval_ast->parent->id = "root"; eval_ast->op = '+'; } }; void test() { expression_ast ast; // = new expression_ast; ast += int(4); expr_ast = ast; qDebug() << "ok"; ast_print printer; printer(expr_ast); } #endif } bool parseText(QString src) { kallup::test(); return true; /* try { using namespace kallup; Parser<dBase> p; p.start(src); QMessageBox::information(0,"Info","SUCCESS"); return true; } catch (QString &e) { QMessageBox::critical(0,"Error", QString("Error in line: %1\n%2") .arg(line_no) .arg(e)); }*/ return false; } <|endoftext|>
<commit_before>// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/net/url_request_fetch_job.h" #include <algorithm> #include <string> #include "atom/browser/api/atom_api_session.h" #include "atom/browser/atom_browser_context.h" #include "base/memory/ptr_util.h" #include "base/strings/string_util.h" #include "native_mate/dictionary.h" #include "native_mate/handle.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_response_writer.h" using content::BrowserThread; namespace atom { namespace { // Convert string to RequestType. net::URLFetcher::RequestType GetRequestType(const std::string& raw) { std::string method = base::ToUpperASCII(raw); if (method.empty() || method == "GET") return net::URLFetcher::GET; else if (method == "POST") return net::URLFetcher::POST; else if (method == "HEAD") return net::URLFetcher::HEAD; else if (method == "DELETE") return net::URLFetcher::DELETE_REQUEST; else if (method == "PUT") return net::URLFetcher::PUT; else if (method == "PATCH") return net::URLFetcher::PATCH; else // Use "GET" as fallback. return net::URLFetcher::GET; } // Pipe the response writer back to URLRequestFetchJob. class ResponsePiper : public net::URLFetcherResponseWriter { public: explicit ResponsePiper(URLRequestFetchJob* job) : first_write_(true), job_(job) {} // net::URLFetcherResponseWriter: int Initialize(const net::CompletionCallback& callback) override { return net::OK; } int Write(net::IOBuffer* buffer, int num_bytes, const net::CompletionCallback& callback) override { if (first_write_) { // The URLFetcherResponseWriter doesn't have an event when headers have // been read, so we have to emulate by hooking to first write event. job_->HeadersCompleted(); first_write_ = false; } return job_->DataAvailable(buffer, num_bytes, callback); } int Finish(const net::CompletionCallback& callback) override { return net::OK; } private: bool first_write_; URLRequestFetchJob* job_; DISALLOW_COPY_AND_ASSIGN(ResponsePiper); }; } // namespace URLRequestFetchJob::URLRequestFetchJob( net::URLRequest* request, net::NetworkDelegate* network_delegate) : JsAsker<net::URLRequestJob>(request, network_delegate), pending_buffer_size_(0), write_num_bytes_(0) { } void URLRequestFetchJob::BeforeStartInUI( v8::Isolate* isolate, v8::Local<v8::Value> value) { mate::Dictionary options; if (!mate::ConvertFromV8(isolate, value, &options)) return; // When |session| is set to |null| we use a new request context for fetch job. mate::Handle<api::Session> session; if (options.Get("session", &session)) { if (session.IsEmpty()) { // We have to create the URLRequestContextGetter on UI thread. url_request_context_getter_ = new brightray::URLRequestContextGetter( this, nullptr, nullptr, base::FilePath(), true, BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO), BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::FILE), nullptr, content::URLRequestInterceptorScopedVector()); } else { AtomBrowserContext* browser_context = session->browser_context(); url_request_context_getter_ = browser_context->url_request_context_getter(); } } } void URLRequestFetchJob::StartAsync(std::unique_ptr<base::Value> options) { if (!options->IsType(base::Value::TYPE_DICTIONARY)) { NotifyStartError(net::URLRequestStatus( net::URLRequestStatus::FAILED, net::ERR_NOT_IMPLEMENTED)); return; } std::string url, method, referrer; base::DictionaryValue* upload_data = nullptr; base::DictionaryValue* dict = static_cast<base::DictionaryValue*>(options.get()); dict->GetString("url", &url); dict->GetString("method", &method); dict->GetString("referrer", &referrer); dict->GetDictionary("uploadData", &upload_data); // Check if URL is valid. GURL formated_url(url); if (!formated_url.is_valid()) { NotifyStartError(net::URLRequestStatus( net::URLRequestStatus::FAILED, net::ERR_INVALID_URL)); return; } // Use |request|'s method if |method| is not specified. net::URLFetcher::RequestType request_type; if (method.empty()) request_type = GetRequestType(request()->method()); else request_type = GetRequestType(method); fetcher_ = net::URLFetcher::Create(formated_url, request_type, this); fetcher_->SaveResponseWithWriter(base::WrapUnique(new ResponsePiper(this))); // A request context getter is passed by the user. if (url_request_context_getter_) fetcher_->SetRequestContext(url_request_context_getter_.get()); else fetcher_->SetRequestContext(request_context_getter()); // Use |request|'s referrer if |referrer| is not specified. if (referrer.empty()) fetcher_->SetReferrer(request()->referrer()); else fetcher_->SetReferrer(referrer); // Set the data needed for POSTs. if (upload_data && request_type == net::URLFetcher::POST) { std::string content_type, data; upload_data->GetString("contentType", &content_type); upload_data->GetString("data", &data); fetcher_->SetUploadData(content_type, data); } // Use |request|'s headers. fetcher_->SetExtraRequestHeaders( request()->extra_request_headers().ToString()); fetcher_->Start(); } void URLRequestFetchJob::HeadersCompleted() { response_info_.reset(new net::HttpResponseInfo); response_info_->headers = fetcher_->GetResponseHeaders(); NotifyHeadersComplete(); } int URLRequestFetchJob::DataAvailable(net::IOBuffer* buffer, int num_bytes, const net::CompletionCallback& callback) { // When pending_buffer_ is empty, there's no ReadRawData() operation waiting // for IO completion, we have to save the parameters until the request is // ready to read data. if (!pending_buffer_.get()) { write_buffer_ = buffer; write_num_bytes_ = num_bytes; write_callback_ = callback; return net::ERR_IO_PENDING; } // Write data to the pending buffer and clear them after the writing. int bytes_read = BufferCopy(buffer, num_bytes, pending_buffer_.get(), pending_buffer_size_); ClearPendingBuffer(); ReadRawDataComplete(bytes_read); return bytes_read; } void URLRequestFetchJob::Kill() { JsAsker<URLRequestJob>::Kill(); fetcher_.reset(); } int URLRequestFetchJob::ReadRawData(net::IOBuffer* dest, int dest_size) { if (GetResponseCode() == 204) { request()->set_received_response_content_length(prefilter_bytes_read()); return net::OK; } // When write_buffer_ is empty, there is no data valable yet, we have to save // the dest buffer util DataAvailable. if (!write_buffer_.get()) { pending_buffer_ = dest; pending_buffer_size_ = dest_size; return net::ERR_IO_PENDING; } // Read from the write buffer and clear them after reading. int bytes_read = BufferCopy(write_buffer_.get(), write_num_bytes_, dest, dest_size); net::CompletionCallback write_callback = write_callback_; ClearWriteBuffer(); write_callback.Run(bytes_read); return bytes_read; } bool URLRequestFetchJob::GetMimeType(std::string* mime_type) const { if (!response_info_ || !response_info_->headers) return false; return response_info_->headers->GetMimeType(mime_type); } void URLRequestFetchJob::GetResponseInfo(net::HttpResponseInfo* info) { if (response_info_) *info = *response_info_; } int URLRequestFetchJob::GetResponseCode() const { if (!response_info_ || !response_info_->headers) return -1; return response_info_->headers->response_code(); } void URLRequestFetchJob::OnURLFetchComplete(const net::URLFetcher* source) { if (!response_info_) { // Since we notify header completion only after first write there will be // no response object constructed for http respones with no content 204. // We notify header completion here. HeadersCompleted(); return; } ClearPendingBuffer(); ClearWriteBuffer(); if (fetcher_->GetStatus().is_success()) ReadRawDataComplete(0); else NotifyStartError(fetcher_->GetStatus()); } int URLRequestFetchJob::BufferCopy(net::IOBuffer* source, int num_bytes, net::IOBuffer* target, int target_size) { int bytes_written = std::min(num_bytes, target_size); memcpy(target->data(), source->data(), bytes_written); return bytes_written; } void URLRequestFetchJob::ClearPendingBuffer() { pending_buffer_ = nullptr; pending_buffer_size_ = 0; } void URLRequestFetchJob::ClearWriteBuffer() { write_buffer_ = nullptr; write_num_bytes_ = 0; write_callback_.Reset(); } } // namespace atom <commit_msg>URLRequestFetchJob should report start error<commit_after>// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/net/url_request_fetch_job.h" #include <algorithm> #include <string> #include "atom/browser/api/atom_api_session.h" #include "atom/browser/atom_browser_context.h" #include "base/memory/ptr_util.h" #include "base/strings/string_util.h" #include "native_mate/dictionary.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_response_writer.h" using content::BrowserThread; namespace atom { namespace { // Convert string to RequestType. net::URLFetcher::RequestType GetRequestType(const std::string& raw) { std::string method = base::ToUpperASCII(raw); if (method.empty() || method == "GET") return net::URLFetcher::GET; else if (method == "POST") return net::URLFetcher::POST; else if (method == "HEAD") return net::URLFetcher::HEAD; else if (method == "DELETE") return net::URLFetcher::DELETE_REQUEST; else if (method == "PUT") return net::URLFetcher::PUT; else if (method == "PATCH") return net::URLFetcher::PATCH; else // Use "GET" as fallback. return net::URLFetcher::GET; } // Pipe the response writer back to URLRequestFetchJob. class ResponsePiper : public net::URLFetcherResponseWriter { public: explicit ResponsePiper(URLRequestFetchJob* job) : first_write_(true), job_(job) {} // net::URLFetcherResponseWriter: int Initialize(const net::CompletionCallback& callback) override { return net::OK; } int Write(net::IOBuffer* buffer, int num_bytes, const net::CompletionCallback& callback) override { if (first_write_) { // The URLFetcherResponseWriter doesn't have an event when headers have // been read, so we have to emulate by hooking to first write event. job_->HeadersCompleted(); first_write_ = false; } return job_->DataAvailable(buffer, num_bytes, callback); } int Finish(const net::CompletionCallback& callback) override { return net::OK; } private: bool first_write_; URLRequestFetchJob* job_; DISALLOW_COPY_AND_ASSIGN(ResponsePiper); }; } // namespace URLRequestFetchJob::URLRequestFetchJob( net::URLRequest* request, net::NetworkDelegate* network_delegate) : JsAsker<net::URLRequestJob>(request, network_delegate), pending_buffer_size_(0), write_num_bytes_(0) { } void URLRequestFetchJob::BeforeStartInUI( v8::Isolate* isolate, v8::Local<v8::Value> value) { mate::Dictionary options; if (!mate::ConvertFromV8(isolate, value, &options)) return; // When |session| is set to |null| we use a new request context for fetch job. v8::Local<v8::Value> val; if (options.Get("session", &val)) { if (val->IsNull()) { // We have to create the URLRequestContextGetter on UI thread. url_request_context_getter_ = new brightray::URLRequestContextGetter( this, nullptr, nullptr, base::FilePath(), true, BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO), BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::FILE), nullptr, content::URLRequestInterceptorScopedVector()); } else { mate::Handle<api::Session> session; if (mate::ConvertFromV8(isolate, val, &session) && !session.IsEmpty()) { AtomBrowserContext* browser_context = session->browser_context(); url_request_context_getter_ = browser_context->url_request_context_getter(); } } } } void URLRequestFetchJob::StartAsync(std::unique_ptr<base::Value> options) { if (!options->IsType(base::Value::TYPE_DICTIONARY)) { NotifyStartError(net::URLRequestStatus( net::URLRequestStatus::FAILED, net::ERR_NOT_IMPLEMENTED)); return; } std::string url, method, referrer; base::DictionaryValue* upload_data = nullptr; base::DictionaryValue* dict = static_cast<base::DictionaryValue*>(options.get()); dict->GetString("url", &url); dict->GetString("method", &method); dict->GetString("referrer", &referrer); dict->GetDictionary("uploadData", &upload_data); // Check if URL is valid. GURL formated_url(url); if (!formated_url.is_valid()) { NotifyStartError(net::URLRequestStatus( net::URLRequestStatus::FAILED, net::ERR_INVALID_URL)); return; } // Use |request|'s method if |method| is not specified. net::URLFetcher::RequestType request_type; if (method.empty()) request_type = GetRequestType(request()->method()); else request_type = GetRequestType(method); fetcher_ = net::URLFetcher::Create(formated_url, request_type, this); fetcher_->SaveResponseWithWriter(base::WrapUnique(new ResponsePiper(this))); // A request context getter is passed by the user. if (url_request_context_getter_) fetcher_->SetRequestContext(url_request_context_getter_.get()); else fetcher_->SetRequestContext(request_context_getter()); // Use |request|'s referrer if |referrer| is not specified. if (referrer.empty()) fetcher_->SetReferrer(request()->referrer()); else fetcher_->SetReferrer(referrer); // Set the data needed for POSTs. if (upload_data && request_type == net::URLFetcher::POST) { std::string content_type, data; upload_data->GetString("contentType", &content_type); upload_data->GetString("data", &data); fetcher_->SetUploadData(content_type, data); } // Use |request|'s headers. fetcher_->SetExtraRequestHeaders( request()->extra_request_headers().ToString()); fetcher_->Start(); } void URLRequestFetchJob::HeadersCompleted() { response_info_.reset(new net::HttpResponseInfo); response_info_->headers = fetcher_->GetResponseHeaders(); NotifyHeadersComplete(); } int URLRequestFetchJob::DataAvailable(net::IOBuffer* buffer, int num_bytes, const net::CompletionCallback& callback) { // When pending_buffer_ is empty, there's no ReadRawData() operation waiting // for IO completion, we have to save the parameters until the request is // ready to read data. if (!pending_buffer_.get()) { write_buffer_ = buffer; write_num_bytes_ = num_bytes; write_callback_ = callback; return net::ERR_IO_PENDING; } // Write data to the pending buffer and clear them after the writing. int bytes_read = BufferCopy(buffer, num_bytes, pending_buffer_.get(), pending_buffer_size_); ClearPendingBuffer(); ReadRawDataComplete(bytes_read); return bytes_read; } void URLRequestFetchJob::Kill() { JsAsker<URLRequestJob>::Kill(); fetcher_.reset(); } int URLRequestFetchJob::ReadRawData(net::IOBuffer* dest, int dest_size) { if (GetResponseCode() == 204) { request()->set_received_response_content_length(prefilter_bytes_read()); return net::OK; } // When write_buffer_ is empty, there is no data valable yet, we have to save // the dest buffer util DataAvailable. if (!write_buffer_.get()) { pending_buffer_ = dest; pending_buffer_size_ = dest_size; return net::ERR_IO_PENDING; } // Read from the write buffer and clear them after reading. int bytes_read = BufferCopy(write_buffer_.get(), write_num_bytes_, dest, dest_size); net::CompletionCallback write_callback = write_callback_; ClearWriteBuffer(); write_callback.Run(bytes_read); return bytes_read; } bool URLRequestFetchJob::GetMimeType(std::string* mime_type) const { if (!response_info_ || !response_info_->headers) return false; return response_info_->headers->GetMimeType(mime_type); } void URLRequestFetchJob::GetResponseInfo(net::HttpResponseInfo* info) { if (response_info_) *info = *response_info_; } int URLRequestFetchJob::GetResponseCode() const { if (!response_info_ || !response_info_->headers) return -1; return response_info_->headers->response_code(); } void URLRequestFetchJob::OnURLFetchComplete(const net::URLFetcher* source) { ClearPendingBuffer(); ClearWriteBuffer(); if (fetcher_->GetStatus().is_success()) { if (!response_info_) { // Since we notify header completion only after first write there will be // no response object constructed for http respones with no content 204. // We notify header completion here. HeadersCompleted(); return; } ReadRawDataComplete(0); } else { NotifyStartError(fetcher_->GetStatus()); } } int URLRequestFetchJob::BufferCopy(net::IOBuffer* source, int num_bytes, net::IOBuffer* target, int target_size) { int bytes_written = std::min(num_bytes, target_size); memcpy(target->data(), source->data(), bytes_written); return bytes_written; } void URLRequestFetchJob::ClearPendingBuffer() { pending_buffer_ = nullptr; pending_buffer_size_ = 0; } void URLRequestFetchJob::ClearWriteBuffer() { write_buffer_ = nullptr; write_num_bytes_ = 0; write_callback_.Reset(); } } // namespace atom <|endoftext|>
<commit_before>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2016 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : hugh/support/test/signal_handler.cpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ // includes, system #include <array> // std::array<> #include <csignal> // std::raise #include <cstdlib> // EXIT_* #include <tuple> // std::tuple<> // includes, project #include <hugh/support/chrono.hpp> #include <hugh/support/signal_handler.hpp> #define HUGH_USE_TRACE #undef HUGH_USE_TRACE #include <hugh/support/trace.hpp> // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) // variables, internal #if defined(_WIN32) unsigned const signal_test_size( 6); #else unsigned const signal_test_size(29); #endif std::array<std::tuple<signed /* signo */, signed /* raised */, bool /* handled */>, signal_test_size> signal_test = { { std::make_tuple(SIGABRT, -1, false), std::make_tuple(SIGFPE, -1, false), std::make_tuple(SIGILL, -1, false), std::make_tuple(SIGINT, -1, false), std::make_tuple(SIGSEGV, -1, false), std::make_tuple(SIGTERM, -1, false), #if !defined(_WIN32) std::make_tuple(SIGALRM, -1, false), std::make_tuple(SIGBUS, -1, false), std::make_tuple(SIGCHLD, -1, false), std::make_tuple(SIGCONT, -1, false), std::make_tuple(SIGHUP, -1, false), std::make_tuple(SIGPIPE, -1, false), std::make_tuple(SIGPOLL, -1, false), std::make_tuple(SIGPROF, -1, false), std::make_tuple(SIGPWR, -1, false), std::make_tuple(SIGQUIT, -1, false), std::make_tuple(SIGSTKFLT, -1, false), std::make_tuple(SIGSYS, -1, false), std::make_tuple(SIGTRAP, -1, false), std::make_tuple(SIGTSTP, -1, false), std::make_tuple(SIGTTIN, -1, false), std::make_tuple(SIGTTOU, -1, false), std::make_tuple(SIGURG, -1, false), std::make_tuple(SIGUSR1, -1, false), std::make_tuple(SIGUSR2, -1, false), std::make_tuple(SIGVTALRM, -1, false), std::make_tuple(SIGWINCH, -1, false), std::make_tuple(SIGXCPU, -1, false), std::make_tuple(SIGXFSZ, -1, false), #endif } }; // functions, internal void signal_handler(signed signo) { TRACE("<unnamed>::signal_handler(" + std::to_string(signo) + ") [" + hugh::support::signal_name(signo) + "]"); for (auto& s : signal_test) { if (signo == std::get<0>(s)) { std::get<2>(s) = true; } } } signed raise_signal(signed signo) { TRACE("<unnamed>::raise_signal"); // current linux/glibc implementation provides raise(2) as a wrapper for tgkill(2), which sends // the signal to the current thread/thread group but not all threads in the process; need to // find out how to make the signal-handler thread part of the parent thread's group! #if !defined(_WIN32) return ::kill(::getpid(), signo); #else return ::raise(signo); #endif } } // namespace { int main() { TRACE("main"); using namespace hugh; support::signal_handler::handler_function_type urg_handler(support::signal_handler::instance->handler(SIGURG)); support::signal_handler::handler_function_type fpe_handler(support::signal_handler::instance->handler(SIGFPE)); for (auto& s : signal_test) { support::signal_handler::instance->handler(std::get<0>(s), signal_handler); } int result(EXIT_SUCCESS); support::clock::duration const delay(std::chrono::microseconds(725)); for (auto& s : signal_test) { std::get<1>(s) = raise_signal(std::get<0>(s)); support::sleep(delay); if ((0 != std::get<1>(s)) || !std::get<2>(s)) { std::cout << "unhandled signal: " << support::signal_name(std::get<0>(s)) << std::endl; result = EXIT_FAILURE; } } if (EXIT_FAILURE != result) { support::signal_handler::instance->handler(SIGURG, urg_handler); support::signal_handler::instance->handler(SIGFPE, fpe_handler); raise_signal(SIGURG); // ignored, direct handler //raise_signal(SIGFPE); // abort, indirect handler support::sleep(delay); } return result; } <commit_msg>fixed: msvc compile<commit_after>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2016 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : hugh/support/test/signal_handler.cpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ // includes, system #include <array> // std::array<> #include <csignal> // std::raise #include <cstdlib> // EXIT_* #include <tuple> // std::tuple<> // includes, project #include <hugh/support/chrono.hpp> #include <hugh/support/signal_handler.hpp> #define HUGH_USE_TRACE #undef HUGH_USE_TRACE #include <hugh/support/trace.hpp> // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) // variables, internal #if defined(_WIN32) unsigned const signal_test_size( 6); #else unsigned const signal_test_size(29); #endif std::array<std::tuple<signed /* signo */, signed /* raised */, bool /* handled */>, signal_test_size> signal_test = { { std::make_tuple(SIGABRT, -1, false), std::make_tuple(SIGFPE, -1, false), std::make_tuple(SIGILL, -1, false), std::make_tuple(SIGINT, -1, false), std::make_tuple(SIGSEGV, -1, false), std::make_tuple(SIGTERM, -1, false), #if !defined(_WIN32) std::make_tuple(SIGALRM, -1, false), std::make_tuple(SIGBUS, -1, false), std::make_tuple(SIGCHLD, -1, false), std::make_tuple(SIGCONT, -1, false), std::make_tuple(SIGHUP, -1, false), std::make_tuple(SIGPIPE, -1, false), std::make_tuple(SIGPOLL, -1, false), std::make_tuple(SIGPROF, -1, false), std::make_tuple(SIGPWR, -1, false), std::make_tuple(SIGQUIT, -1, false), std::make_tuple(SIGSTKFLT, -1, false), std::make_tuple(SIGSYS, -1, false), std::make_tuple(SIGTRAP, -1, false), std::make_tuple(SIGTSTP, -1, false), std::make_tuple(SIGTTIN, -1, false), std::make_tuple(SIGTTOU, -1, false), std::make_tuple(SIGURG, -1, false), std::make_tuple(SIGUSR1, -1, false), std::make_tuple(SIGUSR2, -1, false), std::make_tuple(SIGVTALRM, -1, false), std::make_tuple(SIGWINCH, -1, false), std::make_tuple(SIGXCPU, -1, false), std::make_tuple(SIGXFSZ, -1, false), #endif } }; // functions, internal void signal_handler(signed signo) { TRACE("<unnamed>::signal_handler(" + std::to_string(signo) + ") [" + hugh::support::signal_name(signo) + "]"); for (auto& s : signal_test) { if (signo == std::get<0>(s)) { std::get<2>(s) = true; } } } signed raise_signal(signed signo) { TRACE("<unnamed>::raise_signal"); // current linux/glibc implementation provides raise(2) as a wrapper for tgkill(2), which sends // the signal to the current thread/thread group but not all threads in the process; need to // find out how to make the signal-handler thread part of the parent thread's group! #if !defined(_WIN32) return ::kill(::getpid(), signo); #else return ::raise(signo); #endif } } // namespace { int main() { TRACE("main"); using namespace hugh; #if !defined(_WIN32) support::signal_handler::handler_function_type urg_handler(support::signal_handler::instance->handler(SIGURG)); #endif support::signal_handler::handler_function_type fpe_handler(support::signal_handler::instance->handler(SIGFPE)); for (auto& s : signal_test) { support::signal_handler::instance->handler(std::get<0>(s), signal_handler); } int result(EXIT_SUCCESS); support::clock::duration const delay(std::chrono::microseconds(725)); for (auto& s : signal_test) { std::get<1>(s) = raise_signal(std::get<0>(s)); support::sleep(delay); if ((0 != std::get<1>(s)) || !std::get<2>(s)) { std::cout << "unhandled signal: " << support::signal_name(std::get<0>(s)) << std::endl; result = EXIT_FAILURE; } } if (EXIT_FAILURE != result) { #if !defined(_WIN32) support::signal_handler::instance->handler(SIGURG, urg_handler); #endif support::signal_handler::instance->handler(SIGFPE, fpe_handler); #if !defined(_WIN32) raise_signal(SIGURG); // ignored, direct handler #endif //raise_signal(SIGFPE); // abort, indirect handler support::sleep(delay); } return result; } <|endoftext|>
<commit_before>#include "common/viditem/vscviditemvidstor.h" VSCVidItemVidStor::VSCVidItemVidStor(VidStor cStor, QTreeWidgetItem *parent) : m_cStor(cStor), VSCVidItemInf(parent) { } VSCVidItemVidStor::~VSCVidItemVidStor() { }<commit_msg>Signed-off-by: xsmart <xsmart@veyesys.com><commit_after>#include "common/viditem/vscviditemvidstor.h" VSCVidItemVidStor::VSCVidItemVidStor(VidStor cStor, ClientFactory &pFactory, QTreeWidgetItem *parent) : m_cStor(cStor), VSCVidItemInf(pFactory, parent) { /* if came here, all the item is ready, just start the cStor client */ } VSCVidItemVidStor::~VSCVidItemVidStor() { }<|endoftext|>
<commit_before>// kmsearchpatternedit.cpp // Author: Marc Mutz <Marc@Mutz.com> // This code is under GPL #include <config.h> #include "kmsearchpatternedit.h" #include "kmsearchpattern.h" #include <klocale.h> #include <kdebug.h> #include <klineedit.h> #include <kparts/componentfactory.h> #include <kregexpeditorinterface.h> #include <qpushbutton.h> #include <qdialog.h> #include <qradiobutton.h> #include <qcombobox.h> #include <qbuttongroup.h> #include <assert.h> //============================================================================= // // class KMSearchRuleWidget // //============================================================================= KMSearchRuleWidget::KMSearchRuleWidget(QWidget *parent, KMSearchRule *aRule, const char *name, bool headersOnly, bool absoluteDates) : QHBox(parent,name), mRuleEditBut(0), mRegExpEditDialog(0) { initLists( headersOnly, absoluteDates ); // sFilter{Func,Field}List are local to KMSearchRuleWidget initWidget(); if ( aRule ) setRule(aRule); else reset(); } void KMSearchRuleWidget::initWidget() { setSpacing(4); mRuleField = new QComboBox( true, this, "mRuleField" ); mRuleFunc = new QComboBox( false, this, "mRuleFunc" ); mRuleValue = new KLineEdit( this, "mRuleValue" ); if( !KTrader::self()->query("KRegExpEditor/KRegExpEditor").isEmpty() ) { mRuleEditBut = new QPushButton( i18n("Edit..."), this, "mRuleEditBut" ); connect( mRuleEditBut, SIGNAL( clicked() ), this, SLOT( editRegExp())); connect( mRuleFunc, SIGNAL( activated(int) ), this, SLOT( functionChanged(int) ) ); functionChanged( mRuleFunc->currentItem() ); } mRuleFunc->insertStringList(mFilterFuncList); mRuleFunc->adjustSize(); mRuleField->insertStringList(mFilterFieldList); // don't show sliders when popping up this menu mRuleField->setSizeLimit( mRuleField->count() ); mRuleField->adjustSize(); connect( mRuleField, SIGNAL(textChanged(const QString &)), this, SIGNAL(fieldChanged(const QString &)) ); connect( mRuleValue, SIGNAL(textChanged(const QString &)), this, SIGNAL(contentsChanged(const QString &)) ); } void KMSearchRuleWidget::editRegExp() { if ( mRegExpEditDialog == 0 ) mRegExpEditDialog = KParts::ComponentFactory::createInstanceFromQuery<QDialog>( "KRegExpEditor/KRegExpEditor", QString::null, this ); KRegExpEditorInterface *iface = static_cast<KRegExpEditorInterface *>( mRegExpEditDialog->qt_cast( "KRegExpEditorInterface" ) ); if( iface ) { iface->setRegExp( mRuleValue->text() ); if( mRegExpEditDialog->exec() == QDialog::Accepted ) mRuleValue->setText( iface->regExp() ); } } void KMSearchRuleWidget::functionChanged( int which ) { mRuleEditBut->setEnabled( which == 4 || which == 5 ); } void KMSearchRuleWidget::setRule(KMSearchRule *aRule) { assert ( aRule ); blockSignals(TRUE); //--------------set the field int i = indexOfRuleField( aRule->field() ); if ( i<0 ) { // not found -> user defined field mRuleField->changeItem( QString(aRule->field()), 0 ); i=0; } else // found in the list of predefined fields mRuleField->changeItem( "", 0 ); mRuleField->setCurrentItem( i ); //--------------set function and contents mRuleFunc->setCurrentItem( (int)aRule->function() ); mRuleValue->setText( aRule->contents() ); if (mRuleEditBut) functionChanged( (int)aRule->function() ); blockSignals(FALSE); } KMSearchRule* KMSearchRuleWidget::rule() const { return KMSearchRule::createInstance( ruleFieldToEnglish( mRuleField->currentText() ), (KMSearchRule::Function)mRuleFunc->currentItem(), mRuleValue->text() ); } void KMSearchRuleWidget::reset() { blockSignals(TRUE); mRuleField->changeItem( "", 0 ); mRuleField->setCurrentItem( 0 ); mRuleFunc->setCurrentItem( 0 ); if (mRuleEditBut) mRuleEditBut->setEnabled( false ); mRuleValue->clear(); blockSignals(FALSE); } QCString KMSearchRuleWidget::ruleFieldToEnglish(const QString & i18nVal) { if (i18nVal == i18n("<recipients>")) return "<recipients>"; if (i18nVal == i18n("<body>")) return "<body>"; if (i18nVal == i18n("<message>")) return "<message>"; if (i18nVal == i18n("<any header>")) return "<any header>"; if (i18nVal == i18n("<size in bytes>")) return "<size>"; if (i18nVal == i18n("<age in days>")) return "<age in days>"; if (i18nVal == i18n("<status>")) return "<status>"; return i18nVal.latin1(); } int KMSearchRuleWidget::indexOfRuleField( const QString & aName ) const { int i; if ( aName.isEmpty() ) return -1; QString i18n_aName = i18n( aName.latin1() ); for (i=mFilterFieldList.count()-1; i>=0; i--) { if (*(mFilterFieldList.at(i))==i18n_aName) break; } return i; } void KMSearchRuleWidget::initLists(bool headersOnly, bool absoluteDates) { //---------- initialize list of filter operators if ( mFilterFuncList.isEmpty() ) { // also see KMSearchRule::matches() and KMSearchRule::Function // if you change the following strings! mFilterFuncList.append(i18n("contains")); mFilterFuncList.append(i18n("doesn't contain")); mFilterFuncList.append(i18n("equals")); mFilterFuncList.append(i18n("doesn't equal")); mFilterFuncList.append(i18n("matches regular expr.")); mFilterFuncList.append(i18n("doesn't match reg. expr.")); mFilterFuncList.append(i18n("is greater than")); mFilterFuncList.append(i18n("is less than or equal to")); mFilterFuncList.append(i18n("is less than")); mFilterFuncList.append(i18n("is greater than or equal to")); } //---------- initialize list of filter operators if ( mFilterFieldList.isEmpty() ) { mFilterFieldList.append(""); // also see KMSearchRule::matches() and ruleFieldToEnglish() if // you change the following i18n-ized strings! if( !headersOnly ) mFilterFieldList.append(i18n("<message>")); if( !headersOnly ) mFilterFieldList.append(i18n("<body>")); mFilterFieldList.append(i18n("<any header>")); mFilterFieldList.append(i18n("<recipients>")); mFilterFieldList.append(i18n("<size in bytes>")); if ( !absoluteDates ) mFilterFieldList.append(i18n("<age in days>")); mFilterFieldList.append(i18n("<status>")); // these others only represent message headers and you can add to // them as you like mFilterFieldList.append("Subject"); mFilterFieldList.append("From"); mFilterFieldList.append("To"); mFilterFieldList.append("CC"); mFilterFieldList.append("Reply-To"); mFilterFieldList.append("List-Id"); mFilterFieldList.append("Organization"); mFilterFieldList.append("Resent-From"); mFilterFieldList.append("X-Loop"); mFilterFieldList.append("X-Mailing-List"); } } //============================================================================= // // class KMFilterActionWidgetLister (the filter action editor) // //============================================================================= KMSearchRuleWidgetLister::KMSearchRuleWidgetLister( QWidget *parent, const char* name, bool headersOnly, bool absoluteDates ) : KWidgetLister( 2, FILTER_MAX_RULES, parent, name ) { mRuleList = 0; mHeadersOnly = headersOnly; mAbsoluteDates = absoluteDates; } KMSearchRuleWidgetLister::~KMSearchRuleWidgetLister() { } void KMSearchRuleWidgetLister::setRuleList( QPtrList<KMSearchRule> *aList ) { assert ( aList ); if ( mRuleList ) regenerateRuleListFromWidgets(); mRuleList = aList; if ( mWidgetList.first() ) // move this below next 'if'? mWidgetList.first()->blockSignals(TRUE); if ( aList->count() == 0 ) { slotClear(); mWidgetList.first()->blockSignals(FALSE); return; } int superfluousItems = (int)mRuleList->count() - mMaxWidgets ; if ( superfluousItems > 0 ) { kdDebug(5006) << "KMSearchRuleWidgetLister: Clipping rule list to " << mMaxWidgets << " items!" << endl; for ( ; superfluousItems ; superfluousItems-- ) mRuleList->removeLast(); } // HACK to workaround regression in Qt 3.1.3 and Qt 3.2.0 (fixes bug #63537) setNumberOfShownWidgetsTo( QMAX((int)mRuleList->count(),mMinWidgets)+1 ); // set the right number of widgets setNumberOfShownWidgetsTo( QMAX((int)mRuleList->count(),mMinWidgets) ); // load the actions into the widgets QPtrListIterator<KMSearchRule> rIt( *mRuleList ); QPtrListIterator<QWidget> wIt( mWidgetList ); for ( rIt.toFirst(), wIt.toFirst() ; rIt.current() && wIt.current() ; ++rIt, ++wIt ) { ((KMSearchRuleWidget*)(*wIt))->setRule( (*rIt) ); } for ( ; wIt.current() ; ++wIt ) ((KMSearchRuleWidget*)(*wIt))->reset(); assert( mWidgetList.first() ); mWidgetList.first()->blockSignals(FALSE); } void KMSearchRuleWidgetLister::reset() { if ( mRuleList ) regenerateRuleListFromWidgets(); mRuleList = 0; slotClear(); } QWidget* KMSearchRuleWidgetLister::createWidget( QWidget *parent ) { return new KMSearchRuleWidget(parent, 0, 0, mHeadersOnly, mAbsoluteDates); } void KMSearchRuleWidgetLister::clearWidget( QWidget *aWidget ) { if ( aWidget ) ((KMSearchRuleWidget*)aWidget)->reset(); } void KMSearchRuleWidgetLister::regenerateRuleListFromWidgets() { if ( !mRuleList ) return; mRuleList->clear(); QPtrListIterator<QWidget> it( mWidgetList ); for ( it.toFirst() ; it.current() ; ++it ) { KMSearchRule *r = ((KMSearchRuleWidget*)(*it))->rule(); if ( r ) mRuleList->append( r ); } } //============================================================================= // // class KMSearchPatternEdit // //============================================================================= KMSearchPatternEdit::KMSearchPatternEdit(QWidget *parent, const char *name, bool headersOnly, bool absoluteDates ) : QGroupBox( 1/*columns*/, Horizontal, parent, name ) { setTitle( i18n("Search Criteria") ); initLayout( headersOnly, absoluteDates ); } KMSearchPatternEdit::KMSearchPatternEdit(const QString & title, QWidget *parent, const char *name, bool headersOnly, bool absoluteDates) : QGroupBox( 1/*column*/, Horizontal, title, parent, name ) { initLayout( headersOnly, absoluteDates ); } KMSearchPatternEdit::~KMSearchPatternEdit() { } void KMSearchPatternEdit::initLayout(bool headersOnly, bool absoluteDates) { //------------the radio buttons mAllRBtn = new QRadioButton( i18n("Match a&ll of the following"), this, "mAllRBtn" ); mAnyRBtn = new QRadioButton( i18n("Match an&y of the following"), this, "mAnyRBtn" ); mAllRBtn->setChecked(TRUE); mAnyRBtn->setChecked(FALSE); QButtonGroup *bg = new QButtonGroup( this ); bg->hide(); bg->insert( mAllRBtn, (int)KMSearchPattern::OpAnd ); bg->insert( mAnyRBtn, (int)KMSearchPattern::OpOr ); //------------the list of KMSearchRuleWidget's mRuleLister = new KMSearchRuleWidgetLister( this, "swl", headersOnly, absoluteDates ); mRuleLister->slotClear(); //------------connect a few signals connect( bg, SIGNAL(clicked(int)), this, SLOT(slotRadioClicked(int)) ); KMSearchRuleWidget *srw = (KMSearchRuleWidget*)mRuleLister->mWidgetList.first(); if ( srw ) { connect( srw, SIGNAL(fieldChanged(const QString &)), this, SLOT(slotAutoNameHack()) ); connect( srw, SIGNAL(contentsChanged(const QString &)), this, SLOT(slotAutoNameHack()) ); } else kdDebug(5006) << "KMSearchPatternEdit: no first KMSearchRuleWidget, though slotClear() has been called!" << endl; } void KMSearchPatternEdit::setSearchPattern( KMSearchPattern *aPattern ) { assert( aPattern ); mRuleLister->setRuleList( aPattern ); mPattern = aPattern; blockSignals(TRUE); if ( mPattern->op() == KMSearchPattern::OpOr ) mAnyRBtn->setChecked(TRUE); else mAllRBtn->setChecked(TRUE); blockSignals(FALSE); setEnabled( TRUE ); } void KMSearchPatternEdit::reset() { mRuleLister->reset(); blockSignals(TRUE); mAllRBtn->setChecked( TRUE ); blockSignals(FALSE); setEnabled( FALSE ); } void KMSearchPatternEdit::slotRadioClicked(int aIdx) { if ( mPattern ) mPattern->setOp( (KMSearchPattern::Operator)aIdx ); } void KMSearchPatternEdit::slotAutoNameHack() { mRuleLister->regenerateRuleListFromWidgets(); emit maybeNameChanged(); } #include "kmsearchpatternedit.moc" <commit_msg>added X-Spam-Flag to the keywords list<commit_after>// kmsearchpatternedit.cpp // Author: Marc Mutz <Marc@Mutz.com> // This code is under GPL #include <config.h> #include "kmsearchpatternedit.h" #include "kmsearchpattern.h" #include <klocale.h> #include <kdebug.h> #include <klineedit.h> #include <kparts/componentfactory.h> #include <kregexpeditorinterface.h> #include <qpushbutton.h> #include <qdialog.h> #include <qradiobutton.h> #include <qcombobox.h> #include <qbuttongroup.h> #include <assert.h> //============================================================================= // // class KMSearchRuleWidget // //============================================================================= KMSearchRuleWidget::KMSearchRuleWidget(QWidget *parent, KMSearchRule *aRule, const char *name, bool headersOnly, bool absoluteDates) : QHBox(parent,name), mRuleEditBut(0), mRegExpEditDialog(0) { initLists( headersOnly, absoluteDates ); // sFilter{Func,Field}List are local to KMSearchRuleWidget initWidget(); if ( aRule ) setRule(aRule); else reset(); } void KMSearchRuleWidget::initWidget() { setSpacing(4); mRuleField = new QComboBox( true, this, "mRuleField" ); mRuleFunc = new QComboBox( false, this, "mRuleFunc" ); mRuleValue = new KLineEdit( this, "mRuleValue" ); if( !KTrader::self()->query("KRegExpEditor/KRegExpEditor").isEmpty() ) { mRuleEditBut = new QPushButton( i18n("Edit..."), this, "mRuleEditBut" ); connect( mRuleEditBut, SIGNAL( clicked() ), this, SLOT( editRegExp())); connect( mRuleFunc, SIGNAL( activated(int) ), this, SLOT( functionChanged(int) ) ); functionChanged( mRuleFunc->currentItem() ); } mRuleFunc->insertStringList(mFilterFuncList); mRuleFunc->adjustSize(); mRuleField->insertStringList(mFilterFieldList); // don't show sliders when popping up this menu mRuleField->setSizeLimit( mRuleField->count() ); mRuleField->adjustSize(); connect( mRuleField, SIGNAL(textChanged(const QString &)), this, SIGNAL(fieldChanged(const QString &)) ); connect( mRuleValue, SIGNAL(textChanged(const QString &)), this, SIGNAL(contentsChanged(const QString &)) ); } void KMSearchRuleWidget::editRegExp() { if ( mRegExpEditDialog == 0 ) mRegExpEditDialog = KParts::ComponentFactory::createInstanceFromQuery<QDialog>( "KRegExpEditor/KRegExpEditor", QString::null, this ); KRegExpEditorInterface *iface = static_cast<KRegExpEditorInterface *>( mRegExpEditDialog->qt_cast( "KRegExpEditorInterface" ) ); if( iface ) { iface->setRegExp( mRuleValue->text() ); if( mRegExpEditDialog->exec() == QDialog::Accepted ) mRuleValue->setText( iface->regExp() ); } } void KMSearchRuleWidget::functionChanged( int which ) { mRuleEditBut->setEnabled( which == 4 || which == 5 ); } void KMSearchRuleWidget::setRule(KMSearchRule *aRule) { assert ( aRule ); blockSignals(TRUE); //--------------set the field int i = indexOfRuleField( aRule->field() ); if ( i<0 ) { // not found -> user defined field mRuleField->changeItem( QString(aRule->field()), 0 ); i=0; } else // found in the list of predefined fields mRuleField->changeItem( "", 0 ); mRuleField->setCurrentItem( i ); //--------------set function and contents mRuleFunc->setCurrentItem( (int)aRule->function() ); mRuleValue->setText( aRule->contents() ); if (mRuleEditBut) functionChanged( (int)aRule->function() ); blockSignals(FALSE); } KMSearchRule* KMSearchRuleWidget::rule() const { return KMSearchRule::createInstance( ruleFieldToEnglish( mRuleField->currentText() ), (KMSearchRule::Function)mRuleFunc->currentItem(), mRuleValue->text() ); } void KMSearchRuleWidget::reset() { blockSignals(TRUE); mRuleField->changeItem( "", 0 ); mRuleField->setCurrentItem( 0 ); mRuleFunc->setCurrentItem( 0 ); if (mRuleEditBut) mRuleEditBut->setEnabled( false ); mRuleValue->clear(); blockSignals(FALSE); } QCString KMSearchRuleWidget::ruleFieldToEnglish(const QString & i18nVal) { if (i18nVal == i18n("<recipients>")) return "<recipients>"; if (i18nVal == i18n("<body>")) return "<body>"; if (i18nVal == i18n("<message>")) return "<message>"; if (i18nVal == i18n("<any header>")) return "<any header>"; if (i18nVal == i18n("<size in bytes>")) return "<size>"; if (i18nVal == i18n("<age in days>")) return "<age in days>"; if (i18nVal == i18n("<status>")) return "<status>"; return i18nVal.latin1(); } int KMSearchRuleWidget::indexOfRuleField( const QString & aName ) const { int i; if ( aName.isEmpty() ) return -1; QString i18n_aName = i18n( aName.latin1() ); for (i=mFilterFieldList.count()-1; i>=0; i--) { if (*(mFilterFieldList.at(i))==i18n_aName) break; } return i; } void KMSearchRuleWidget::initLists(bool headersOnly, bool absoluteDates) { //---------- initialize list of filter operators if ( mFilterFuncList.isEmpty() ) { // also see KMSearchRule::matches() and KMSearchRule::Function // if you change the following strings! mFilterFuncList.append(i18n("contains")); mFilterFuncList.append(i18n("doesn't contain")); mFilterFuncList.append(i18n("equals")); mFilterFuncList.append(i18n("doesn't equal")); mFilterFuncList.append(i18n("matches regular expr.")); mFilterFuncList.append(i18n("doesn't match reg. expr.")); mFilterFuncList.append(i18n("is greater than")); mFilterFuncList.append(i18n("is less than or equal to")); mFilterFuncList.append(i18n("is less than")); mFilterFuncList.append(i18n("is greater than or equal to")); } //---------- initialize list of filter operators if ( mFilterFieldList.isEmpty() ) { mFilterFieldList.append(""); // also see KMSearchRule::matches() and ruleFieldToEnglish() if // you change the following i18n-ized strings! if( !headersOnly ) mFilterFieldList.append(i18n("<message>")); if( !headersOnly ) mFilterFieldList.append(i18n("<body>")); mFilterFieldList.append(i18n("<any header>")); mFilterFieldList.append(i18n("<recipients>")); mFilterFieldList.append(i18n("<size in bytes>")); if ( !absoluteDates ) mFilterFieldList.append(i18n("<age in days>")); mFilterFieldList.append(i18n("<status>")); // these others only represent message headers and you can add to // them as you like mFilterFieldList.append("Subject"); mFilterFieldList.append("From"); mFilterFieldList.append("To"); mFilterFieldList.append("CC"); mFilterFieldList.append("Reply-To"); mFilterFieldList.append("List-Id"); mFilterFieldList.append("Organization"); mFilterFieldList.append("Resent-From"); mFilterFieldList.append("X-Loop"); mFilterFieldList.append("X-Mailing-List"); mFilterFieldList.append("X-Spam-Flag"); } } //============================================================================= // // class KMFilterActionWidgetLister (the filter action editor) // //============================================================================= KMSearchRuleWidgetLister::KMSearchRuleWidgetLister( QWidget *parent, const char* name, bool headersOnly, bool absoluteDates ) : KWidgetLister( 2, FILTER_MAX_RULES, parent, name ) { mRuleList = 0; mHeadersOnly = headersOnly; mAbsoluteDates = absoluteDates; } KMSearchRuleWidgetLister::~KMSearchRuleWidgetLister() { } void KMSearchRuleWidgetLister::setRuleList( QPtrList<KMSearchRule> *aList ) { assert ( aList ); if ( mRuleList ) regenerateRuleListFromWidgets(); mRuleList = aList; if ( mWidgetList.first() ) // move this below next 'if'? mWidgetList.first()->blockSignals(TRUE); if ( aList->count() == 0 ) { slotClear(); mWidgetList.first()->blockSignals(FALSE); return; } int superfluousItems = (int)mRuleList->count() - mMaxWidgets ; if ( superfluousItems > 0 ) { kdDebug(5006) << "KMSearchRuleWidgetLister: Clipping rule list to " << mMaxWidgets << " items!" << endl; for ( ; superfluousItems ; superfluousItems-- ) mRuleList->removeLast(); } // HACK to workaround regression in Qt 3.1.3 and Qt 3.2.0 (fixes bug #63537) setNumberOfShownWidgetsTo( QMAX((int)mRuleList->count(),mMinWidgets)+1 ); // set the right number of widgets setNumberOfShownWidgetsTo( QMAX((int)mRuleList->count(),mMinWidgets) ); // load the actions into the widgets QPtrListIterator<KMSearchRule> rIt( *mRuleList ); QPtrListIterator<QWidget> wIt( mWidgetList ); for ( rIt.toFirst(), wIt.toFirst() ; rIt.current() && wIt.current() ; ++rIt, ++wIt ) { ((KMSearchRuleWidget*)(*wIt))->setRule( (*rIt) ); } for ( ; wIt.current() ; ++wIt ) ((KMSearchRuleWidget*)(*wIt))->reset(); assert( mWidgetList.first() ); mWidgetList.first()->blockSignals(FALSE); } void KMSearchRuleWidgetLister::reset() { if ( mRuleList ) regenerateRuleListFromWidgets(); mRuleList = 0; slotClear(); } QWidget* KMSearchRuleWidgetLister::createWidget( QWidget *parent ) { return new KMSearchRuleWidget(parent, 0, 0, mHeadersOnly, mAbsoluteDates); } void KMSearchRuleWidgetLister::clearWidget( QWidget *aWidget ) { if ( aWidget ) ((KMSearchRuleWidget*)aWidget)->reset(); } void KMSearchRuleWidgetLister::regenerateRuleListFromWidgets() { if ( !mRuleList ) return; mRuleList->clear(); QPtrListIterator<QWidget> it( mWidgetList ); for ( it.toFirst() ; it.current() ; ++it ) { KMSearchRule *r = ((KMSearchRuleWidget*)(*it))->rule(); if ( r ) mRuleList->append( r ); } } //============================================================================= // // class KMSearchPatternEdit // //============================================================================= KMSearchPatternEdit::KMSearchPatternEdit(QWidget *parent, const char *name, bool headersOnly, bool absoluteDates ) : QGroupBox( 1/*columns*/, Horizontal, parent, name ) { setTitle( i18n("Search Criteria") ); initLayout( headersOnly, absoluteDates ); } KMSearchPatternEdit::KMSearchPatternEdit(const QString & title, QWidget *parent, const char *name, bool headersOnly, bool absoluteDates) : QGroupBox( 1/*column*/, Horizontal, title, parent, name ) { initLayout( headersOnly, absoluteDates ); } KMSearchPatternEdit::~KMSearchPatternEdit() { } void KMSearchPatternEdit::initLayout(bool headersOnly, bool absoluteDates) { //------------the radio buttons mAllRBtn = new QRadioButton( i18n("Match a&ll of the following"), this, "mAllRBtn" ); mAnyRBtn = new QRadioButton( i18n("Match an&y of the following"), this, "mAnyRBtn" ); mAllRBtn->setChecked(TRUE); mAnyRBtn->setChecked(FALSE); QButtonGroup *bg = new QButtonGroup( this ); bg->hide(); bg->insert( mAllRBtn, (int)KMSearchPattern::OpAnd ); bg->insert( mAnyRBtn, (int)KMSearchPattern::OpOr ); //------------the list of KMSearchRuleWidget's mRuleLister = new KMSearchRuleWidgetLister( this, "swl", headersOnly, absoluteDates ); mRuleLister->slotClear(); //------------connect a few signals connect( bg, SIGNAL(clicked(int)), this, SLOT(slotRadioClicked(int)) ); KMSearchRuleWidget *srw = (KMSearchRuleWidget*)mRuleLister->mWidgetList.first(); if ( srw ) { connect( srw, SIGNAL(fieldChanged(const QString &)), this, SLOT(slotAutoNameHack()) ); connect( srw, SIGNAL(contentsChanged(const QString &)), this, SLOT(slotAutoNameHack()) ); } else kdDebug(5006) << "KMSearchPatternEdit: no first KMSearchRuleWidget, though slotClear() has been called!" << endl; } void KMSearchPatternEdit::setSearchPattern( KMSearchPattern *aPattern ) { assert( aPattern ); mRuleLister->setRuleList( aPattern ); mPattern = aPattern; blockSignals(TRUE); if ( mPattern->op() == KMSearchPattern::OpOr ) mAnyRBtn->setChecked(TRUE); else mAllRBtn->setChecked(TRUE); blockSignals(FALSE); setEnabled( TRUE ); } void KMSearchPatternEdit::reset() { mRuleLister->reset(); blockSignals(TRUE); mAllRBtn->setChecked( TRUE ); blockSignals(FALSE); setEnabled( FALSE ); } void KMSearchPatternEdit::slotRadioClicked(int aIdx) { if ( mPattern ) mPattern->setOp( (KMSearchPattern::Operator)aIdx ); } void KMSearchPatternEdit::slotAutoNameHack() { mRuleLister->regenerateRuleListFromWidgets(); emit maybeNameChanged(); } #include "kmsearchpatternedit.moc" <|endoftext|>
<commit_before>/* * Graph.cpp * * Created on: 04.02.2013 * Author: cls */ #include "Graph.h" namespace EnsembleClustering { Graph::Graph(count n) : n(n), deg(n, 0), adja(n), eweights(n) { // set name from global id static int64_t graphId = 1; std::stringstream sstm; sstm << "G#" << graphId++; this->name = sstm.str(); } Graph::~Graph() { // TODO Auto-generated destructor stub } // TODO: replace by for_each index Graph::find(node u, node v) const { index vi = 0; for (node x : this->adja[u]) { if (x == v) { return vi; } vi++; } return none; } void Graph::insertEdge(node u, node v, edgeweight weight) { if (u == v) { // self-loop case this->adja[u].push_back(u); this->deg[u] += 1; this->eweights[u].push_back(weight); for (int attrId = 0; attrId < this->edgeMaps_double.size(); ++attrId) { double defaultAttr = this->edgeAttrDefaults_double[attrId]; this->edgeMaps_double[attrId][u].push_back(defaultAttr); } } else { // set adjacency this->adja[u].push_back(v); this->adja[v].push_back(u); // increment degree counters this->deg[u] += 1; this->deg[v] += 1; // set edge weight this->eweights[u].push_back(weight); this->eweights[v].push_back(weight); // loop over all attributes, setting default attr for (int attrId = 0; attrId < this->edgeMaps_double.size(); ++attrId) { double defaultAttr = this->edgeAttrDefaults_double[attrId]; this->edgeMaps_double[attrId][u].push_back(defaultAttr); this->edgeMaps_double[attrId][v].push_back(defaultAttr); } } } void Graph::removeEdge(node u, node v) { // remove adjacency index vi = find(u, v); index ui = find(v, u); if (vi == none) { throw std::runtime_error("edge does not exist"); // TODO: what if edge does not exist? } else { this->adja[u][vi] = none; this->adja[v][ui] = none; // decrement degree counters this->deg[u] -= 1; this->deg[v] -= 1; // remove edge weight this->eweights[u][vi] = this->nullWeight; this->eweights[v][ui] = this->nullWeight; // TODO: remove attributes } } edgeweight Graph::weight(node u, node v) const { index vi = find(u, v); if (vi != none) { return this->eweights[u][vi]; } else { return 0.0; } } void Graph::setWeight(node u, node v, edgeweight w) { if (u == v) { // self-loop case index ui = find(u, u); if (ui != none) { this->eweights[u][ui] = w; } else { insertEdge(u, u, w); } } else { index vi = find(u, v); index ui = find(v, u); if ((vi != none) && (ui != none)) { this->eweights[u][vi] = w; this->eweights[v][ui] = w; } else { insertEdge(u, v, w); } } } bool Graph::hasEdge(node u, node v) const { return (find(u, v) != none); } node Graph::addNode() { node v = this->n; this->n += 1; //update per node data structures this->deg.push_back(0); // update per edge data structures std::vector<node> adjacencyVector; // vector of adjacencies for new node std::vector<edgeweight> edgeWeightVector; // vector of edge weights for new node this->adja.push_back(adjacencyVector); this->eweights.push_back(edgeWeightVector); // update edge attribute data structures for (int attrId = 0; attrId < this->edgeMaps_double.size(); ++attrId) { std::vector<double> attrVector; this->edgeMaps_double[attrId].push_back(attrVector); } return v; } void Graph::extendNodeRange(int64_t n) { throw std::runtime_error("TODO"); // TODO: } bool Graph::isEmpty() { return (n == 0); } int64_t Graph::numberOfNodes() const { return this->n; } count Graph::degree(node v) const { return deg[v]; } edgeweight Graph::weightedDegree(node v) const { // weighted degree as sum over incident edge weight edgeweight wDeg = 0.0; for (edgeweight w : this->eweights[v]) { wDeg += w; } return wDeg; } int64_t Graph::numberOfEdges() const { // sum over all stored degrees // TODO: parallel sum? count mm = 0; this->forNodes([&](node v) { mm += this->deg[v]; }); count m = mm / 2; return m; } edgeweight Graph::totalEdgeWeight() { edgeweight sum = 0.0; sum = this->parallelSumForWeightedEdges([&](node u, node v, edgeweight ew) { return ew; }); return sum; } void Graph::setName(std::string name) { this->name = name; } std::string Graph::toString() { std::stringstream strm; strm << "Graph(name=" << this->getName() << ", n=" << this->numberOfNodes() << ", m=" << this->numberOfEdges() << ")"; return strm.str(); } std::string Graph::getName() { // TODO: unneccessary if name becomes public attribute return this->name; } edgeweight Graph::totalNodeWeight() { throw std::runtime_error("DEPRECATED"); } void Graph::setAttribute_double(node u, node v, int attrId, double attr) { if (u == v) { // self-loop case index ui = find(u, u); if (ui != none) { this->edgeMaps_double.at(attrId)[u][ui] = attr; } else { throw std::runtime_error("What if edge does not exist?"); } } else { index vi = find(u, v); index ui = find(v, u); if ((vi != none) && (ui != none)) { // DEBUG int s = this->edgeMaps_double.size(); int sm = this->edgeMaps_double[attrId].size(); int smu = this->edgeMaps_double[attrId][u].size(); int smv = this->edgeMaps_double[attrId][v].size(); // DEBUG this->edgeMaps_double[attrId][u][vi] = attr; this->edgeMaps_double[attrId][v][ui] = attr; } else { throw std::runtime_error("What if edge does not exist?"); } } } double Graph::attribute_double(node u, node v, int attrId) const { assert (attrId < this->edgeMaps_double.size()); index vi = find(u, v); if (vi != none) { return this->edgeMaps_double[attrId][u][vi]; } else { throw std::runtime_error("TODO: what if edge does not exist?"); } } count Graph::numberOfSelfLoops() const { count nl; this->forEdges([&](node u, node v) { if (u == v) { nl += 1; } }); return nl; } int Graph::addEdgeAttribute_double(double defaultValue) { int attrId = this->edgeMaps_double.size(); std::vector<std::vector<double> > edgeMap; edgeMap.resize(this->n); // create empty vector<attr> for each node this->edgeMaps_double.push_back(edgeMap); this->edgeAttrDefaults_double.push_back(defaultValue); if (this->numberOfEdges() > 0) { throw std::runtime_error("TODO: set attributes for already existing edges"); } // TODO: set attribute for already existing edges return attrId; } } /* namespace EnsembleClustering */ <commit_msg>fixed G.numberOfSelfLoops<commit_after>/* * Graph.cpp * * Created on: 04.02.2013 * Author: cls */ #include "Graph.h" namespace EnsembleClustering { Graph::Graph(count n) : n(n), deg(n, 0), adja(n), eweights(n) { // set name from global id static int64_t graphId = 1; std::stringstream sstm; sstm << "G#" << graphId++; this->name = sstm.str(); } Graph::~Graph() { // TODO Auto-generated destructor stub } // TODO: replace by for_each index Graph::find(node u, node v) const { index vi = 0; for (node x : this->adja[u]) { if (x == v) { return vi; } vi++; } return none; } void Graph::insertEdge(node u, node v, edgeweight weight) { if (u == v) { // self-loop case this->adja[u].push_back(u); this->deg[u] += 1; this->eweights[u].push_back(weight); for (int attrId = 0; attrId < this->edgeMaps_double.size(); ++attrId) { double defaultAttr = this->edgeAttrDefaults_double[attrId]; this->edgeMaps_double[attrId][u].push_back(defaultAttr); } } else { // set adjacency this->adja[u].push_back(v); this->adja[v].push_back(u); // increment degree counters this->deg[u] += 1; this->deg[v] += 1; // set edge weight this->eweights[u].push_back(weight); this->eweights[v].push_back(weight); // loop over all attributes, setting default attr for (int attrId = 0; attrId < this->edgeMaps_double.size(); ++attrId) { double defaultAttr = this->edgeAttrDefaults_double[attrId]; this->edgeMaps_double[attrId][u].push_back(defaultAttr); this->edgeMaps_double[attrId][v].push_back(defaultAttr); } } } void Graph::removeEdge(node u, node v) { // remove adjacency index vi = find(u, v); index ui = find(v, u); if (vi == none) { throw std::runtime_error("edge does not exist"); // TODO: what if edge does not exist? } else { this->adja[u][vi] = none; this->adja[v][ui] = none; // decrement degree counters this->deg[u] -= 1; this->deg[v] -= 1; // remove edge weight this->eweights[u][vi] = this->nullWeight; this->eweights[v][ui] = this->nullWeight; // TODO: remove attributes } } edgeweight Graph::weight(node u, node v) const { index vi = find(u, v); if (vi != none) { return this->eweights[u][vi]; } else { return 0.0; } } void Graph::setWeight(node u, node v, edgeweight w) { if (u == v) { // self-loop case index ui = find(u, u); if (ui != none) { this->eweights[u][ui] = w; } else { insertEdge(u, u, w); } } else { index vi = find(u, v); index ui = find(v, u); if ((vi != none) && (ui != none)) { this->eweights[u][vi] = w; this->eweights[v][ui] = w; } else { insertEdge(u, v, w); } } } bool Graph::hasEdge(node u, node v) const { return (find(u, v) != none); } node Graph::addNode() { node v = this->n; this->n += 1; //update per node data structures this->deg.push_back(0); // update per edge data structures std::vector<node> adjacencyVector; // vector of adjacencies for new node std::vector<edgeweight> edgeWeightVector; // vector of edge weights for new node this->adja.push_back(adjacencyVector); this->eweights.push_back(edgeWeightVector); // update edge attribute data structures for (int attrId = 0; attrId < this->edgeMaps_double.size(); ++attrId) { std::vector<double> attrVector; this->edgeMaps_double[attrId].push_back(attrVector); } return v; } void Graph::extendNodeRange(int64_t n) { throw std::runtime_error("TODO"); // TODO: } bool Graph::isEmpty() { return (n == 0); } int64_t Graph::numberOfNodes() const { return this->n; } count Graph::degree(node v) const { return deg[v]; } edgeweight Graph::weightedDegree(node v) const { // weighted degree as sum over incident edge weight edgeweight wDeg = 0.0; for (edgeweight w : this->eweights[v]) { wDeg += w; } return wDeg; } int64_t Graph::numberOfEdges() const { // sum over all stored degrees // TODO: parallel sum? count mm = 0; this->forNodes([&](node v) { mm += this->deg[v]; }); count m = mm / 2; return m; } edgeweight Graph::totalEdgeWeight() { edgeweight sum = 0.0; sum = this->parallelSumForWeightedEdges([&](node u, node v, edgeweight ew) { return ew; }); return sum; } void Graph::setName(std::string name) { this->name = name; } std::string Graph::toString() { std::stringstream strm; strm << "Graph(name=" << this->getName() << ", n=" << this->numberOfNodes() << ", m=" << this->numberOfEdges() << ")"; return strm.str(); } std::string Graph::getName() { // TODO: unneccessary if name becomes public attribute return this->name; } edgeweight Graph::totalNodeWeight() { throw std::runtime_error("DEPRECATED"); } void Graph::setAttribute_double(node u, node v, int attrId, double attr) { if (u == v) { // self-loop case index ui = find(u, u); if (ui != none) { this->edgeMaps_double.at(attrId)[u][ui] = attr; } else { throw std::runtime_error("What if edge does not exist?"); } } else { index vi = find(u, v); index ui = find(v, u); if ((vi != none) && (ui != none)) { // DEBUG int s = this->edgeMaps_double.size(); int sm = this->edgeMaps_double[attrId].size(); int smu = this->edgeMaps_double[attrId][u].size(); int smv = this->edgeMaps_double[attrId][v].size(); // DEBUG this->edgeMaps_double[attrId][u][vi] = attr; this->edgeMaps_double[attrId][v][ui] = attr; } else { throw std::runtime_error("What if edge does not exist?"); } } } double Graph::attribute_double(node u, node v, int attrId) const { assert (attrId < this->edgeMaps_double.size()); index vi = find(u, v); if (vi != none) { return this->edgeMaps_double[attrId][u][vi]; } else { throw std::runtime_error("TODO: what if edge does not exist?"); } } count Graph::numberOfSelfLoops() const { count nl = 0; this->forEdges([&](node u, node v) { if (u == v) { nl += 1; } }); return nl; } int Graph::addEdgeAttribute_double(double defaultValue) { int attrId = this->edgeMaps_double.size(); std::vector<std::vector<double> > edgeMap; edgeMap.resize(this->n); // create empty vector<attr> for each node this->edgeMaps_double.push_back(edgeMap); this->edgeAttrDefaults_double.push_back(defaultValue); if (this->numberOfEdges() > 0) { throw std::runtime_error("TODO: set attributes for already existing edges"); } // TODO: set attribute for already existing edges return attrId; } } /* namespace EnsembleClustering */ <|endoftext|>
<commit_before>//===-- ProcessLinux.cpp ----------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes // Other libraries and framework includes #include "lldb/Core/PluginManager.h" #include "lldb/Host/Host.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/DynamicLoader.h" #include "lldb/Target/Target.h" #include "ProcessLinux.h" #include "ProcessMonitor.h" #include "LinuxThread.h" using namespace lldb; using namespace lldb_private; //------------------------------------------------------------------------------ // Static functions. Process* ProcessLinux::CreateInstance(Target& target, Listener &listener) { return new ProcessLinux(target, listener); } void ProcessLinux::Initialize() { static bool g_initialized = false; if (!g_initialized) { PluginManager::RegisterPlugin(GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance); g_initialized = true; } } void ProcessLinux::Terminate() { } const char * ProcessLinux::GetPluginNameStatic() { return "plugin.process.linux"; } const char * ProcessLinux::GetPluginDescriptionStatic() { return "Process plugin for Linux"; } //------------------------------------------------------------------------------ // Constructors and destructors. ProcessLinux::ProcessLinux(Target& target, Listener &listener) : Process(target, listener), m_monitor(NULL), m_module(NULL) { // FIXME: Putting this code in the ctor and saving the byte order in a // member variable is a hack to avoid const qual issues in GetByteOrder. ObjectFile *obj_file = GetTarget().GetExecutableModule()->GetObjectFile(); m_byte_order = obj_file->GetByteOrder(); } ProcessLinux::~ProcessLinux() { delete m_monitor; } //------------------------------------------------------------------------------ // Process protocol. bool ProcessLinux::CanDebug(Target &target) { // For now we are just making sure the file exists for a given module ModuleSP exe_module_sp(target.GetExecutableModule()); if (exe_module_sp.get()) return exe_module_sp->GetFileSpec().Exists(); return false; } Error ProcessLinux::DoAttachToProcessWithID(lldb::pid_t pid) { return Error(1, eErrorTypeGeneric); } Error ProcessLinux::WillLaunch(Module* module) { Error error; m_dyld_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.linux-dyld")); if (m_dyld_ap.get() == NULL) error.SetErrorString("unable to find the dynamic loader named " "'dynamic-loader.linux-dyld'"); return error; } Error ProcessLinux::DoLaunch(Module *module, char const *argv[], char const *envp[], uint32_t launch_flags, const char *stdin_path, const char *stdout_path, const char *stderr_path) { Error error; assert(m_monitor == NULL); SetPrivateState(eStateLaunching); m_monitor = new ProcessMonitor(this, module, argv, envp, stdin_path, stdout_path, stderr_path, error); m_module = module; if (!error.Success()) return error; SetID(m_monitor->GetPID()); return error; } void ProcessLinux::DidLaunch() { if (m_dyld_ap.get() != NULL) m_dyld_ap->DidLaunch(); } Error ProcessLinux::DoResume() { assert(GetPrivateState() == eStateStopped && "Bad state for DoResume!"); // Set our state to running. This ensures inferior threads do not post a // state change first. SetPrivateState(eStateRunning); bool did_resume = false; uint32_t thread_count = m_thread_list.GetSize(false); for (uint32_t i = 0; i < thread_count; ++i) { LinuxThread *thread = static_cast<LinuxThread*>( m_thread_list.GetThreadAtIndex(i, false).get()); did_resume = thread->Resume() || did_resume; } assert(did_resume && "Process resume failed!"); return Error(); } addr_t ProcessLinux::GetImageInfoAddress() { Target *target = &GetTarget(); ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile(); Address addr = obj_file->GetImageInfoAddress(); if (addr.IsValid()) return addr.GetLoadAddress(target); else return LLDB_INVALID_ADDRESS; } Error ProcessLinux::DoHalt(bool &caused_stop) { return Error(1, eErrorTypeGeneric); } Error ProcessLinux::DoDetach() { return Error(1, eErrorTypeGeneric); } Error ProcessLinux::DoSignal(int signal) { return Error(1, eErrorTypeGeneric); } Error ProcessLinux::DoDestroy() { Error error; if (!HasExited()) { // Shut down the private state thread as we will synchronize with events // ourselves. Discard all current thread plans. PausePrivateStateThread(); GetThreadList().DiscardThreadPlans(); // Bringing the inferior into limbo will be caught by our monitor // thread, in turn updating the process state. if (!m_monitor->BringProcessIntoLimbo()) { error.SetErrorToGenericError(); error.SetErrorString("Process termination failed."); return error; } // Wait for the event to arrive. This guaranteed to be an exit event. StateType state; EventSP event; do { state = WaitForStateChangedEventsPrivate(NULL, event); } while (state != eStateExited); // Restart standard event handling and send the process the final kill, // driving it out of limbo. ResumePrivateStateThread(); } if (kill(m_monitor->GetPID(), SIGKILL)) error.SetErrorToErrno(); return error; } void ProcessLinux::SendMessage(const ProcessMessage &message) { Mutex::Locker lock(m_message_mutex); m_message_queue.push(message); switch (message.GetKind()) { default: SetPrivateState(eStateStopped); break; case ProcessMessage::eExitMessage: SetExitStatus(message.GetExitStatus(), NULL); break; case ProcessMessage::eSignalMessage: SetExitStatus(-1, NULL); break; } } void ProcessLinux::RefreshStateAfterStop() { Mutex::Locker lock(m_message_mutex); if (m_message_queue.empty()) return; ProcessMessage &message = m_message_queue.front(); // Resolve the thread this message corresponds to. lldb::tid_t tid = message.GetTID(); LinuxThread *thread = static_cast<LinuxThread*>( GetThreadList().FindThreadByID(tid, false).get()); switch (message.GetKind()) { default: assert(false && "Unexpected message kind!"); break; case ProcessMessage::eExitMessage: case ProcessMessage::eSignalMessage: thread->ExitNotify(); break; case ProcessMessage::eTraceMessage: thread->TraceNotify(); break; case ProcessMessage::eBreakpointMessage: thread->BreakNotify(); break; } m_message_queue.pop(); } bool ProcessLinux::IsAlive() { StateType state = GetPrivateState(); return state != eStateExited && state != eStateInvalid; } size_t ProcessLinux::DoReadMemory(addr_t vm_addr, void *buf, size_t size, Error &error) { return m_monitor->ReadMemory(vm_addr, buf, size, error); } size_t ProcessLinux::DoWriteMemory(addr_t vm_addr, const void *buf, size_t size, Error &error) { return m_monitor->WriteMemory(vm_addr, buf, size, error); } addr_t ProcessLinux::DoAllocateMemory(size_t size, uint32_t permissions, Error &error) { return 0; } addr_t ProcessLinux::AllocateMemory(size_t size, uint32_t permissions, Error &error) { return 0; } Error ProcessLinux::DoDeallocateMemory(lldb::addr_t ptr) { return Error(1, eErrorTypeGeneric); } size_t ProcessLinux::GetSoftwareBreakpointTrapOpcode(BreakpointSite* bp_site) { static const uint8_t g_i386_opcode[] = { 0xCC }; ArchSpec arch = GetTarget().GetArchitecture(); const uint8_t *opcode = NULL; size_t opcode_size = 0; switch (arch.GetGenericCPUType()) { default: assert(false && "CPU type not supported!"); break; case ArchSpec::eCPU_i386: case ArchSpec::eCPU_x86_64: opcode = g_i386_opcode; opcode_size = sizeof(g_i386_opcode); break; } bp_site->SetTrapOpcode(opcode, opcode_size); return opcode_size; } Error ProcessLinux::EnableBreakpoint(BreakpointSite *bp_site) { return EnableSoftwareBreakpoint(bp_site); } Error ProcessLinux::DisableBreakpoint(BreakpointSite *bp_site) { return DisableSoftwareBreakpoint(bp_site); } uint32_t ProcessLinux::UpdateThreadListIfNeeded() { // Do not allow recursive updates. return m_thread_list.GetSize(false); } ByteOrder ProcessLinux::GetByteOrder() const { // FIXME: We should be able to extract this value directly. See comment in // ProcessLinux(). return m_byte_order; } DynamicLoader * ProcessLinux::GetDynamicLoader() { return m_dyld_ap.get(); } //------------------------------------------------------------------------------ // ProcessInterface protocol. const char * ProcessLinux::GetPluginName() { return "process.linux"; } const char * ProcessLinux::GetShortPluginName() { return "process.linux"; } uint32_t ProcessLinux::GetPluginVersion() { return 1; } void ProcessLinux::GetPluginCommandHelp(const char *command, Stream *strm) { } Error ProcessLinux::ExecutePluginCommand(Args &command, Stream *strm) { return Error(1, eErrorTypeGeneric); } Log * ProcessLinux::EnablePluginLogging(Stream *strm, Args &command) { return NULL; } //------------------------------------------------------------------------------ // Utility functions. bool ProcessLinux::HasExited() { switch (GetPrivateState()) { default: break; case eStateUnloaded: case eStateCrashed: case eStateDetached: case eStateExited: return true; } return false; } <commit_msg>Only enqueue valid ProcessLinux messages.<commit_after>//===-- ProcessLinux.cpp ----------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes // Other libraries and framework includes #include "lldb/Core/PluginManager.h" #include "lldb/Host/Host.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/DynamicLoader.h" #include "lldb/Target/Target.h" #include "ProcessLinux.h" #include "ProcessMonitor.h" #include "LinuxThread.h" using namespace lldb; using namespace lldb_private; //------------------------------------------------------------------------------ // Static functions. Process* ProcessLinux::CreateInstance(Target& target, Listener &listener) { return new ProcessLinux(target, listener); } void ProcessLinux::Initialize() { static bool g_initialized = false; if (!g_initialized) { PluginManager::RegisterPlugin(GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance); g_initialized = true; } } void ProcessLinux::Terminate() { } const char * ProcessLinux::GetPluginNameStatic() { return "plugin.process.linux"; } const char * ProcessLinux::GetPluginDescriptionStatic() { return "Process plugin for Linux"; } //------------------------------------------------------------------------------ // Constructors and destructors. ProcessLinux::ProcessLinux(Target& target, Listener &listener) : Process(target, listener), m_monitor(NULL), m_module(NULL) { // FIXME: Putting this code in the ctor and saving the byte order in a // member variable is a hack to avoid const qual issues in GetByteOrder. ObjectFile *obj_file = GetTarget().GetExecutableModule()->GetObjectFile(); m_byte_order = obj_file->GetByteOrder(); } ProcessLinux::~ProcessLinux() { delete m_monitor; } //------------------------------------------------------------------------------ // Process protocol. bool ProcessLinux::CanDebug(Target &target) { // For now we are just making sure the file exists for a given module ModuleSP exe_module_sp(target.GetExecutableModule()); if (exe_module_sp.get()) return exe_module_sp->GetFileSpec().Exists(); return false; } Error ProcessLinux::DoAttachToProcessWithID(lldb::pid_t pid) { return Error(1, eErrorTypeGeneric); } Error ProcessLinux::WillLaunch(Module* module) { Error error; m_dyld_ap.reset(DynamicLoader::FindPlugin(this, "dynamic-loader.linux-dyld")); if (m_dyld_ap.get() == NULL) error.SetErrorString("unable to find the dynamic loader named " "'dynamic-loader.linux-dyld'"); return error; } Error ProcessLinux::DoLaunch(Module *module, char const *argv[], char const *envp[], uint32_t launch_flags, const char *stdin_path, const char *stdout_path, const char *stderr_path) { Error error; assert(m_monitor == NULL); SetPrivateState(eStateLaunching); m_monitor = new ProcessMonitor(this, module, argv, envp, stdin_path, stdout_path, stderr_path, error); m_module = module; if (!error.Success()) return error; SetID(m_monitor->GetPID()); return error; } void ProcessLinux::DidLaunch() { if (m_dyld_ap.get() != NULL) m_dyld_ap->DidLaunch(); } Error ProcessLinux::DoResume() { assert(GetPrivateState() == eStateStopped && "Bad state for DoResume!"); // Set our state to running. This ensures inferior threads do not post a // state change first. SetPrivateState(eStateRunning); bool did_resume = false; uint32_t thread_count = m_thread_list.GetSize(false); for (uint32_t i = 0; i < thread_count; ++i) { LinuxThread *thread = static_cast<LinuxThread*>( m_thread_list.GetThreadAtIndex(i, false).get()); did_resume = thread->Resume() || did_resume; } assert(did_resume && "Process resume failed!"); return Error(); } addr_t ProcessLinux::GetImageInfoAddress() { Target *target = &GetTarget(); ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile(); Address addr = obj_file->GetImageInfoAddress(); if (addr.IsValid()) return addr.GetLoadAddress(target); else return LLDB_INVALID_ADDRESS; } Error ProcessLinux::DoHalt(bool &caused_stop) { return Error(1, eErrorTypeGeneric); } Error ProcessLinux::DoDetach() { return Error(1, eErrorTypeGeneric); } Error ProcessLinux::DoSignal(int signal) { return Error(1, eErrorTypeGeneric); } Error ProcessLinux::DoDestroy() { Error error; if (!HasExited()) { // Shut down the private state thread as we will synchronize with events // ourselves. Discard all current thread plans. PausePrivateStateThread(); GetThreadList().DiscardThreadPlans(); // Bringing the inferior into limbo will be caught by our monitor // thread, in turn updating the process state. if (!m_monitor->BringProcessIntoLimbo()) { error.SetErrorToGenericError(); error.SetErrorString("Process termination failed."); return error; } // Wait for the event to arrive. This guaranteed to be an exit event. StateType state; EventSP event; do { state = WaitForStateChangedEventsPrivate(NULL, event); } while (state != eStateExited); // Restart standard event handling and send the process the final kill, // driving it out of limbo. ResumePrivateStateThread(); } if (kill(m_monitor->GetPID(), SIGKILL)) error.SetErrorToErrno(); return error; } void ProcessLinux::SendMessage(const ProcessMessage &message) { Mutex::Locker lock(m_message_mutex); switch (message.GetKind()) { default: SetPrivateState(eStateStopped); break; case ProcessMessage::eInvalidMessage: return; case ProcessMessage::eExitMessage: SetExitStatus(message.GetExitStatus(), NULL); break; case ProcessMessage::eSignalMessage: SetExitStatus(-1, NULL); break; } m_message_queue.push(message); } void ProcessLinux::RefreshStateAfterStop() { Mutex::Locker lock(m_message_mutex); if (m_message_queue.empty()) return; ProcessMessage &message = m_message_queue.front(); // Resolve the thread this message corresponds to. lldb::tid_t tid = message.GetTID(); LinuxThread *thread = static_cast<LinuxThread*>( GetThreadList().FindThreadByID(tid, false).get()); switch (message.GetKind()) { default: assert(false && "Unexpected message kind!"); break; case ProcessMessage::eExitMessage: case ProcessMessage::eSignalMessage: thread->ExitNotify(); break; case ProcessMessage::eTraceMessage: thread->TraceNotify(); break; case ProcessMessage::eBreakpointMessage: thread->BreakNotify(); break; } m_message_queue.pop(); } bool ProcessLinux::IsAlive() { StateType state = GetPrivateState(); return state != eStateExited && state != eStateInvalid; } size_t ProcessLinux::DoReadMemory(addr_t vm_addr, void *buf, size_t size, Error &error) { return m_monitor->ReadMemory(vm_addr, buf, size, error); } size_t ProcessLinux::DoWriteMemory(addr_t vm_addr, const void *buf, size_t size, Error &error) { return m_monitor->WriteMemory(vm_addr, buf, size, error); } addr_t ProcessLinux::DoAllocateMemory(size_t size, uint32_t permissions, Error &error) { return 0; } addr_t ProcessLinux::AllocateMemory(size_t size, uint32_t permissions, Error &error) { return 0; } Error ProcessLinux::DoDeallocateMemory(lldb::addr_t ptr) { return Error(1, eErrorTypeGeneric); } size_t ProcessLinux::GetSoftwareBreakpointTrapOpcode(BreakpointSite* bp_site) { static const uint8_t g_i386_opcode[] = { 0xCC }; ArchSpec arch = GetTarget().GetArchitecture(); const uint8_t *opcode = NULL; size_t opcode_size = 0; switch (arch.GetGenericCPUType()) { default: assert(false && "CPU type not supported!"); break; case ArchSpec::eCPU_i386: case ArchSpec::eCPU_x86_64: opcode = g_i386_opcode; opcode_size = sizeof(g_i386_opcode); break; } bp_site->SetTrapOpcode(opcode, opcode_size); return opcode_size; } Error ProcessLinux::EnableBreakpoint(BreakpointSite *bp_site) { return EnableSoftwareBreakpoint(bp_site); } Error ProcessLinux::DisableBreakpoint(BreakpointSite *bp_site) { return DisableSoftwareBreakpoint(bp_site); } uint32_t ProcessLinux::UpdateThreadListIfNeeded() { // Do not allow recursive updates. return m_thread_list.GetSize(false); } ByteOrder ProcessLinux::GetByteOrder() const { // FIXME: We should be able to extract this value directly. See comment in // ProcessLinux(). return m_byte_order; } DynamicLoader * ProcessLinux::GetDynamicLoader() { return m_dyld_ap.get(); } //------------------------------------------------------------------------------ // ProcessInterface protocol. const char * ProcessLinux::GetPluginName() { return "process.linux"; } const char * ProcessLinux::GetShortPluginName() { return "process.linux"; } uint32_t ProcessLinux::GetPluginVersion() { return 1; } void ProcessLinux::GetPluginCommandHelp(const char *command, Stream *strm) { } Error ProcessLinux::ExecutePluginCommand(Args &command, Stream *strm) { return Error(1, eErrorTypeGeneric); } Log * ProcessLinux::EnablePluginLogging(Stream *strm, Args &command) { return NULL; } //------------------------------------------------------------------------------ // Utility functions. bool ProcessLinux::HasExited() { switch (GetPrivateState()) { default: break; case eStateUnloaded: case eStateCrashed: case eStateDetached: case eStateExited: return true; } return false; } <|endoftext|>
<commit_before>#include <QtQml> #include <QEvent> #include "qamousesensor.h" QAMouseSensor::QAMouseSensor(QQuickItem* parent) : QQuickItem(parent) { // setAcceptedMouseButtons(Qt::LeftButton); // setFiltersChildMouseEvents(true); timerId = 0; m_filter = 0; } void QAMouseSensor::mousePressEvent(QMouseEvent *event) { if (timerId != 0) { killTimer(timerId); timerId = 0; } timerId = startTimer(800,Qt::CoarseTimer); return QQuickItem::mousePressEvent(event); } void QAMouseSensor::mouseMoveEvent(QMouseEvent *event) { if (timerId != 0) { killTimer(timerId); timerId = 0; } QQuickItem::mouseMoveEvent(event); } void QAMouseSensor::mouseReleaseEvent(QMouseEvent *event) { if (timerId != 0) { killTimer(timerId); timerId = 0; } QQuickItem::mouseReleaseEvent(event); } void QAMouseSensor::timerEvent(QTimerEvent *event) { killTimer(timerId); Q_UNUSED(event); timerId = 0; emit pressAndHold(); } bool QAMouseSensor::eventFilter(QObject *, QEvent *event) { if (!isEnabled()) return false; switch (event->type()) { case QEvent::MouseButtonPress: mousePressEvent((QMouseEvent*) event); break; case QEvent::MouseMove: mouseMoveEvent((QMouseEvent*) event); break; case QEvent::MouseButtonRelease: mouseReleaseEvent((QMouseEvent*) event); break; } return false; } void QAMouseSensor::search(QObject *object, bool installFilter) { if (installFilter) { object->installEventFilter(this); } else { object->removeEventFilter(this); } QObjectList children = object->children(); Q_FOREACH(QObject* child,children) { search(child,installFilter); } } QObject *QAMouseSensor::filter() const { return m_filter; } void QAMouseSensor::setFilter(QObject *listenOn) { if (m_filter) { search(m_filter,false); } m_filter = listenOn; if (m_filter) { search(m_filter,true); } } <commit_msg>QAMouseSensor: mouseMoveEvent should not clear long press timer<commit_after>#include <QtQml> #include <QEvent> #include "qamousesensor.h" QAMouseSensor::QAMouseSensor(QQuickItem* parent) : QQuickItem(parent) { // setAcceptedMouseButtons(Qt::LeftButton); // setFiltersChildMouseEvents(true); timerId = 0; m_filter = 0; } void QAMouseSensor::mousePressEvent(QMouseEvent *event) { if (timerId != 0) { killTimer(timerId); timerId = 0; } timerId = startTimer(800,Qt::CoarseTimer); return QQuickItem::mousePressEvent(event); } void QAMouseSensor::mouseMoveEvent(QMouseEvent *event) { QQuickItem::mouseMoveEvent(event); } void QAMouseSensor::mouseReleaseEvent(QMouseEvent *event) { if (timerId != 0) { killTimer(timerId); timerId = 0; } QQuickItem::mouseReleaseEvent(event); } void QAMouseSensor::timerEvent(QTimerEvent *event) { killTimer(timerId); Q_UNUSED(event); timerId = 0; emit pressAndHold(); } bool QAMouseSensor::eventFilter(QObject *, QEvent *event) { if (!isEnabled()) return false; switch (event->type()) { case QEvent::MouseButtonPress: mousePressEvent((QMouseEvent*) event); break; case QEvent::MouseMove: mouseMoveEvent((QMouseEvent*) event); break; case QEvent::MouseButtonRelease: mouseReleaseEvent((QMouseEvent*) event); break; case QEvent::Timer: break; default: break; } return false; } void QAMouseSensor::search(QObject *object, bool installFilter) { if (installFilter) { object->installEventFilter(this); } else { object->removeEventFilter(this); } QObjectList children = object->children(); Q_FOREACH(QObject* child,children) { search(child,installFilter); } } QObject *QAMouseSensor::filter() const { return m_filter; } void QAMouseSensor::setFilter(QObject *listenOn) { if (m_filter) { search(m_filter,false); } m_filter = listenOn; if (m_filter) { search(m_filter,true); } } <|endoftext|>
<commit_before>// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/net/url_request_fetch_job.h" #include <algorithm> #include <string> #include "atom/browser/api/atom_api_session.h" #include "atom/browser/atom_browser_context.h" #include "base/memory/ptr_util.h" #include "base/strings/string_util.h" #include "native_mate/dictionary.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_response_writer.h" using content::BrowserThread; namespace atom { namespace { // Convert string to RequestType. net::URLFetcher::RequestType GetRequestType(const std::string& raw) { std::string method = base::ToUpperASCII(raw); if (method.empty() || method == "GET") return net::URLFetcher::GET; else if (method == "POST") return net::URLFetcher::POST; else if (method == "HEAD") return net::URLFetcher::HEAD; else if (method == "DELETE") return net::URLFetcher::DELETE_REQUEST; else if (method == "PUT") return net::URLFetcher::PUT; else if (method == "PATCH") return net::URLFetcher::PATCH; else // Use "GET" as fallback. return net::URLFetcher::GET; } // Pipe the response writer back to URLRequestFetchJob. class ResponsePiper : public net::URLFetcherResponseWriter { public: explicit ResponsePiper(URLRequestFetchJob* job) : first_write_(true), job_(job) {} // net::URLFetcherResponseWriter: int Initialize(const net::CompletionCallback& callback) override { return net::OK; } int Write(net::IOBuffer* buffer, int num_bytes, const net::CompletionCallback& callback) override { if (first_write_) { // The URLFetcherResponseWriter doesn't have an event when headers have // been read, so we have to emulate by hooking to first write event. job_->HeadersCompleted(); first_write_ = false; } return job_->DataAvailable(buffer, num_bytes, callback); } int Finish(int net_error, const net::CompletionCallback& callback) override { return net::OK; } private: bool first_write_; URLRequestFetchJob* job_; DISALLOW_COPY_AND_ASSIGN(ResponsePiper); }; } // namespace URLRequestFetchJob::URLRequestFetchJob( net::URLRequest* request, net::NetworkDelegate* network_delegate) : JsAsker<net::URLRequestJob>(request, network_delegate), pending_buffer_size_(0), write_num_bytes_(0) { } void URLRequestFetchJob::BeforeStartInUI( v8::Isolate* isolate, v8::Local<v8::Value> value) { mate::Dictionary options; if (!mate::ConvertFromV8(isolate, value, &options)) return; // When |session| is set to |null| we use a new request context for fetch job. v8::Local<v8::Value> val; if (options.Get("session", &val)) { if (val->IsNull()) { // We have to create the URLRequestContextGetter on UI thread. url_request_context_getter_ = new brightray::URLRequestContextGetter( this, nullptr, nullptr, base::FilePath(), true, BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO), BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::FILE), nullptr, content::URLRequestInterceptorScopedVector()); } else { mate::Handle<api::Session> session; if (mate::ConvertFromV8(isolate, val, &session) && !session.IsEmpty()) { AtomBrowserContext* browser_context = session->browser_context(); url_request_context_getter_ = browser_context->url_request_context_getter(); } } } } void URLRequestFetchJob::StartAsync(std::unique_ptr<base::Value> options) { if (!options->IsType(base::Value::TYPE_DICTIONARY)) { NotifyStartError(net::URLRequestStatus( net::URLRequestStatus::FAILED, net::ERR_NOT_IMPLEMENTED)); return; } std::string url, method, referrer; base::DictionaryValue* upload_data = nullptr; base::DictionaryValue* dict = static_cast<base::DictionaryValue*>(options.get()); dict->GetString("url", &url); dict->GetString("method", &method); dict->GetString("referrer", &referrer); dict->GetDictionary("uploadData", &upload_data); // Check if URL is valid. GURL formated_url(url); if (!formated_url.is_valid()) { NotifyStartError(net::URLRequestStatus( net::URLRequestStatus::FAILED, net::ERR_INVALID_URL)); return; } // Use |request|'s method if |method| is not specified. net::URLFetcher::RequestType request_type; if (method.empty()) request_type = GetRequestType(request()->method()); else request_type = GetRequestType(method); fetcher_ = net::URLFetcher::Create(formated_url, request_type, this); fetcher_->SaveResponseWithWriter(base::WrapUnique(new ResponsePiper(this))); // A request context getter is passed by the user. if (url_request_context_getter_) fetcher_->SetRequestContext(url_request_context_getter_.get()); else fetcher_->SetRequestContext(request_context_getter()); // Use |request|'s referrer if |referrer| is not specified. if (referrer.empty()) fetcher_->SetReferrer(request()->referrer()); else fetcher_->SetReferrer(referrer); // Set the data needed for POSTs. if (upload_data && request_type == net::URLFetcher::POST) { std::string content_type, data; upload_data->GetString("contentType", &content_type); upload_data->GetString("data", &data); fetcher_->SetUploadData(content_type, data); } // Use |request|'s headers. fetcher_->SetExtraRequestHeaders( request()->extra_request_headers().ToString()); fetcher_->Start(); } void URLRequestFetchJob::HeadersCompleted() { response_info_.reset(new net::HttpResponseInfo); response_info_->headers = fetcher_->GetResponseHeaders(); NotifyHeadersComplete(); } int URLRequestFetchJob::DataAvailable(net::IOBuffer* buffer, int num_bytes, const net::CompletionCallback& callback) { // When pending_buffer_ is empty, there's no ReadRawData() operation waiting // for IO completion, we have to save the parameters until the request is // ready to read data. if (!pending_buffer_.get()) { write_buffer_ = buffer; write_num_bytes_ = num_bytes; write_callback_ = callback; return net::ERR_IO_PENDING; } // Write data to the pending buffer and clear them after the writing. int bytes_read = BufferCopy(buffer, num_bytes, pending_buffer_.get(), pending_buffer_size_); ClearPendingBuffer(); ReadRawDataComplete(bytes_read); return bytes_read; } void URLRequestFetchJob::Kill() { JsAsker<URLRequestJob>::Kill(); fetcher_.reset(); } int URLRequestFetchJob::ReadRawData(net::IOBuffer* dest, int dest_size) { if (GetResponseCode() == 204) { request()->set_received_response_content_length(prefilter_bytes_read()); return net::OK; } // When write_buffer_ is empty, there is no data valable yet, we have to save // the dest buffer util DataAvailable. if (!write_buffer_.get()) { pending_buffer_ = dest; pending_buffer_size_ = dest_size; return net::ERR_IO_PENDING; } // Read from the write buffer and clear them after reading. int bytes_read = BufferCopy(write_buffer_.get(), write_num_bytes_, dest, dest_size); net::CompletionCallback write_callback = write_callback_; ClearWriteBuffer(); write_callback.Run(bytes_read); return bytes_read; } bool URLRequestFetchJob::GetMimeType(std::string* mime_type) const { if (!response_info_ || !response_info_->headers) return false; return response_info_->headers->GetMimeType(mime_type); } void URLRequestFetchJob::GetResponseInfo(net::HttpResponseInfo* info) { if (response_info_) *info = *response_info_; } int URLRequestFetchJob::GetResponseCode() const { if (!response_info_ || !response_info_->headers) return -1; return response_info_->headers->response_code(); } void URLRequestFetchJob::OnURLFetchComplete(const net::URLFetcher* source) { ClearPendingBuffer(); ClearWriteBuffer(); if (fetcher_->GetStatus().is_success()) { if (!response_info_) { // Since we notify header completion only after first write there will be // no response object constructed for http respones with no content 204. // We notify header completion here. HeadersCompleted(); return; } ReadRawDataComplete(0); } else { NotifyStartError(fetcher_->GetStatus()); } } int URLRequestFetchJob::BufferCopy(net::IOBuffer* source, int num_bytes, net::IOBuffer* target, int target_size) { int bytes_written = std::min(num_bytes, target_size); memcpy(target->data(), source->data(), bytes_written); return bytes_written; } void URLRequestFetchJob::ClearPendingBuffer() { pending_buffer_ = nullptr; pending_buffer_size_ = 0; } void URLRequestFetchJob::ClearWriteBuffer() { write_buffer_ = nullptr; write_num_bytes_ = 0; write_callback_.Reset(); } } // namespace atom <commit_msg>Update URLRequestFetchJob<commit_after>// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/net/url_request_fetch_job.h" #include <algorithm> #include <string> #include "atom/browser/api/atom_api_session.h" #include "atom/browser/atom_browser_context.h" #include "base/memory/ptr_util.h" #include "base/strings/string_util.h" #include "native_mate/dictionary.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_response_writer.h" using content::BrowserThread; namespace atom { namespace { // Convert string to RequestType. net::URLFetcher::RequestType GetRequestType(const std::string& raw) { std::string method = base::ToUpperASCII(raw); if (method.empty() || method == "GET") return net::URLFetcher::GET; else if (method == "POST") return net::URLFetcher::POST; else if (method == "HEAD") return net::URLFetcher::HEAD; else if (method == "DELETE") return net::URLFetcher::DELETE_REQUEST; else if (method == "PUT") return net::URLFetcher::PUT; else if (method == "PATCH") return net::URLFetcher::PATCH; else // Use "GET" as fallback. return net::URLFetcher::GET; } // Pipe the response writer back to URLRequestFetchJob. class ResponsePiper : public net::URLFetcherResponseWriter { public: explicit ResponsePiper(URLRequestFetchJob* job) : first_write_(true), job_(job) {} // net::URLFetcherResponseWriter: int Initialize(const net::CompletionCallback& callback) override { return net::OK; } int Write(net::IOBuffer* buffer, int num_bytes, const net::CompletionCallback& callback) override { if (first_write_) { // The URLFetcherResponseWriter doesn't have an event when headers have // been read, so we have to emulate by hooking to first write event. job_->HeadersCompleted(); first_write_ = false; } return job_->DataAvailable(buffer, num_bytes, callback); } int Finish(int net_error, const net::CompletionCallback& callback) override { return net::OK; } private: bool first_write_; URLRequestFetchJob* job_; DISALLOW_COPY_AND_ASSIGN(ResponsePiper); }; } // namespace URLRequestFetchJob::URLRequestFetchJob( net::URLRequest* request, net::NetworkDelegate* network_delegate) : JsAsker<net::URLRequestJob>(request, network_delegate), pending_buffer_size_(0), write_num_bytes_(0) { } void URLRequestFetchJob::BeforeStartInUI( v8::Isolate* isolate, v8::Local<v8::Value> value) { mate::Dictionary options; if (!mate::ConvertFromV8(isolate, value, &options)) return; // When |session| is set to |null| we use a new request context for fetch job. v8::Local<v8::Value> val; if (options.Get("session", &val)) { if (val->IsNull()) { // We have to create the URLRequestContextGetter on UI thread. url_request_context_getter_ = new brightray::URLRequestContextGetter( this, nullptr, nullptr, base::FilePath(), true, BrowserThread::GetTaskRunnerForThread(BrowserThread::IO), BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE), nullptr, content::URLRequestInterceptorScopedVector()); } else { mate::Handle<api::Session> session; if (mate::ConvertFromV8(isolate, val, &session) && !session.IsEmpty()) { AtomBrowserContext* browser_context = session->browser_context(); url_request_context_getter_ = browser_context->url_request_context_getter(); } } } } void URLRequestFetchJob::StartAsync(std::unique_ptr<base::Value> options) { if (!options->IsType(base::Value::TYPE_DICTIONARY)) { NotifyStartError(net::URLRequestStatus( net::URLRequestStatus::FAILED, net::ERR_NOT_IMPLEMENTED)); return; } std::string url, method, referrer; base::DictionaryValue* upload_data = nullptr; base::DictionaryValue* dict = static_cast<base::DictionaryValue*>(options.get()); dict->GetString("url", &url); dict->GetString("method", &method); dict->GetString("referrer", &referrer); dict->GetDictionary("uploadData", &upload_data); // Check if URL is valid. GURL formated_url(url); if (!formated_url.is_valid()) { NotifyStartError(net::URLRequestStatus( net::URLRequestStatus::FAILED, net::ERR_INVALID_URL)); return; } // Use |request|'s method if |method| is not specified. net::URLFetcher::RequestType request_type; if (method.empty()) request_type = GetRequestType(request()->method()); else request_type = GetRequestType(method); fetcher_ = net::URLFetcher::Create(formated_url, request_type, this); fetcher_->SaveResponseWithWriter(base::WrapUnique(new ResponsePiper(this))); // A request context getter is passed by the user. if (url_request_context_getter_) fetcher_->SetRequestContext(url_request_context_getter_.get()); else fetcher_->SetRequestContext(request_context_getter()); // Use |request|'s referrer if |referrer| is not specified. if (referrer.empty()) fetcher_->SetReferrer(request()->referrer()); else fetcher_->SetReferrer(referrer); // Set the data needed for POSTs. if (upload_data && request_type == net::URLFetcher::POST) { std::string content_type, data; upload_data->GetString("contentType", &content_type); upload_data->GetString("data", &data); fetcher_->SetUploadData(content_type, data); } // Use |request|'s headers. fetcher_->SetExtraRequestHeaders( request()->extra_request_headers().ToString()); fetcher_->Start(); } void URLRequestFetchJob::HeadersCompleted() { response_info_.reset(new net::HttpResponseInfo); response_info_->headers = fetcher_->GetResponseHeaders(); NotifyHeadersComplete(); } int URLRequestFetchJob::DataAvailable(net::IOBuffer* buffer, int num_bytes, const net::CompletionCallback& callback) { // When pending_buffer_ is empty, there's no ReadRawData() operation waiting // for IO completion, we have to save the parameters until the request is // ready to read data. if (!pending_buffer_.get()) { write_buffer_ = buffer; write_num_bytes_ = num_bytes; write_callback_ = callback; return net::ERR_IO_PENDING; } // Write data to the pending buffer and clear them after the writing. int bytes_read = BufferCopy(buffer, num_bytes, pending_buffer_.get(), pending_buffer_size_); ClearPendingBuffer(); ReadRawDataComplete(bytes_read); return bytes_read; } void URLRequestFetchJob::Kill() { JsAsker<URLRequestJob>::Kill(); fetcher_.reset(); } int URLRequestFetchJob::ReadRawData(net::IOBuffer* dest, int dest_size) { if (GetResponseCode() == 204) { request()->set_received_response_content_length(prefilter_bytes_read()); return net::OK; } // When write_buffer_ is empty, there is no data valable yet, we have to save // the dest buffer util DataAvailable. if (!write_buffer_.get()) { pending_buffer_ = dest; pending_buffer_size_ = dest_size; return net::ERR_IO_PENDING; } // Read from the write buffer and clear them after reading. int bytes_read = BufferCopy(write_buffer_.get(), write_num_bytes_, dest, dest_size); net::CompletionCallback write_callback = write_callback_; ClearWriteBuffer(); write_callback.Run(bytes_read); return bytes_read; } bool URLRequestFetchJob::GetMimeType(std::string* mime_type) const { if (!response_info_ || !response_info_->headers) return false; return response_info_->headers->GetMimeType(mime_type); } void URLRequestFetchJob::GetResponseInfo(net::HttpResponseInfo* info) { if (response_info_) *info = *response_info_; } int URLRequestFetchJob::GetResponseCode() const { if (!response_info_ || !response_info_->headers) return -1; return response_info_->headers->response_code(); } void URLRequestFetchJob::OnURLFetchComplete(const net::URLFetcher* source) { ClearPendingBuffer(); ClearWriteBuffer(); if (fetcher_->GetStatus().is_success()) { if (!response_info_) { // Since we notify header completion only after first write there will be // no response object constructed for http respones with no content 204. // We notify header completion here. HeadersCompleted(); return; } ReadRawDataComplete(0); } else { NotifyStartError(fetcher_->GetStatus()); } } int URLRequestFetchJob::BufferCopy(net::IOBuffer* source, int num_bytes, net::IOBuffer* target, int target_size) { int bytes_written = std::min(num_bytes, target_size); memcpy(target->data(), source->data(), bytes_written); return bytes_written; } void URLRequestFetchJob::ClearPendingBuffer() { pending_buffer_ = nullptr; pending_buffer_size_ = 0; } void URLRequestFetchJob::ClearWriteBuffer() { write_buffer_ = nullptr; write_num_bytes_ = 0; write_callback_.Reset(); } } // namespace atom <|endoftext|>
<commit_before>/* accountconfig.cpp - Kopete account config page Copyright (c) 2003 by Olivier Goffart <ogoffart@tiscalinet.be> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "accountconfig.h" #include <qpushbutton.h> #include <qlistview.h> #include <qlayout.h> #include <klocale.h> #include <kiconloader.h> #include <kmessagebox.h> #include <kdialogbase.h> #include "kopeteprotocol.h" #include "kopeteaccount.h" #include "addaccountwizard.h" #include "accountconfigbase.h" #include "editaccountwidget.h" #include "kopeteaccountmanager.h" AccountConfig::AccountConfig(QWidget * parent) : ConfigModule (i18n("Accounts"),i18n("Here You Can Manage Your Accounts"),"personal", parent ) { QVBoxLayout *topLayout = new QVBoxLayout( this ); m_view=new AccountConfigBase(this); topLayout->add(m_view); m_view->mButtonUp->setPixmap( SmallIcon("up") ); m_view->mButtonDown->setPixmap( SmallIcon("down") ); m_view->mAccountList->setSorting( -1 ); connect( m_view->mButtonNew , SIGNAL(clicked() ) , this , SLOT( slotAddAccount())); connect( m_view->mButtonEdit , SIGNAL(clicked() ) , this , SLOT( slotEditAccount())); connect( m_view->mButtonRemove , SIGNAL(clicked() ) , this , SLOT( slotRemoveAccount())); connect( m_view->mAccountList , SIGNAL(selectionChanged() ) , this , SLOT( slotItemSelected())); connect( m_view->mButtonUp , SIGNAL(clicked() ) , this , SLOT( slotAccountUp())); connect( m_view->mButtonDown , SIGNAL(clicked() ) , this , SLOT( slotAccountDown())); slotItemSelected(); // m_addwizard=0L; } AccountConfig::~AccountConfig() { } void AccountConfig::save() { KopeteAccountManager::manager()->save(); } void AccountConfig::reopen() { m_view->mAccountList->clear(); m_accountItems.clear(); QPtrList<KopeteAccount> accounts = KopeteAccountManager::manager()->accounts(); for(KopeteAccount *i=accounts.first() ; i; i=accounts.next() ) { QListViewItem* lvi= new QListViewItem(m_view->mAccountList); lvi->setText(0,i->protocol()->displayName() + QString::fromLatin1(" ") ); lvi->setPixmap( 0, SmallIcon( i->protocol()->pluginIcon() ) ); lvi->setText(1, i->accountId()); m_accountItems.insert(lvi,i); } } void AccountConfig::slotItemSelected() { QListViewItem *itemSelected = m_view->mAccountList->selectedItem(); m_view->mButtonEdit->setEnabled( itemSelected ); m_view->mButtonRemove->setEnabled( itemSelected ); if( itemSelected ) { m_view->mButtonUp->setEnabled( itemSelected->itemAbove() ); m_view->mButtonDown->setEnabled( itemSelected->itemBelow() ); } else { m_view->mButtonUp->setEnabled( itemSelected ); m_view->mButtonDown->setEnabled( itemSelected ); } } void AccountConfig::slotAccountUp() { QListViewItem *itemSelected = m_view->mAccountList->selectedItem(); itemSelected->itemAbove()->moveItem( itemSelected ); slotItemSelected(); } void AccountConfig::slotAccountDown() { QListViewItem *itemSelected = m_view->mAccountList->selectedItem(); itemSelected->moveItem( itemSelected->itemBelow() ); slotItemSelected(); } void AccountConfig::slotAddAccount() { AddAccountWizard *m_addwizard; m_addwizard= new AddAccountWizard( this , "addAccountWizard" , true); connect(m_addwizard, SIGNAL( destroyed(QObject*)) , this, SLOT (slotAddWizardDone())); m_addwizard->show(); } void AccountConfig::slotEditAccount() { QListViewItem *lvi=m_view->mAccountList->selectedItem(); if(!lvi) return; KopeteAccount *ident=m_accountItems[lvi]; KopeteProtocol *proto=ident->protocol(); KDialogBase *editDialog= new KDialogBase( this,"editDialog", true, i18n( "Edit Account" ), KDialogBase::Ok|KDialogBase::Cancel, KDialogBase::Ok, true ); editDialog->resize( 525, 400 ); EditAccountWidget *m_accountWidget = proto->createEditAccountWidget(ident,editDialog); QWidget *qWidget = dynamic_cast<QWidget*>( m_accountWidget ); if (!m_accountWidget) return; editDialog->setMainWidget(qWidget); if(editDialog->exec() == QDialog::Accepted ) { if(m_accountWidget->validateData()) { m_accountWidget->apply(); } } editDialog->deleteLater(); reopen(); } void AccountConfig::slotRemoveAccount() { QListViewItem *lvi=m_view->mAccountList->selectedItem(); if(lvi) { KopeteAccount *i=m_accountItems[lvi]; if( KMessageBox::questionYesNo( this, i18n("Are you sure you want to remove the account %1").arg( i->accountId() ), i18n("Remove Account")) == KMessageBox::Yes ) { m_accountItems.remove(lvi); i->deleteLater(); delete lvi; } } } void AccountConfig::slotAddWizardDone() { reopen(); } #include "accountconfig.moc" <commit_msg>Follow UI guidelines for message boxes<commit_after>/* accountconfig.cpp - Kopete account config page Copyright (c) 2003 by Olivier Goffart <ogoffart@tiscalinet.be> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "accountconfig.h" #include <qpushbutton.h> #include <qlistview.h> #include <qlayout.h> #include <klocale.h> #include <kiconloader.h> #include <kmessagebox.h> #include <kdialogbase.h> #include "kopeteprotocol.h" #include "kopeteaccount.h" #include "addaccountwizard.h" #include "accountconfigbase.h" #include "editaccountwidget.h" #include "kopeteaccountmanager.h" AccountConfig::AccountConfig(QWidget * parent) : ConfigModule (i18n("Accounts"),i18n("Here You Can Manage Your Accounts"),"personal", parent ) { QVBoxLayout *topLayout = new QVBoxLayout( this ); m_view=new AccountConfigBase(this); topLayout->add(m_view); m_view->mButtonUp->setPixmap( SmallIcon("up") ); m_view->mButtonDown->setPixmap( SmallIcon("down") ); m_view->mAccountList->setSorting( -1 ); connect( m_view->mButtonNew , SIGNAL(clicked() ) , this , SLOT( slotAddAccount())); connect( m_view->mButtonEdit , SIGNAL(clicked() ) , this , SLOT( slotEditAccount())); connect( m_view->mButtonRemove , SIGNAL(clicked() ) , this , SLOT( slotRemoveAccount())); connect( m_view->mAccountList , SIGNAL(selectionChanged() ) , this , SLOT( slotItemSelected())); connect( m_view->mButtonUp , SIGNAL(clicked() ) , this , SLOT( slotAccountUp())); connect( m_view->mButtonDown , SIGNAL(clicked() ) , this , SLOT( slotAccountDown())); slotItemSelected(); // m_addwizard=0L; } AccountConfig::~AccountConfig() { } void AccountConfig::save() { KopeteAccountManager::manager()->save(); } void AccountConfig::reopen() { m_view->mAccountList->clear(); m_accountItems.clear(); QPtrList<KopeteAccount> accounts = KopeteAccountManager::manager()->accounts(); for(KopeteAccount *i=accounts.first() ; i; i=accounts.next() ) { QListViewItem* lvi= new QListViewItem(m_view->mAccountList); lvi->setText(0,i->protocol()->displayName() + QString::fromLatin1(" ") ); lvi->setPixmap( 0, SmallIcon( i->protocol()->pluginIcon() ) ); lvi->setText(1, i->accountId()); m_accountItems.insert(lvi,i); } } void AccountConfig::slotItemSelected() { QListViewItem *itemSelected = m_view->mAccountList->selectedItem(); m_view->mButtonEdit->setEnabled( itemSelected ); m_view->mButtonRemove->setEnabled( itemSelected ); if( itemSelected ) { m_view->mButtonUp->setEnabled( itemSelected->itemAbove() ); m_view->mButtonDown->setEnabled( itemSelected->itemBelow() ); } else { m_view->mButtonUp->setEnabled( itemSelected ); m_view->mButtonDown->setEnabled( itemSelected ); } } void AccountConfig::slotAccountUp() { QListViewItem *itemSelected = m_view->mAccountList->selectedItem(); itemSelected->itemAbove()->moveItem( itemSelected ); slotItemSelected(); } void AccountConfig::slotAccountDown() { QListViewItem *itemSelected = m_view->mAccountList->selectedItem(); itemSelected->moveItem( itemSelected->itemBelow() ); slotItemSelected(); } void AccountConfig::slotAddAccount() { AddAccountWizard *m_addwizard; m_addwizard= new AddAccountWizard( this , "addAccountWizard" , true); connect(m_addwizard, SIGNAL( destroyed(QObject*)) , this, SLOT (slotAddWizardDone())); m_addwizard->show(); } void AccountConfig::slotEditAccount() { QListViewItem *lvi=m_view->mAccountList->selectedItem(); if(!lvi) return; KopeteAccount *ident=m_accountItems[lvi]; KopeteProtocol *proto=ident->protocol(); KDialogBase *editDialog= new KDialogBase( this,"editDialog", true, i18n( "Edit Account" ), KDialogBase::Ok|KDialogBase::Cancel, KDialogBase::Ok, true ); editDialog->resize( 525, 400 ); EditAccountWidget *m_accountWidget = proto->createEditAccountWidget(ident,editDialog); QWidget *qWidget = dynamic_cast<QWidget*>( m_accountWidget ); if (!m_accountWidget) return; editDialog->setMainWidget(qWidget); if(editDialog->exec() == QDialog::Accepted ) { if(m_accountWidget->validateData()) { m_accountWidget->apply(); } } editDialog->deleteLater(); reopen(); } void AccountConfig::slotRemoveAccount() { QListViewItem *lvi=m_view->mAccountList->selectedItem(); if(lvi) { KopeteAccount *i=m_accountItems[lvi]; if( KMessageBox::warningContinueCancel( this, i18n("Are you sure you want to remove the account \"%1?\"").arg( i->accountId() ), i18n("Remove Account"), i18n("Remove Account")) == KMessageBox::Yes ) { m_accountItems.remove(lvi); i->deleteLater(); delete lvi; } } } void AccountConfig::slotAddWizardDone() { reopen(); } #include "accountconfig.moc" <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2011 LunarG, Inc. * Copyright 2011 Jose Fonseca * All Rights Reserved. * * 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 <assert.h> #include <stdlib.h> #include <iostream> #include <dlfcn.h> #include "glproc.hpp" #include "glws.hpp" namespace glws { static Display *display = NULL; static EGLDisplay eglDisplay = EGL_NO_DISPLAY; static int screen = 0; class EglVisual : public Visual { public: EGLConfig config; XVisualInfo *visinfo; EglVisual() : config(0), visinfo(0) {} ~EglVisual() { XFree(visinfo); } }; static void describeEvent(const XEvent &event) { if (0) { switch (event.type) { case ConfigureNotify: std::cerr << "ConfigureNotify"; break; case Expose: std::cerr << "Expose"; break; case KeyPress: std::cerr << "KeyPress"; break; case MapNotify: std::cerr << "MapNotify"; break; case ReparentNotify: std::cerr << "ReparentNotify"; break; default: std::cerr << "Event " << event.type; } std::cerr << " " << event.xany.window << "\n"; } } class EglDrawable : public Drawable { public: Window window; EGLSurface surface; EGLint api; EglDrawable(const Visual *vis, int w, int h) : Drawable(vis, w, h), api(EGL_OPENGL_ES_API) { XVisualInfo *visinfo = static_cast<const EglVisual *>(visual)->visinfo; Window root = RootWindow(display, screen); /* window attributes */ XSetWindowAttributes attr; attr.background_pixel = 0; attr.border_pixel = 0; attr.colormap = XCreateColormap(display, root, visinfo->visual, AllocNone); attr.event_mask = StructureNotifyMask; unsigned long mask; mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask; int x = 0, y = 0; window = XCreateWindow( display, root, x, y, width, height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr); XSizeHints sizehints; sizehints.x = x; sizehints.y = y; sizehints.width = width; sizehints.height = height; sizehints.flags = USSize | USPosition; XSetNormalHints(display, window, &sizehints); const char *name = "glretrace"; XSetStandardProperties( display, window, name, name, None, (char **)NULL, 0, &sizehints); eglWaitNative(EGL_CORE_NATIVE_ENGINE); EGLConfig config = static_cast<const EglVisual *>(visual)->config; surface = eglCreateWindowSurface(eglDisplay, config, (EGLNativeWindowType)window, NULL); } void waitForEvent(int type) { XEvent event; do { XWindowEvent(display, window, StructureNotifyMask, &event); describeEvent(event); } while (event.type != type); } ~EglDrawable() { eglDestroySurface(eglDisplay, surface); eglWaitClient(); XDestroyWindow(display, window); eglWaitNative(EGL_CORE_NATIVE_ENGINE); } void resize(int w, int h) { if (w == width && h == height) { return; } eglWaitClient(); // We need to ensure that pending events are processed here, and XSync // with discard = True guarantees that, but it appears the limited // event processing we do so far is sufficient //XSync(display, True); Drawable::resize(w, h); XResizeWindow(display, window, w, h); // Tell the window manager to respect the requested size XSizeHints size_hints; size_hints.max_width = size_hints.min_width = w; size_hints.max_height = size_hints.min_height = h; size_hints.flags = PMinSize | PMaxSize; XSetWMNormalHints(display, window, &size_hints); waitForEvent(ConfigureNotify); eglWaitNative(EGL_CORE_NATIVE_ENGINE); } void show(void) { if (visible) { return; } eglWaitClient(); XMapWindow(display, window); waitForEvent(MapNotify); eglWaitNative(EGL_CORE_NATIVE_ENGINE); Drawable::show(); } void swapBuffers(void) { eglBindAPI(api); eglSwapBuffers(eglDisplay, surface); } }; class EglContext : public Context { public: EGLContext context; EglContext(const Visual *vis, Profile prof, EGLContext ctx) : Context(vis, prof), context(ctx) {} ~EglContext() { eglDestroyContext(eglDisplay, context); } }; /** * Load the symbols from the specified shared object into global namespace, so * that they can be later found by dlsym(RTLD_NEXT, ...); */ static void load(const char *filename) { if (!dlopen(filename, RTLD_GLOBAL | RTLD_LAZY)) { std::cerr << "error: unable to open " << filename << "\n"; exit(1); } } void init(void) { load("libEGL.so.1"); display = XOpenDisplay(NULL); if (!display) { std::cerr << "error: unable to open display " << XDisplayName(NULL) << "\n"; exit(1); } screen = DefaultScreen(display); eglDisplay = eglGetDisplay((EGLNativeDisplayType)display); if (eglDisplay == EGL_NO_DISPLAY) { std::cerr << "error: unable to get EGL display\n"; XCloseDisplay(display); exit(1); } EGLint major, minor; if (!eglInitialize(eglDisplay, &major, &minor)) { std::cerr << "error: unable to initialize EGL display\n"; XCloseDisplay(display); exit(1); } } void cleanup(void) { if (display) { eglTerminate(eglDisplay); XCloseDisplay(display); display = NULL; } } Visual * createVisual(bool doubleBuffer, Profile profile) { EglVisual *visual = new EglVisual(); // possible combinations const EGLint api_bits_gl[7] = { EGL_OPENGL_BIT | EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT, EGL_OPENGL_BIT | EGL_OPENGL_ES_BIT, EGL_OPENGL_BIT | EGL_OPENGL_ES2_BIT, EGL_OPENGL_BIT, EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT, EGL_OPENGL_ES2_BIT, EGL_OPENGL_ES_BIT, }; const EGLint api_bits_gles1[7] = { EGL_OPENGL_BIT | EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT, EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT, EGL_OPENGL_BIT | EGL_OPENGL_ES_BIT, EGL_OPENGL_ES_BIT, EGL_OPENGL_BIT | EGL_OPENGL_ES2_BIT, EGL_OPENGL_BIT, EGL_OPENGL_ES2_BIT, }; const EGLint api_bits_gles2[7] = { EGL_OPENGL_BIT | EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT, EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT, EGL_OPENGL_BIT | EGL_OPENGL_ES2_BIT, EGL_OPENGL_ES2_BIT, EGL_OPENGL_BIT | EGL_OPENGL_ES_BIT, EGL_OPENGL_BIT, EGL_OPENGL_ES_BIT, }; const EGLint *api_bits; switch(profile) { case PROFILE_COMPAT: api_bits = api_bits_gl; break; case PROFILE_ES1: api_bits = api_bits_gles1; break; case PROFILE_ES2: api_bits = api_bits_gles2; break; default: return NULL; }; for (int i = 0; i < 7; i++) { Attributes<EGLint> attribs; attribs.add(EGL_SURFACE_TYPE, EGL_WINDOW_BIT); attribs.add(EGL_RED_SIZE, 1); attribs.add(EGL_GREEN_SIZE, 1); attribs.add(EGL_BLUE_SIZE, 1); attribs.add(EGL_ALPHA_SIZE, 1); attribs.add(EGL_DEPTH_SIZE, 1); attribs.add(EGL_STENCIL_SIZE, 1); attribs.add(EGL_RENDERABLE_TYPE, api_bits[i]); attribs.end(EGL_NONE); EGLint num_configs, vid; if (eglChooseConfig(eglDisplay, attribs, &visual->config, 1, &num_configs) && num_configs == 1 && eglGetConfigAttrib(eglDisplay, visual->config, EGL_NATIVE_VISUAL_ID, &vid)) { XVisualInfo templ; int num_visuals; templ.visualid = vid; visual->visinfo = XGetVisualInfo(display, VisualIDMask, &templ, &num_visuals); break; } } assert(visual->visinfo); return visual; } Drawable * createDrawable(const Visual *visual, int width, int height) { return new EglDrawable(visual, width, height); } Context * createContext(const Visual *_visual, Context *shareContext, Profile profile, bool debug) { const EglVisual *visual = static_cast<const EglVisual *>(_visual); EGLContext share_context = EGL_NO_CONTEXT; EGLContext context; Attributes<EGLint> attribs; if (shareContext) { share_context = static_cast<EglContext*>(shareContext)->context; } EGLint api = eglQueryAPI(); switch (profile) { case PROFILE_COMPAT: load("libGL.so.1"); eglBindAPI(EGL_OPENGL_API); break; case PROFILE_CORE: assert(0); return NULL; case PROFILE_ES1: load("libGLESv1_CM.so.1"); eglBindAPI(EGL_OPENGL_ES_API); break; case PROFILE_ES2: load("libGLESv2.so.2"); eglBindAPI(EGL_OPENGL_ES_API); attribs.add(EGL_CONTEXT_CLIENT_VERSION, 2); break; default: return NULL; } attribs.end(EGL_NONE); context = eglCreateContext(eglDisplay, visual->config, share_context, attribs); if (!context) return NULL; eglBindAPI(api); return new EglContext(visual, profile, context); } bool makeCurrent(Drawable *drawable, Context *context) { if (!drawable || !context) { return eglMakeCurrent(eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); } else { EglDrawable *eglDrawable = static_cast<EglDrawable *>(drawable); EglContext *eglContext = static_cast<EglContext *>(context); EGLBoolean ok; ok = eglMakeCurrent(eglDisplay, eglDrawable->surface, eglDrawable->surface, eglContext->context); if (ok) { EGLint api; eglQueryContext(eglDisplay, eglContext->context, EGL_CONTEXT_CLIENT_TYPE, &api); eglDrawable->api = api; } return ok; } } bool processEvents(void) { while (XPending(display) > 0) { XEvent event; XNextEvent(display, &event); describeEvent(event); } return true; } } /* namespace glws */ <commit_msg>Recreate egl surface when glViewport for watching framebuffer in qapitrace's surface tab.<commit_after>/************************************************************************** * * Copyright 2011 LunarG, Inc. * Copyright 2011 Jose Fonseca * All Rights Reserved. * * 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 <assert.h> #include <stdlib.h> #include <iostream> #include <dlfcn.h> #include "glproc.hpp" #include "glws.hpp" namespace glws { static Display *display = NULL; static EGLDisplay eglDisplay = EGL_NO_DISPLAY; static int screen = 0; class EglVisual : public Visual { public: EGLConfig config; XVisualInfo *visinfo; EglVisual() : config(0), visinfo(0) {} ~EglVisual() { XFree(visinfo); } }; static void describeEvent(const XEvent &event) { if (0) { switch (event.type) { case ConfigureNotify: std::cerr << "ConfigureNotify"; break; case Expose: std::cerr << "Expose"; break; case KeyPress: std::cerr << "KeyPress"; break; case MapNotify: std::cerr << "MapNotify"; break; case ReparentNotify: std::cerr << "ReparentNotify"; break; default: std::cerr << "Event " << event.type; } std::cerr << " " << event.xany.window << "\n"; } } class EglDrawable : public Drawable { public: Window window; EGLSurface surface; EGLint api; EglDrawable(const Visual *vis, int w, int h) : Drawable(vis, w, h), api(EGL_OPENGL_ES_API) { XVisualInfo *visinfo = static_cast<const EglVisual *>(visual)->visinfo; Window root = RootWindow(display, screen); /* window attributes */ XSetWindowAttributes attr; attr.background_pixel = 0; attr.border_pixel = 0; attr.colormap = XCreateColormap(display, root, visinfo->visual, AllocNone); attr.event_mask = StructureNotifyMask; unsigned long mask; mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask; int x = 0, y = 0; window = XCreateWindow( display, root, x, y, width, height, 0, visinfo->depth, InputOutput, visinfo->visual, mask, &attr); XSizeHints sizehints; sizehints.x = x; sizehints.y = y; sizehints.width = width; sizehints.height = height; sizehints.flags = USSize | USPosition; XSetNormalHints(display, window, &sizehints); const char *name = "glretrace"; XSetStandardProperties( display, window, name, name, None, (char **)NULL, 0, &sizehints); eglWaitNative(EGL_CORE_NATIVE_ENGINE); EGLConfig config = static_cast<const EglVisual *>(visual)->config; surface = eglCreateWindowSurface(eglDisplay, config, (EGLNativeWindowType)window, NULL); } void waitForEvent(int type) { XEvent event; do { XWindowEvent(display, window, StructureNotifyMask, &event); describeEvent(event); } while (event.type != type); } ~EglDrawable() { eglDestroySurface(eglDisplay, surface); eglWaitClient(); XDestroyWindow(display, window); eglWaitNative(EGL_CORE_NATIVE_ENGINE); } void recreate(void) { EGLContext currentContext = eglGetCurrentContext(); EGLSurface currentDrawSurface = eglGetCurrentSurface(EGL_DRAW); EGLSurface currentReadSurface = eglGetCurrentSurface(EGL_DRAW); bool rebindDrawSurface = currentDrawSurface == surface; bool rebindReadSurface = currentReadSurface == surface; if (rebindDrawSurface || rebindReadSurface) { eglMakeCurrent(eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); } eglDestroySurface(eglDisplay, surface); EGLConfig config = static_cast<const EglVisual *>(visual)->config; surface = eglCreateWindowSurface(eglDisplay, config, (EGLNativeWindowType)window, NULL); if (rebindDrawSurface || rebindReadSurface) { eglMakeCurrent(eglDisplay, surface, surface, currentContext); } } void resize(int w, int h) { if (w == width && h == height) { return; } eglWaitClient(); // We need to ensure that pending events are processed here, and XSync // with discard = True guarantees that, but it appears the limited // event processing we do so far is sufficient //XSync(display, True); Drawable::resize(w, h); XResizeWindow(display, window, w, h); // Tell the window manager to respect the requested size XSizeHints size_hints; size_hints.max_width = size_hints.min_width = w; size_hints.max_height = size_hints.min_height = h; size_hints.flags = PMinSize | PMaxSize; XSetWMNormalHints(display, window, &size_hints); waitForEvent(ConfigureNotify); eglWaitNative(EGL_CORE_NATIVE_ENGINE); /* * Some implementations won't update the backbuffer unless we recreate * the EGL surface. */ int eglWidth; int eglHeight; eglQuerySurface(eglDisplay, surface, EGL_WIDTH, &eglWidth); eglQuerySurface(eglDisplay, surface, EGL_HEIGHT, &eglHeight); if (eglWidth != width || eglHeight != height) { recreate(); eglQuerySurface(eglDisplay, surface, EGL_WIDTH, &eglWidth); eglQuerySurface(eglDisplay, surface, EGL_HEIGHT, &eglHeight); } assert(eglWidth == width); assert(eglHeight == height); } void show(void) { if (visible) { return; } eglWaitClient(); XMapWindow(display, window); waitForEvent(MapNotify); eglWaitNative(EGL_CORE_NATIVE_ENGINE); Drawable::show(); } void swapBuffers(void) { eglBindAPI(api); eglSwapBuffers(eglDisplay, surface); } }; class EglContext : public Context { public: EGLContext context; EglContext(const Visual *vis, Profile prof, EGLContext ctx) : Context(vis, prof), context(ctx) {} ~EglContext() { eglDestroyContext(eglDisplay, context); } }; /** * Load the symbols from the specified shared object into global namespace, so * that they can be later found by dlsym(RTLD_NEXT, ...); */ static void load(const char *filename) { if (!dlopen(filename, RTLD_GLOBAL | RTLD_LAZY)) { std::cerr << "error: unable to open " << filename << "\n"; exit(1); } } void init(void) { load("libEGL.so.1"); display = XOpenDisplay(NULL); if (!display) { std::cerr << "error: unable to open display " << XDisplayName(NULL) << "\n"; exit(1); } screen = DefaultScreen(display); eglDisplay = eglGetDisplay((EGLNativeDisplayType)display); if (eglDisplay == EGL_NO_DISPLAY) { std::cerr << "error: unable to get EGL display\n"; XCloseDisplay(display); exit(1); } EGLint major, minor; if (!eglInitialize(eglDisplay, &major, &minor)) { std::cerr << "error: unable to initialize EGL display\n"; XCloseDisplay(display); exit(1); } } void cleanup(void) { if (display) { eglTerminate(eglDisplay); XCloseDisplay(display); display = NULL; } } Visual * createVisual(bool doubleBuffer, Profile profile) { EglVisual *visual = new EglVisual(); // possible combinations const EGLint api_bits_gl[7] = { EGL_OPENGL_BIT | EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT, EGL_OPENGL_BIT | EGL_OPENGL_ES_BIT, EGL_OPENGL_BIT | EGL_OPENGL_ES2_BIT, EGL_OPENGL_BIT, EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT, EGL_OPENGL_ES2_BIT, EGL_OPENGL_ES_BIT, }; const EGLint api_bits_gles1[7] = { EGL_OPENGL_BIT | EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT, EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT, EGL_OPENGL_BIT | EGL_OPENGL_ES_BIT, EGL_OPENGL_ES_BIT, EGL_OPENGL_BIT | EGL_OPENGL_ES2_BIT, EGL_OPENGL_BIT, EGL_OPENGL_ES2_BIT, }; const EGLint api_bits_gles2[7] = { EGL_OPENGL_BIT | EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT, EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT, EGL_OPENGL_BIT | EGL_OPENGL_ES2_BIT, EGL_OPENGL_ES2_BIT, EGL_OPENGL_BIT | EGL_OPENGL_ES_BIT, EGL_OPENGL_BIT, EGL_OPENGL_ES_BIT, }; const EGLint *api_bits; switch(profile) { case PROFILE_COMPAT: api_bits = api_bits_gl; break; case PROFILE_ES1: api_bits = api_bits_gles1; break; case PROFILE_ES2: api_bits = api_bits_gles2; break; default: return NULL; }; for (int i = 0; i < 7; i++) { Attributes<EGLint> attribs; attribs.add(EGL_SURFACE_TYPE, EGL_WINDOW_BIT); attribs.add(EGL_RED_SIZE, 1); attribs.add(EGL_GREEN_SIZE, 1); attribs.add(EGL_BLUE_SIZE, 1); attribs.add(EGL_ALPHA_SIZE, 1); attribs.add(EGL_DEPTH_SIZE, 1); attribs.add(EGL_STENCIL_SIZE, 1); attribs.add(EGL_RENDERABLE_TYPE, api_bits[i]); attribs.end(EGL_NONE); EGLint num_configs, vid; if (eglChooseConfig(eglDisplay, attribs, &visual->config, 1, &num_configs) && num_configs == 1 && eglGetConfigAttrib(eglDisplay, visual->config, EGL_NATIVE_VISUAL_ID, &vid)) { XVisualInfo templ; int num_visuals; templ.visualid = vid; visual->visinfo = XGetVisualInfo(display, VisualIDMask, &templ, &num_visuals); break; } } assert(visual->visinfo); return visual; } Drawable * createDrawable(const Visual *visual, int width, int height) { return new EglDrawable(visual, width, height); } Context * createContext(const Visual *_visual, Context *shareContext, Profile profile, bool debug) { const EglVisual *visual = static_cast<const EglVisual *>(_visual); EGLContext share_context = EGL_NO_CONTEXT; EGLContext context; Attributes<EGLint> attribs; if (shareContext) { share_context = static_cast<EglContext*>(shareContext)->context; } EGLint api = eglQueryAPI(); switch (profile) { case PROFILE_COMPAT: load("libGL.so.1"); eglBindAPI(EGL_OPENGL_API); break; case PROFILE_CORE: assert(0); return NULL; case PROFILE_ES1: load("libGLESv1_CM.so.1"); eglBindAPI(EGL_OPENGL_ES_API); break; case PROFILE_ES2: load("libGLESv2.so.2"); eglBindAPI(EGL_OPENGL_ES_API); attribs.add(EGL_CONTEXT_CLIENT_VERSION, 2); break; default: return NULL; } attribs.end(EGL_NONE); context = eglCreateContext(eglDisplay, visual->config, share_context, attribs); if (!context) return NULL; eglBindAPI(api); return new EglContext(visual, profile, context); } bool makeCurrent(Drawable *drawable, Context *context) { if (!drawable || !context) { return eglMakeCurrent(eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); } else { EglDrawable *eglDrawable = static_cast<EglDrawable *>(drawable); EglContext *eglContext = static_cast<EglContext *>(context); EGLBoolean ok; ok = eglMakeCurrent(eglDisplay, eglDrawable->surface, eglDrawable->surface, eglContext->context); if (ok) { EGLint api; eglQueryContext(eglDisplay, eglContext->context, EGL_CONTEXT_CLIENT_TYPE, &api); eglDrawable->api = api; } return ok; } } bool processEvents(void) { while (XPending(display) > 0) { XEvent event; XNextEvent(display, &event); describeEvent(event); } return true; } } /* namespace glws */ <|endoftext|>
<commit_before>/* MusicXML Library Copyright (C) Grame 2006-2013 This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France research@grame.fr */ #include <sstream> #include "guido.h" using namespace std; namespace MusicXML2 { //______________________________________________________________________________ Sguidoparam guidoparam::create(string value, bool quote) { guidoparam * o = new guidoparam(value, quote); assert(o!=0); return o; } Sguidoparam guidoparam::create(long value, bool quote) { guidoparam * o = new guidoparam(value, quote); assert(o!=0); return o; } Sguidoelement guidoelement::create(string name, string sep) { guidoelement * o = new guidoelement(name, sep); assert(o!=0); return o; } Sguidonote guidonote::create(unsigned short voice) { guidonotestatus * status = guidonotestatus::get(voice); guidonote * o = new guidonote (voice,"", status->fOctave, status->fDur, ""); assert(o!=0); return o; } Sguidonote guidonote::create(unsigned short voice, string name, char oct, guidonoteduration& dur, string acc) { guidonote * o = new guidonote (voice, name, oct, dur, acc); assert(o!=0); return o; } Sguidoseq guidoseq::create() { guidoseq* o = new guidoseq(); assert(o!=0); return o;} Sguidochord guidochord::create() { guidochord* o = new guidochord(); assert(o!=0); return o;} Sguidotag guidotag::create(string name) { guidotag* o = new guidotag(name); assert(o!=0); return o;} Sguidotag guidotag::create(string name, string sep) { guidotag* o = new guidotag(name, sep); assert(o!=0); return o;} //______________________________________________________________________________ guidonotestatus* guidonotestatus::fInstances[kMaxInstances] = { 0 }; guidonotestatus* guidonotestatus::get (unsigned short voice) { if (voice < kMaxInstances) { if (!fInstances[voice]) fInstances[voice] = new guidonotestatus; return fInstances[voice]; } return 0; } void guidonotestatus::resetall () { for (int i=0; i<kMaxInstances; i++) { if (fInstances[i]) fInstances[i]->reset(); } } void guidonotestatus::freeall () { for (int i=0; i<kMaxInstances; i++) { delete fInstances[i]; fInstances[i] = 0; } } //______________________________________________________________________________ void guidoparam::set (string value, bool quote) { fValue = value; fQuote = quote; } //______________________________________________________________________________ void guidoparam::set (long value, bool quote) { stringstream s; s << value; s >> fValue; fQuote = quote; } //______________________________________________________________________________ long guidoelement::add (Sguidoelement& elt) { fElements.push_back(elt); return fElements.size()-1; } long guidoelement::add (Sguidoparam& param) { fParams.push_back(param); return fParams.size()-1; } long guidoelement::add (Sguidoparam param) { fParams.push_back(param); return fParams.size()-1; } static string add_escape(const char* str) { string out; while (*str) { if (*str == '"') out += '\\'; out += *str++; } return out; } //______________________________________________________________________________ // print the optional parameters section void guidoelement::printparams(ostream& os) const { if (!fParams.empty()) { os << "<"; vector<Sguidoparam>::const_iterator param; for (param = fParams.begin(); param != fParams.end(); ) { if ((*param)->quote()) os << "\"" << add_escape((*param)->get().c_str()) << "\""; else os << (*param)->get(); if (++param != fParams.end()) os << ", "; } os << ">"; } } //______________________________________________________________________________ // print a chord // note that a score is a chord of sequences void guidochord::print(ostream& os) const { os << fStartList; int n = countNotes(); const char* seqsep = ""; for (auto e: fElements) { // checking for elements separator // sequences (i.e. score) are handled as chords // that's why there are special cases for seq const char* sep = ((e->isNote() || (!e->isSeq() && e->countNotes())) && --n) ? ", " : " "; /// Handle the special cases: /// - If we are in a chord and e is a note, and next event is TieEnd, then the separater is " " and "," should be applied after TieEnd! Sguidoelement next_e, pre_e; bool nextExist = getNext(e, next_e); bool preExist = getPrev(e, pre_e); if ((e->isNote())&& nextExist && (next_e->getName().find("tieEnd") != std::string::npos) ) { sep = " "; } if ((e->getName().find("tieEnd") != std::string::npos) && (preExist) && (pre_e->isNote()) && nextExist) { sep = ", "; } os << seqsep << e << sep; if (e->isSeq()) seqsep = ", \n"; } os << fEndList; } //______________________________________________________________________________ void guidoelement::print(ostream& os) const { os << fName; printparams (os); // print the enclosed elements if (!fElements.empty()) { os << fStartList; string sep = " "; for (auto e: fElements) { os << sep << e; } os << fEndList << endl; } } //______________________________________________________________________________ ostream& operator<< (ostream& os, const Sguidoelement& elt) { elt->print(os); return os; } //______________________________________________________________________________ void guidonote::set (unsigned short voice, string name, char octave, guidonoteduration& dur, string acc) { guidonotestatus * status = guidonotestatus::get(voice); stringstream s; long dots = dur.fDots; fNote = name; fAccidental = acc; fOctave = octave; fDuration = dur; s << name; // octave is ignored in case of rests if (name[0] != '_') { if (!acc.empty()) s << acc; if (name != "empty") { if (!status) s << (int)octave; else if (status->fOctave != octave) { s << (int)octave; status->fOctave = octave; } } } //// AC Note 20/02/2017: Not generating Durations, causes problems on multi-voice scores with Pickup measures! //if (!status || (*status != dur)) { if (dur.fNum != 1) { s << "*" << (int)dur.fNum; } s << "/" << (int)dur.fDenom; if (status) *status = dur; //} while (dots-- > 0) s << "."; s >> fName; } //______________________________________________________________________________ guidoelement::guidoelement(string name, string sep) : fName(name), fSep(sep) {} guidoelement::~guidoelement() {} int guidoelement::countNotes () const { int count = 0; for (auto e: fElements) { if (e->isNote()) count++; else count += e->countNotes(); } return count; } //______________________________________________________________________________ guidoparam::guidoparam(string value, bool quote) : fValue(value), fQuote(quote) {} guidoparam::guidoparam(long value, bool quote) { set(value, quote); } guidoparam::~guidoparam () {} //______________________________________________________________________________ guidonote::guidonote(unsigned short voice, string name, char octave, guidonoteduration& dur, string acc) : guidoelement(""), fDuration(1,4) { set(voice, name, octave, dur, acc); } guidonote::~guidonote() {} //______________________________________________________________________________ guidoseq::guidoseq() : guidoelement("") { fStartList="["; fEndList=" ]"; } guidoseq::~guidoseq() {} //______________________________________________________________________________ guidochord::guidochord () : guidoelement("", ", ") { fStartList="{"; fEndList=" }"; } guidochord::~guidochord() {} //______________________________________________________________________________ guidotag::guidotag(string name) : guidoelement("\\"+name) { fStartList="("; fEndList=")"; } guidotag::guidotag(string name, string sep) : guidoelement("\\"+name,sep) { fStartList="("; fEndList=")"; } guidotag::~guidotag() {} } <commit_msg>xml2guido: Bypass notestatus avoiding octave parsing in guido note names as it conflicts with Partial rendering<commit_after>/* MusicXML Library Copyright (C) Grame 2006-2013 This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France research@grame.fr */ #include <sstream> #include "guido.h" using namespace std; namespace MusicXML2 { //______________________________________________________________________________ Sguidoparam guidoparam::create(string value, bool quote) { guidoparam * o = new guidoparam(value, quote); assert(o!=0); return o; } Sguidoparam guidoparam::create(long value, bool quote) { guidoparam * o = new guidoparam(value, quote); assert(o!=0); return o; } Sguidoelement guidoelement::create(string name, string sep) { guidoelement * o = new guidoelement(name, sep); assert(o!=0); return o; } Sguidonote guidonote::create(unsigned short voice) { guidonotestatus * status = guidonotestatus::get(voice); guidonote * o = new guidonote (voice,"", status->fOctave, status->fDur, ""); assert(o!=0); return o; } Sguidonote guidonote::create(unsigned short voice, string name, char oct, guidonoteduration& dur, string acc) { guidonote * o = new guidonote (voice, name, oct, dur, acc); assert(o!=0); return o; } Sguidoseq guidoseq::create() { guidoseq* o = new guidoseq(); assert(o!=0); return o;} Sguidochord guidochord::create() { guidochord* o = new guidochord(); assert(o!=0); return o;} Sguidotag guidotag::create(string name) { guidotag* o = new guidotag(name); assert(o!=0); return o;} Sguidotag guidotag::create(string name, string sep) { guidotag* o = new guidotag(name, sep); assert(o!=0); return o;} //______________________________________________________________________________ guidonotestatus* guidonotestatus::fInstances[kMaxInstances] = { 0 }; guidonotestatus* guidonotestatus::get (unsigned short voice) { if (voice < kMaxInstances) { if (!fInstances[voice]) fInstances[voice] = new guidonotestatus; return fInstances[voice]; } return 0; } void guidonotestatus::resetall () { for (int i=0; i<kMaxInstances; i++) { if (fInstances[i]) fInstances[i]->reset(); } } void guidonotestatus::freeall () { for (int i=0; i<kMaxInstances; i++) { delete fInstances[i]; fInstances[i] = 0; } } //______________________________________________________________________________ void guidoparam::set (string value, bool quote) { fValue = value; fQuote = quote; } //______________________________________________________________________________ void guidoparam::set (long value, bool quote) { stringstream s; s << value; s >> fValue; fQuote = quote; } //______________________________________________________________________________ long guidoelement::add (Sguidoelement& elt) { fElements.push_back(elt); return fElements.size()-1; } long guidoelement::add (Sguidoparam& param) { fParams.push_back(param); return fParams.size()-1; } long guidoelement::add (Sguidoparam param) { fParams.push_back(param); return fParams.size()-1; } static string add_escape(const char* str) { string out; while (*str) { if (*str == '"') out += '\\'; out += *str++; } return out; } //______________________________________________________________________________ // print the optional parameters section void guidoelement::printparams(ostream& os) const { if (!fParams.empty()) { os << "<"; vector<Sguidoparam>::const_iterator param; for (param = fParams.begin(); param != fParams.end(); ) { if ((*param)->quote()) os << "\"" << add_escape((*param)->get().c_str()) << "\""; else os << (*param)->get(); if (++param != fParams.end()) os << ", "; } os << ">"; } } //______________________________________________________________________________ // print a chord // note that a score is a chord of sequences void guidochord::print(ostream& os) const { os << fStartList; int n = countNotes(); const char* seqsep = ""; for (auto e: fElements) { // checking for elements separator // sequences (i.e. score) are handled as chords // that's why there are special cases for seq const char* sep = ((e->isNote() || (!e->isSeq() && e->countNotes())) && --n) ? ", " : " "; /// Handle the special cases: /// - If we are in a chord and e is a note, and next event is TieEnd, then the separater is " " and "," should be applied after TieEnd! Sguidoelement next_e, pre_e; bool nextExist = getNext(e, next_e); bool preExist = getPrev(e, pre_e); if ((e->isNote())&& nextExist && (next_e->getName().find("tieEnd") != std::string::npos) ) { sep = " "; } if ((e->getName().find("tieEnd") != std::string::npos) && (preExist) && (pre_e->isNote()) && nextExist) { sep = ", "; } os << seqsep << e << sep; if (e->isSeq()) seqsep = ", \n"; } os << fEndList; } //______________________________________________________________________________ void guidoelement::print(ostream& os) const { os << fName; printparams (os); // print the enclosed elements if (!fElements.empty()) { os << fStartList; string sep = " "; for (auto e: fElements) { os << sep << e; } os << fEndList << endl; } } //______________________________________________________________________________ ostream& operator<< (ostream& os, const Sguidoelement& elt) { elt->print(os); return os; } //______________________________________________________________________________ void guidonote::set (unsigned short voice, string name, char octave, guidonoteduration& dur, string acc) { guidonotestatus * status = guidonotestatus::get(voice); stringstream s; long dots = dur.fDots; fNote = name; fAccidental = acc; fOctave = octave; fDuration = dur; s << name; // octave is ignored in case of rests if (name[0] != '_') { if (!acc.empty()) s << acc; if (name != "empty") { // AC 2021: Not generating Octave will cause problems when parsing Partial XML s << (int)octave; status->fOctave = octave; // if (!status) // s << (int)octave; // else if (status->fOctave != octave) { // s << (int)octave; // status->fOctave = octave; // } } } //// AC Note 20/02/2017: Not generating Durations, causes problems on multi-voice scores with Pickup measures! //if (!status || (*status != dur)) { if (dur.fNum != 1) { s << "*" << (int)dur.fNum; } s << "/" << (int)dur.fDenom; if (status) *status = dur; //} while (dots-- > 0) s << "."; s >> fName; } //______________________________________________________________________________ guidoelement::guidoelement(string name, string sep) : fName(name), fSep(sep) {} guidoelement::~guidoelement() {} int guidoelement::countNotes () const { int count = 0; for (auto e: fElements) { if (e->isNote()) count++; else count += e->countNotes(); } return count; } //______________________________________________________________________________ guidoparam::guidoparam(string value, bool quote) : fValue(value), fQuote(quote) {} guidoparam::guidoparam(long value, bool quote) { set(value, quote); } guidoparam::~guidoparam () {} //______________________________________________________________________________ guidonote::guidonote(unsigned short voice, string name, char octave, guidonoteduration& dur, string acc) : guidoelement(""), fDuration(1,4) { set(voice, name, octave, dur, acc); } guidonote::~guidonote() {} //______________________________________________________________________________ guidoseq::guidoseq() : guidoelement("") { fStartList="["; fEndList=" ]"; } guidoseq::~guidoseq() {} //______________________________________________________________________________ guidochord::guidochord () : guidoelement("", ", ") { fStartList="{"; fEndList=" }"; } guidochord::~guidochord() {} //______________________________________________________________________________ guidotag::guidotag(string name) : guidoelement("\\"+name) { fStartList="("; fEndList=")"; } guidotag::guidotag(string name, string sep) : guidoelement("\\"+name,sep) { fStartList="("; fEndList=")"; } guidotag::~guidotag() {} } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: hi_factory.cxx,v $ * $Revision: 1.15 $ * * 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. * ************************************************************************/ #include <precomp.h> #include "hi_factory.hxx" // NOT FULLY DEFINED SERVICES #include <ary/idl/i_ce.hxx> #include <toolkit/hf_title.hxx> #include "hfi_doc.hxx" #include "hfi_navibar.hxx" #include "hfi_tag.hxx" #include "hfi_typetext.hxx" #include "hi_linkhelper.hxx" extern const String C_sCellStyle_SummaryLeft("imsum_left"); extern const String C_sCellStyle_SummaryRight("imsum_right"); extern const String C_sCellStyle_MDetail("imdetail"); extern const String C_sMemberTitle("membertitle"); namespace { const char C_sSpace[92] = " " " " " "; } void HtmlFactory_Idl::produce_SummaryDeclaration( Xml::Element & o_row, const client & i_ce ) const { produce_InternalLink(o_row, i_ce); } void HtmlFactory_Idl::produce_InternalLink( Xml::Element & o_screen, const client & i_ce ) const { StreamLock aLocalLink(100); aLocalLink() << "#" << i_ce.LocalName(); o_screen >> *new Html::TableCell << new Html::ClassAttr( C_sCellStyle_SummaryLeft ) >> *new Html::Link( aLocalLink().c_str() ) << i_ce.LocalName(); } void HtmlFactory_Idl::produce_ShortDoc( Xml::Element & o_screen, const client & i_ce ) const { Xml::Element & rDetailsRowCell = o_screen >> *new Html::TableCell << new Html::ClassAttr( C_sCellStyle_SummaryRight ); HF_IdlShortDocu aLinkDoc(Env(), rDetailsRowCell); aLinkDoc.Produce_byData( i_ce ); rDetailsRowCell << new Xml::XmlCode("&nbsp;"); } // KORR_FUTURE: Does not belong here (implementation inheritance)! void HtmlFactory_Idl::produce_Bases( Xml::Element & o_screen, const client & i_ce, const String & i_sLabel ) const { ary::idl::Type_id nBaseT = baseOf(i_ce); if ( nBaseT.IsValid() ) { HF_DocEntryList aDocList( o_screen ); aDocList.Produce_Term(i_sLabel); int nDepth = 0; Xml::Element & rBaseList = aDocList.Produce_Definition() >> *new Xml::AnElement("pre") << new Xml::AnAttribute("style","font-family:monospace;"); rBaseList >> *new Html::Strong << i_ce.LocalName(); rBaseList << "\n"; recursive_ShowBases( rBaseList, nBaseT, nDepth ); } } void HtmlFactory_Idl::produce_Members( ce_list & it_list, const String & i_summaryTitle, const String & i_summaryLabel, const String & i_detailsTitle, const String & i_detailsLabel, const E_MemberViewType i_viewType ) const { csv_assert( it_list ); ::std::auto_ptr< HF_SubTitleTable > pSummary; if ( ( i_viewType == viewtype_summary ) || ( i_viewType == viewtype_complete ) ) { pSummary.reset( new HF_SubTitleTable( CurOut(), i_summaryLabel, i_summaryTitle, 2 ) ); } ::std::auto_ptr< HF_SubTitleTable > pDetails; if ( ( i_viewType == viewtype_details ) || ( i_viewType == viewtype_complete ) ) { pDetails.reset( new HF_SubTitleTable( CurOut(), i_detailsLabel, i_detailsTitle, 1 ) ); } for ( ; it_list.operator bool(); ++it_list ) { const ary::idl::CodeEntity & rCe = Env().Data().Find_Ce(*it_list); if ( pSummary.get() ) { Xml::Element & rSummaryRow = pSummary->Add_Row(); produce_SummaryDeclaration(rSummaryRow, rCe); // produce_InternalLink(rSummaryRow, rCe); produce_ShortDoc(rSummaryRow, rCe); } if ( pDetails.get() ) produce_MemberDetails(*pDetails, rCe); } } void HtmlFactory_Idl::produce_Title( HF_TitleTable & o_title, const String & i_label, const client & i_ce ) const { StreamLock slAnnotations(200); get_Annotations(slAnnotations(), i_ce); StreamLock slTitle(200); slTitle() << i_label << " " << i_ce.LocalName(); o_title.Produce_Title( slAnnotations().c_str(), slTitle().c_str() ); } void HtmlFactory_Idl::get_Annotations( StreamStr & o_out, const client & i_ce ) const { const ary::doc::OldIdlDocu * doc = Get_IdlDocu(i_ce.Docu()); if (doc != 0) { if (doc->IsDeprecated()) o_out << "deprecated "; if (NOT doc->IsPublished()) o_out << "unpublished "; } // KORR // Need to display "unpublished", if there is no docu. } void HtmlFactory_Idl::write_Docu( Xml::Element & o_screen, const client & i_ce ) const { const ary::doc::OldIdlDocu * doc = Get_IdlDocu(i_ce.Docu()); if (doc != 0) { HF_DocEntryList aDocuList( o_screen ); HF_IdlDocu aDocu( Env(), aDocuList ); aDocu.Produce_byData(i_ce); } write_ManualLinks(o_screen, i_ce); } void HtmlFactory_Idl::write_ManualLinks( Xml::Element & o_screen, const client & i_ce ) const { const StringVector & rLinks2Descrs = i_ce.Secondaries().Links2DescriptionInManual(); if ( rLinks2Descrs.size() == 0 ) return; o_screen >> *new Html::Label(C_sLocalManualLinks.c_str()+1) // Leave out the leading '#'. << " "; HF_DocEntryList aDocuList( o_screen ); aDocuList.Produce_Term("Developers Guide"); csv_assert(rLinks2Descrs.size() % 2 == 0); for ( StringVector::const_iterator it = rLinks2Descrs.begin(); it != rLinks2Descrs.end(); ++it ) { Xml::Element & rLink = aDocuList.Produce_Definition() >> *new Html::Link( Env().Link2Manual(*it)); if ( (*(it+1)).empty() ) // HACK KORR_FUTURE // Research what happens with manual links which contain normal characters // in non-utf-8 texts. And research, why utfF-8 does not work here. rLink << new Xml::XmlCode(*it); else rLink << new Xml::XmlCode( *(it+1) ); ++it; } // end for } void HtmlFactory_Idl::produce_MemberDetails( HF_SubTitleTable & , const client & ) const { // Dummy, which does not need to do anything. } void HtmlFactory_Idl::recursive_ShowBases( Xml::Element & o_screen, type_id i_baseType, int & io_nDepth ) const { // Show this base ++io_nDepth; const ary::idl::CodeEntity * pCe = Env().Linker().Search_CeFromType(i_baseType); csv_assert(io_nDepth > 0); if (io_nDepth > 30) io_nDepth = 30; o_screen << (C_sSpace + 93 - 3*io_nDepth) << new csi::xml::XmlCode("&#x2517") << " "; if (pCe == 0) { HF_IdlTypeText aText( Env(), o_screen, false ); aText.Produce_byData( i_baseType ); o_screen << "\n"; --io_nDepth; return; } HF_IdlTypeText aBaseLink( Env(), o_screen, true ); aBaseLink.Produce_byData(pCe->CeId()); o_screen << "\n"; // Bases ary::idl::Type_id nBaseT = baseOf(*pCe); if (nBaseT.IsValid()) recursive_ShowBases(o_screen,nBaseT,io_nDepth); --io_nDepth; return; } HtmlFactory_Idl::type_id HtmlFactory_Idl::inq_BaseOf( const client & ) const { // Unused dummy. return type_id(0); } <commit_msg>#100000#fix for missing type for solaris<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: hi_factory.cxx,v $ * $Revision: 1.16 $ * * 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. * ************************************************************************/ #include <precomp.h> #include "hi_factory.hxx" // NOT FULLY DEFINED SERVICES #include <ary/idl/i_ce.hxx> #include <toolkit/hf_title.hxx> #include "hfi_doc.hxx" #include "hfi_navibar.hxx" #include "hfi_tag.hxx" #include "hfi_typetext.hxx" #include "hi_linkhelper.hxx" extern const String C_sCellStyle_SummaryLeft("imsum_left"); extern const String C_sCellStyle_SummaryRight("imsum_right"); extern const String C_sCellStyle_MDetail("imdetail"); extern const String C_sMemberTitle("membertitle"); namespace { const char C_sSpace[92] = " " " " " "; } void HtmlFactory_Idl::produce_SummaryDeclaration( Xml::Element & o_row, const client & i_ce ) const { produce_InternalLink(o_row, i_ce); } void HtmlFactory_Idl::produce_InternalLink( Xml::Element & o_screen, const client & i_ce ) const { StreamLock aLocalLink(100); aLocalLink() << "#" << i_ce.LocalName(); o_screen >> *new Html::TableCell << new Html::ClassAttr( C_sCellStyle_SummaryLeft ) >> *new Html::Link( aLocalLink().c_str() ) << i_ce.LocalName(); } void HtmlFactory_Idl::produce_ShortDoc( Xml::Element & o_screen, const client & i_ce ) const { Xml::Element & rDetailsRowCell = o_screen >> *new Html::TableCell << new Html::ClassAttr( C_sCellStyle_SummaryRight ); HF_IdlShortDocu aLinkDoc(Env(), rDetailsRowCell); aLinkDoc.Produce_byData( i_ce ); rDetailsRowCell << new Xml::XmlCode("&nbsp;"); } // KORR_FUTURE: Does not belong here (implementation inheritance)! void HtmlFactory_Idl::produce_Bases( Xml::Element & o_screen, const client & i_ce, const String & i_sLabel ) const { ary::idl::Type_id nBaseT = baseOf(i_ce); if ( nBaseT.IsValid() ) { HF_DocEntryList aDocList( o_screen ); aDocList.Produce_Term(i_sLabel); int nDepth = 0; Xml::Element & rBaseList = aDocList.Produce_Definition() >> *new Xml::AnElement("pre") << new Xml::AnAttribute("style","font-family:monospace;"); rBaseList >> *new Html::Strong << i_ce.LocalName(); rBaseList << "\n"; recursive_ShowBases( rBaseList, nBaseT, nDepth ); } } void HtmlFactory_Idl::produce_Members( ce_list & it_list, const String & i_summaryTitle, const String & i_summaryLabel, const String & i_detailsTitle, const String & i_detailsLabel, const E_MemberViewType i_viewType ) const { csv_assert( it_list ); Dyn< HF_SubTitleTable > pSummary; if ( ( i_viewType == viewtype_summary ) || ( i_viewType == viewtype_complete ) ) { pSummary = new HF_SubTitleTable( CurOut(), i_summaryLabel, i_summaryTitle, 2 ); } Dyn< HF_SubTitleTable > pDetails; if ( ( i_viewType == viewtype_details ) || ( i_viewType == viewtype_complete ) ) { pDetails = new HF_SubTitleTable( CurOut(), i_detailsLabel, i_detailsTitle, 1 ); } for ( ; it_list.operator bool(); ++it_list ) { const ary::idl::CodeEntity & rCe = Env().Data().Find_Ce(*it_list); if ( pSummary ) { Xml::Element & rSummaryRow = pSummary->Add_Row(); produce_SummaryDeclaration(rSummaryRow, rCe); // produce_InternalLink(rSummaryRow, rCe); produce_ShortDoc(rSummaryRow, rCe); } if ( pDetails ) produce_MemberDetails(*pDetails, rCe); } } void HtmlFactory_Idl::produce_Title( HF_TitleTable & o_title, const String & i_label, const client & i_ce ) const { StreamLock slAnnotations(200); get_Annotations(slAnnotations(), i_ce); StreamLock slTitle(200); slTitle() << i_label << " " << i_ce.LocalName(); o_title.Produce_Title( slAnnotations().c_str(), slTitle().c_str() ); } void HtmlFactory_Idl::get_Annotations( StreamStr & o_out, const client & i_ce ) const { const ary::doc::OldIdlDocu * doc = Get_IdlDocu(i_ce.Docu()); if (doc != 0) { if (doc->IsDeprecated()) o_out << "deprecated "; if (NOT doc->IsPublished()) o_out << "unpublished "; } // KORR // Need to display "unpublished", if there is no docu. } void HtmlFactory_Idl::write_Docu( Xml::Element & o_screen, const client & i_ce ) const { const ary::doc::OldIdlDocu * doc = Get_IdlDocu(i_ce.Docu()); if (doc != 0) { HF_DocEntryList aDocuList( o_screen ); HF_IdlDocu aDocu( Env(), aDocuList ); aDocu.Produce_byData(i_ce); } write_ManualLinks(o_screen, i_ce); } void HtmlFactory_Idl::write_ManualLinks( Xml::Element & o_screen, const client & i_ce ) const { const StringVector & rLinks2Descrs = i_ce.Secondaries().Links2DescriptionInManual(); if ( rLinks2Descrs.size() == 0 ) return; o_screen >> *new Html::Label(C_sLocalManualLinks.c_str()+1) // Leave out the leading '#'. << " "; HF_DocEntryList aDocuList( o_screen ); aDocuList.Produce_Term("Developers Guide"); csv_assert(rLinks2Descrs.size() % 2 == 0); for ( StringVector::const_iterator it = rLinks2Descrs.begin(); it != rLinks2Descrs.end(); ++it ) { Xml::Element & rLink = aDocuList.Produce_Definition() >> *new Html::Link( Env().Link2Manual(*it)); if ( (*(it+1)).empty() ) // HACK KORR_FUTURE // Research what happens with manual links which contain normal characters // in non-utf-8 texts. And research, why utfF-8 does not work here. rLink << new Xml::XmlCode(*it); else rLink << new Xml::XmlCode( *(it+1) ); ++it; } // end for } void HtmlFactory_Idl::produce_MemberDetails( HF_SubTitleTable & , const client & ) const { // Dummy, which does not need to do anything. } void HtmlFactory_Idl::recursive_ShowBases( Xml::Element & o_screen, type_id i_baseType, int & io_nDepth ) const { // Show this base ++io_nDepth; const ary::idl::CodeEntity * pCe = Env().Linker().Search_CeFromType(i_baseType); csv_assert(io_nDepth > 0); if (io_nDepth > 30) io_nDepth = 30; o_screen << (C_sSpace + 93 - 3*io_nDepth) << new csi::xml::XmlCode("&#x2517") << " "; if (pCe == 0) { HF_IdlTypeText aText( Env(), o_screen, false ); aText.Produce_byData( i_baseType ); o_screen << "\n"; --io_nDepth; return; } HF_IdlTypeText aBaseLink( Env(), o_screen, true ); aBaseLink.Produce_byData(pCe->CeId()); o_screen << "\n"; // Bases ary::idl::Type_id nBaseT = baseOf(*pCe); if (nBaseT.IsValid()) recursive_ShowBases(o_screen,nBaseT,io_nDepth); --io_nDepth; return; } HtmlFactory_Idl::type_id HtmlFactory_Idl::inq_BaseOf( const client & ) const { // Unused dummy. return type_id(0); } <|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <kdebug.h> #include <qfile.h> #include <qdir.h> #include <qtextstream.h> #include <qregexp.h> #include <kglobal.h> #include <klocale.h> #include <ktempfile.h> #include <kstandarddirs.h> #include <libkcal/event.h> #include <libkcal/freebusy.h> //#include <libkcal/imipscheduler.h> #include <libkcal/dummyscheduler.h> #include <libkcal/icalformat.h> #include <libkcal/calendar.h> #ifndef KORG_NOMAIL #include "mailscheduler.h" #endif #include "koprefs.h" #include "outgoingdialog.h" #include "koeventviewerdialog.h" #include "docprefs.h" #include "kogroupware.h" #include "freebusymanager.h" #include "docprefs.h" class ScheduleItemOutVisitor : public IncidenceBase::Visitor { public: ScheduleItemOutVisitor() : mItem(0) {} bool act( IncidenceBase *incidence, ScheduleItemOut *item ) { mItem = item; return (incidence && mItem) ? incidence->accept( *this ) : false; } protected: bool visit( Event *event ) { mItem->setText( 0, event->summary() ); mItem->setText( 1, event->dtStartDateStr() ); if ( event->doesFloat() ) { //If the event floats set the start and end times to no time mItem->setText( 2, i18n("no time") ); mItem->setText( 4, i18n("no time") ); } else { //If it does not float mItem->setText( 2, event->dtStartTimeStr() ); } if ( event->hasEndDate() ) { mItem->setText( 3, event->dtEndDateStr() ); if ( !event->doesFloat() ) mItem->setText( 4, event->dtEndTimeStr() ); } else { mItem->setText( 3, i18n("no date") ); mItem->setText( 4, i18n("no time") ); } return true; } bool visit( Todo *todo ) { mItem->setText( 0, todo->summary() ); if ( todo->hasStartDate() ) { mItem->setText( 1, todo->dtStartDateStr() ); if ( !todo->doesFloat() ) mItem->setText( 2, todo->dtStartTimeStr() ); } if ( todo->hasDueDate() ) { mItem->setText( 3, todo->dtDueDateStr() ); if ( !todo->doesFloat() ) mItem->setText( 4, todo->dtDueTimeStr() ); } return true; } bool visit( Journal *journal ) { mItem->setText( 0, journal->description().left(50) ); mItem->setText( 1, journal->dtStartDateStr() ); if ( !journal->doesFloat() ) mItem->setText( 2, journal->dtStartTimeStr() ); return true; } bool visit( FreeBusy *fb ) { mItem->setText( 0, i18n("Free Busy Object") ); mItem->setText( 1, fb->dtStartDateStr() ); mItem->setText( 2, fb->dtStartTimeStr() ); mItem->setText( 3, KGlobal::locale()->formatDate( fb->dtEnd().date() ) ); mItem->setText( 4, KGlobal::locale()->formatTime( fb->dtEnd().time() ) ); return true; } protected: ScheduleItemOut *mItem; }; ScheduleItemOut::ScheduleItemOut(QListView *parent,IncidenceBase *ev, Scheduler::Method method, const QString &recipients) : QListViewItem(parent) { mIncidence = ev; mMethod = method; mRecipients = recipients; // kdDebug(5850) << "ScheduleItemOut: setting the summary" << endl; // FIXME: use a visitor here ScheduleItemOutVisitor v; if ( !mIncidence || !v.act( mIncidence, this ) ) { setText( 0, i18n("Unable to interpret incidence") ); } //Set the Method setText(5,Scheduler::translatedMethodName(mMethod)); } OutgoingDialog::OutgoingDialog(Calendar *calendar,QWidget* parent, const char* name,bool modal, WFlags fl) : OutgoingDialog_base(parent,name,modal,fl) { mCalendar = calendar; mFormat = new ICalFormat; if (KOPrefs::instance()->mIMIPScheduler == KOPrefs::IMIPDummy ) { mScheduler = new DummyScheduler(mCalendar); } else { #ifndef KORG_NOMAIL mScheduler = new MailScheduler(mCalendar); #else mScheduler = new DummyScheduler(mCalendar); #endif } mScheduler->setFreeBusyCache( KOGroupware::instance()->freeBusyManager() ); mMessageListView->setColumnAlignment(1,AlignHCenter); mMessageListView->setColumnAlignment(2,AlignHCenter); mMessageListView->setColumnAlignment(3,AlignHCenter); mMessageListView->setColumnAlignment(4,AlignHCenter); QObject::connect(mMessageListView,SIGNAL(doubleClicked(QListViewItem *)), this,SLOT(showEvent(QListViewItem *))); mDocPrefs = new DocPrefs("groupschedule"); loadMessages(); } OutgoingDialog::~OutgoingDialog() { delete mScheduler; delete mDocPrefs; delete mFormat; } bool OutgoingDialog::addMessage(IncidenceBase *incidence,Scheduler::Method method) { kdDebug(5850) << "Outgoing::addMessage" << "Method:" << method << endl; if (method == Scheduler::Publish) return false; if( mDocPrefs ) { if (method != Scheduler::Cancel) { mDocPrefs->writeEntry( incidence->uid()+"-scheduled", true ); } else { if (!mDocPrefs->readBoolEntry(incidence->uid()+"-scheduled") ) return true; } } if (KOPrefs::instance()->mIMIPSend == KOPrefs::IMIPOutbox) { new ScheduleItemOut(mMessageListView,incidence,method); saveMessage(incidence,method); emit numMessagesChanged(mMessageListView->childCount()); } else { mScheduler->performTransaction(incidence,method); } return true; } bool OutgoingDialog::addMessage(IncidenceBase *incidence,Scheduler::Method method, const QString &recipients) { //if (method != Scheduler::Publish) return false; if( mDocPrefs ) { if (method != Scheduler::Cancel) { mDocPrefs->writeEntry( incidence->uid()+"-scheduled", true ); } else { if (!mDocPrefs->readBoolEntry(incidence->uid()+"-scheduled") ) return true; } } if (KOPrefs::instance()->mIMIPSend == KOPrefs::IMIPOutbox) { new ScheduleItemOut(mMessageListView,incidence,method,recipients); saveMessage(incidence,method,recipients); emit numMessagesChanged(mMessageListView->childCount()); } else { mScheduler->performTransaction(incidence,method,recipients); } return true; } void OutgoingDialog::send() { kdDebug(5850) << "OutgoingDialog::send" << endl; ScheduleItemOut *item = (ScheduleItemOut *)(mMessageListView->firstChild()); while(item) { bool success; if (item->method() == Scheduler::Publish) { success = mScheduler->publish(item->event(),item->recipients()); } else { success = mScheduler->performTransaction(item->event(),item->method()); } ScheduleItemOut *oldItem = item; item = (ScheduleItemOut *)(item->nextSibling()); if (success) { deleteMessage(oldItem->event()); delete (oldItem->event()); delete oldItem; } } emit numMessagesChanged(mMessageListView->childCount()); } void OutgoingDialog::deleteItem() { ScheduleItemOut *item = (ScheduleItemOut *)(mMessageListView->selectedItem()); if(!item) return; deleteMessage(item->event()); delete(item->event()); mMessageListView->takeItem(item); emit numMessagesChanged(mMessageListView->childCount()); } void OutgoingDialog::showEvent( QListViewItem *qitem ) { ScheduleItemOut *item = (ScheduleItemOut *)qitem; QString sendText; Incidence *incidence = dynamic_cast<Incidence *>( item->event() ); if ( incidence ) { KOEventViewerDialog *eventViewer = new KOEventViewerDialog(this); eventViewer->setIncidence( incidence ); sendText = "<hr><h4>"+i18n("Event will be sent to:")+"</h4>"; switch ( item->method() ) { case Scheduler::Publish: { sendText += item->recipients(); break; } case Scheduler::Request: case Scheduler::Refresh: case Scheduler::Cancel: case Scheduler::Add: case Scheduler::Declinecounter: { sendText += i18n("All attendees"); break; } case Scheduler::Reply: case Scheduler::Counter: { sendText += i18n("The organizer %1").arg( incidence->organizer().fullName() ); break; } case Scheduler::NoMethod: { sendText += ""; break; } default: sendText = ""; } eventViewer->addText(sendText); eventViewer->show(); } } bool OutgoingDialog::saveMessage(IncidenceBase *incidence,Scheduler::Method method, const QString &recipients) { KTempFile ktfile(locateLocal("data","korganizer/outgoing/"),"ics"); QString messageText = mFormat->createScheduleMessage(incidence,method); QTextStream *qts = ktfile.textStream(); qts->setEncoding( QTextStream::UnicodeUTF8 ); *qts << messageText; *qts << "METHOD-BEGIN:" << endl << method << endl << ":METHOD-END" << endl; *qts << "RECIPIENTS-BEGIN:" << endl << recipients << endl << ":RECIPIENTS-END" << endl; mMessageMap[incidence]=ktfile.name(); return true; } bool OutgoingDialog::deleteMessage(IncidenceBase *incidence) { QFile f( mMessageMap[incidence] ); mMessageMap.remove(incidence); if ( !f.exists() ) return false; else return f.remove(); } void OutgoingDialog::loadMessages() { Scheduler::Method method; QString recipients; QString outgoingDirName = locateLocal("data","korganizer/outgoing"); QDir outgoingDir(outgoingDirName); QStringList outgoing = outgoingDir.entryList(QDir::Files); QStringList::ConstIterator it; for(it = outgoing.begin(); it != outgoing.end(); ++it) { kdDebug(5850) << "-- File: " << (*it) << endl; QFile f(outgoingDirName + "/" + (*it)); bool inserted = false; QMap<IncidenceBase*, QString>::Iterator iter; for ( iter = mMessageMap.begin(); iter != mMessageMap.end(); ++iter ) { if (iter.data() == outgoingDirName + "/" + (*it)) inserted = true; } if (!inserted) { if (!f.open(IO_ReadOnly)) { kdDebug(5850) << "OutgoingDialog::loadMessage(): Can't open file'" << (*it) << "'" << endl; } else { QTextStream t(&f); t.setEncoding( QTextStream::Latin1 ); QString messageString = t.read(); messageString.replace( QRegExp("\n[ \t]"), ""); messageString = QString::fromUtf8( messageString.latin1() ); ScheduleMessage *message = mFormat->parseScheduleMessage(mCalendar, messageString); int begin_pos = messageString.find("METHOD-BEGIN:"); begin_pos = messageString.find('\n',begin_pos)+1; QString meth = messageString.mid(begin_pos,1); switch (meth.toInt()) { case 0:method=Scheduler::Publish; break; case 1:method=Scheduler::Request; break; case 2:method=Scheduler::Refresh; break; case 3:method=Scheduler::Cancel; break; case 4:method=Scheduler::Add; break; case 5:method=Scheduler::Reply; break; case 6:method=Scheduler::Counter; break; case 7:method=Scheduler::Declinecounter; break; default :method=Scheduler::NoMethod; break; } begin_pos = messageString.find("RECIPIENTS-BEGIN:"); begin_pos = messageString.find('\n',begin_pos)+1; int end_pos = messageString.find(":RECIPIENTS-END",begin_pos)-1; recipients = messageString.mid(begin_pos, end_pos-begin_pos); kdDebug(5850) << "Outgoing::loadMessage(): Recipients: " << recipients << endl; if (message) { bool inserted = false; QMap<IncidenceBase*, QString>::Iterator iter; for ( iter = mMessageMap.begin(); iter != mMessageMap.end(); ++iter ) { if (iter.data() == outgoingDirName + "/" + (*it)) inserted = true; } if (!inserted) { kdDebug(5850) << "OutgoingDialog::loadMessage(): got message '" << (*it) << "'" << endl; IncidenceBase *inc = message->event(); new ScheduleItemOut(mMessageListView,inc,method,recipients); mMessageMap[message->event()]=outgoingDirName + "/" + (*it); } } else { QString errorMessage; if (mFormat->exception()) { errorMessage = mFormat->exception()->message(); } kdDebug(5850) << "OutgoingDialog::loadMessage(): Error parsing " "message: " << errorMessage << endl; } f.close(); } } } emit numMessagesChanged(mMessageListView->childCount()); } void OutgoingDialog::setDocumentId( const QString &id ) { mDocPrefs->setDoc( id ); } #include "outgoingdialog.moc" <commit_msg>Fix space in debug output<commit_after>/* This file is part of KOrganizer. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <kdebug.h> #include <qfile.h> #include <qdir.h> #include <qtextstream.h> #include <qregexp.h> #include <kglobal.h> #include <klocale.h> #include <ktempfile.h> #include <kstandarddirs.h> #include <libkcal/event.h> #include <libkcal/freebusy.h> //#include <libkcal/imipscheduler.h> #include <libkcal/dummyscheduler.h> #include <libkcal/icalformat.h> #include <libkcal/calendar.h> #ifndef KORG_NOMAIL #include "mailscheduler.h" #endif #include "koprefs.h" #include "outgoingdialog.h" #include "koeventviewerdialog.h" #include "docprefs.h" #include "kogroupware.h" #include "freebusymanager.h" #include "docprefs.h" class ScheduleItemOutVisitor : public IncidenceBase::Visitor { public: ScheduleItemOutVisitor() : mItem(0) {} bool act( IncidenceBase *incidence, ScheduleItemOut *item ) { mItem = item; return (incidence && mItem) ? incidence->accept( *this ) : false; } protected: bool visit( Event *event ) { mItem->setText( 0, event->summary() ); mItem->setText( 1, event->dtStartDateStr() ); if ( event->doesFloat() ) { //If the event floats set the start and end times to no time mItem->setText( 2, i18n("no time") ); mItem->setText( 4, i18n("no time") ); } else { //If it does not float mItem->setText( 2, event->dtStartTimeStr() ); } if ( event->hasEndDate() ) { mItem->setText( 3, event->dtEndDateStr() ); if ( !event->doesFloat() ) mItem->setText( 4, event->dtEndTimeStr() ); } else { mItem->setText( 3, i18n("no date") ); mItem->setText( 4, i18n("no time") ); } return true; } bool visit( Todo *todo ) { mItem->setText( 0, todo->summary() ); if ( todo->hasStartDate() ) { mItem->setText( 1, todo->dtStartDateStr() ); if ( !todo->doesFloat() ) mItem->setText( 2, todo->dtStartTimeStr() ); } if ( todo->hasDueDate() ) { mItem->setText( 3, todo->dtDueDateStr() ); if ( !todo->doesFloat() ) mItem->setText( 4, todo->dtDueTimeStr() ); } return true; } bool visit( Journal *journal ) { mItem->setText( 0, journal->description().left(50) ); mItem->setText( 1, journal->dtStartDateStr() ); if ( !journal->doesFloat() ) mItem->setText( 2, journal->dtStartTimeStr() ); return true; } bool visit( FreeBusy *fb ) { mItem->setText( 0, i18n("Free Busy Object") ); mItem->setText( 1, fb->dtStartDateStr() ); mItem->setText( 2, fb->dtStartTimeStr() ); mItem->setText( 3, KGlobal::locale()->formatDate( fb->dtEnd().date() ) ); mItem->setText( 4, KGlobal::locale()->formatTime( fb->dtEnd().time() ) ); return true; } protected: ScheduleItemOut *mItem; }; ScheduleItemOut::ScheduleItemOut(QListView *parent,IncidenceBase *ev, Scheduler::Method method, const QString &recipients) : QListViewItem(parent) { mIncidence = ev; mMethod = method; mRecipients = recipients; // kdDebug(5850) << "ScheduleItemOut: setting the summary" << endl; // FIXME: use a visitor here ScheduleItemOutVisitor v; if ( !mIncidence || !v.act( mIncidence, this ) ) { setText( 0, i18n("Unable to interpret incidence") ); } //Set the Method setText(5,Scheduler::translatedMethodName(mMethod)); } OutgoingDialog::OutgoingDialog(Calendar *calendar,QWidget* parent, const char* name,bool modal, WFlags fl) : OutgoingDialog_base(parent,name,modal,fl) { mCalendar = calendar; mFormat = new ICalFormat; if (KOPrefs::instance()->mIMIPScheduler == KOPrefs::IMIPDummy ) { mScheduler = new DummyScheduler(mCalendar); } else { #ifndef KORG_NOMAIL mScheduler = new MailScheduler(mCalendar); #else mScheduler = new DummyScheduler(mCalendar); #endif } mScheduler->setFreeBusyCache( KOGroupware::instance()->freeBusyManager() ); mMessageListView->setColumnAlignment(1,AlignHCenter); mMessageListView->setColumnAlignment(2,AlignHCenter); mMessageListView->setColumnAlignment(3,AlignHCenter); mMessageListView->setColumnAlignment(4,AlignHCenter); QObject::connect(mMessageListView,SIGNAL(doubleClicked(QListViewItem *)), this,SLOT(showEvent(QListViewItem *))); mDocPrefs = new DocPrefs("groupschedule"); loadMessages(); } OutgoingDialog::~OutgoingDialog() { delete mScheduler; delete mDocPrefs; delete mFormat; } bool OutgoingDialog::addMessage(IncidenceBase *incidence,Scheduler::Method method) { kdDebug(5850) << "Outgoing::addMessage, " << "Method:" << method << endl; if (method == Scheduler::Publish) return false; if( mDocPrefs ) { if (method != Scheduler::Cancel) { mDocPrefs->writeEntry( incidence->uid()+"-scheduled", true ); } else { if (!mDocPrefs->readBoolEntry(incidence->uid()+"-scheduled") ) return true; } } if (KOPrefs::instance()->mIMIPSend == KOPrefs::IMIPOutbox) { new ScheduleItemOut(mMessageListView,incidence,method); saveMessage(incidence,method); emit numMessagesChanged(mMessageListView->childCount()); } else { mScheduler->performTransaction(incidence,method); } return true; } bool OutgoingDialog::addMessage(IncidenceBase *incidence,Scheduler::Method method, const QString &recipients) { //if (method != Scheduler::Publish) return false; if( mDocPrefs ) { if (method != Scheduler::Cancel) { mDocPrefs->writeEntry( incidence->uid()+"-scheduled", true ); } else { if (!mDocPrefs->readBoolEntry(incidence->uid()+"-scheduled") ) return true; } } if (KOPrefs::instance()->mIMIPSend == KOPrefs::IMIPOutbox) { new ScheduleItemOut(mMessageListView,incidence,method,recipients); saveMessage(incidence,method,recipients); emit numMessagesChanged(mMessageListView->childCount()); } else { mScheduler->performTransaction(incidence,method,recipients); } return true; } void OutgoingDialog::send() { kdDebug(5850) << "OutgoingDialog::send" << endl; ScheduleItemOut *item = (ScheduleItemOut *)(mMessageListView->firstChild()); while(item) { bool success; if (item->method() == Scheduler::Publish) { success = mScheduler->publish(item->event(),item->recipients()); } else { success = mScheduler->performTransaction(item->event(),item->method()); } ScheduleItemOut *oldItem = item; item = (ScheduleItemOut *)(item->nextSibling()); if (success) { deleteMessage(oldItem->event()); delete (oldItem->event()); delete oldItem; } } emit numMessagesChanged(mMessageListView->childCount()); } void OutgoingDialog::deleteItem() { ScheduleItemOut *item = (ScheduleItemOut *)(mMessageListView->selectedItem()); if(!item) return; deleteMessage(item->event()); delete(item->event()); mMessageListView->takeItem(item); emit numMessagesChanged(mMessageListView->childCount()); } void OutgoingDialog::showEvent( QListViewItem *qitem ) { ScheduleItemOut *item = (ScheduleItemOut *)qitem; QString sendText; Incidence *incidence = dynamic_cast<Incidence *>( item->event() ); if ( incidence ) { KOEventViewerDialog *eventViewer = new KOEventViewerDialog(this); eventViewer->setIncidence( incidence ); sendText = "<hr><h4>"+i18n("Event will be sent to:")+"</h4>"; switch ( item->method() ) { case Scheduler::Publish: { sendText += item->recipients(); break; } case Scheduler::Request: case Scheduler::Refresh: case Scheduler::Cancel: case Scheduler::Add: case Scheduler::Declinecounter: { sendText += i18n("All attendees"); break; } case Scheduler::Reply: case Scheduler::Counter: { sendText += i18n("The organizer %1").arg( incidence->organizer().fullName() ); break; } case Scheduler::NoMethod: { sendText += ""; break; } default: sendText = ""; } eventViewer->addText(sendText); eventViewer->show(); } } bool OutgoingDialog::saveMessage(IncidenceBase *incidence,Scheduler::Method method, const QString &recipients) { KTempFile ktfile(locateLocal("data","korganizer/outgoing/"),"ics"); QString messageText = mFormat->createScheduleMessage(incidence,method); QTextStream *qts = ktfile.textStream(); qts->setEncoding( QTextStream::UnicodeUTF8 ); *qts << messageText; *qts << "METHOD-BEGIN:" << endl << method << endl << ":METHOD-END" << endl; *qts << "RECIPIENTS-BEGIN:" << endl << recipients << endl << ":RECIPIENTS-END" << endl; mMessageMap[incidence]=ktfile.name(); return true; } bool OutgoingDialog::deleteMessage(IncidenceBase *incidence) { QFile f( mMessageMap[incidence] ); mMessageMap.remove(incidence); if ( !f.exists() ) return false; else return f.remove(); } void OutgoingDialog::loadMessages() { Scheduler::Method method; QString recipients; QString outgoingDirName = locateLocal("data","korganizer/outgoing"); QDir outgoingDir(outgoingDirName); QStringList outgoing = outgoingDir.entryList(QDir::Files); QStringList::ConstIterator it; for(it = outgoing.begin(); it != outgoing.end(); ++it) { kdDebug(5850) << "-- File: " << (*it) << endl; QFile f(outgoingDirName + "/" + (*it)); bool inserted = false; QMap<IncidenceBase*, QString>::Iterator iter; for ( iter = mMessageMap.begin(); iter != mMessageMap.end(); ++iter ) { if (iter.data() == outgoingDirName + "/" + (*it)) inserted = true; } if (!inserted) { if (!f.open(IO_ReadOnly)) { kdDebug(5850) << "OutgoingDialog::loadMessage(): Can't open file'" << (*it) << "'" << endl; } else { QTextStream t(&f); t.setEncoding( QTextStream::Latin1 ); QString messageString = t.read(); messageString.replace( QRegExp("\n[ \t]"), ""); messageString = QString::fromUtf8( messageString.latin1() ); ScheduleMessage *message = mFormat->parseScheduleMessage(mCalendar, messageString); int begin_pos = messageString.find("METHOD-BEGIN:"); begin_pos = messageString.find('\n',begin_pos)+1; QString meth = messageString.mid(begin_pos,1); switch (meth.toInt()) { case 0:method=Scheduler::Publish; break; case 1:method=Scheduler::Request; break; case 2:method=Scheduler::Refresh; break; case 3:method=Scheduler::Cancel; break; case 4:method=Scheduler::Add; break; case 5:method=Scheduler::Reply; break; case 6:method=Scheduler::Counter; break; case 7:method=Scheduler::Declinecounter; break; default :method=Scheduler::NoMethod; break; } begin_pos = messageString.find("RECIPIENTS-BEGIN:"); begin_pos = messageString.find('\n',begin_pos)+1; int end_pos = messageString.find(":RECIPIENTS-END",begin_pos)-1; recipients = messageString.mid(begin_pos, end_pos-begin_pos); kdDebug(5850) << "Outgoing::loadMessage(): Recipients: " << recipients << endl; if (message) { bool inserted = false; QMap<IncidenceBase*, QString>::Iterator iter; for ( iter = mMessageMap.begin(); iter != mMessageMap.end(); ++iter ) { if (iter.data() == outgoingDirName + "/" + (*it)) inserted = true; } if (!inserted) { kdDebug(5850) << "OutgoingDialog::loadMessage(): got message '" << (*it) << "'" << endl; IncidenceBase *inc = message->event(); new ScheduleItemOut(mMessageListView,inc,method,recipients); mMessageMap[message->event()]=outgoingDirName + "/" + (*it); } } else { QString errorMessage; if (mFormat->exception()) { errorMessage = mFormat->exception()->message(); } kdDebug(5850) << "OutgoingDialog::loadMessage(): Error parsing " "message: " << errorMessage << endl; } f.close(); } } } emit numMessagesChanged(mMessageListView->childCount()); } void OutgoingDialog::setDocumentId( const QString &id ) { mDocPrefs->setDoc( id ); } #include "outgoingdialog.moc" <|endoftext|>
<commit_before>#include <ir/index_manager/index/MultiTermPositions.h> using namespace izenelib::ir::indexmanager; MultiTermPositions::MultiTermPositions(void) { current = NULL; pTermPositionQueue = NULL; } MultiTermPositions::~MultiTermPositions(void) { close(); } docid_t MultiTermPositions::doc() { return current->termPositions->doc(); } count_t MultiTermPositions::freq() { return current->termPositions->freq(); } bool MultiTermPositions::next() { if (pTermPositionQueue == NULL) { initQueue(); if (current) return true; return false; } while (pTermPositionQueue->size() > 0) { if (current->termPositions->next()) { return true; } else { pTermPositionQueue->pop(); if (pTermPositionQueue->size() > 0) { current = pTermPositionQueue->top(); return true; } } } return false; } count_t MultiTermPositions::next(docid_t*& docs, count_t*& freqs) { if (pTermPositionQueue == NULL) { initQueue(); } int c = -1; while (pTermPositionQueue->size() > 0) { current = pTermPositionQueue->top(); c = current->termPositions->next(docs,freqs); if (c> 0) return c; else pTermPositionQueue->pop(); } return c; } freq_t MultiTermPositions::docFreq() { BarrelTermPositionsEntry* pEntry; freq_t df = 0; list<BarrelTermPositionsEntry*>::iterator iter = termPositionsList.begin(); while (iter != termPositionsList.end()) { pEntry = (*iter); df += pEntry->termPositions->docFreq(); iter++; } return df; } freq_t MultiTermPositions::docLength() { cout<<"MultiTermPositions "<<this<<endl; list<BarrelTermPositionsEntry*>::iterator iter = termPositionsList.begin(); return (*iter)->termPositions->docLength(); } int64_t MultiTermPositions::getCTF() { BarrelTermPositionsEntry* pEntry; int64_t ctf = 0; list<BarrelTermPositionsEntry*>::iterator iter = termPositionsList.begin(); while (iter != termPositionsList.end()) { pEntry = (*iter); ctf += pEntry->termPositions->getCTF(); iter++; } return ctf; } void MultiTermPositions::close() { list<BarrelTermPositionsEntry*>::iterator iter = termPositionsList.begin(); while (iter != termPositionsList.end()) { delete (*iter); iter++; } termPositionsList.clear(); if (pTermPositionQueue) { delete pTermPositionQueue; pTermPositionQueue = NULL; } current = NULL; } loc_t MultiTermPositions::nextPosition() { return current->termPositions->nextPosition(); } int32_t MultiTermPositions::nextPositions(loc_t*& positions) { return current->termPositions->nextPositions(positions); } void MultiTermPositions::add(BarrelInfo* pBarrelInfo,TermPositions* pTermPositions) { termPositionsList.push_back(new BarrelTermPositionsEntry(pBarrelInfo,pTermPositions)); if (current == NULL) current = termPositionsList.front(); } void MultiTermPositions::initQueue() { pTermPositionQueue = new TermPositionQueue(termPositionsList.size()); list<BarrelTermPositionsEntry*>::iterator iter = termPositionsList.begin(); BarrelTermPositionsEntry* pEntry; while (iter != termPositionsList.end()) { pEntry = *iter; if (pEntry->termPositions->next()) pTermPositionQueue->insert(pEntry); iter++; } if (pTermPositionQueue->size() > 0) current = pTermPositionQueue->top(); else current = NULL; } <commit_msg>clear debug info<commit_after>#include <ir/index_manager/index/MultiTermPositions.h> using namespace izenelib::ir::indexmanager; MultiTermPositions::MultiTermPositions(void) { current = NULL; pTermPositionQueue = NULL; } MultiTermPositions::~MultiTermPositions(void) { close(); } docid_t MultiTermPositions::doc() { return current->termPositions->doc(); } count_t MultiTermPositions::freq() { return current->termPositions->freq(); } bool MultiTermPositions::next() { if (pTermPositionQueue == NULL) { initQueue(); if (current) return true; return false; } while (pTermPositionQueue->size() > 0) { if (current->termPositions->next()) { return true; } else { pTermPositionQueue->pop(); if (pTermPositionQueue->size() > 0) { current = pTermPositionQueue->top(); return true; } } } return false; } count_t MultiTermPositions::next(docid_t*& docs, count_t*& freqs) { if (pTermPositionQueue == NULL) { initQueue(); } int c = -1; while (pTermPositionQueue->size() > 0) { current = pTermPositionQueue->top(); c = current->termPositions->next(docs,freqs); if (c> 0) return c; else pTermPositionQueue->pop(); } return c; } freq_t MultiTermPositions::docFreq() { BarrelTermPositionsEntry* pEntry; freq_t df = 0; list<BarrelTermPositionsEntry*>::iterator iter = termPositionsList.begin(); while (iter != termPositionsList.end()) { pEntry = (*iter); df += pEntry->termPositions->docFreq(); iter++; } return df; } freq_t MultiTermPositions::docLength() { list<BarrelTermPositionsEntry*>::iterator iter = termPositionsList.begin(); return (*iter)->termPositions->docLength(); } int64_t MultiTermPositions::getCTF() { BarrelTermPositionsEntry* pEntry; int64_t ctf = 0; list<BarrelTermPositionsEntry*>::iterator iter = termPositionsList.begin(); while (iter != termPositionsList.end()) { pEntry = (*iter); ctf += pEntry->termPositions->getCTF(); iter++; } return ctf; } void MultiTermPositions::close() { list<BarrelTermPositionsEntry*>::iterator iter = termPositionsList.begin(); while (iter != termPositionsList.end()) { delete (*iter); iter++; } termPositionsList.clear(); if (pTermPositionQueue) { delete pTermPositionQueue; pTermPositionQueue = NULL; } current = NULL; } loc_t MultiTermPositions::nextPosition() { return current->termPositions->nextPosition(); } int32_t MultiTermPositions::nextPositions(loc_t*& positions) { return current->termPositions->nextPositions(positions); } void MultiTermPositions::add(BarrelInfo* pBarrelInfo,TermPositions* pTermPositions) { termPositionsList.push_back(new BarrelTermPositionsEntry(pBarrelInfo,pTermPositions)); if (current == NULL) current = termPositionsList.front(); } void MultiTermPositions::initQueue() { pTermPositionQueue = new TermPositionQueue(termPositionsList.size()); list<BarrelTermPositionsEntry*>::iterator iter = termPositionsList.begin(); BarrelTermPositionsEntry* pEntry; while (iter != termPositionsList.end()) { pEntry = *iter; if (pEntry->termPositions->next()) pTermPositionQueue->insert(pEntry); iter++; } if (pTermPositionQueue->size() > 0) current = pTermPositionQueue->top(); else current = NULL; } <|endoftext|>
<commit_before>// https://www.codeeval.com/open_challenges/84/ #include <iostream> #include <fstream> using namespace std; bool isBalanced(string str); // - An empty string "" bool isEmpty(string str) { return str.length() == 0; } // - One or more of the following characters: 'a' to 'z', ' ' (a space) or ':' (a colon) bool isLegalChars(string str) { for(string::iterator it = str.begin(); it != str.end(); ++it) { char ch = *it; if ((ch < 'a' || ch > 'z') && ch != ':' && ch != ' ') { return false; } } return true; } // - An open parenthesis '(', followed by a message with balanced parentheses, followed by a close parenthesis ')'. bool isContainingBalanced(string str) { char firstChar = str.at(0); char lastChar = str.at(str.length() - 1); if (firstChar == '(' && lastChar == ')') { string innerStr = str.substr(1, str.length() - 2); return isBalanced(innerStr); } else { return false; } } // - A message with balanced parentheses followed by another message with balanced parentheses. bool isDoubleBalanced(string str) { if ((str.find(')') == -1) && (str.find('(') == -1)) { // A "double" message will always have at least one paren. return false; } for (int separator = 1; separator < str.length(); ++separator) { string leftStr = str.substr(0, separator); string rightStr = str.substr(separator); if (isBalanced(leftStr) && isBalanced(rightStr)) { return true; } } return false; } // - A smiley face ":)" or a frowny face ":(" bool isEmoticon(string str) { if ((str.compare(":)") == 0) || (str.compare(":(") == 0)) { return true; } return false; } bool isBalanced(string str) { if (isEmpty(str)) { return true; } else if (isLegalChars(str)) { return true; } else if (isContainingBalanced(str)) { return true; } else if (isDoubleBalanced(str)) { return true; } else if (isEmoticon(str)) { return true; } return false; } int main(int argc, char** argv) { ifstream file; file.open(argv[1]); string line; while (getline(file, line)) { if (isBalanced(line)) { cout << "YES" << endl; } else { cout << "NO" << endl; } } }<commit_msg>Balanced Smileys. Hardest one yet.<commit_after>// https://www.codeeval.com/open_challenges/84/ #include <iostream> #include <fstream> using namespace std; bool isBalanced(string str, int parenDepth); bool isBalanced(string str, int parenDepth) { for (int chIndex = 0; chIndex < str.length(); ++chIndex) { char ch = str.at(chIndex); //cout << parenDepth << " " << ch << endl; if (ch == '(') { parenDepth++; } else if (ch == ')') { parenDepth--; } else if (ch == '[') { if (isBalanced(str.substr(chIndex + 1), parenDepth)) { // must be a smiley } else if (isBalanced(str.substr(chIndex + 1), parenDepth + 1)) { parenDepth++; } } else if (ch == ']') { if (isBalanced(str.substr(chIndex + 1), parenDepth)) { // must be a smiley } else if (isBalanced(str.substr(chIndex + 1), parenDepth - 1)) { parenDepth--; } } if (parenDepth == -1) { return false; } } return (parenDepth == 0); } // thanks http://stackoverflow.com/questions/5878775/how-to-find-and-replace-string string replaceAll(string subject, string search, string replace) { size_t pos = 0; while ((pos = subject.find(search, pos)) != string::npos) { subject.replace(pos, search.length(), replace); pos += replace.length(); } return subject; } int main(int argc, char** argv) { ifstream file; file.open(argv[1]); string line; while (getline(file, line)) { line = replaceAll(line, ":(", "["); line = replaceAll(line, ":)", "]"); if (isBalanced(line, 0)) { cout << "YES" << endl; } else { cout << "NO" << endl; } } }<|endoftext|>
<commit_before>#ifndef CLUSTERING_IMMEDIATE_CONSISTENCY_BRANCH_HASH_REGION_HPP_ #define CLUSTERING_IMMEDIATE_CONSISTENCY_BRANCH_HASH_REGION_HPP_ // TODO: Find a good location for this file. #include <stdint.h> #include <algorithm> #include <vector> #include "rpc/serialize_macros.hpp" #include "utils.hpp" // Returns a value in [0, HASH_REGION_HASH_SIZE). const uint64_t HASH_REGION_HASH_SIZE = 1ULL << 63; uint64_t hash_region_hasher(const uint8_t *s, size_t len); // Forms a region that shards an inner_region_t by a different // dimension: hash values, which are computed by the function // hash_region_hasher. Represents a rectangle, with one range of // coordinates represented by the inner region, the other range of // coordinates being a range of hash values. This doesn't really // change _much_ about our perspective of regions, but one thing in // particular is that every multistore should have a // get_multistore_joined_region return value with .beg == 0, .end == // HASH_REGION_HASH_SIZE. template <class inner_region_t> class hash_region_t { public: // Produces the empty region. hash_region_t() : beg(0), end(0), inner(inner_region_t::empty()) { } // For use with non-equal beg and end, non-empty inner. hash_region_t(uint64_t _beg, uint64_t _end, const inner_region_t &_inner) : beg(_beg), end(_end), inner(_inner) { guarantee(beg < end); guarantee(!region_is_empty(inner)); } // For use with a non-empty inner, I think. explicit hash_region_t(const inner_region_t &_inner) : beg(0), end(HASH_REGION_HASH_SIZE), inner(_inner) { guarantee(!region_is_empty(inner)); } static hash_region_t universe() { return hash_region_t(inner_region_t::universe()); } static hash_region_t empty() { return hash_region_t(); } // beg < end unless 0 == end and 0 == beg. uint64_t beg, end; inner_region_t inner; private: RDB_MAKE_ME_SERIALIZABLE_3(beg, end, inner); // This is a copyable type. }; template <class inner_region_t> bool region_is_empty(const hash_region_t<inner_region_t> &r) { return r.beg == r.end || region_is_empty(r.inner); } template <class inner_region_t> bool region_is_superset(const hash_region_t<inner_region_t> &potential_superset, const hash_region_t<inner_region_t> &potential_subset) { return region_is_empty(potential_subset) || (potential_superset.beg <= potential_subset.beg && potential_superset.end >= potential_subset.end && region_is_superset(potential_superset.inner, potential_subset.inner)); } template <class inner_region_t> hash_region_t<inner_region_t> region_intersection(const hash_region_t<inner_region_t> &r1, const hash_region_t<inner_region_t> &r2) { if (r1.end <= r2.beg || r2.end <= r1.beg) { return hash_region_t<inner_region_t>(); } inner_region_t inner_intersection = region_intersection(r1.inner, r2.inner); if (region_is_empty(inner_intersection)) { return hash_region_t<inner_region_t>(); } return hash_region_t<inner_region_t>(std::max(r1.beg, r2.beg), std::min(r1.end, r2.end), inner_intersection); } template <class inner_region_t> bool all_have_same_hash_interval(const std::vector< hash_region_t<inner_region_t> > &vec) { rassert(!vec.empty()); for (int i = 1, e = vec.size(); i < e; ++i) { if (vec[i].beg != vec[0].beg || vec[i].end != vec[0].end) { return false; } } return true; } template <class inner_region_t> bool all_have_same_inner(const std::vector< hash_region_t<inner_region_t> > &vec) { rassert(!vec.empty()); for (int i = 1, e = vec.size(); i < e; ++i) { if (vec[0].inner != vec[i].inner) { return false; } } return true; } template <class inner_region_t> MUST_USE region_join_result_t region_join(const std::vector< hash_region_t<inner_region_t> > &vec, hash_region_t<inner_region_t> *out) { // Our regions are generally limited to being rectangles. Here we // only support joins that join things row-wise or column-wise. // Either all the begs and ends are the same, or all the inners // are the same, of the regions in the vec. if (vec.empty()) { *out = hash_region_t<inner_region_t>(); return REGION_JOIN_OK; } if (all_have_same_hash_interval(vec)) { // Try joining the inner regions. std::vector<inner_region_t> inners; inners.reserve(vec.size()); for (int i = 0, e = vec.size(); i < e; ++i) { inners.push_back(vec[i].inner); } region_join_result_t res; inner_region_t inner; res = region_join(inners, &inner); if (res == REGION_JOIN_OK) { *out = hash_region_t<inner_region_t>(vec[0].beg, vec[0].end, inner); } return res; } if (all_have_same_inner(vec)) { std::vector< std::pair<uint64_t, uint64_t> > intervals; intervals.reserve(vec.size()); for (int i = 0, e = vec.size(); i < e; ++i) { intervals.push_back(std::pair<uint64_t, uint64_t>(vec[i].beg, vec[i].end)); } std::sort(intervals.begin(), intervals.end()); for (int i = 1, e = intervals.size(); i < e; ++i) { // TODO: Why the fuck is one a "bad region" and one a "bad // join"? if (intervals[i - 1].second < intervals[i].first) { return REGION_JOIN_BAD_REGION; } else if (intervals[i - 1].second > intervals[i].first) { return REGION_JOIN_BAD_JOIN; } } *out = hash_region_t<inner_region_t>(intervals.front().first, intervals.back().second, vec[0].inner); return REGION_JOIN_OK; } // TODO: Invent a new error code like REGION_JOIN_BAD_RECTANGLE. // I think it's always a sign of programmer error. rassert(false); return REGION_JOIN_BAD_REGION; // Or is it BAD_JOIN? BAD_RECTANGLE? } template <class inner_region_t> bool region_overlaps(const hash_region_t<inner_region_t> &r1, const hash_region_t<inner_region_t> &r2) { return r1.beg < r2.end && r2.beg < r1.end && region_overlaps(r1.inner, r2.inner); } template <class inner_region_t> std::vector< hash_region_t<key_range_t> > region_subtract_many(const hash_region_t<key_range_t> &minuend, const std::vector<hash_region_t<key_range_t>& subtrahends) { std::vector< hash_region_t<key_range_t> > buf; std::vector< hash_region_t<key_range_t> > temp_result_buf; buf.push_back(minuend); for (std::vector< hash_region_t<key_range_t> >::const_iterator s = subtrahends.begin(); s != subtrahends.end(); ++s) { for (std::vector< hash_region_t<key_range_t> >::const_iterator m = buf.begin(); m != buf.end(); ++m) { } } } template <class inner_region_t> bool operator==(const hash_region_t<inner_region_t> &r1, const hash_region_t<inner_region_t> &r2) { return r1.beg == r2.beg && r1.end == r2.end && r1.inner == r2.inner; } template <class inner_region_t> bool operator!=(const hash_region_t<inner_region_t> &r1, const hash_region_t<inner_region_t> &r2) { return !(r1 == r2); } // Used for making std::sets of hash_region_t. template <class inner_region_t> bool operator<(const hash_region_t<inner_region_t> &r1, const hash_region_t<inner_region_t> &r2) { return (r1.beg < r2.beg || (r1.beg == r2.beg && (r1.end < r2.end || (r1.end == r2.end && r1.inner < r2.inner)))); } #endif // CLUSTERING_IMMEDIATE_CONSISTENCY_BRANCH_HASH_REGION_HPP_ <commit_msg>Implemented region_subtract_many for hash_region_t. Many things still do not compile.<commit_after>#ifndef CLUSTERING_IMMEDIATE_CONSISTENCY_BRANCH_HASH_REGION_HPP_ #define CLUSTERING_IMMEDIATE_CONSISTENCY_BRANCH_HASH_REGION_HPP_ // TODO: Find a good location for this file. #include <stdint.h> #include <algorithm> #include <vector> #include "rpc/serialize_macros.hpp" #include "utils.hpp" // Returns a value in [0, HASH_REGION_HASH_SIZE). const uint64_t HASH_REGION_HASH_SIZE = 1ULL << 63; uint64_t hash_region_hasher(const uint8_t *s, size_t len); // Forms a region that shards an inner_region_t by a different // dimension: hash values, which are computed by the function // hash_region_hasher. Represents a rectangle, with one range of // coordinates represented by the inner region, the other range of // coordinates being a range of hash values. This doesn't really // change _much_ about our perspective of regions, but one thing in // particular is that every multistore should have a // get_multistore_joined_region return value with .beg == 0, .end == // HASH_REGION_HASH_SIZE. template <class inner_region_t> class hash_region_t { public: // Produces the empty region. hash_region_t() : beg(0), end(0), inner(inner_region_t::empty()) { } // For use with non-equal beg and end, non-empty inner. hash_region_t(uint64_t _beg, uint64_t _end, const inner_region_t &_inner) : beg(_beg), end(_end), inner(_inner) { guarantee(beg < end); guarantee(!region_is_empty(inner)); } // For use with a non-empty inner, I think. explicit hash_region_t(const inner_region_t &_inner) : beg(0), end(HASH_REGION_HASH_SIZE), inner(_inner) { guarantee(!region_is_empty(inner)); } static hash_region_t universe() { return hash_region_t(inner_region_t::universe()); } static hash_region_t empty() { return hash_region_t(); } // beg < end unless 0 == end and 0 == beg. uint64_t beg, end; inner_region_t inner; private: RDB_MAKE_ME_SERIALIZABLE_3(beg, end, inner); // This is a copyable type. }; template <class inner_region_t> bool region_is_empty(const hash_region_t<inner_region_t> &r) { return r.beg == r.end || region_is_empty(r.inner); } template <class inner_region_t> bool region_is_superset(const hash_region_t<inner_region_t> &potential_superset, const hash_region_t<inner_region_t> &potential_subset) { return region_is_empty(potential_subset) || (potential_superset.beg <= potential_subset.beg && potential_superset.end >= potential_subset.end && region_is_superset(potential_superset.inner, potential_subset.inner)); } template <class inner_region_t> hash_region_t<inner_region_t> region_intersection(const hash_region_t<inner_region_t> &r1, const hash_region_t<inner_region_t> &r2) { if (r1.end <= r2.beg || r2.end <= r1.beg) { return hash_region_t<inner_region_t>(); } inner_region_t inner_intersection = region_intersection(r1.inner, r2.inner); if (region_is_empty(inner_intersection)) { return hash_region_t<inner_region_t>(); } return hash_region_t<inner_region_t>(std::max(r1.beg, r2.beg), std::min(r1.end, r2.end), inner_intersection); } template <class inner_region_t> bool all_have_same_hash_interval(const std::vector< hash_region_t<inner_region_t> > &vec) { rassert(!vec.empty()); for (int i = 1, e = vec.size(); i < e; ++i) { if (vec[i].beg != vec[0].beg || vec[i].end != vec[0].end) { return false; } } return true; } template <class inner_region_t> bool all_have_same_inner(const std::vector< hash_region_t<inner_region_t> > &vec) { rassert(!vec.empty()); for (int i = 1, e = vec.size(); i < e; ++i) { if (vec[0].inner != vec[i].inner) { return false; } } return true; } template <class inner_region_t> MUST_USE region_join_result_t region_join(const std::vector< hash_region_t<inner_region_t> > &vec, hash_region_t<inner_region_t> *out) { // Our regions are generally limited to being rectangles. Here we // only support joins that join things row-wise or column-wise. // Either all the begs and ends are the same, or all the inners // are the same, of the regions in the vec. if (vec.empty()) { *out = hash_region_t<inner_region_t>(); return REGION_JOIN_OK; } if (all_have_same_hash_interval(vec)) { // Try joining the inner regions. std::vector<inner_region_t> inners; inners.reserve(vec.size()); for (int i = 0, e = vec.size(); i < e; ++i) { inners.push_back(vec[i].inner); } region_join_result_t res; inner_region_t inner; res = region_join(inners, &inner); if (res == REGION_JOIN_OK) { *out = hash_region_t<inner_region_t>(vec[0].beg, vec[0].end, inner); } return res; } if (all_have_same_inner(vec)) { std::vector< std::pair<uint64_t, uint64_t> > intervals; intervals.reserve(vec.size()); for (int i = 0, e = vec.size(); i < e; ++i) { intervals.push_back(std::pair<uint64_t, uint64_t>(vec[i].beg, vec[i].end)); } std::sort(intervals.begin(), intervals.end()); for (int i = 1, e = intervals.size(); i < e; ++i) { // TODO: Why the fuck is one a "bad region" and one a "bad // join"? if (intervals[i - 1].second < intervals[i].first) { return REGION_JOIN_BAD_REGION; } else if (intervals[i - 1].second > intervals[i].first) { return REGION_JOIN_BAD_JOIN; } } *out = hash_region_t<inner_region_t>(intervals.front().first, intervals.back().second, vec[0].inner); return REGION_JOIN_OK; } // TODO: Invent a new error code like REGION_JOIN_BAD_RECTANGLE. // I think it's always a sign of programmer error. rassert(false); return REGION_JOIN_BAD_REGION; // Or is it BAD_JOIN? BAD_RECTANGLE? } template <class inner_region_t> bool region_overlaps(const hash_region_t<inner_region_t> &r1, const hash_region_t<inner_region_t> &r2) { return r1.beg < r2.end && r2.beg < r1.end && region_overlaps(r1.inner, r2.inner); } template <class inner_region_t> std::vector< hash_region_t<inner_region_t> > region_subtract_many(const hash_region_t<inner_region_t> &minuend, const std::vector< hash_region_t<inner_region_t> >& subtrahends) { std::vector< hash_region_t<inner_region_t> > buf; std::vector< hash_region_t<inner_region_t> > temp_result_buf; buf.push_back(minuend); for (typename std::vector< hash_region_t<inner_region_t> >::const_iterator s = subtrahends.begin(); s != subtrahends.end(); ++s) { for (typename std::vector< hash_region_t<inner_region_t> >::const_iterator m = buf.begin(); m != buf.end(); ++m) { // Subtract s from m, push back onto temp_result_buf. // (See the "subtraction drawing" after this function.) // We first subtract m.inner - s.inner, combining the // difference with m's hash interval to create a set of // regions w. Then m.inner is intersected with s.inner, // and the hash range is formed from subtracting s's hash // range from m's, possibly creating x and/or z. const std::vector<inner_region_t> s_vec(1, s->inner); const std::vector<inner_region_t> w_inner = region_subtract_many(m->inner, s_vec); for (typename std::vector<inner_region_t>::const_iterator it = w_inner.begin(); it != w_inner.end(); ++it) { temp_result_buf.push_back(hash_region_t<inner_region_t>(m->beg, m->end, *it)); } // This outer conditional check is unnecessary, but it // might improve performance because we avoid trying an // unnecessary region intersection. if (m->beg < s->beg || s->end < m->end) { inner_region_t isect = region_intersection(m->inner, s->inner); if (!region_is_empty(isect)) { // Add x, if it exists. if (m->beg < s->beg) { temp_result_buf.push_back(hash_region_t<inner_region_t>(m->beg, std::min(s->beg, m->end), isect)); } // Add z, if it exists. if (s->end < m->end) { temp_result_buf.push_back(hash_region_t<inner_region_t>(std::max(m->beg, s->end), m->end, isect)); } } } } buf.swap(temp_result_buf); temp_result_buf.clear(); } return buf; } // The "subtraction drawing": /* _____________________ | . z . | | .______. | |w_j| s | w_k | | |______| | | . . | | . x . | ^ |___.______.__________| | | hash values inner_region_t --> */ template <class inner_region_t> bool operator==(const hash_region_t<inner_region_t> &r1, const hash_region_t<inner_region_t> &r2) { return r1.beg == r2.beg && r1.end == r2.end && r1.inner == r2.inner; } template <class inner_region_t> bool operator!=(const hash_region_t<inner_region_t> &r1, const hash_region_t<inner_region_t> &r2) { return !(r1 == r2); } // Used for making std::sets of hash_region_t. template <class inner_region_t> bool operator<(const hash_region_t<inner_region_t> &r1, const hash_region_t<inner_region_t> &r2) { return (r1.beg < r2.beg || (r1.beg == r2.beg && (r1.end < r2.end || (r1.end == r2.end && r1.inner < r2.inner)))); } #endif // CLUSTERING_IMMEDIATE_CONSISTENCY_BRANCH_HASH_REGION_HPP_ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: prs_cpp.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-11-02 17:03:30 $ * * 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 ADC_CPP_PRS_CPP_HXX #define ADC_CPP_PRS_CPP_HXX // USED SERVICES // BASE CLASSES #include <autodoc/prs_code.hxx> // COMPONENTS // PARAMETERS namespace cpp { struct S_RunningData; class Cpluplus_Parser : public autodoc::CodeParser_Ifc { public: Cpluplus_Parser(); virtual ~Cpluplus_Parser(); virtual void Setup( ary::Repository & o_rRepository, const autodoc::DocumentationParser_Ifc & i_rDocumentationInterpreter ); virtual void Run( const autodoc::FileCollector_Ifc & i_rFiles ); private: Dyn<S_RunningData> pRunningData; }; } // namespace cpp #endif <commit_msg>INTEGRATION: CWS changefileheader (1.5.22); FILE MERGED 2008/03/28 16:02:32 rt 1.5.22.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: prs_cpp.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 ADC_CPP_PRS_CPP_HXX #define ADC_CPP_PRS_CPP_HXX // USED SERVICES // BASE CLASSES #include <autodoc/prs_code.hxx> // COMPONENTS // PARAMETERS namespace cpp { struct S_RunningData; class Cpluplus_Parser : public autodoc::CodeParser_Ifc { public: Cpluplus_Parser(); virtual ~Cpluplus_Parser(); virtual void Setup( ary::Repository & o_rRepository, const autodoc::DocumentationParser_Ifc & i_rDocumentationInterpreter ); virtual void Run( const autodoc::FileCollector_Ifc & i_rFiles ); private: Dyn<S_RunningData> pRunningData; }; } // namespace cpp #endif <|endoftext|>
<commit_before> #include "ksp_plugin/part.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace principia { using si::Kilogram; using si::Metre; using si::Second; namespace ksp_plugin { class PartTest : public testing::Test { protected: PartTest() : degrees_of_freedom_({ Barycentric::origin + Displacement<Barycentric>({1 * Metre, 2 * Metre, 3 * Metre}), Velocity<Barycentric>({4 * Metre / Second, 5 * Metre / Second, 6 * Metre / Second})}), mass_(7 * Kilogram), gravitational_acceleration_to_be_applied_by_ksp_( Vector<Acceleration, Barycentric>( {8 * Metre / Second / Second, 9 * Metre / Second / Second, 10 * Metre / Second / Second})), part_(degrees_of_freedom_, mass_, gravitational_acceleration_to_be_applied_by_ksp_) {} DegreesOfFreedom<Barycentric> degrees_of_freedom_; Mass mass_; Vector<Acceleration, Barycentric> gravitational_acceleration_to_be_applied_by_ksp_; Part<Barycentric> part_; }; TEST_F(PartTest, Serialization) { serialization::Part message; part_.WriteToMessage(&message); EXPECT_TRUE(message.has_degrees_of_freedom()); EXPECT_TRUE(message.degrees_of_freedom().t1().has_point()); EXPECT_TRUE(message.degrees_of_freedom().t1().point().has_multivector()); EXPECT_TRUE(message.degrees_of_freedom().t1(). point().multivector().has_vector()); EXPECT_EQ(1, message.degrees_of_freedom().t1(). point().multivector().vector().x().quantity().magnitude()); EXPECT_EQ(2, message.degrees_of_freedom().t1(). point().multivector().vector().y().quantity().magnitude()); EXPECT_EQ(3, message.degrees_of_freedom().t1(). point().multivector().vector().z().quantity().magnitude()); EXPECT_TRUE(message.degrees_of_freedom().t2().has_multivector()); EXPECT_TRUE(message.degrees_of_freedom().t2().multivector().has_vector()); EXPECT_EQ(4, message.degrees_of_freedom().t2(). multivector().vector().x().quantity().magnitude()); EXPECT_EQ(5, message.degrees_of_freedom().t2(). multivector().vector().y().quantity().magnitude()); EXPECT_EQ(6, message.degrees_of_freedom().t2(). multivector().vector().z().quantity().magnitude()); EXPECT_TRUE(message.has_mass()); EXPECT_EQ(7, message.mass().magnitude()); EXPECT_TRUE(message.has_gravitational_acceleration_to_be_applied_by_ksp()); EXPECT_TRUE(message.gravitational_acceleration_to_be_applied_by_ksp(). has_vector()); EXPECT_EQ(8, message.gravitational_acceleration_to_be_applied_by_ksp(). vector().x().quantity().magnitude()); EXPECT_EQ(9, message.gravitational_acceleration_to_be_applied_by_ksp(). vector().y().quantity().magnitude()); EXPECT_EQ(10, message.gravitational_acceleration_to_be_applied_by_ksp(). vector().z().quantity().magnitude()); Part<Barycentric> p = Part<Barycentric>::ReadFromMessage(message); EXPECT_EQ(part_.degrees_of_freedom(), p.degrees_of_freedom()); EXPECT_EQ(part_.mass(), p.mass()); EXPECT_EQ(part_.gravitational_acceleration_to_be_applied_by_ksp(), p.gravitational_acceleration_to_be_applied_by_ksp()); } } // namespace ksp_plugin } // namespace principia <commit_msg>maybe fix what is hopefully @Norgg's last compile error<commit_after> #include "ksp_plugin/part.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace principia { using si::Kilogram; using si::Metre; using si::Second; namespace ksp_plugin { class PartTest : public testing::Test { protected: PartTest() : part_(degrees_of_freedom_, mass_, gravitational_acceleration_to_be_applied_by_ksp_) {} DegreesOfFreedom<Barycentric> const degrees_of_freedom_ = { Barycentric::origin + Displacement<Barycentric>({1 * Metre, 2 * Metre, 3 * Metre}), Velocity<Barycentric>({4 * Metre / Second, 5 * Metre / Second, 6 * Metre / Second})}; Mass const mass_ = 7 * Kilogram; Vector<Acceleration, Barycentric> const gravitational_acceleration_to_be_applied_by_ksp_ = Vector<Acceleration, Barycentric>({8 * Metre / Second / Second, 9 * Metre / Second / Second, 10 * Metre / Second / Second}); Part<Barycentric> const part_; }; TEST_F(PartTest, Serialization) { serialization::Part message; part_.WriteToMessage(&message); EXPECT_TRUE(message.has_degrees_of_freedom()); EXPECT_TRUE(message.degrees_of_freedom().t1().has_point()); EXPECT_TRUE(message.degrees_of_freedom().t1().point().has_multivector()); EXPECT_TRUE(message.degrees_of_freedom().t1(). point().multivector().has_vector()); EXPECT_EQ(1, message.degrees_of_freedom().t1(). point().multivector().vector().x().quantity().magnitude()); EXPECT_EQ(2, message.degrees_of_freedom().t1(). point().multivector().vector().y().quantity().magnitude()); EXPECT_EQ(3, message.degrees_of_freedom().t1(). point().multivector().vector().z().quantity().magnitude()); EXPECT_TRUE(message.degrees_of_freedom().t2().has_multivector()); EXPECT_TRUE(message.degrees_of_freedom().t2().multivector().has_vector()); EXPECT_EQ(4, message.degrees_of_freedom().t2(). multivector().vector().x().quantity().magnitude()); EXPECT_EQ(5, message.degrees_of_freedom().t2(). multivector().vector().y().quantity().magnitude()); EXPECT_EQ(6, message.degrees_of_freedom().t2(). multivector().vector().z().quantity().magnitude()); EXPECT_TRUE(message.has_mass()); EXPECT_EQ(7, message.mass().magnitude()); EXPECT_TRUE(message.has_gravitational_acceleration_to_be_applied_by_ksp()); EXPECT_TRUE(message.gravitational_acceleration_to_be_applied_by_ksp(). has_vector()); EXPECT_EQ(8, message.gravitational_acceleration_to_be_applied_by_ksp(). vector().x().quantity().magnitude()); EXPECT_EQ(9, message.gravitational_acceleration_to_be_applied_by_ksp(). vector().y().quantity().magnitude()); EXPECT_EQ(10, message.gravitational_acceleration_to_be_applied_by_ksp(). vector().z().quantity().magnitude()); Part<Barycentric> p = Part<Barycentric>::ReadFromMessage(message); EXPECT_EQ(part_.degrees_of_freedom(), p.degrees_of_freedom()); EXPECT_EQ(part_.mass(), p.mass()); EXPECT_EQ(part_.gravitational_acceleration_to_be_applied_by_ksp(), p.gravitational_acceleration_to_be_applied_by_ksp()); } } // namespace ksp_plugin } // namespace principia <|endoftext|>
<commit_before>/** * @file CommonLanguageAnalyzer.cpp * @author Kent, Vernkin * @date Nov 23, 2009 * @details * Common Language Analyzer for Chinese/Japanese/Korean. */ /** * @brief Rewrite CLA using new interfaces. * @author Wei */ ////#define SF1_TIME_CHECK //#include <util/profiler/ProfilerGroup.h> // #include <la/analyzer/CommonLanguageAnalyzer.h> #include <la/util/UStringUtil.h> #include <la/common/Term.h> //#include <la/dict/UpdateDictThread.h> // //using namespace izenelib::util; //using namespace izenelib::ir::idmanager; //using namespace std; // namespace la { CommonLanguageAnalyzer::CommonLanguageAnalyzer() : Analyzer(), pSynonymContainer_( NULL ), pSynonymResult_( NULL ), pStemmer_( NULL ), bCaseSensitive_(false), bContainLower_(false), bExtractEngStem_(false), bExtractSynonym_(false), bChinese_(false) { pStemmer_ = new stem::Stemmer(); pStemmer_->init(stem::STEM_LANG_ENGLISH); lowercase_string_buffer_ = new char[term_string_buffer_limit_]; lowercase_ustring_buffer_ = new UString::CharT[term_ustring_buffer_limit_]; synonym_ustring_buffer_ = new UString::CharT[term_ustring_buffer_limit_]; stemming_ustring_buffer_ = new UString::CharT[term_ustring_buffer_limit_]; } CommonLanguageAnalyzer::CommonLanguageAnalyzer( const std::string & synonymDictPath, UString::EncodingType synonymEncode) : Analyzer(), pSynonymContainer_( NULL ), pSynonymResult_( NULL ), synonymEncode_( synonymEncode ), pStemmer_( NULL ), bCaseSensitive_(false), bContainLower_(false), bExtractEngStem_(false), bExtractSynonym_(false), bChinese_(false), bRemoveStopwords_(false) { pSynonymContainer_ = izenelib::am::VSynonymContainer::createObject(); pSynonymContainer_->setSynonymDelimiter(","); pSynonymContainer_->setWordDelimiter("_"); if( pSynonymContainer_->loadSynonym( synonymDictPath.c_str() ) != 1 ) { string msg = "Failed to load synonym dictionary from path: "; msg += synonymDictPath; throw std::logic_error( msg ); } uscSPtr_.reset( new UpdatableSynonymContainer( pSynonymContainer_, synonymDictPath ) ); UpdateDictThread::staticUDT.addRelatedDict( synonymDictPath.c_str(), uscSPtr_ ); pSynonymResult_ = izenelib::am::VSynonym::createObject(); pStemmer_ = new stem::Stemmer(); pStemmer_->init(stem::STEM_LANG_ENGLISH); lowercase_string_buffer_ = new char[term_string_buffer_limit_]; lowercase_ustring_buffer_ = new UString::CharT[term_ustring_buffer_limit_]; synonym_ustring_buffer_ = new UString::CharT[term_ustring_buffer_limit_]; stemming_ustring_buffer_ = new UString::CharT[term_ustring_buffer_limit_]; } void CommonLanguageAnalyzer::setSynonymUpdateInterval(unsigned int seconds) { UpdateDictThread::staticUDT.setCheckInterval(seconds); if( !UpdateDictThread::staticUDT.isStarted() ) UpdateDictThread::staticUDT.start(); } CommonLanguageAnalyzer::~CommonLanguageAnalyzer() { delete pSynonymContainer_; delete pSynonymResult_; delete pStemmer_; delete lowercase_string_buffer_; delete lowercase_ustring_buffer_; delete synonym_ustring_buffer_; delete stemming_ustring_buffer_; } void CommonLanguageAnalyzer::analyzeSynonym(TermList& outList, size_t n) { static UString SPACE(" ", izenelib::util::UString::UTF_8); TermList syOutList; size_t wordCount = outList.size(); for(size_t i = 0; i < wordCount; i++) { // cout << "[off]" <<outList[i].wordOffset_<<" [level]"<<outList[i].getLevel() <<" [andor]" <<(unsigned int)(outList[i].getAndOrBit()) // << " "<< outList[i].textString()<<endl; // find synonym for word(s) for (size_t len = 1; (len <= n) && (i+len <= wordCount) ; len++) { // with space bool ret = false; unsigned int subLevel = 0; UString combine; if (len > 1) { for (size_t j = 0; j < len-1; j++) { combine.append(outList[i+j].text_); combine.append(SPACE); } combine.append(outList[i+len-1].text_); ret = getSynonym(combine, outList[i].wordOffset_, Term::OR, outList[i].getLevel(), syOutList, subLevel); } // without space if (!ret) { combine.clear(); for (size_t j = 0; j < len; j++) combine.append(outList[i+j].text_); ret = getSynonym(combine, outList[i].wordOffset_, Term::OR, outList[i].getLevel(), syOutList, subLevel); } // adjust if (ret) { outList[i].setStats(outList[i].getAndOrBit(), outList[i].getLevel()+subLevel); for (size_t j = 1; j < len; j++) { outList[i+j].wordOffset_ = outList[i].wordOffset_; outList[i+j].setStats(outList[i+j].getAndOrBit(), outList[i].getLevel()); } break; } } syOutList.push_back(outList[i]); } outList.swap(syOutList); } bool CommonLanguageAnalyzer::getSynonym( const UString& combine, int offset, const unsigned char andOrBit, const unsigned int level, TermList& syOutList, unsigned int& subLevel) { bool ret = false; //cout << "combined: "; combine.displayStringValue( izenelib::util::UString::UTF_8 ); cout << endl; char* combineStr = lowercase_string_buffer_; UString::convertString(UString::UTF_8, combine.c_str(), combine.length(), lowercase_string_buffer_, term_string_buffer_limit_); //cout << "combined string: " << string(combineStr) << endl; UString::CharT * synonymResultUstr = NULL; size_t synonymResultUstrLen = 0; pSynonymContainer_ = uscSPtr_->getSynonymContainer(); pSynonymContainer_->searchNgetSynonym( combineStr, pSynonymResult_ ); for (int i =0; i<pSynonymResult_->getSynonymCount(0); i++) { char * synonymResult = pSynonymResult_->getWord(0, i); if( synonymResult ) { if (strcmp(combineStr, synonymResult) == 0) { //cout << "synonym self: "<<string(synonymResult) <<endl; continue; } cout << "synonym : "<<string(synonymResult) <<endl; ret = true; size_t synonymResultLen = strlen(synonymResult); if(synonymResultLen <= term_ustring_buffer_limit_) { synonymResultUstr = synonym_ustring_buffer_; synonymResultUstrLen = UString::toUcs2(synonymEncode_, synonymResult, synonymResultLen, synonym_ustring_buffer_, term_ustring_buffer_limit_); } // word segmentment UString term(synonymResultUstr, synonymResultUstrLen); TermList termList; if (innerAnalyzer_.get()) { innerAnalyzer_->analyze(term, termList); if (termList.size() <= 1) { syOutList.add(synonymResultUstr, synonymResultUstrLen, offset, NULL, andOrBit, level+subLevel); subLevel++; } else { for(TermList::iterator iter = termList.begin(); iter != termList.end(); ++iter) { syOutList.add(iter->text_.c_str(), iter->text_.length(), offset, NULL, Term::AND, level+subLevel); } subLevel++; } } else { syOutList.add(synonymResultUstr, synonymResultUstrLen, offset, NULL, andOrBit, level+subLevel); subLevel++; } } } return ret; } int CommonLanguageAnalyzer::analyze_impl( const Term& input, void* data, HookType func ) { parse(input.text_); unsigned char topAndOrBit = Term::AND; int lastWordOffset = -1; while( nextToken() ) { if( len() == 0 ) continue; if( bRemoveStopwords_ && isStopword() ) continue; /* { UString foo(token(), len()); string bar; foo.convertString(bar, UString::UTF_8); cout << "(" << bar << ") --<> " << isIndex() << "," << offset() << "," << isRaw() << "," << level() << endl; }*/ if( bChinese_ == true ) { int curWordOffset = offset(); if( lastWordOffset == lastWordOffset ) topAndOrBit = Term::OR; else topAndOrBit = Term::AND; lastWordOffset = curWordOffset; } if( isIndex() ) { if(isSpecialChar()) { func( data, token(), len(), offset(), Term::SpecialCharPOS, Term::AND, level(), true); continue; } if(isRaw()) { func( data, token(), len(), offset(), pos(), Term::OR, level(), false); continue; } // foreign language, e.g. English if( isAlpha() ) { UString::CharT* lowercaseTermUstr = lowercase_ustring_buffer_; bool lowercaseIsDifferent = UString::toLowerString(token(), len(), lowercase_ustring_buffer_, term_ustring_buffer_limit_); char* lowercaseTerm = lowercase_string_buffer_; UString::convertString(UString::UTF_8, lowercaseTermUstr, len(), lowercase_string_buffer_, term_string_buffer_limit_); UString::CharT* stemmingTermUstr = NULL; size_t stemmingTermUstrSize = 0; UString::CharT * synonymResultUstr = NULL; size_t synonymResultUstrLen = 0; if(bExtractEngStem_) { /// TODO: write a UCS2 based stemmer string stem_term; pStemmer_->stem( lowercaseTerm, stem_term ); if( strcmp(stem_term.c_str(), lowercaseTerm) != 0 ) { stemmingTermUstr = stemming_ustring_buffer_; stemmingTermUstrSize = UString::toUcs2(UString::UTF_8, stem_term.c_str(), stem_term.size(), stemming_ustring_buffer_, term_ustring_buffer_limit_); } } if(bExtractSynonym_) { pSynonymContainer_ = uscSPtr_->getSynonymContainer(); pSynonymContainer_->searchNgetSynonym( lowercaseTerm, pSynonymResult_ ); char * synonymResult = pSynonymResult_->getHeadWord(0); if( synonymResult ) { size_t synonymResultLen = strlen(synonymResult); if(synonymResultLen <= term_ustring_buffer_limit_) { synonymResultUstr = synonym_ustring_buffer_; synonymResultUstrLen = UString::toUcs2(synonymEncode_, synonymResult, synonymResultLen, synonym_ustring_buffer_, term_ustring_buffer_limit_); } } } if( stemmingTermUstr || synonymResultUstr || (bCaseSensitive_ && bContainLower_ && lowercaseIsDifferent) ) { /// have more than one output if(bCaseSensitive_) { func( data, token(), len(), offset(), Term::EnglishPOS, Term::OR, level()+1, false); } else { func( data, lowercaseTermUstr, len(), offset(), Term::EnglishPOS, Term::OR, level()+1, false); } if(stemmingTermUstr) { func( data, stemmingTermUstr, stemmingTermUstrSize, offset(), Term::EnglishPOS, Term::OR, level()+1, false); } if(synonymResultUstr) { func( data, synonymResultUstr, synonymResultUstrLen, offset(), NULL, Term::OR, level()+1, false); } if(bCaseSensitive_ && bContainLower_ && lowercaseIsDifferent) { func( data, lowercaseTermUstr, len(), offset(), Term::EnglishPOS, Term::OR, level()+1, false); } } else { /// have only one output if(bCaseSensitive_) { func( data, token(), len(), offset(), Term::EnglishPOS, Term::AND, level(), false); } else { func( data, lowercaseTermUstr, len(), offset(), Term::EnglishPOS, Term::AND, level(), false); } } } else { if(bExtractSynonym_) { UString::CharT * synonymResultUstr = NULL; size_t synonymResultUstrLen = 0; pSynonymContainer_ = uscSPtr_->getSynonymContainer(); pSynonymContainer_->searchNgetSynonym( nativeToken(), pSynonymResult_ ); bool hasSynonym = false; for (int i =0; i<pSynonymResult_->getSynonymCount(0); i++) { char * synonymResult = pSynonymResult_->getWord(0, i); if( synonymResult ) { if (strcmp(nativeToken(), synonymResult) == 0) { cout << "synonym self: "<<string(synonymResult) <<endl; continue; } cout << "synonym : "<<string(synonymResult) <<endl; size_t synonymResultLen = strlen(synonymResult); if(synonymResultLen <= term_ustring_buffer_limit_) { synonymResultUstr = synonym_ustring_buffer_; synonymResultUstrLen = UString::toUcs2(synonymEncode_, synonymResult, synonymResultLen, synonym_ustring_buffer_, term_ustring_buffer_limit_); } hasSynonym = true; func( data, synonymResultUstr, synonymResultUstrLen, offset(), NULL, Term::OR, level()+1, false); } } if (hasSynonym) { func( data, token(), len(), offset(), pos(), Term::OR, level()+1, false); } else { func( data, token(), len(), offset(), pos(), topAndOrBit, level(), false); } } else { func( data, token(), len(), offset(), pos(), topAndOrBit, level(), false); } } } } return offset(); } } <commit_msg>fix conflict<commit_after>/** * @file CommonLanguageAnalyzer.cpp * @author Kent, Vernkin * @date Nov 23, 2009 * @details * Common Language Analyzer for Chinese/Japanese/Korean. */ /** * @brief Rewrite CLA using new interfaces. * @author Wei */ ////#define SF1_TIME_CHECK //#include <util/profiler/ProfilerGroup.h> // #include <la/analyzer/CommonLanguageAnalyzer.h> #include <la/util/UStringUtil.h> #include <la/common/Term.h> //#include <la/dict/UpdateDictThread.h> // //using namespace izenelib::util; //using namespace izenelib::ir::idmanager; //using namespace std; // namespace la { CommonLanguageAnalyzer::CommonLanguageAnalyzer() : Analyzer(), pSynonymContainer_( NULL ), pSynonymResult_( NULL ), pStemmer_( NULL ), bCaseSensitive_(false), bContainLower_(false), bExtractEngStem_(false), bExtractSynonym_(false), bChinese_(false) { pStemmer_ = new stem::Stemmer(); pStemmer_->init(stem::STEM_LANG_ENGLISH); lowercase_string_buffer_ = new char[term_string_buffer_limit_]; lowercase_ustring_buffer_ = new UString::CharT[term_ustring_buffer_limit_]; synonym_ustring_buffer_ = new UString::CharT[term_ustring_buffer_limit_]; stemming_ustring_buffer_ = new UString::CharT[term_ustring_buffer_limit_]; } CommonLanguageAnalyzer::CommonLanguageAnalyzer( const std::string & synonymDictPath, UString::EncodingType synonymEncode) : Analyzer(), pSynonymContainer_( NULL ), pSynonymResult_( NULL ), synonymEncode_( synonymEncode ), pStemmer_( NULL ), bCaseSensitive_(false), bContainLower_(false), bExtractEngStem_(false), bExtractSynonym_(false), bChinese_(false), bRemoveStopwords_(false) { pSynonymContainer_ = izenelib::am::VSynonymContainer::createObject(); pSynonymContainer_->setSynonymDelimiter(","); pSynonymContainer_->setWordDelimiter("_"); if( pSynonymContainer_->loadSynonym( synonymDictPath.c_str() ) != 1 ) { string msg = "Failed to load synonym dictionary from path: "; msg += synonymDictPath; throw std::logic_error( msg ); } uscSPtr_.reset( new UpdatableSynonymContainer( pSynonymContainer_, synonymDictPath ) ); UpdateDictThread::staticUDT.addRelatedDict( synonymDictPath.c_str(), uscSPtr_ ); pSynonymResult_ = izenelib::am::VSynonym::createObject(); pStemmer_ = new stem::Stemmer(); pStemmer_->init(stem::STEM_LANG_ENGLISH); lowercase_string_buffer_ = new char[term_string_buffer_limit_]; lowercase_ustring_buffer_ = new UString::CharT[term_ustring_buffer_limit_]; synonym_ustring_buffer_ = new UString::CharT[term_ustring_buffer_limit_]; stemming_ustring_buffer_ = new UString::CharT[term_ustring_buffer_limit_]; } void CommonLanguageAnalyzer::setSynonymUpdateInterval(unsigned int seconds) { UpdateDictThread::staticUDT.setCheckInterval(seconds); if( !UpdateDictThread::staticUDT.isStarted() ) UpdateDictThread::staticUDT.start(); } CommonLanguageAnalyzer::~CommonLanguageAnalyzer() { delete pSynonymContainer_; delete pSynonymResult_; delete pStemmer_; delete lowercase_string_buffer_; delete lowercase_ustring_buffer_; delete synonym_ustring_buffer_; delete stemming_ustring_buffer_; } void CommonLanguageAnalyzer::analyzeSynonym(TermList& outList, size_t n) { static UString SPACE(" ", izenelib::util::UString::UTF_8); TermList syOutList; size_t wordCount = outList.size(); for(size_t i = 0; i < wordCount; i++) { // cout << "[off]" <<outList[i].wordOffset_<<" [level]"<<outList[i].getLevel() <<" [andor]" <<(unsigned int)(outList[i].getAndOrBit()) // << " "<< outList[i].textString()<<endl; // find synonym for word(s) for (size_t len = 1; (len <= n) && (i+len <= wordCount) ; len++) { // with space bool ret = false; unsigned int subLevel = 0; UString combine; if (len > 1) { for (size_t j = 0; j < len-1; j++) { combine.append(outList[i+j].text_); combine.append(SPACE); } combine.append(outList[i+len-1].text_); ret = getSynonym(combine, outList[i].wordOffset_, Term::OR, outList[i].getLevel(), syOutList, subLevel); } // without space if (!ret) { combine.clear(); for (size_t j = 0; j < len; j++) combine.append(outList[i+j].text_); ret = getSynonym(combine, outList[i].wordOffset_, Term::OR, outList[i].getLevel(), syOutList, subLevel); } // adjust if (ret) { outList[i].setStats(outList[i].getAndOrBit(), outList[i].getLevel()+subLevel); for (size_t j = 1; j < len; j++) { outList[i+j].wordOffset_ = outList[i].wordOffset_; outList[i+j].setStats(outList[i+j].getAndOrBit(), outList[i].getLevel()); } break; } } syOutList.push_back(outList[i]); } outList.swap(syOutList); } bool CommonLanguageAnalyzer::getSynonym( const UString& combine, int offset, const unsigned char andOrBit, const unsigned int level, TermList& syOutList, unsigned int& subLevel) { bool ret = false; //cout << "combined: "; combine.displayStringValue( izenelib::util::UString::UTF_8 ); cout << endl; char* combineStr = lowercase_string_buffer_; UString::convertString(UString::UTF_8, combine.c_str(), combine.length(), lowercase_string_buffer_, term_string_buffer_limit_); //cout << "combined string: " << string(combineStr) << endl; UString::CharT * synonymResultUstr = NULL; size_t synonymResultUstrLen = 0; pSynonymContainer_ = uscSPtr_->getSynonymContainer(); pSynonymContainer_->searchNgetSynonym( combineStr, pSynonymResult_ ); for (int i =0; i<pSynonymResult_->getSynonymCount(0); i++) { char * synonymResult = pSynonymResult_->getWord(0, i); if( synonymResult ) { if (strcmp(combineStr, synonymResult) == 0) { //cout << "synonym self: "<<string(synonymResult) <<endl; continue; } cout << "synonym : "<<string(synonymResult) <<endl; ret = true; size_t synonymResultLen = strlen(synonymResult); if(synonymResultLen <= term_ustring_buffer_limit_) { synonymResultUstr = synonym_ustring_buffer_; synonymResultUstrLen = UString::toUcs2(synonymEncode_, synonymResult, synonymResultLen, synonym_ustring_buffer_, term_ustring_buffer_limit_); } // word segmentment UString term(synonymResultUstr, synonymResultUstrLen); TermList termList; if (innerAnalyzer_.get()) { innerAnalyzer_->analyze(term, termList); if (termList.size() <= 1) { syOutList.add(synonymResultUstr, synonymResultUstrLen, offset, NULL, andOrBit, level+subLevel); subLevel++; } else { for(TermList::iterator iter = termList.begin(); iter != termList.end(); ++iter) { syOutList.add(iter->text_.c_str(), iter->text_.length(), offset, NULL, Term::AND, level+subLevel); } subLevel++; } } else { syOutList.add(synonymResultUstr, synonymResultUstrLen, offset, NULL, andOrBit, level+subLevel); subLevel++; } } } return ret; } int CommonLanguageAnalyzer::analyze_impl( const Term& input, void* data, HookType func ) { parse(input.text_); unsigned char topAndOrBit = Term::AND; int lastWordOffset = -1; while( nextToken() ) { if( len() == 0 ) continue; if( bRemoveStopwords_ && isStopword() ) continue; /* { UString foo(token(), len()); string bar; foo.convertString(bar, UString::UTF_8); cout << "(" << bar << ") --<> " << isIndex() << "," << offset() << "," << isRaw() << "," << level() << endl; }*/ if( bChinese_ == true ) { int curWordOffset = offset(); if( lastWordOffset == lastWordOffset ) topAndOrBit = Term::OR; else topAndOrBit = Term::AND; lastWordOffset = curWordOffset; } if( isIndex() ) { if(isSpecialChar()) { func( data, token(), len(), offset(), Term::SpecialCharPOS, Term::AND, level(), true); continue; } if(isRaw()) { func( data, token(), len(), offset(), pos(), Term::OR, level(), false); continue; } // foreign language, e.g. English if( isAlpha() ) { UString::CharT* lowercaseTermUstr = lowercase_ustring_buffer_; bool lowercaseIsDifferent = UString::toLowerString(token(), len(), lowercase_ustring_buffer_, term_ustring_buffer_limit_); char* lowercaseTerm = lowercase_string_buffer_; UString::convertString(UString::UTF_8, lowercaseTermUstr, len(), lowercase_string_buffer_, term_string_buffer_limit_); UString::CharT* stemmingTermUstr = NULL; size_t stemmingTermUstrSize = 0; UString::CharT * synonymResultUstr = NULL; size_t synonymResultUstrLen = 0; if(bExtractEngStem_) { /// TODO: write a UCS2 based stemmer string stem_term; pStemmer_->stem( lowercaseTerm, stem_term ); if( strcmp(stem_term.c_str(), lowercaseTerm) != 0 ) { stemmingTermUstr = stemming_ustring_buffer_; stemmingTermUstrSize = UString::toUcs2(UString::UTF_8, stem_term.c_str(), stem_term.size(), stemming_ustring_buffer_, term_ustring_buffer_limit_); } } if(bExtractSynonym_) { pSynonymContainer_ = uscSPtr_->getSynonymContainer(); pSynonymContainer_->searchNgetSynonym( lowercaseTerm, pSynonymResult_ ); char * synonymResult = pSynonymResult_->getHeadWord(0); if( synonymResult ) { size_t synonymResultLen = strlen(synonymResult); if(synonymResultLen <= term_ustring_buffer_limit_) { synonymResultUstr = synonym_ustring_buffer_; synonymResultUstrLen = UString::toUcs2(synonymEncode_, synonymResult, synonymResultLen, synonym_ustring_buffer_, term_ustring_buffer_limit_); } } } if( stemmingTermUstr || synonymResultUstr || (bCaseSensitive_ && bContainLower_ && lowercaseIsDifferent) ) { /// have more than one output if(bCaseSensitive_) { func( data, token(), len(), offset(), Term::EnglishPOS, Term::OR, level()+1, false); } else { func( data, lowercaseTermUstr, len(), offset(), Term::EnglishPOS, Term::OR, level()+1, false); } if(stemmingTermUstr) { func( data, stemmingTermUstr, stemmingTermUstrSize, offset(), Term::EnglishPOS, Term::OR, level()+1, false); } if(synonymResultUstr) { func( data, synonymResultUstr, synonymResultUstrLen, offset(), NULL, Term::OR, level()+1, false); } if(bCaseSensitive_ && bContainLower_ && lowercaseIsDifferent) { func( data, lowercaseTermUstr, len(), offset(), Term::EnglishPOS, Term::OR, level()+1, false); } } else { /// have only one output if(bCaseSensitive_) { func( data, token(), len(), offset(), Term::EnglishPOS, Term::AND, level(), false); } else { func( data, lowercaseTermUstr, len(), offset(), Term::EnglishPOS, Term::AND, level(), false); } } } else { if(bExtractSynonym_) { UString::CharT * synonymResultUstr = NULL; size_t synonymResultUstrLen = 0; pSynonymContainer_ = uscSPtr_->getSynonymContainer(); pSynonymContainer_->searchNgetSynonym( nativeToken(), pSynonymResult_ ); bool hasSynonym = false; for (int i =0; i<pSynonymResult_->getSynonymCount(0); i++) { char * synonymResult = pSynonymResult_->getWord(0, i); if( synonymResult ) { if (strcmp(nativeToken(), synonymResult) == 0) { cout << "synonym self: "<<string(synonymResult) <<endl; continue; } cout << "synonym : "<<string(synonymResult) <<endl; size_t synonymResultLen = strlen(synonymResult); if(synonymResultLen <= term_ustring_buffer_limit_) { synonymResultUstr = synonym_ustring_buffer_; synonymResultUstrLen = UString::toUcs2(synonymEncode_, synonymResult, synonymResultLen, synonym_ustring_buffer_, term_ustring_buffer_limit_); } hasSynonym = true; func( data, synonymResultUstr, synonymResultUstrLen, offset(), NULL, Term::OR, level()+1, false); } } if (hasSynonym) { func( data, token(), len(), offset(), pos(), Term::OR, level()+1, false); } else { func( data, token(), len(), offset(), pos(), topAndOrBit, level(), false); } } else { func( data, token(), len(), offset(), pos(), topAndOrBit, level(), false); } } } } return offset(); } } <|endoftext|>
<commit_before>#include "get_code.h" #include <set> #include <fstream> #include <boost/regex.hpp> #include <boost/format.hpp> using namespace thewizardplusplus::wizard_basic_3; using namespace boost; using namespace boost::filesystem; const auto LIBRARIES_PATH = std::string("libraries"); const auto INCLUDE_OPERATOR_PATTERN = regex( R"pattern(\binclude\s*"((?:\\.|[^"])*)")pattern" //" ); struct CodeGetter { const path script_base_path; std::string operator()(const smatch& match) const { const auto including_path = std::string(match[1]); const auto path_relative_to_interpreter = path(initial_path()).append(LIBRARIES_PATH).append(including_path); if (exists(path_relative_to_interpreter)) { return GetCode(path_relative_to_interpreter); } else { return GetCode(path(script_base_path).append(including_path)); } } }; namespace thewizardplusplus { namespace wizard_basic_3 { auto GetCode(const path& filename) -> std::string { static auto included_files = std::set<path>(); const auto absolute_path = canonical(filename); if (included_files.count(absolute_path)) { return ""; } included_files.insert(absolute_path); std::ifstream file; file.exceptions(std::ifstream::failbit | std::ifstream::badbit); auto code = std::string(); try { file.open(filename.string()); code = std::string( std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>() ); } catch(const std::ifstream::failure& exception) { throw std::runtime_error( (format(R"(unable to read script %s (%s))") % filename % exception.what()).str() ); } return regex_replace( code, INCLUDE_OPERATOR_PATTERN, CodeGetter{filename.parent_path()} ); } } } <commit_msg>Add explanatory comment.<commit_after>#include "get_code.h" #include <set> #include <fstream> #include <boost/regex.hpp> #include <boost/format.hpp> using namespace thewizardplusplus::wizard_basic_3; using namespace boost; using namespace boost::filesystem; const auto LIBRARIES_PATH = std::string("libraries"); const auto INCLUDE_OPERATOR_PATTERN = regex( R"pattern(\binclude\s*"((?:\\.|[^"])*)")pattern" // comment with closing quote for bugfix stupid syntax highlighter in Atom // " ); struct CodeGetter { const path script_base_path; std::string operator()(const smatch& match) const { const auto including_path = std::string(match[1]); const auto path_relative_to_interpreter = path(initial_path()).append(LIBRARIES_PATH).append(including_path); if (exists(path_relative_to_interpreter)) { return GetCode(path_relative_to_interpreter); } else { return GetCode(path(script_base_path).append(including_path)); } } }; namespace thewizardplusplus { namespace wizard_basic_3 { auto GetCode(const path& filename) -> std::string { static auto included_files = std::set<path>(); const auto absolute_path = canonical(filename); if (included_files.count(absolute_path)) { return ""; } included_files.insert(absolute_path); std::ifstream file; file.exceptions(std::ifstream::failbit | std::ifstream::badbit); auto code = std::string(); try { file.open(filename.string()); code = std::string( std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>() ); } catch(const std::ifstream::failure& exception) { throw std::runtime_error( (format(R"(unable to read script %s (%s))") % filename % exception.what()).str() ); } return regex_replace( code, INCLUDE_OPERATOR_PATTERN, CodeGetter{filename.parent_path()} ); } } } <|endoftext|>
<commit_before>/* * GLBlendState.cpp * * This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "GLBlendState.h" #include "../Ext/GLExtensions.h" #include "../Ext/GLExtensionRegistry.h" #include "../GLCore.h" #include "../GLTypes.h" #include "../GLProfile.h" #include "../../PipelineStateUtils.h" #include "../../../Core/HelperMacros.h" #include "../Texture/GLRenderTarget.h" #include "GLStateManager.h" #include <LLGL/PipelineStateFlags.h> namespace LLGL { static void Convert(GLfloat (&dst)[4], const ColorRGBAf& src) { dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } GLBlendState::GLBlendState(const BlendDescriptor& desc, std::uint32_t numColorAttachments) { Convert(blendColor_, desc.blendFactor); blendColorDynamic_ = desc.blendFactorDynamic; blendColorEnabled_ = IsStaticBlendFactorEnabled(desc); sampleAlphaToCoverage_ = desc.alphaToCoverageEnabled; sampleMask_ = desc.sampleMask; #ifdef LLGL_OPENGL if (desc.logicOp != LogicOp::Disabled) { logicOpEnabled_ = true; logicOp_ = GLTypes::Map(desc.logicOp); } #endif if (desc.independentBlendEnabled) { GLDrawBufferState::Convert(drawBuffers_[0], desc.targets[0]); numDrawBuffers_ = 1; } else { numDrawBuffers_ = numColorAttachments; for (std::uint32_t i = 0; i < numColorAttachments; ++i) GLDrawBufferState::Convert(drawBuffers_[i], desc.targets[i]); } #if 0//TODO if (multiSampleEnabled_) stateMngr.SetSampleMask(sampleMask_); #endif } void GLBlendState::Bind(GLStateManager& stateMngr) { /* Set blend factor */ if (blendColorEnabled_) stateMngr.SetBlendColor(blendColor_); stateMngr.Set(GLState::SAMPLE_ALPHA_TO_COVERAGE, sampleAlphaToCoverage_); #ifdef LLGL_OPENGL if (logicOpEnabled_) { /* Enable logic pixel operation */ stateMngr.Enable(GLState::COLOR_LOGIC_OP); stateMngr.SetLogicOp(logicOp_); /* Bind only color masks for all draw buffers */ BindDrawBufferColorMasks(stateMngr); } else { /* Disable logic pixel operation */ stateMngr.Disable(GLState::COLOR_LOGIC_OP); /* Bind blend states for all draw buffers */ BindDrawBufferStates(stateMngr); } #else // LLGL_OPENGL /* Bind blend states for all draw buffers */ BindDrawBufferStates(stateMngr); #endif // /LLGL_OPENGL } void GLBlendState::BindColorMaskOnly(GLStateManager& stateMngr) { BindDrawBufferColorMasks(stateMngr); } int GLBlendState::CompareSWO(const GLBlendState& lhs, const GLBlendState& rhs) { LLGL_COMPARE_MEMBER_SWO ( blendColor_[0] ); LLGL_COMPARE_MEMBER_SWO ( blendColor_[1] ); LLGL_COMPARE_MEMBER_SWO ( blendColor_[2] ); LLGL_COMPARE_MEMBER_SWO ( blendColor_[3] ); LLGL_COMPARE_MEMBER_SWO ( sampleAlphaToCoverage_ ); //LLGL_COMPARE_MEMBER_SWO ( sampleMask_ ); #ifdef LLGL_OPENGL LLGL_COMPARE_BOOL_MEMBER_SWO( logicOpEnabled_ ); LLGL_COMPARE_MEMBER_SWO ( logicOp_ ); #endif LLGL_COMPARE_MEMBER_SWO ( numDrawBuffers_ ); for (decltype(numDrawBuffers_) i = 0; i < lhs.numDrawBuffers_; ++i) { auto order = GLDrawBufferState::CompareSWO(lhs.drawBuffers_[i], rhs.drawBuffers_[i]); if (order != 0) return order; } return 0; } /* * ======= Private: ======= */ void GLBlendState::BindDrawBufferStates(GLStateManager& stateMngr) { if (numDrawBuffers_ == 1) { /* Bind blend states for all draw buffers */ BindDrawBufferState(drawBuffers_[0]); } else if (numDrawBuffers_ > 1) { #ifdef GL_ARB_draw_buffers_blend if (HasExtension(GLExt::ARB_draw_buffers_blend)) { /* Bind blend states for respective draw buffers directly via extension */ for (GLuint i = 0; i < numDrawBuffers_; ++i) BindIndexedDrawBufferState(drawBuffers_[i], i); } else #endif // /GL_ARB_draw_buffers_blend { /* Bind blend states with emulated draw buffer setting */ for (GLuint i = 0; i < numDrawBuffers_; ++i) { GLProfile::DrawBuffer(GLTypes::ToColorAttachment(i)); BindDrawBufferState(drawBuffers_[i]); } /* Restore draw buffer settings for current render target */ if (auto boundRenderTarget = stateMngr.GetBoundRenderTarget()) boundRenderTarget->SetDrawBuffers(); } } } void GLBlendState::BindDrawBufferColorMasks(GLStateManager& stateMngr) { if (numDrawBuffers_ == 1) { /* Bind color mask for all draw buffers */ BindDrawBufferColorMask(drawBuffers_[0]); } else if (numDrawBuffers_ > 1) { #ifdef GL_EXT_draw_buffers2 if (HasExtension(GLExt::EXT_draw_buffers2)) { /* Bind color mask for respective draw buffers directly via extension */ for (GLuint i = 0; i < numDrawBuffers_; ++i) BindIndexedDrawBufferColorMask(drawBuffers_[i], i); } else #endif // /GL_EXT_draw_buffers2 { /* Bind color masks with emulated draw buffer setting */ for (GLuint i = 0; i < numDrawBuffers_; ++i) { GLProfile::DrawBuffer(GLTypes::ToColorAttachment(i)); BindDrawBufferColorMask(drawBuffers_[i]); } /* Restore draw buffer settings for current render target */ if (auto boundRenderTarget = stateMngr.GetBoundRenderTarget()) boundRenderTarget->SetDrawBuffers(); } } } //TODO: GL_BLEND should be enabled/disabled with state manager void GLBlendState::BindDrawBufferState(const GLDrawBufferState& state) { glColorMask(state.colorMask[0], state.colorMask[1], state.colorMask[2], state.colorMask[3]); if (state.blendEnabled) { glEnable(GL_BLEND); glBlendFuncSeparate(state.srcColor, state.dstColor, state.srcAlpha, state.dstAlpha); glBlendEquationSeparate(state.funcColor, state.funcAlpha); } else glDisable(GL_BLEND); } //TODO: GL_BLEND should be enabled/disabled with state manager void GLBlendState::BindIndexedDrawBufferState(const GLDrawBufferState& state, GLuint index) { #ifdef LLGL_GLEXT_DRAW_BUFFERS_BLEND glColorMaski(index, state.colorMask[0], state.colorMask[1], state.colorMask[2], state.colorMask[3]); if (state.blendEnabled) { glEnablei(GL_BLEND, index); glBlendFuncSeparatei(index, state.srcColor, state.dstColor, state.srcAlpha, state.dstAlpha); glBlendEquationSeparatei(index, state.funcColor, state.funcAlpha); } else glDisablei(GL_BLEND, index); #endif // /LLGL_GLEXT_DRAW_BUFFERS_BLEND } void GLBlendState::BindDrawBufferColorMask(const GLDrawBufferState& state) { glColorMask(state.colorMask[0], state.colorMask[1], state.colorMask[2], state.colorMask[3]); } void GLBlendState::BindIndexedDrawBufferColorMask(const GLDrawBufferState& state, GLuint index) { #ifdef LLGL_GLEXT_DRAW_BUFFERS2 glColorMaski(index, state.colorMask[0], state.colorMask[1], state.colorMask[2], state.colorMask[3]); #endif // /LLGL_GLEXT_DRAW_BUFFERS2 } /* * GLDrawBufferState struct */ void GLBlendState::GLDrawBufferState::Convert(GLDrawBufferState& dst, const BlendTargetDescriptor& src) { dst.blendEnabled = GLBoolean(src.blendEnabled); dst.srcColor = GLTypes::Map(src.srcColor); dst.dstColor = GLTypes::Map(src.dstColor); dst.funcColor = GLTypes::Map(src.colorArithmetic); dst.srcAlpha = GLTypes::Map(src.srcAlpha); dst.dstAlpha = GLTypes::Map(src.dstAlpha); dst.funcAlpha = GLTypes::Map(src.alphaArithmetic); dst.colorMask[0] = GLBoolean(src.colorMask.r); dst.colorMask[1] = GLBoolean(src.colorMask.g); dst.colorMask[2] = GLBoolean(src.colorMask.b); dst.colorMask[3] = GLBoolean(src.colorMask.a); } int GLBlendState::GLDrawBufferState::CompareSWO(const GLDrawBufferState& lhs, const GLDrawBufferState& rhs) { LLGL_COMPARE_BOOL_MEMBER_SWO( blendEnabled ); LLGL_COMPARE_MEMBER_SWO ( srcColor ); LLGL_COMPARE_MEMBER_SWO ( dstColor ); LLGL_COMPARE_MEMBER_SWO ( funcColor ); LLGL_COMPARE_MEMBER_SWO ( srcAlpha ); LLGL_COMPARE_MEMBER_SWO ( dstAlpha ); LLGL_COMPARE_MEMBER_SWO ( funcAlpha ); LLGL_COMPARE_MEMBER_SWO ( colorMask[0] ); LLGL_COMPARE_MEMBER_SWO ( colorMask[1] ); LLGL_COMPARE_MEMBER_SWO ( colorMask[2] ); LLGL_COMPARE_MEMBER_SWO ( colorMask[3] ); return 0; } } // /namespace LLGL // ================================================================================ <commit_msg>Fixed condition of "independentBlendEnabled" for GL backend.<commit_after>/* * GLBlendState.cpp * * This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "GLBlendState.h" #include "../Ext/GLExtensions.h" #include "../Ext/GLExtensionRegistry.h" #include "../GLCore.h" #include "../GLTypes.h" #include "../GLProfile.h" #include "../../PipelineStateUtils.h" #include "../../../Core/HelperMacros.h" #include "../Texture/GLRenderTarget.h" #include "GLStateManager.h" #include <LLGL/PipelineStateFlags.h> namespace LLGL { static void Convert(GLfloat (&dst)[4], const ColorRGBAf& src) { dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } GLBlendState::GLBlendState(const BlendDescriptor& desc, std::uint32_t numColorAttachments) { Convert(blendColor_, desc.blendFactor); blendColorDynamic_ = desc.blendFactorDynamic; blendColorEnabled_ = IsStaticBlendFactorEnabled(desc); sampleAlphaToCoverage_ = desc.alphaToCoverageEnabled; sampleMask_ = desc.sampleMask; #ifdef LLGL_OPENGL if (desc.logicOp != LogicOp::Disabled) { logicOpEnabled_ = true; logicOp_ = GLTypes::Map(desc.logicOp); } #endif if (desc.independentBlendEnabled) { numDrawBuffers_ = numColorAttachments; for (std::uint32_t i = 0; i < numColorAttachments; ++i) GLDrawBufferState::Convert(drawBuffers_[i], desc.targets[i]); } else { GLDrawBufferState::Convert(drawBuffers_[0], desc.targets[0]); numDrawBuffers_ = 1; } #if 0//TODO if (multiSampleEnabled_) stateMngr.SetSampleMask(sampleMask_); #endif } void GLBlendState::Bind(GLStateManager& stateMngr) { /* Set blend factor */ if (blendColorEnabled_) stateMngr.SetBlendColor(blendColor_); stateMngr.Set(GLState::SAMPLE_ALPHA_TO_COVERAGE, sampleAlphaToCoverage_); #ifdef LLGL_OPENGL if (logicOpEnabled_) { /* Enable logic pixel operation */ stateMngr.Enable(GLState::COLOR_LOGIC_OP); stateMngr.SetLogicOp(logicOp_); /* Bind only color masks for all draw buffers */ BindDrawBufferColorMasks(stateMngr); } else { /* Disable logic pixel operation */ stateMngr.Disable(GLState::COLOR_LOGIC_OP); /* Bind blend states for all draw buffers */ BindDrawBufferStates(stateMngr); } #else // LLGL_OPENGL /* Bind blend states for all draw buffers */ BindDrawBufferStates(stateMngr); #endif // /LLGL_OPENGL } void GLBlendState::BindColorMaskOnly(GLStateManager& stateMngr) { BindDrawBufferColorMasks(stateMngr); } int GLBlendState::CompareSWO(const GLBlendState& lhs, const GLBlendState& rhs) { LLGL_COMPARE_MEMBER_SWO ( blendColor_[0] ); LLGL_COMPARE_MEMBER_SWO ( blendColor_[1] ); LLGL_COMPARE_MEMBER_SWO ( blendColor_[2] ); LLGL_COMPARE_MEMBER_SWO ( blendColor_[3] ); LLGL_COMPARE_MEMBER_SWO ( sampleAlphaToCoverage_ ); //LLGL_COMPARE_MEMBER_SWO ( sampleMask_ ); #ifdef LLGL_OPENGL LLGL_COMPARE_BOOL_MEMBER_SWO( logicOpEnabled_ ); LLGL_COMPARE_MEMBER_SWO ( logicOp_ ); #endif LLGL_COMPARE_MEMBER_SWO ( numDrawBuffers_ ); for (decltype(numDrawBuffers_) i = 0; i < lhs.numDrawBuffers_; ++i) { auto order = GLDrawBufferState::CompareSWO(lhs.drawBuffers_[i], rhs.drawBuffers_[i]); if (order != 0) return order; } return 0; } /* * ======= Private: ======= */ void GLBlendState::BindDrawBufferStates(GLStateManager& stateMngr) { if (numDrawBuffers_ == 1) { /* Bind blend states for all draw buffers */ BindDrawBufferState(drawBuffers_[0]); } else if (numDrawBuffers_ > 1) { #ifdef GL_ARB_draw_buffers_blend if (HasExtension(GLExt::ARB_draw_buffers_blend)) { /* Bind blend states for respective draw buffers directly via extension */ for (GLuint i = 0; i < numDrawBuffers_; ++i) BindIndexedDrawBufferState(drawBuffers_[i], i); } else #endif // /GL_ARB_draw_buffers_blend { /* Bind blend states with emulated draw buffer setting */ for (GLuint i = 0; i < numDrawBuffers_; ++i) { GLProfile::DrawBuffer(GLTypes::ToColorAttachment(i)); BindDrawBufferState(drawBuffers_[i]); } /* Restore draw buffer settings for current render target */ if (auto boundRenderTarget = stateMngr.GetBoundRenderTarget()) boundRenderTarget->SetDrawBuffers(); } } } void GLBlendState::BindDrawBufferColorMasks(GLStateManager& stateMngr) { if (numDrawBuffers_ == 1) { /* Bind color mask for all draw buffers */ BindDrawBufferColorMask(drawBuffers_[0]); } else if (numDrawBuffers_ > 1) { #ifdef GL_EXT_draw_buffers2 if (HasExtension(GLExt::EXT_draw_buffers2)) { /* Bind color mask for respective draw buffers directly via extension */ for (GLuint i = 0; i < numDrawBuffers_; ++i) BindIndexedDrawBufferColorMask(drawBuffers_[i], i); } else #endif // /GL_EXT_draw_buffers2 { /* Bind color masks with emulated draw buffer setting */ for (GLuint i = 0; i < numDrawBuffers_; ++i) { GLProfile::DrawBuffer(GLTypes::ToColorAttachment(i)); BindDrawBufferColorMask(drawBuffers_[i]); } /* Restore draw buffer settings for current render target */ if (auto boundRenderTarget = stateMngr.GetBoundRenderTarget()) boundRenderTarget->SetDrawBuffers(); } } } //TODO: GL_BLEND should be enabled/disabled with state manager void GLBlendState::BindDrawBufferState(const GLDrawBufferState& state) { glColorMask(state.colorMask[0], state.colorMask[1], state.colorMask[2], state.colorMask[3]); if (state.blendEnabled) { glEnable(GL_BLEND); glBlendFuncSeparate(state.srcColor, state.dstColor, state.srcAlpha, state.dstAlpha); glBlendEquationSeparate(state.funcColor, state.funcAlpha); } else glDisable(GL_BLEND); } //TODO: GL_BLEND should be enabled/disabled with state manager void GLBlendState::BindIndexedDrawBufferState(const GLDrawBufferState& state, GLuint index) { #ifdef LLGL_GLEXT_DRAW_BUFFERS_BLEND glColorMaski(index, state.colorMask[0], state.colorMask[1], state.colorMask[2], state.colorMask[3]); if (state.blendEnabled) { glEnablei(GL_BLEND, index); glBlendFuncSeparatei(index, state.srcColor, state.dstColor, state.srcAlpha, state.dstAlpha); glBlendEquationSeparatei(index, state.funcColor, state.funcAlpha); } else glDisablei(GL_BLEND, index); #endif // /LLGL_GLEXT_DRAW_BUFFERS_BLEND } void GLBlendState::BindDrawBufferColorMask(const GLDrawBufferState& state) { glColorMask(state.colorMask[0], state.colorMask[1], state.colorMask[2], state.colorMask[3]); } void GLBlendState::BindIndexedDrawBufferColorMask(const GLDrawBufferState& state, GLuint index) { #ifdef LLGL_GLEXT_DRAW_BUFFERS2 glColorMaski(index, state.colorMask[0], state.colorMask[1], state.colorMask[2], state.colorMask[3]); #endif // /LLGL_GLEXT_DRAW_BUFFERS2 } /* * GLDrawBufferState struct */ void GLBlendState::GLDrawBufferState::Convert(GLDrawBufferState& dst, const BlendTargetDescriptor& src) { dst.blendEnabled = GLBoolean(src.blendEnabled); dst.srcColor = GLTypes::Map(src.srcColor); dst.dstColor = GLTypes::Map(src.dstColor); dst.funcColor = GLTypes::Map(src.colorArithmetic); dst.srcAlpha = GLTypes::Map(src.srcAlpha); dst.dstAlpha = GLTypes::Map(src.dstAlpha); dst.funcAlpha = GLTypes::Map(src.alphaArithmetic); dst.colorMask[0] = GLBoolean(src.colorMask.r); dst.colorMask[1] = GLBoolean(src.colorMask.g); dst.colorMask[2] = GLBoolean(src.colorMask.b); dst.colorMask[3] = GLBoolean(src.colorMask.a); } int GLBlendState::GLDrawBufferState::CompareSWO(const GLDrawBufferState& lhs, const GLDrawBufferState& rhs) { LLGL_COMPARE_BOOL_MEMBER_SWO( blendEnabled ); LLGL_COMPARE_MEMBER_SWO ( srcColor ); LLGL_COMPARE_MEMBER_SWO ( dstColor ); LLGL_COMPARE_MEMBER_SWO ( funcColor ); LLGL_COMPARE_MEMBER_SWO ( srcAlpha ); LLGL_COMPARE_MEMBER_SWO ( dstAlpha ); LLGL_COMPARE_MEMBER_SWO ( funcAlpha ); LLGL_COMPARE_MEMBER_SWO ( colorMask[0] ); LLGL_COMPARE_MEMBER_SWO ( colorMask[1] ); LLGL_COMPARE_MEMBER_SWO ( colorMask[2] ); LLGL_COMPARE_MEMBER_SWO ( colorMask[3] ); return 0; } } // /namespace LLGL // ================================================================================ <|endoftext|>
<commit_before>// // Created by Zal on 11/19/16. // #include <assert.h> #include <utility> #include "BinaryMatrix.h" void BinaryMatrix::BinaryMatrix(int w, int h) { this->width = w; this->height = h; this->baseSize = sizeof(char) * 8; int n = w*h; this->dataLength = (n % baseSize == 0)? n/baseSize : n/baseSize +1; this->data = new char[dataLength]; } void BinaryMatrix::~BinaryMatrix() { delete[] data; } void BinaryMatrix::T() { this->transposed = !this->transposed; } BinaryMatrix BinaryMatrix::binMultiply(const BinaryMatrix& other) { BinaryMatrix res(this->width, this->height); for(int i = 0; i < this->dataLength; ++i) { res.data[i] = !(this->data[i] ^ other.data[i]); } return res; } std::pair<int, int> BinaryMatrix::elem_accessor(int i, int rows, int cols, bool transposed) { if (transposed) { return std::make_pair(i % rows, i / rows); } else { return std::make_pair(i / cols, i % cols); } } char BinaryMatrix::get_bit(char elem, int bit_id) { return (elem >> (this->baseSize - bit_id)) & 1; } char BinaryMatrix::set_bit(char elem, int bit_id, char bit) { // assumes originally the bit is set to 0 char mask = 1 << (this->baseSize - bit_id); if (get_bit(elem, bit_id) == 1 && bit == 0) { return (elem & !(1 << mask)); } else { return (elem | (bit << mask)); } } BinaryMatrix BinaryMatrix::tBinMultiply(const BinaryMatrix& other) { int w = this->width; int h = this->height; if (this->transposed) { w = other.width; h = other.height; } int this_n = this->dataLength; int other_n = other.dataLength; int res_n = res.dataLength; BinaryMatrix res(w, h); for (int bit_id = 0; bit_id < (w * h); ++bit_id) { std::pair<int, int> this_rc = elem_accessor(bit_id, this_n, this->baseSize, this->transposed); std::pair<int, int> other_rc = elem_accessor(bit_id, other_n, other->baseSize, other.transposed); std::pair<int, int> res_rc = elem_accessor(bit_id, res_n, res->baseSize, res.transposed); char this_c = this->data[this_rc.first]; char other_c = other.data[other_rc.first]; char res_c = res.data[res_rc.first]; char answer = !(get_bit(this_c, this_rc.second) ^ get_bit(other_c, other_rc.second)) & 1; res.data[res_rc.first] = set_bit(res_c, res_rc.second, answer); } return res; } double BinaryMatrix::doubleMultiply(const double& other) { } BinaryMatrix BinaryMatrix::operator*(const BinaryMatrix& other ) { if(this->transposed != other.transposed) { assert(this->width == other.height); assert(this->height == other.width); return this->tBinMultiply(other); } else { assert(this->width == other.width); assert(this->height == other.height); return this->binMultiply(other); } } <commit_msg>Fixed set_bit op<commit_after>// // Created by Zal on 11/19/16. // #include <assert.h> #include <utility> #include "BinaryMatrix.h" void BinaryMatrix::BinaryMatrix(int w, int h) { this->width = w; this->height = h; this->baseSize = sizeof(char) * 8; int n = w*h; this->dataLength = (n % baseSize == 0)? n/baseSize : n/baseSize +1; this->data = new char[dataLength]; } void BinaryMatrix::~BinaryMatrix() { delete[] data; } void BinaryMatrix::T() { this->transposed = !this->transposed; } BinaryMatrix BinaryMatrix::binMultiply(const BinaryMatrix& other) { BinaryMatrix res(this->width, this->height); for(int i = 0; i < this->dataLength; ++i) { res.data[i] = !(this->data[i] ^ other.data[i]); } return res; } std::pair<int, int> BinaryMatrix::elem_accessor(int i, int rows, int cols, bool transposed) { if (transposed) { return std::make_pair(i % rows, i / rows); } else { return std::make_pair(i / cols, i % cols); } } char BinaryMatrix::get_bit(char elem, int bit_id) { return (elem >> (this->baseSize - bit_id)) & 1; } char BinaryMatrix::set_bit(char elem, int bit_id, char bit) { if (bit == 0) { char mask = 1 << (this->baseSize - bit_id); return (elem & !mask); } else { return (elem | (bit << (this->baseSize - bit_id))); } } BinaryMatrix BinaryMatrix::tBinMultiply(const BinaryMatrix& other) { int w = this->width; int h = this->height; if (this->transposed) { w = other.width; h = other.height; } int this_n = this->dataLength; int other_n = other.dataLength; int res_n = res.dataLength; BinaryMatrix res(w, h); for (int bit_id = 0; bit_id < (w * h); ++bit_id) { std::pair<int, int> this_rc = elem_accessor(bit_id, this_n, this->baseSize, this->transposed); std::pair<int, int> other_rc = elem_accessor(bit_id, other_n, other->baseSize, other.transposed); std::pair<int, int> res_rc = elem_accessor(bit_id, res_n, res->baseSize, res.transposed); char this_c = this->data[this_rc.first]; char other_c = other.data[other_rc.first]; char res_c = res.data[res_rc.first]; char answer = !(get_bit(this_c, this_rc.second) ^ get_bit(other_c, other_rc.second)) & 1; res.data[res_rc.first] = set_bit(res_c, res_rc.second, answer); } return res; } double BinaryMatrix::doubleMultiply(const double& other) { } BinaryMatrix BinaryMatrix::operator*(const BinaryMatrix& other ) { if(this->transposed != other.transposed) { assert(this->width == other.height); assert(this->height == other.width); return this->tBinMultiply(other); } else { assert(this->width == other.width); assert(this->height == other.height); return this->binMultiply(other); } } <|endoftext|>
<commit_before>#include <QString> #include <functional> #include <future> #include <memory> #include "kernel.h" #include "coverage.h" #include "columndefinition.h" #include "table.h" #include "attributerecord.h" #include "polygon.h" #include "geometry.h" #include "feature.h" #include "featurecoverage.h" #include "symboltable.h" #include "OperationExpression.h" #include "operationmetadata.h" #include "operation.h" #include "operationhelper.h" #include "operationhelperfeatures.h" #include "commandhandler.h" #include "featureiterator.h" #include "selectionfeatures.h" using namespace Ilwis; using namespace BaseOperations; SelectionFeatures::SelectionFeatures() { } SelectionFeatures::SelectionFeatures(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr) { } SelectionFeatures::~SelectionFeatures() { } bool SelectionFeatures::execute(ExecutionContext *ctx, SymbolTable &symTable) { if (_prepState == sNOTPREPARED) if((_prepState = prepare(ctx, symTable)) != sPREPARED) return false; IFeatureCoverage outputFC = _outputObj.get<FeatureCoverage>(); IFeatureCoverage inputFC = _inputObj.get<FeatureCoverage>(); SubSetAsyncFunc selection = [&](const std::vector<quint32>& subset ) -> bool { FeatureIterator iterIn(inputFC, subset); for_each(iterIn, iterIn.end(), [&](SPFeatureI feature){ QVariant v = feature->cell(_attribColumn); SPFeatureI newFeature = outputFC->newFeatureFrom(feature); _attTable->record(NEW_RECORD,{newFeature->featureid(), v}); ++iterIn; } ); return true; }; ctx->_threaded = false; bool resource = OperationHelperFeatures::execute(ctx,selection, inputFC, outputFC, _attTable); if ( resource && ctx != 0) { outputFC->attributeTable(_attTable); QVariant value; value.setValue<IFeatureCoverage>(outputFC); ctx->addOutput(symTable, value, outputFC->name(), itFEATURE,outputFC->source()); } return true; } Ilwis::OperationImplementation *SelectionFeatures::create(quint64 metaid, const Ilwis::OperationExpression &expr) { return new SelectionFeatures(metaid, expr); } Ilwis::OperationImplementation::State SelectionFeatures::prepare(ExecutionContext *, const SymbolTable &) { IlwisTypes inputType = itFEATURE; QString fc = _expression.parm(0).value(); if (!_inputObj.prepare(fc, inputType)) { ERROR2(ERR_COULD_NOT_LOAD_2,fc,""); return sPREPAREFAILED; } IFeatureCoverage inputFC = _inputObj.get<FeatureCoverage>(); quint64 copylist = itCOORDSYSTEM; QString selector = _expression.parm(1).value(); selector = selector.remove('"'); int index = selector.indexOf("box="); Box2D<double> box; if ( index != -1) { QString crdlist = "box(" + selector.mid(index+4) + ")"; _box = Box3D<double>(crdlist); copylist |= itDOMAIN | itTABLE; } index = selector.indexOf("polygon="); if ( index != -1) { //TODO copylist |= itDOMAIN | itTABLE; } index = selector.indexOf("attribute="); if ( index != -1 ) { if (! inputFC->attributeTable().isValid()) { ERROR2(ERR_NO_FOUND2,"attribute-table", "coverage"); return sPREPAREFAILED; } _attribColumn = selector.mid(index+10); copylist |= itENVELOPE; } _outputObj = OperationHelperFeatures::initialize(_inputObj,inputType, copylist); if ( !_outputObj.isValid()) { ERROR1(ERR_NO_INITIALIZED_1, "output coverage"); return sPREPAREFAILED; } QString outputName = _expression.parm(0,false).value(); if ( outputName != sUNDEF) _outputObj->setName(outputName); if ( _attribColumn != "") { QString url = "ilwis://internalcatalog/" + outputName; Resource resource(url, itFLATTABLE); _attTable.prepare(resource); IDomain covdom; if (!covdom.prepare("count")){ return sPREPAREFAILED; } _attTable->addColumn(FEATUREIDCOLUMN,covdom); _attTable->addColumn(_attribColumn, inputFC->attributeTable()->columndefinition(_attribColumn).datadef().domain()); IFeatureCoverage outputFC = _outputObj.get<FeatureCoverage>(); outputFC->attributeTable(_attTable); } if ( (_box.isValid() && !_box.isNull()) == 0) { //TODO selections in features on bounding box } return sPREPARED; } quint64 SelectionFeatures::createMetadata() { QString url = QString("ilwis://operations/selection"); Resource resource(QUrl(url), itOPERATIONMETADATA); resource.addProperty("namespace","ilwis"); resource.addProperty("longname","selection"); resource.addProperty("syntax","selection(featurecoverage,selection-definition)"); resource.addProperty("description",TR("the operation select parts of the spatial extent or attributes to create a 'smaller' coverage")); resource.addProperty("inparameters","2"); resource.addProperty("pin_1_type", itFEATURE); resource.addProperty("pin_1_name", TR("input rastercoverage")); resource.addProperty("pin_1_desc",TR("input rastercoverage with a domain as specified by the selection")); resource.addProperty("pin_2_type", itSTRING); resource.addProperty("pin_2_name", TR("selection-definition")); resource.addProperty("pin_2_desc",TR("Selection can either be attribute, layer index or area definition (e.g. box)")); resource.addProperty("pout_1_type", itFEATURE); resource.addProperty("pout_1_name", TR("rastercoverage were the selection has been applied")); resource.addProperty("pout_1_desc",TR("")); resource.prepare(); url += "=" + QString::number(resource.id()); resource.setUrl(url); mastercatalog()->addItems({resource}); return resource.id(); } <commit_msg>renamed a wrongly named variable<commit_after>#include <QString> #include <functional> #include <future> #include <memory> #include "kernel.h" #include "coverage.h" #include "columndefinition.h" #include "table.h" #include "attributerecord.h" #include "polygon.h" #include "geometry.h" #include "feature.h" #include "featurecoverage.h" #include "symboltable.h" #include "OperationExpression.h" #include "operationmetadata.h" #include "operation.h" #include "operationhelper.h" #include "operationhelperfeatures.h" #include "commandhandler.h" #include "featureiterator.h" #include "selectionfeatures.h" using namespace Ilwis; using namespace BaseOperations; SelectionFeatures::SelectionFeatures() { } SelectionFeatures::SelectionFeatures(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr) { } SelectionFeatures::~SelectionFeatures() { } bool SelectionFeatures::execute(ExecutionContext *ctx, SymbolTable &symTable) { if (_prepState == sNOTPREPARED) if((_prepState = prepare(ctx, symTable)) != sPREPARED) return false; IFeatureCoverage outputFC = _outputObj.get<FeatureCoverage>(); IFeatureCoverage inputFC = _inputObj.get<FeatureCoverage>(); SubSetAsyncFunc selection = [&](const std::vector<quint32>& subset ) -> bool { FeatureIterator iterIn(inputFC, subset); for_each(iterIn, iterIn.end(), [&](SPFeatureI feature){ QVariant v = feature->cell(_attribColumn); SPFeatureI newFeature = outputFC->newFeatureFrom(feature); _attTable->record(NEW_RECORD,{newFeature->featureid(), v}); ++iterIn; } ); return true; }; ctx->_threaded = false; bool ok = OperationHelperFeatures::execute(ctx,selection, inputFC, outputFC, _attTable); if ( ok && ctx != 0) { outputFC->attributeTable(_attTable); QVariant value; value.setValue<IFeatureCoverage>(outputFC); ctx->addOutput(symTable, value, outputFC->name(), itFEATURE,outputFC->source()); } return true; } Ilwis::OperationImplementation *SelectionFeatures::create(quint64 metaid, const Ilwis::OperationExpression &expr) { return new SelectionFeatures(metaid, expr); } Ilwis::OperationImplementation::State SelectionFeatures::prepare(ExecutionContext *, const SymbolTable &) { IlwisTypes inputType = itFEATURE; QString fc = _expression.parm(0).value(); if (!_inputObj.prepare(fc, inputType)) { ERROR2(ERR_COULD_NOT_LOAD_2,fc,""); return sPREPAREFAILED; } IFeatureCoverage inputFC = _inputObj.get<FeatureCoverage>(); quint64 copylist = itCOORDSYSTEM; QString selector = _expression.parm(1).value(); selector = selector.remove('"'); int index = selector.indexOf("box="); Box2D<double> box; if ( index != -1) { QString crdlist = "box(" + selector.mid(index+4) + ")"; _box = Box3D<double>(crdlist); copylist |= itDOMAIN | itTABLE; } index = selector.indexOf("polygon="); if ( index != -1) { //TODO copylist |= itDOMAIN | itTABLE; } index = selector.indexOf("attribute="); if ( index != -1 ) { if (! inputFC->attributeTable().isValid()) { ERROR2(ERR_NO_FOUND2,"attribute-table", "coverage"); return sPREPAREFAILED; } _attribColumn = selector.mid(index+10); copylist |= itENVELOPE; } _outputObj = OperationHelperFeatures::initialize(_inputObj,inputType, copylist); if ( !_outputObj.isValid()) { ERROR1(ERR_NO_INITIALIZED_1, "output coverage"); return sPREPAREFAILED; } QString outputName = _expression.parm(0,false).value(); if ( outputName != sUNDEF) _outputObj->setName(outputName); if ( _attribColumn != "") { QString url = "ilwis://internalcatalog/" + outputName; Resource resource(url, itFLATTABLE); _attTable.prepare(resource); IDomain covdom; if (!covdom.prepare("count")){ return sPREPAREFAILED; } _attTable->addColumn(FEATUREIDCOLUMN,covdom); _attTable->addColumn(_attribColumn, inputFC->attributeTable()->columndefinition(_attribColumn).datadef().domain()); IFeatureCoverage outputFC = _outputObj.get<FeatureCoverage>(); outputFC->attributeTable(_attTable); } if ( (_box.isValid() && !_box.isNull()) == 0) { //TODO selections in features on bounding box } return sPREPARED; } quint64 SelectionFeatures::createMetadata() { QString url = QString("ilwis://operations/selection"); Resource resource(QUrl(url), itOPERATIONMETADATA); resource.addProperty("namespace","ilwis"); resource.addProperty("longname","selection"); resource.addProperty("syntax","selection(featurecoverage,selection-definition)"); resource.addProperty("description",TR("the operation select parts of the spatial extent or attributes to create a 'smaller' coverage")); resource.addProperty("inparameters","2"); resource.addProperty("pin_1_type", itFEATURE); resource.addProperty("pin_1_name", TR("input rastercoverage")); resource.addProperty("pin_1_desc",TR("input rastercoverage with a domain as specified by the selection")); resource.addProperty("pin_2_type", itSTRING); resource.addProperty("pin_2_name", TR("selection-definition")); resource.addProperty("pin_2_desc",TR("Selection can either be attribute, layer index or area definition (e.g. box)")); resource.addProperty("pout_1_type", itFEATURE); resource.addProperty("pout_1_name", TR("rastercoverage were the selection has been applied")); resource.addProperty("pout_1_desc",TR("")); resource.prepare(); url += "=" + QString::number(resource.id()); resource.setUrl(url); mastercatalog()->addItems({resource}); return resource.id(); } <|endoftext|>
<commit_before>/* **** **** **** **** **** **** **** **** * * * _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * _/ _/ _/ _/ _/ _/ * _/ _/ _/ _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * * bit by bit * bbb/core/type/container/type_holder.hpp * * author: ISHII 2bit * mail: 2bit@backspace.tokyo * * **** **** **** **** **** **** **** **** */ #pragma once #include <bbb/core/type/utility.hpp> #include <bbb/core/type/integer_sequence/integer_range.hpp> #include <bbb/core/type/logic.hpp> namespace bbb { namespace type_sequences { template <typename ... types> struct type_sequence; template <> struct type_sequence<> {}; template <typename type, typename ... types> struct type_sequence<type, types ...> { using head = type; using tails = type_sequence<types ...>; }; }; using namespace type_sequences; }; <commit_msg>update type/container<commit_after>/* **** **** **** **** **** **** **** **** * * * _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * _/ _/ _/ _/ _/ _/ * _/ _/ _/ _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * * bit by bit * bbb/core/type/container/type_holder.hpp * * author: ISHII 2bit * mail: 2bit@backspace.tokyo * * **** **** **** **** **** **** **** **** */ #pragma once #include <bbb/core/type/utility.hpp> #include <bbb/core/type/integer_sequence/integer_range.hpp> #include <bbb/core/type/logic.hpp> namespace bbb { namespace type_sequences { template <typename ... types> struct type_sequence; template <> struct type_sequence<> { static constexpr std::size_t size = 0; }; template <typename type, typename ... types> struct type_sequence<type, types ...> { using head = type; using tails = type_sequence<types ...>; static constexpr std::size_t size = sizeof...(types) + 1; }; namespace detail { template <typename sequence> struct is_sequence : std::false_type {}; template <typename ... types> struct is_sequence<type_sequence<types ...>> : std::true_type {}; } template <typename sequence> constexpr bool is_sequence() { return detail::is_sequence<sequence>::value; } template <typename sequence, typename std::enable_if<is_sequence<sequence>()>::type * = nullptr> constexpr bool is_null() { return sequence::size == 0; } }; using namespace type_sequences; }; <|endoftext|>
<commit_before>//===================================================== // Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr> //===================================================== // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // 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 General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // #ifndef EIGEN2_INTERFACE_HH #define EIGEN2_INTERFACE_HH // #include <cblas.h> #include <Eigen/Array> #include <Eigen/Cholesky> #include <Eigen/LU> #include <Eigen/QR> #include <vector> #include "btl.hh" using namespace Eigen; template<class real, int SIZE=Dynamic> class eigen2_interface { public : enum {IsFixedSize = (SIZE!=Dynamic)}; typedef real real_type; typedef std::vector<real> stl_vector; typedef std::vector<stl_vector> stl_matrix; typedef Eigen::Matrix<real,SIZE,SIZE> gene_matrix; typedef Eigen::Matrix<real,SIZE,1> gene_vector; static inline std::string name( void ) { return EIGEN_MAKESTRING(BTL_PREFIX); } static void free_matrix(gene_matrix & A, int N) {} static void free_vector(gene_vector & B) {} static BTL_DONT_INLINE void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){ A.resize(A_stl[0].size(), A_stl.size()); for (int j=0; j<A_stl.size() ; j++){ for (int i=0; i<A_stl[j].size() ; i++){ A.coeffRef(i,j) = A_stl[j][i]; } } } static BTL_DONT_INLINE void vector_from_stl(gene_vector & B, stl_vector & B_stl){ B.resize(B_stl.size(),1); for (int i=0; i<B_stl.size() ; i++){ B.coeffRef(i) = B_stl[i]; } } static BTL_DONT_INLINE void vector_to_stl(gene_vector & B, stl_vector & B_stl){ for (int i=0; i<B_stl.size() ; i++){ B_stl[i] = B.coeff(i); } } static BTL_DONT_INLINE void matrix_to_stl(gene_matrix & A, stl_matrix & A_stl){ int N=A_stl.size(); for (int j=0;j<N;j++){ A_stl[j].resize(N); for (int i=0;i<N;i++){ A_stl[j][i] = A.coeff(i,j); } } } static inline void matrix_matrix_product(const gene_matrix & A, const gene_matrix & B, gene_matrix & X, int N){ X = (A*B).lazy(); } static inline void transposed_matrix_matrix_product(const gene_matrix & A, const gene_matrix & B, gene_matrix & X, int N){ X = (A.transpose()*B.transpose()).lazy(); } static inline void ata_product(const gene_matrix & A, gene_matrix & X, int N){ X = (A.transpose()*A).lazy(); } static inline void aat_product(const gene_matrix & A, gene_matrix & X, int N){ X = (A*A.transpose()).lazy(); } static inline void matrix_vector_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N){ X = (A*B).lazy(); } static inline void symv(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N){ X = (A.template selfadjointView<LowerTriangular>() * B)/*.lazy()*/; // ei_product_selfadjoint_vector<real,0,LowerTriangularBit,false,false>(N,A.data(),N, B.data(), 1, X.data(), 1); } template<typename Dest, typename Src> static void triassign(Dest& dst, const Src& src) { typedef typename Dest::Scalar Scalar; typedef typename ei_packet_traits<Scalar>::type Packet; const int PacketSize = sizeof(Packet)/sizeof(Scalar); int size = dst.cols(); for(int j=0; j<size; j+=1) { // const int alignedEnd = alignedStart + ((innerSize-alignedStart) & ~packetAlignedMask); Scalar* A0 = dst.data() + j*dst.stride(); int starti = j; int alignedEnd = starti; int alignedStart = (starti) + ei_first_aligned(&A0[starti], size-starti); alignedEnd = alignedStart + ((size-alignedStart)/(2*PacketSize))*(PacketSize*2); // do the non-vectorizable part of the assignment for (int index = starti; index<alignedStart ; ++index) { if(Dest::Flags&RowMajorBit) dst.copyCoeff(j, index, src); else dst.copyCoeff(index, j, src); } // do the vectorizable part of the assignment for (int index = alignedStart; index<alignedEnd; index+=PacketSize) { if(Dest::Flags&RowMajorBit) dst.template copyPacket<Src, Aligned, Unaligned>(j, index, src); else dst.template copyPacket<Src, Aligned, Unaligned>(index, j, src); } // do the non-vectorizable part of the assignment for (int index = alignedEnd; index<size; ++index) { if(Dest::Flags&RowMajorBit) dst.copyCoeff(j, index, src); else dst.copyCoeff(index, j, src); } //dst.col(j).tail(N-j) = src.col(j).tail(N-j); } } static EIGEN_DONT_INLINE void syr2(gene_matrix & A, gene_vector & X, gene_vector & Y, int N){ // ei_product_selfadjoint_rank2_update<real,0,LowerTriangularBit>(N,A.data(),N, X.data(), 1, Y.data(), 1, -1); for(int j=0; j<N; ++j) A.col(j).tail(N-j) += X[j] * Y.tail(N-j) + Y[j] * X.tail(N-j); } static EIGEN_DONT_INLINE void ger(gene_matrix & A, gene_vector & X, gene_vector & Y, int N){ for(int j=0; j<N; ++j) A.col(j) += X * Y[j]; } static EIGEN_DONT_INLINE void rot(gene_vector & A, gene_vector & B, real c, real s, int N){ ei_apply_rotation_in_the_plane(A, B, c, s); } static inline void atv_product(gene_matrix & A, gene_vector & B, gene_vector & X, int N){ X = (A.transpose()*B).lazy(); } static inline void axpy(real coef, const gene_vector & X, gene_vector & Y, int N){ Y += coef * X; } static inline void axpby(real a, const gene_vector & X, real b, gene_vector & Y, int N){ Y = a*X + b*Y; } static EIGEN_DONT_INLINE void copy_matrix(const gene_matrix & source, gene_matrix & cible, int N){ cible = source; } static EIGEN_DONT_INLINE void copy_vector(const gene_vector & source, gene_vector & cible, int N){ cible = source; } static inline void trisolve_lower(const gene_matrix & L, const gene_vector& B, gene_vector& X, int N){ X = L.template triangularView<LowerTriangular>().solve(B); } static inline void trisolve_lower_matrix(const gene_matrix & L, const gene_matrix& B, gene_matrix& X, int N){ X = L.template triangularView<LowerTriangular>().solve(B); } static inline void cholesky(const gene_matrix & X, gene_matrix & C, int N){ C = X; ei_llt_inplace<LowerTriangular>::blocked(C); //C = X.llt().matrixL(); // C = X; // Cholesky<gene_matrix>::computeInPlace(C); // Cholesky<gene_matrix>::computeInPlaceBlock(C); } static inline void lu_decomp(const gene_matrix & X, gene_matrix & C, int N){ RowVectorXi piv(N); int nb; C = X; ei_partial_lu_inplace(C,piv,nb); //C = X.lu().matrixLU(); } static inline void partial_lu_decomp(const gene_matrix & X, gene_matrix & C, int N){ C = X.partialPivLu().matrixLU(); } static inline void tridiagonalization(const gene_matrix & X, gene_matrix & C, int N){ typename Tridiagonalization<gene_matrix>::CoeffVectorType aux(N-1); C = X; Tridiagonalization<gene_matrix>::_compute(C, aux); // C = Tridiagonalization<gene_matrix>(X).packedMatrix(); } static inline void hessenberg(const gene_matrix & X, gene_matrix & C, int N){ C = HessenbergDecomposition<gene_matrix>(X).packedMatrix(); } }; #endif <commit_msg>fix BTL's eigen interface<commit_after>//===================================================== // Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr> //===================================================== // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // 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 General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // #ifndef EIGEN2_INTERFACE_HH #define EIGEN2_INTERFACE_HH #include <Eigen/Eigen> #include <vector> #include "btl.hh" using namespace Eigen; template<class real, int SIZE=Dynamic> class eigen2_interface { public : enum {IsFixedSize = (SIZE!=Dynamic)}; typedef real real_type; typedef std::vector<real> stl_vector; typedef std::vector<stl_vector> stl_matrix; typedef Eigen::Matrix<real,SIZE,SIZE> gene_matrix; typedef Eigen::Matrix<real,SIZE,1> gene_vector; static inline std::string name( void ) { return EIGEN_MAKESTRING(BTL_PREFIX); } static void free_matrix(gene_matrix & A, int N) {} static void free_vector(gene_vector & B) {} static BTL_DONT_INLINE void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){ A.resize(A_stl[0].size(), A_stl.size()); for (int j=0; j<A_stl.size() ; j++){ for (int i=0; i<A_stl[j].size() ; i++){ A.coeffRef(i,j) = A_stl[j][i]; } } } static BTL_DONT_INLINE void vector_from_stl(gene_vector & B, stl_vector & B_stl){ B.resize(B_stl.size(),1); for (int i=0; i<B_stl.size() ; i++){ B.coeffRef(i) = B_stl[i]; } } static BTL_DONT_INLINE void vector_to_stl(gene_vector & B, stl_vector & B_stl){ for (int i=0; i<B_stl.size() ; i++){ B_stl[i] = B.coeff(i); } } static BTL_DONT_INLINE void matrix_to_stl(gene_matrix & A, stl_matrix & A_stl){ int N=A_stl.size(); for (int j=0;j<N;j++){ A_stl[j].resize(N); for (int i=0;i<N;i++){ A_stl[j][i] = A.coeff(i,j); } } } static inline void matrix_matrix_product(const gene_matrix & A, const gene_matrix & B, gene_matrix & X, int N){ X.noalias() = A*B; } static inline void transposed_matrix_matrix_product(const gene_matrix & A, const gene_matrix & B, gene_matrix & X, int N){ X.noalias() = A.transpose()*B.transpose(); } static inline void ata_product(const gene_matrix & A, gene_matrix & X, int N){ X.noalias() = A.transpose()*A; } static inline void aat_product(const gene_matrix & A, gene_matrix & X, int N){ X.noalias() = A*A.transpose(); } static inline void matrix_vector_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N){ X.noalias() = A*B; } static inline void symv(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N){ X.noalias() = (A.template selfadjointView<Lower>() * B); // ei_product_selfadjoint_vector<real,0,LowerTriangularBit,false,false>(N,A.data(),N, B.data(), 1, X.data(), 1); } template<typename Dest, typename Src> static void triassign(Dest& dst, const Src& src) { typedef typename Dest::Scalar Scalar; typedef typename ei_packet_traits<Scalar>::type Packet; const int PacketSize = sizeof(Packet)/sizeof(Scalar); int size = dst.cols(); for(int j=0; j<size; j+=1) { // const int alignedEnd = alignedStart + ((innerSize-alignedStart) & ~packetAlignedMask); Scalar* A0 = dst.data() + j*dst.stride(); int starti = j; int alignedEnd = starti; int alignedStart = (starti) + ei_first_aligned(&A0[starti], size-starti); alignedEnd = alignedStart + ((size-alignedStart)/(2*PacketSize))*(PacketSize*2); // do the non-vectorizable part of the assignment for (int index = starti; index<alignedStart ; ++index) { if(Dest::Flags&RowMajorBit) dst.copyCoeff(j, index, src); else dst.copyCoeff(index, j, src); } // do the vectorizable part of the assignment for (int index = alignedStart; index<alignedEnd; index+=PacketSize) { if(Dest::Flags&RowMajorBit) dst.template copyPacket<Src, Aligned, Unaligned>(j, index, src); else dst.template copyPacket<Src, Aligned, Unaligned>(index, j, src); } // do the non-vectorizable part of the assignment for (int index = alignedEnd; index<size; ++index) { if(Dest::Flags&RowMajorBit) dst.copyCoeff(j, index, src); else dst.copyCoeff(index, j, src); } //dst.col(j).tail(N-j) = src.col(j).tail(N-j); } } static EIGEN_DONT_INLINE void syr2(gene_matrix & A, gene_vector & X, gene_vector & Y, int N){ // ei_product_selfadjoint_rank2_update<real,0,LowerTriangularBit>(N,A.data(),N, X.data(), 1, Y.data(), 1, -1); for(int j=0; j<N; ++j) A.col(j).tail(N-j) += X[j] * Y.tail(N-j) + Y[j] * X.tail(N-j); } static EIGEN_DONT_INLINE void ger(gene_matrix & A, gene_vector & X, gene_vector & Y, int N){ for(int j=0; j<N; ++j) A.col(j) += X * Y[j]; } static EIGEN_DONT_INLINE void rot(gene_vector & A, gene_vector & B, real c, real s, int N){ ei_apply_rotation_in_the_plane(A, B, c, s); } static inline void atv_product(gene_matrix & A, gene_vector & B, gene_vector & X, int N){ X.noalias() = (A.transpose()*B); } static inline void axpy(real coef, const gene_vector & X, gene_vector & Y, int N){ Y += coef * X; } static inline void axpby(real a, const gene_vector & X, real b, gene_vector & Y, int N){ Y = a*X + b*Y; } static EIGEN_DONT_INLINE void copy_matrix(const gene_matrix & source, gene_matrix & cible, int N){ cible = source; } static EIGEN_DONT_INLINE void copy_vector(const gene_vector & source, gene_vector & cible, int N){ cible = source; } static inline void trisolve_lower(const gene_matrix & L, const gene_vector& B, gene_vector& X, int N){ X = L.template triangularView<Lower>().solve(B); } static inline void trisolve_lower_matrix(const gene_matrix & L, const gene_matrix& B, gene_matrix& X, int N){ X = L.template triangularView<Lower>().solve(B); } static inline void cholesky(const gene_matrix & X, gene_matrix & C, int N){ C = X; ei_llt_inplace<Lower>::blocked(C); //C = X.llt().matrixL(); // C = X; // Cholesky<gene_matrix>::computeInPlace(C); // Cholesky<gene_matrix>::computeInPlaceBlock(C); } static inline void lu_decomp(const gene_matrix & X, gene_matrix & C, int N){ RowVectorXi piv(N); int nb; C = X; ei_partial_lu_inplace(C,piv,nb); //C = X.lu().matrixLU(); } static inline void partial_lu_decomp(const gene_matrix & X, gene_matrix & C, int N){ C = X.partialPivLu().matrixLU(); } static inline void tridiagonalization(const gene_matrix & X, gene_matrix & C, int N){ typename Tridiagonalization<gene_matrix>::CoeffVectorType aux(N-1); C = X; Tridiagonalization<gene_matrix>::_compute(C, aux); // C = Tridiagonalization<gene_matrix>(X).packedMatrix(); } static inline void hessenberg(const gene_matrix & X, gene_matrix & C, int N){ C = HessenbergDecomposition<gene_matrix>(X).packedMatrix(); } }; #endif <|endoftext|>
<commit_before>#include "ir.h" #include <numeric> #include <Eigen/Dense> TLANG_NAMESPACE_BEGIN class IRPrinter : public IRVisitor { public: int current_indent; IRPrinter() { current_indent = -1; } template <typename... Args> void print(std::string f, Args &&... args) { for (int i = 0; i < current_indent; i++) fmt::print(" "); fmt::print(f, std::forward<Args>(args)...); fmt::print("\n"); } static void run(IRNode *node) { auto p = IRPrinter(); node->accept(&p); } void visit(Block *stmt_list) { current_indent++; for (auto &stmt : stmt_list->statements) { stmt->accept(this); } current_indent--; } void visit(AssignStmt *assign) { print("{} = {}", assign->id.name(), assign->rhs->serialize()); } void visit(AllocaStmt *alloca) { print("{}alloca {}", alloca->type_hint(), alloca->ident.name()); } void visit(BinaryOpStmt *bin) { print("{}{} = {} {} {}", bin->type_hint(), bin->name(), binary_type_name(bin->op_type), bin->lhs->name(), bin->rhs->name()); } void visit(IfStmt *if_stmt) { print("if {} {{", if_stmt->condition->serialize()); if (if_stmt->true_statements) if_stmt->true_statements->accept(this); if (if_stmt->false_statements) { print("}} else {{"); if_stmt->false_statements->accept(this); } print("}}"); } void visit(FrontendPrintStmt *print_stmt) { print("print {}", print_stmt->expr.serialize()); } void visit(PrintStmt *print_stmt) { print("{}print {}", print_stmt->type_hint(), print_stmt->stmt->name()); } void visit(ConstStatement *const_stmt) { print("{}{} = const {}", const_stmt->type_hint(), const_stmt->name(), const_stmt->value); } void visit(ForStmt *for_stmt) { print("for {} in range({}, {}) {{", for_stmt->loop_var_id.name(), for_stmt->begin->serialize(), for_stmt->end->serialize()); for_stmt->body->accept(this); print("}}"); } void visit(LocalLoadStmt *stmt) { print("{}{} = load {}", stmt->type_hint(), stmt->name(), stmt->ident.name()); } void visit(LocalStoreStmt *stmt) { print("[store] {} = {}", stmt->ident.name(), stmt->stmt->name()); } }; class IRModifiedException {}; // Lower Expr tree to a bunch of binary/unary(binary/unary) statements // Goal: eliminate Expression, and mutable local variables. Make AST SSA. class LowerAST : public IRVisitor { public: LowerAST() { } // TODO: remove this /* VecStatement expand(ExprH expr) { auto ret = VecStatement(); expr->flatten(ret); return ret; } */ void visit(Block *stmt_list) { for (auto &stmt : stmt_list->statements) { stmt->accept(this); } } void visit(AllocaStmt *alloca) { // print("{} <- alloca {}", alloca->lhs.name(), // data_type_name(alloca->type)); } void visit(BinaryOpStmt *bin) { // this will not appear here } void visit(IfStmt *if_stmt) { if (if_stmt->true_statements) if_stmt->true_statements->accept(this); if (if_stmt->false_statements) { if_stmt->false_statements->accept(this); } } void visit(LocalLoadStmt *) { } void visit(LocalStoreStmt *) { } void visit(PrintStmt *stmt) { } void visit(FrontendPrintStmt *stmt) { // expand rhs auto expr = stmt->expr; VecStatement flattened; expr->flatten(flattened); auto print = std::make_unique<PrintStmt>(flattened.back().get()); flattened.push_back(std::move(print)); stmt->parent->replace_with(stmt, flattened); throw IRModifiedException(); } void visit(ConstStatement *const_stmt) { // this will not appear here } void visit(ForStmt *for_stmt) { for_stmt->body->accept(this); } void visit(AssignStmt *assign) { // expand rhs auto expr = assign->rhs; VecStatement flattened; expr->flatten(flattened); if (true) { // local variable // emit local store stmt auto local_store = std::make_unique<LocalStoreStmt>(assign->id, flattened.back().get()); flattened.push_back(std::move(local_store)); } else { // global variable } assign->parent->replace_with(assign, flattened); throw IRModifiedException(); } static void run(IRNode *node) { LowerAST inst; while (true) { bool modified = false; try { node->accept(&inst); } catch (IRModifiedException) { modified = true; } if (!modified) break; } } }; // Vector width, vectorization plan etc class PropagateSchedule : public IRVisitor {}; // "Type" here does not include vector width // Variable lookup and Type inference class TypeCheck : public IRVisitor { public: TypeCheck() { allow_undefined_visitor = true; } void visit(AllocaStmt *stmt) { auto block = stmt->parent; auto ident = stmt->ident; TC_ASSERT(block->local_variables.find(ident) == block->local_variables.end()); block->local_variables.insert(std::make_pair(ident, stmt->type)); } void visit(IfStmt *if_stmt) { if (if_stmt->true_statements) if_stmt->true_statements->accept(this); if (if_stmt->false_statements) { if_stmt->false_statements->accept(this); } } void visit(Block *stmt_list) { for (auto &stmt : stmt_list->statements) { stmt->accept(this); } } void visit(LocalLoadStmt *stmt) { auto block = stmt->parent; auto lookup = block->lookup_var(stmt->ident); stmt->type = lookup; } void visit(BinaryOpStmt *stmt) { TC_ASSERT(stmt->lhs->type != DataType::unknown || stmt->rhs->type != DataType::unknown); if (stmt->lhs->type == DataType::unknown && stmt->lhs->is<ConstStatement>()) { stmt->lhs->type = stmt->rhs->type; } if (stmt->rhs->type == DataType::unknown && stmt->rhs->is<ConstStatement>()) { stmt->rhs->type = stmt->lhs->type; } TC_ASSERT(stmt->lhs->type != DataType::unknown); TC_ASSERT(stmt->rhs->type != DataType::unknown); TC_ASSERT(stmt->lhs->type == stmt->rhs->type); stmt->type = stmt->lhs->type; } static void run(IRNode *node) { TypeCheck inst; node->accept(&inst); } }; #define declare(x) \ auto x = ExpressionHandle(std::make_shared<IdExpression>(#x)); #define var(type, x) Var<type>(x); auto test_ast = []() { CoreState::set_trigger_gdb_when_crash(true); declare(a); declare(b); declare(p); declare(q); declare(i); declare(j); var(float32, a); var(float32, b); var(int32, p); var(int32, q); a = a + b; p = p + q; Print(a); If(a < 500).Then([&] { Print(b); }).Else([&] { Print(a); }); If(a > 5) .Then([&] { b = (b + 1) / 3; b = b * 3; }) .Else([&] { b = b + 2; b = b - 4; }); For(i, 0, 100, [&] { For(j, 0, 200, [&] { ExprH k = i + j; Print(k); // While(k < 500, [&] { Print(k); }); }); }); Print(b); auto root = context.root(); TC_INFO("AST"); IRPrinter::run(root); LowerAST::run(root); TC_INFO("Lowered"); IRPrinter::run(root); TypeCheck::run(root); TC_INFO("TypeChecked"); IRPrinter::run(root); }; TC_REGISTER_TASK(test_ast); TLANG_NAMESPACE_END <commit_msg>visit for statement<commit_after>#include "ir.h" #include <numeric> #include <Eigen/Dense> TLANG_NAMESPACE_BEGIN class IRPrinter : public IRVisitor { public: int current_indent; IRPrinter() { current_indent = -1; } template <typename... Args> void print(std::string f, Args &&... args) { for (int i = 0; i < current_indent; i++) fmt::print(" "); fmt::print(f, std::forward<Args>(args)...); fmt::print("\n"); } static void run(IRNode *node) { auto p = IRPrinter(); node->accept(&p); } void visit(Block *stmt_list) { current_indent++; for (auto &stmt : stmt_list->statements) { stmt->accept(this); } current_indent--; } void visit(AssignStmt *assign) { print("{} = {}", assign->id.name(), assign->rhs->serialize()); } void visit(AllocaStmt *alloca) { print("{}alloca {}", alloca->type_hint(), alloca->ident.name()); } void visit(BinaryOpStmt *bin) { print("{}{} = {} {} {}", bin->type_hint(), bin->name(), binary_type_name(bin->op_type), bin->lhs->name(), bin->rhs->name()); } void visit(IfStmt *if_stmt) { print("if {} {{", if_stmt->condition->serialize()); if (if_stmt->true_statements) if_stmt->true_statements->accept(this); if (if_stmt->false_statements) { print("}} else {{"); if_stmt->false_statements->accept(this); } print("}}"); } void visit(FrontendPrintStmt *print_stmt) { print("print {}", print_stmt->expr.serialize()); } void visit(PrintStmt *print_stmt) { print("{}print {}", print_stmt->type_hint(), print_stmt->stmt->name()); } void visit(ConstStatement *const_stmt) { print("{}{} = const {}", const_stmt->type_hint(), const_stmt->name(), const_stmt->value); } void visit(ForStmt *for_stmt) { print("for {} in range({}, {}) {{", for_stmt->loop_var_id.name(), for_stmt->begin->serialize(), for_stmt->end->serialize()); for_stmt->body->accept(this); print("}}"); } void visit(LocalLoadStmt *stmt) { print("{}{} = load {}", stmt->type_hint(), stmt->name(), stmt->ident.name()); } void visit(LocalStoreStmt *stmt) { print("[store] {} = {}", stmt->ident.name(), stmt->stmt->name()); } }; class IRModifiedException {}; // Lower Expr tree to a bunch of binary/unary(binary/unary) statements // Goal: eliminate Expression, and mutable local variables. Make AST SSA. class LowerAST : public IRVisitor { public: LowerAST() { } // TODO: remove this /* VecStatement expand(ExprH expr) { auto ret = VecStatement(); expr->flatten(ret); return ret; } */ void visit(Block *stmt_list) { for (auto &stmt : stmt_list->statements) { stmt->accept(this); } } void visit(AllocaStmt *alloca) { // print("{} <- alloca {}", alloca->lhs.name(), // data_type_name(alloca->type)); } void visit(BinaryOpStmt *bin) { // this will not appear here } void visit(IfStmt *if_stmt) { if (if_stmt->true_statements) if_stmt->true_statements->accept(this); if (if_stmt->false_statements) { if_stmt->false_statements->accept(this); } } void visit(LocalLoadStmt *) { } void visit(LocalStoreStmt *) { } void visit(PrintStmt *stmt) { } void visit(FrontendPrintStmt *stmt) { // expand rhs auto expr = stmt->expr; VecStatement flattened; expr->flatten(flattened); auto print = std::make_unique<PrintStmt>(flattened.back().get()); flattened.push_back(std::move(print)); stmt->parent->replace_with(stmt, flattened); throw IRModifiedException(); } void visit(ConstStatement *const_stmt) { // this will not appear here } void visit(ForStmt *for_stmt) { for_stmt->body->accept(this); } void visit(AssignStmt *assign) { // expand rhs auto expr = assign->rhs; VecStatement flattened; expr->flatten(flattened); if (true) { // local variable // emit local store stmt auto local_store = std::make_unique<LocalStoreStmt>(assign->id, flattened.back().get()); flattened.push_back(std::move(local_store)); } else { // global variable } assign->parent->replace_with(assign, flattened); throw IRModifiedException(); } static void run(IRNode *node) { LowerAST inst; while (true) { bool modified = false; try { node->accept(&inst); } catch (IRModifiedException) { modified = true; } if (!modified) break; } } }; // Vector width, vectorization plan etc class PropagateSchedule : public IRVisitor {}; // "Type" here does not include vector width // Variable lookup and Type inference class TypeCheck : public IRVisitor { public: TypeCheck() { allow_undefined_visitor = true; } void visit(AllocaStmt *stmt) { auto block = stmt->parent; auto ident = stmt->ident; TC_ASSERT(block->local_variables.find(ident) == block->local_variables.end()); block->local_variables.insert(std::make_pair(ident, stmt->type)); } void visit(IfStmt *if_stmt) { if (if_stmt->true_statements) if_stmt->true_statements->accept(this); if (if_stmt->false_statements) { if_stmt->false_statements->accept(this); } } void visit(Block *stmt_list) { for (auto &stmt : stmt_list->statements) { stmt->accept(this); } } void visit(LocalLoadStmt *stmt) { auto block = stmt->parent; auto lookup = block->lookup_var(stmt->ident); stmt->type = lookup; } void visit(ForStmt *stmt) { auto block = stmt->parent; auto lookup = block->lookup_var(stmt->loop_var_id); TC_ASSERT(block->local_variables.find(stmt->loop_var_id) == block->local_variables.end()); block->local_variables.insert( std::make_pair(stmt->loop_var_id, DataType::i32)); stmt->body->accept(this); } void visit(BinaryOpStmt *stmt) { TC_ASSERT(stmt->lhs->type != DataType::unknown || stmt->rhs->type != DataType::unknown); if (stmt->lhs->type == DataType::unknown && stmt->lhs->is<ConstStatement>()) { stmt->lhs->type = stmt->rhs->type; } if (stmt->rhs->type == DataType::unknown && stmt->rhs->is<ConstStatement>()) { stmt->rhs->type = stmt->lhs->type; } TC_ASSERT(stmt->lhs->type != DataType::unknown); TC_ASSERT(stmt->rhs->type != DataType::unknown); TC_ASSERT(stmt->lhs->type == stmt->rhs->type); stmt->type = stmt->lhs->type; } static void run(IRNode *node) { TypeCheck inst; node->accept(&inst); } }; #define declare(x) \ auto x = ExpressionHandle(std::make_shared<IdExpression>(#x)); #define var(type, x) Var<type>(x); auto test_ast = []() { CoreState::set_trigger_gdb_when_crash(true); declare(a); declare(b); declare(p); declare(q); declare(i); declare(j); var(float32, a); var(float32, b); var(int32, p); var(int32, q); a = a + b; p = p + q; Print(a); If(a < 500).Then([&] { Print(b); }).Else([&] { Print(a); }); If(a > 5) .Then([&] { b = (b + 1) / 3; b = b * 3; }) .Else([&] { b = b + 2; b = b - 4; }); For(i, 0, 100, [&] { For(j, 0, 200, [&] { ExprH k = i + j; Print(k); // While(k < 500, [&] { Print(k); }); }); }); Print(b); auto root = context.root(); TC_INFO("AST"); IRPrinter::run(root); LowerAST::run(root); TC_INFO("Lowered"); IRPrinter::run(root); TypeCheck::run(root); TC_INFO("TypeChecked"); IRPrinter::run(root); }; TC_REGISTER_TASK(test_ast); TLANG_NAMESPACE_END <|endoftext|>
<commit_before>#include "common/PosixThreadImpl.h" extern "C" { void* rho_nativethread_start(); void rho_nativethread_end(void*); } namespace rho { namespace common { IMPLEMENT_LOGCLASS(CPosixThreadImpl, "RhoThread"); CPosixThreadImpl::CPosixThreadImpl() :m_stop_wait(false) { #if defined(OS_ANDROID) // Android has no pthread_condattr_xxx API pthread_cond_init(&m_condSync, NULL); #else pthread_condattr_t sync_details; pthread_condattr_init(&sync_details); pthread_cond_init(&m_condSync, &sync_details); pthread_condattr_destroy(&sync_details); #endif } CPosixThreadImpl::~CPosixThreadImpl() { pthread_cond_destroy(&m_condSync); } void *runProc(void *pv) { IRhoRunnable *p = static_cast<IRhoRunnable *>(pv); void *pData = rho_nativethread_start(); p->runObject(); rho_nativethread_end(pData); return 0; } void CPosixThreadImpl::start(IRhoRunnable *pRunnable, IRhoRunnable::EPriority ePriority) { pthread_attr_t attr; int return_val = pthread_attr_init(&attr); //return_val = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); RHO_ASSERT(!return_val); if ( ePriority != IRhoRunnable::epNormal) { sched_param param; return_val = pthread_attr_getschedparam (&attr, &param); param.sched_priority = ePriority == IRhoRunnable::epLow ? 20 : 100; //TODO: sched_priority return_val = pthread_attr_setschedparam (&attr, &param); } int thread_error = pthread_create(&m_thread, &attr, &runProc, pRunnable); return_val = pthread_attr_destroy(&attr); RHO_ASSERT(!return_val); RHO_ASSERT(thread_error==0); } void CPosixThreadImpl::stop(unsigned int nTimeoutToKill) { stopWait(); //TODO: wait for nTimeoutToKill and kill thread void* status; pthread_join(m_thread,&status); } void CPosixThreadImpl::wait(unsigned int nTimeout) { struct timespec ts; struct timeval tp; gettimeofday(&tp, NULL); /* Convert from timeval to timespec */ ts.tv_sec = tp.tv_sec; ts.tv_nsec = tp.tv_usec * 1000; unsigned long long max; bool timed_wait; if ( (unsigned)ts.tv_sec + nTimeout >= (unsigned)ts.tv_sec ) { timed_wait = true; ts.tv_sec += nTimeout; max = ((unsigned long long)tp.tv_sec + nTimeout)*1000000 + tp.tv_usec; } else timed_wait = false; common::CMutexLock oLock(m_mxSync); while (!m_stop_wait) { if (timed_wait) { pthread_cond_timedwait(&m_condSync, m_mxSync.getNativeMutex(), &ts); gettimeofday(&tp, NULL); unsigned long long now = ((unsigned long long)tp.tv_sec)*1000000 + tp.tv_usec; if (now > max) m_stop_wait = true; } else pthread_cond_wait(&m_condSync, m_mxSync.getNativeMutex()); } m_stop_wait = false; } void CPosixThreadImpl::sleep(unsigned int nTimeout) { ::usleep(1000*nTimeout); } void CPosixThreadImpl::stopWait() { common::CMutexLock oLock(m_mxSync); m_stop_wait = true; pthread_cond_broadcast(&m_condSync); } } // namespace common } // namespace rho <commit_msg>One more fix of posix thread wait implementation<commit_after>#include "common/PosixThreadImpl.h" extern "C" { void* rho_nativethread_start(); void rho_nativethread_end(void*); } namespace rho { namespace common { IMPLEMENT_LOGCLASS(CPosixThreadImpl, "RhoThread"); CPosixThreadImpl::CPosixThreadImpl() :m_stop_wait(false) { #if defined(OS_ANDROID) // Android has no pthread_condattr_xxx API pthread_cond_init(&m_condSync, NULL); #else pthread_condattr_t sync_details; pthread_condattr_init(&sync_details); pthread_cond_init(&m_condSync, &sync_details); pthread_condattr_destroy(&sync_details); #endif } CPosixThreadImpl::~CPosixThreadImpl() { pthread_cond_destroy(&m_condSync); } void *runProc(void *pv) { IRhoRunnable *p = static_cast<IRhoRunnable *>(pv); void *pData = rho_nativethread_start(); p->runObject(); rho_nativethread_end(pData); return 0; } void CPosixThreadImpl::start(IRhoRunnable *pRunnable, IRhoRunnable::EPriority ePriority) { pthread_attr_t attr; int return_val = pthread_attr_init(&attr); //return_val = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); RHO_ASSERT(!return_val); if ( ePriority != IRhoRunnable::epNormal) { sched_param param; return_val = pthread_attr_getschedparam (&attr, &param); param.sched_priority = ePriority == IRhoRunnable::epLow ? 20 : 100; //TODO: sched_priority return_val = pthread_attr_setschedparam (&attr, &param); } int thread_error = pthread_create(&m_thread, &attr, &runProc, pRunnable); return_val = pthread_attr_destroy(&attr); RHO_ASSERT(!return_val); RHO_ASSERT(thread_error==0); } void CPosixThreadImpl::stop(unsigned int nTimeoutToKill) { stopWait(); //TODO: wait for nTimeoutToKill and kill thread void* status; pthread_join(m_thread,&status); } void CPosixThreadImpl::wait(unsigned int nTimeout) { struct timeval tp; struct timespec ts; unsigned long long max; bool timed_wait = (int)nTimeout >= 0; if (timed_wait) { gettimeofday(&tp, NULL); /* Convert from timeval to timespec */ ts.tv_sec = tp.tv_sec; ts.tv_nsec = tp.tv_usec * 1000; ts.tv_sec += nTimeout; max = ((unsigned long long)tp.tv_sec + nTimeout)*1000000 + tp.tv_usec; } common::CMutexLock oLock(m_mxSync); while (!m_stop_wait) { if (timed_wait) { gettimeofday(&tp, NULL); unsigned long long now = ((unsigned long long)tp.tv_sec)*1000000 + tp.tv_usec; if (now > max) break; pthread_cond_timedwait(&m_condSync, m_mxSync.getNativeMutex(), &ts); } else pthread_cond_wait(&m_condSync, m_mxSync.getNativeMutex()); } m_stop_wait = false; } void CPosixThreadImpl::sleep(unsigned int nTimeout) { ::usleep(1000*nTimeout); } void CPosixThreadImpl::stopWait() { common::CMutexLock oLock(m_mxSync); m_stop_wait = true; pthread_cond_broadcast(&m_condSync); } } // namespace common } // namespace rho <|endoftext|>
<commit_before>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Benchmark.h" #include "SkCanvas.h" #include "SkMatrixConvolutionImageFilter.h" #include "SkPaint.h" #include "SkRandom.h" #include "SkString.h" class MatrixConvolutionBench : public Benchmark { public: MatrixConvolutionBench(SkMatrixConvolutionImageFilter::TileMode tileMode, bool convolveAlpha) : fName("matrixconvolution") { SkISize kernelSize = SkISize::Make(3, 3); SkScalar kernel[9] = { SkIntToScalar( 1), SkIntToScalar( 1), SkIntToScalar( 1), SkIntToScalar( 1), SkIntToScalar(-7), SkIntToScalar( 1), SkIntToScalar( 1), SkIntToScalar( 1), SkIntToScalar( 1), }; SkScalar gain = 0.3f, bias = SkIntToScalar(100); SkIPoint kernelOffset = SkIPoint::Make(1, 1); fFilter = SkMatrixConvolutionImageFilter::Make(kernelSize, kernel, gain, bias, kernelOffset, tileMode, convolveAlpha, nullptr); } protected: virtual const char* onGetName() { return fName.c_str(); } virtual void onDraw(int loops, SkCanvas* canvas) { SkPaint paint; this->setupPaint(&paint); paint.setAntiAlias(true); SkRandom rand; for (int i = 0; i < loops; i++) { SkRect r = SkRect::MakeWH(rand.nextUScalar1() * 400, rand.nextUScalar1() * 400); paint.setImageFilter(fFilter); canvas->drawOval(r, paint); } } private: sk_sp<SkImageFilter> fFilter; SkString fName; typedef Benchmark INHERITED; }; DEF_BENCH( return new MatrixConvolutionBench(SkMatrixConvolutionImageFilter::kClamp_TileMode, true); ) DEF_BENCH( return new MatrixConvolutionBench(SkMatrixConvolutionImageFilter::kRepeat_TileMode, true); ) DEF_BENCH( return new MatrixConvolutionBench(SkMatrixConvolutionImageFilter::kClampToBlack_TileMode, true); ) DEF_BENCH( return new MatrixConvolutionBench(SkMatrixConvolutionImageFilter::kClampToBlack_TileMode, false); ) <commit_msg>distinguish distinct matrixconvolution benchmarks<commit_after>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Benchmark.h" #include "SkCanvas.h" #include "SkMatrixConvolutionImageFilter.h" #include "SkPaint.h" #include "SkRandom.h" #include "SkString.h" static const char* name(SkMatrixConvolutionImageFilter::TileMode mode) { switch (mode) { case SkMatrixConvolutionImageFilter::kClamp_TileMode: return "clamp"; case SkMatrixConvolutionImageFilter::kRepeat_TileMode: return "repeat"; case SkMatrixConvolutionImageFilter::kClampToBlack_TileMode: return "clampToBlack"; } return "oops"; } class MatrixConvolutionBench : public Benchmark { public: MatrixConvolutionBench(SkMatrixConvolutionImageFilter::TileMode tileMode, bool convolveAlpha) : fName(SkStringPrintf("matrixconvolution_%s%s", name(tileMode), convolveAlpha ? "" : "_noConvolveAlpha")) { SkISize kernelSize = SkISize::Make(3, 3); SkScalar kernel[9] = { SkIntToScalar( 1), SkIntToScalar( 1), SkIntToScalar( 1), SkIntToScalar( 1), SkIntToScalar(-7), SkIntToScalar( 1), SkIntToScalar( 1), SkIntToScalar( 1), SkIntToScalar( 1), }; SkScalar gain = 0.3f, bias = SkIntToScalar(100); SkIPoint kernelOffset = SkIPoint::Make(1, 1); fFilter = SkMatrixConvolutionImageFilter::Make(kernelSize, kernel, gain, bias, kernelOffset, tileMode, convolveAlpha, nullptr); } protected: virtual const char* onGetName() { return fName.c_str(); } virtual void onDraw(int loops, SkCanvas* canvas) { SkPaint paint; this->setupPaint(&paint); paint.setAntiAlias(true); SkRandom rand; for (int i = 0; i < loops; i++) { SkRect r = SkRect::MakeWH(rand.nextUScalar1() * 400, rand.nextUScalar1() * 400); paint.setImageFilter(fFilter); canvas->drawOval(r, paint); } } private: sk_sp<SkImageFilter> fFilter; SkString fName; typedef Benchmark INHERITED; }; DEF_BENCH( return new MatrixConvolutionBench(SkMatrixConvolutionImageFilter::kClamp_TileMode, true); ) DEF_BENCH( return new MatrixConvolutionBench(SkMatrixConvolutionImageFilter::kRepeat_TileMode, true); ) DEF_BENCH( return new MatrixConvolutionBench(SkMatrixConvolutionImageFilter::kClampToBlack_TileMode, true); ) DEF_BENCH( return new MatrixConvolutionBench(SkMatrixConvolutionImageFilter::kClampToBlack_TileMode, false); ) <|endoftext|>
<commit_before>// Seek Thermal Viewer/Streamer // http://github.com/fnoop/maverick #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "seek.h" #include "SeekCam.h" #include <iostream> #include <string> #include <signal.h> #include <memory> #include "args.h" using namespace cv; using namespace LibSeek; // Setup sig handling static volatile sig_atomic_t sigflag = 0; void handle_sig(int sig) { sigflag = 1; } // Function to process a raw (corrected) seek frame void process_frame(Mat &inframe, Mat &outframe, float scale, int colormap, int rotate) { Mat frame_g8, frame_g16; // Transient Mat containers for processing normalize(inframe, frame_g16, 0, 65535, NORM_MINMAX); // Convert seek CV_16UC1 to CV_8UC1 frame_g8 = frame_g16; frame_g8.convertTo( frame_g8, CV_8UC1, 1.0/256.0 ); // Rotate image if (rotate == 90) { transpose(frame_g8, frame_g8); flip(frame_g8, frame_g8, 1); } else if (rotate == 180) { flip(frame_g8, frame_g8, -1); } else if (rotate == 270) { transpose(frame_g8, frame_g8); flip(frame_g8, frame_g8, 0); } // Resize image: http://docs.opencv.org/3.2.0/da/d54/group__imgproc__transform.html#ga5bb5a1fea74ea38e1a5445ca803ff121 // Note this is expensive computationally, only do if option set != 1 if (scale != 1.0) resize(frame_g8, frame_g8, Size(), scale, scale, INTER_LINEAR); // Apply colormap: http://docs.opencv.org/3.2.0/d3/d50/group__imgproc__colormap.html#ga9a805d8262bcbe273f16be9ea2055a65 if (colormap != -1) { applyColorMap(frame_g8, outframe, colormap); } else { outframe = frame_g8; } } int main(int argc, char** argv) { // Setup arguments for parser args::ArgumentParser parser("Seek Thermal Viewer"); args::HelpFlag help(parser, "help", "Display this help menu", {'h', "help"}); args::ValueFlag<string> _output(parser, "output", "Output Stream - name of the video file to write", {'o', "output"}); args::ValueFlag<int> _fps(parser, "fps", "Video Output FPS - Kludge factor", {'f', "fps"}); args::ValueFlag<float> _scale(parser, "scaling", "Output Scaling - multiple of original image", {'s', "scale"}); args::ValueFlag<int> _colormap(parser, "colormap", "Color Map - number between 0 and 12", {'c', "colormap"}); args::ValueFlag<int> _rotate(parser, "rotate", "Rotation - 0, 90, 180 or 270 (default) degrees", {'r', "rotate"}); args::ValueFlag<string> _camtype(parser, "camtype", "Seek Thermal Camera Model - seek or seekpro", {'t', "camtype"}); // Parse arguments try { parser.ParseCLI(argc, argv); } catch (args::Help) { std::cout << parser; return 0; } catch (args::ParseError e) { std::cerr << e.what() << std::endl; std::cerr << parser; return 1; } catch (args::ValidationError e) { std::cerr << e.what() << std::endl; std::cerr << parser; return 1; } float scale = 1.0; if (_scale) scale = args::get(_scale); string output = "window"; if (_output) output = args::get(_output); string camtype = "seek"; if (_camtype) camtype = args::get(_camtype); // 7fps seems to be about what you get from a seek thermal compact // Note: fps doesn't influence how often frames are processed, just the VideoWriter interpolation int fps = 7; if (_fps) fps = args::get(_fps); // Colormap int corresponding to enum: http://docs.opencv.org/3.2.0/d3/d50/group__imgproc__colormap.html int colormap = -1; if (_colormap) colormap = args::get(_colormap); // Rotate default is landscape view to match camera logo/markings int rotate = 270; if (_rotate) rotate = args::get(_rotate); // Register signals signal(SIGINT, handle_sig); signal(SIGTERM, handle_sig); // Setup seek camera LibSeek::SeekCam* seek; LibSeek::SeekThermalPro seekpro; LibSeek::SeekThermal seekclassic; if (camtype == "seekpro") seek = &seekpro; else seek = &seekclassic; if (!seek->open()) { cout << "Error accessing camera" << endl; return 1; } // Mat containers for seek frames Mat seekframe, outframe; // Retrieve a single frame, resize to requested scaling value and then determine size of matrix // so we can size the VideoWriter stream correctly seek->retrieve(seekframe); process_frame(seekframe, outframe, scale, colormap, rotate); // Create an output object, if output specified then setup the pipeline unless output is set to 'window' VideoWriter writer; if (output != "window") { writer.open(output, 0, fps, Size(outframe.cols, outframe.rows), true); if (!writer.isOpened()) { cerr << "Error can't create video writer" << endl; return 1; } else { cout << "Video stream created, dimension: " << outframe.cols << "x" << outframe.rows << ", fps:" << fps << endl; } } // Main loop to retrieve frames from camera and output while (true) { // If signal for interrupt/termination was received, break out of main loop and exit if (sigflag || !seek->grab()) { if (!seek->grab()) cout << "No more frames from camera, exiting" << endl; if (sigflag) cout << "Break signal detected, exiting" << endl; break; } // Retrieve frame from seek and process seek->retrieve(seekframe); process_frame(seekframe, outframe, scale, colormap, rotate); if (output == "window") { imshow("SeekThermal", outframe); char c = waitKey(10); if (c == 's') { waitKey(0); } } else { writer << outframe; } } } <commit_msg>Added flat field calibration support to seek_viewer util<commit_after>// Seek Thermal Viewer/Streamer // http://github.com/fnoop/maverick #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "seek.h" #include "SeekCam.h" #include <iostream> #include <string> #include <signal.h> #include <memory> #include "args.h" using namespace cv; using namespace LibSeek; // Setup sig handling static volatile sig_atomic_t sigflag = 0; void handle_sig(int sig) { sigflag = 1; } // Function to process a raw (corrected) seek frame void process_frame(Mat &inframe, Mat &outframe, float scale, int colormap, int rotate) { Mat frame_g8, frame_g16; // Transient Mat containers for processing normalize(inframe, frame_g16, 0, 65535, NORM_MINMAX); // Convert seek CV_16UC1 to CV_8UC1 frame_g8 = frame_g16; frame_g8.convertTo( frame_g8, CV_8UC1, 1.0/256.0 ); // Rotate image if (rotate == 90) { transpose(frame_g8, frame_g8); flip(frame_g8, frame_g8, 1); } else if (rotate == 180) { flip(frame_g8, frame_g8, -1); } else if (rotate == 270) { transpose(frame_g8, frame_g8); flip(frame_g8, frame_g8, 0); } // Resize image: http://docs.opencv.org/3.2.0/da/d54/group__imgproc__transform.html#ga5bb5a1fea74ea38e1a5445ca803ff121 // Note this is expensive computationally, only do if option set != 1 if (scale != 1.0) resize(frame_g8, frame_g8, Size(), scale, scale, INTER_LINEAR); // Apply colormap: http://docs.opencv.org/3.2.0/d3/d50/group__imgproc__colormap.html#ga9a805d8262bcbe273f16be9ea2055a65 if (colormap != -1) { applyColorMap(frame_g8, outframe, colormap); } else { outframe = frame_g8; } } int main(int argc, char** argv) { // Setup arguments for parser args::ArgumentParser parser("Seek Thermal Viewer"); args::HelpFlag help(parser, "help", "Display this help menu", {'h', "help"}); args::ValueFlag<string> _output(parser, "output", "Output Stream - name of the video file to write", {'o', "output"}); args::ValueFlag<string> _ffc(parser, "ffc", "Additional Flat Field calibration - provide ffc file", {'c', "calffc"}); args::ValueFlag<int> _fps(parser, "fps", "Video Output FPS - Kludge factor", {'f', "fps"}); args::ValueFlag<float> _scale(parser, "scaling", "Output Scaling - multiple of original image", {'s', "scale"}); args::ValueFlag<int> _colormap(parser, "colormap", "Color Map - number between 0 and 12", {'c', "colormap"}); args::ValueFlag<int> _rotate(parser, "rotate", "Rotation - 0, 90, 180 or 270 (default) degrees", {'r', "rotate"}); args::ValueFlag<string> _camtype(parser, "camtype", "Seek Thermal Camera Model - seek or seekpro", {'t', "camtype"}); // Parse arguments try { parser.ParseCLI(argc, argv); } catch (args::Help) { std::cout << parser; return 0; } catch (args::ParseError e) { std::cerr << e.what() << std::endl; std::cerr << parser; return 1; } catch (args::ValidationError e) { std::cerr << e.what() << std::endl; std::cerr << parser; return 1; } float scale = 1.0; if (_scale) scale = args::get(_scale); string output = "window"; if (_output) output = args::get(_output); string camtype = "seek"; if (_camtype) camtype = args::get(_camtype); // 7fps seems to be about what you get from a seek thermal compact // Note: fps doesn't influence how often frames are processed, just the VideoWriter interpolation int fps = 7; if (_fps) fps = args::get(_fps); // Colormap int corresponding to enum: http://docs.opencv.org/3.2.0/d3/d50/group__imgproc__colormap.html int colormap = -1; if (_colormap) colormap = args::get(_colormap); // Rotate default is landscape view to match camera logo/markings int rotate = 270; if (_rotate) rotate = args::get(_rotate); // Register signals signal(SIGINT, handle_sig); signal(SIGTERM, handle_sig); // Setup seek camera LibSeek::SeekCam* seek; LibSeek::SeekThermalPro seekpro(args::get(_ffc)); LibSeek::SeekThermal seekclassic(args::get(_ffc)); if (camtype == "seekpro") seek = &seekpro; else seek = &seekclassic; if (!seek->open()) { cout << "Error accessing camera" << endl; return 1; } // Mat containers for seek frames Mat seekframe, outframe; // Retrieve a single frame, resize to requested scaling value and then determine size of matrix // so we can size the VideoWriter stream correctly seek->retrieve(seekframe); process_frame(seekframe, outframe, scale, colormap, rotate); // Create an output object, if output specified then setup the pipeline unless output is set to 'window' VideoWriter writer; if (output != "window") { writer.open(output, 0, fps, Size(outframe.cols, outframe.rows), true); if (!writer.isOpened()) { cerr << "Error can't create video writer" << endl; return 1; } else { cout << "Video stream created, dimension: " << outframe.cols << "x" << outframe.rows << ", fps:" << fps << endl; } } // Main loop to retrieve frames from camera and output while (true) { // If signal for interrupt/termination was received, break out of main loop and exit if (sigflag || !seek->grab()) { if (!seek->grab()) cout << "No more frames from camera, exiting" << endl; if (sigflag) cout << "Break signal detected, exiting" << endl; break; } // Retrieve frame from seek and process seek->retrieve(seekframe); process_frame(seekframe, outframe, scale, colormap, rotate); if (output == "window") { imshow("SeekThermal", outframe); char c = waitKey(10); if (c == 's') { waitKey(0); } } else { writer << outframe; } } } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <string.h> #include <cstring> #include <wait.h> #include <vector> #include <fcntl.h> #include <cstdlib> #include <errno.h> #include <sys/stat.h> #include <boost/algorithm/string/trim.hpp> #include <boost/algorithm/string.hpp> using namespace std; using namespace boost; void execfunction(char **argv, string command) { int pid = fork(); if(-1 == pid) { perror("There was an error with fork(). "); } else if(pid == 0) { if(-1 == execvp(command.c_str(), argv)) { perror("There was an error with execvp() "); exit(1); } _exit(0); } else { int status; wait(&status); if(-1 == status) { perror("There was an error with wait(). "); } } } int main() { int savestdout; if(-1 == (savestdout = dup(1))) { perror("There was an error with dup(). "); } if(-1 == close(1)) { perror("There was an error with close(). "); } vector<string> branches; //call execvp to run git branch string file_name = "tempfile"; int write_to; char **argv = new char*[3]; argv[0] = const_cast<char*>("git"); argv[1] = const_cast<char*>("branch"); argv[2] = 0; if(-1 == (write_to = open(file_name.c_str() , O_CREAT | O_WRONLY | O_APPEND | O_TRUNC, S_IRUSR | S_IWUSR))) { perror("There was an error with open(). "); exit(1); } execfunction(argv, "git"); delete []argv; if(-1 == close(write_to)) { perror("There was an error with close(). "); } if(-1 == dup2(savestdout, 1)) { perror("There was an error with dup2(). "); } int read_from; if(-1 == (read_from = open(file_name.c_str(), O_RDONLY))) { perror("There was an error with open(). "); } int size; char c[BUFSIZ]; if(-1 == (size = read(read_from, &c, BUFSIZ))) { perror("There was an error with read(). "); } while(size > 0) { branches.push_back(string(c)); if(-1 == (size = read(read_from, &c, BUFSIZ))) { perror("There was an error with read(). "); } } if(-1 == close(read_from)) { perror("There was an error with close(). "); } //take all branch names and put into vector //for each branch name, call execvp git checkout branchname for(unsigned int i = 0; i < branches.size(); ++i) { branches.at(i) = (branches.at(i)).substr(2, (branches.at(i)).size()-3); cout << branches.at(i) << endl; } argv = new char*[3]; argv[0] = const_cast<char*>("rm"); argv[1] = const_cast<char*>(file_name.c_str()); argv[2] = 0; execfunction(argv, "rm"); delete []argv; //then open/create a file called branchname for whatever branch we are on for(unsigned int i = 0; i < branches.size(); ++i) { } //then call execvp git log to have all the output go to file //close file //reopen stdout return 0; } <commit_msg>creates files for each branch and puts in the commit history in there<commit_after>#include <iostream> #include <string> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <string.h> #include <cstring> #include <wait.h> #include <vector> #include <fcntl.h> #include <cstdlib> #include <errno.h> #include <sys/stat.h> #include <boost/algorithm/string/trim.hpp> #include <boost/algorithm/string.hpp> using namespace std; using namespace boost; void execfunction(char **argv, string command) { int pid = fork(); if(-1 == pid) { perror("There was an error with fork(). "); } else if(pid == 0) { if(-1 == execvp(command.c_str(), argv)) { perror("There was an error with execvp() "); exit(1); } _exit(0); } else { int status; wait(&status); if(-1 == status) { perror("There was an error with wait(). "); } } } int main() { int savestdout; if(-1 == (savestdout = dup(1))) { perror("There was an error with dup(). "); } if(-1 == close(1)) { perror("There was an error with close(). "); } vector<string> branches; //call execvp to run git branch string file_name = "tempfile"; int write_to; char **argv = new char*[3]; argv[0] = const_cast<char*>("git"); argv[1] = const_cast<char*>("branch"); argv[2] = 0; if(-1 == (write_to = open(file_name.c_str() , O_CREAT | O_WRONLY | O_APPEND | O_TRUNC, S_IRUSR | S_IWUSR))) { perror("There was an error with open(). "); exit(1); } execfunction(argv, "git"); delete []argv; if(-1 == close(write_to)) { perror("There was an error with close(). "); } if(-1 == dup2(savestdout, 1)) { perror("There was an error with dup2(). "); } int read_from; if(-1 == (read_from = open(file_name.c_str(), O_RDONLY))) { perror("There was an error with open(). "); } int size; char c[BUFSIZ]; if(-1 == (size = read(read_from, &c, BUFSIZ))) { perror("There was an error with read(). "); } while(size > 0) { branches.push_back(string(c)); if(-1 == (size = read(read_from, &c, BUFSIZ))) { perror("There was an error with read(). "); } } if(-1 == close(read_from)) { perror("There was an error with close(). "); } //take all branch names and put into vector //for each branch name, call execvp git checkout branchname for(unsigned int i = 0; i < branches.size(); ++i) { branches.at(i) = (branches.at(i)).substr(2, (branches.at(i)).size()-3); cout << branches.at(i) << endl; } argv = new char*[3]; argv[0] = const_cast<char*>("rm"); argv[1] = const_cast<char*>(file_name.c_str()); argv[2] = 0; execfunction(argv, "rm"); delete []argv; //then open/create a file called branchname for whatever branch we are on if(-1 == (savestdout = dup(1))) { perror("There was an error with dup(). "); } if(-1 == close(1)) { perror("There was an error with close(). "); } for(unsigned int i = 0; i < branches.size(); ++i) { argv = new char*[4]; argv[0] = const_cast<char*>("git"); argv[1] = const_cast<char*>("checkout"); argv[2] = const_cast<char*>((branches.at(i)).c_str()); argv[3] = 0; execfunction(argv, "git"); delete []argv; string name = branches.at(i); name += "Branch"; if(-1 == (write_to = open(name.c_str() , O_CREAT | O_WRONLY | O_APPEND | O_TRUNC, S_IRUSR | S_IWUSR))) { perror("There was an error with open(). "); exit(1); } argv = new char*[3]; argv[0] = const_cast<char*>("git"); argv[1] = const_cast<char*>("log"); argv[2] = 0; execfunction(argv, "git"); delete []argv; if(-1 == close(write_to)) { perror("There was an error with close(). "); } } if(-1 == dup2(savestdout, 1)) { perror("There was an error with dup2(). "); } argv = new char*[4]; argv[0] = const_cast<char*>("git"); argv[1] = const_cast<char*>("checkout"); argv[2] = const_cast<char*>("master"); argv[3] = 0; execfunction(argv, "git"); delete []argv; //then call execvp git log to have all the output go to file //close file return 0; } <|endoftext|>
<commit_before> #include "loop.h" #include "kscreen.h" #include "config.h" #include "output.h" #include "mode.h" #include <QX11Info> #include <QtCore/QDebug> #include <X11/X.h> #include <X11/Xlib.h> #include <X11/extensions/Xrandr.h> Loop::Loop(QObject* parent): QObject(parent) { QMetaObject::invokeMethod(this, "start"); } Loop::~Loop() { } void Loop::start() { qDebug() << "START"; KScreen* screen = KScreen::self(); Config* config = screen->config(); Time time; { XRRScreenResources* r = XRRGetScreenResources(QX11Info::display(), XRootWindow(QX11Info::display(), 0)); qDebug() << "RTime: " << r->timestamp; } qDebug() << "Time: " << XRRTimes(QX11Info::display(), 0, &time); qDebug() << "Time: " << time; // config->outputs()[65]->setEnabled(true); // config->outputs()[65]->setPos(QPoint(0,0)); // config->outputs()[65]->setPrimary(false); // config->outputs()[65]->setCurrentMode(70); // config->outputs()[68]->setEnabled(true); // config->outputs()[68]->setCurrentMode(70); config->outputs()[68]->setPos(QPoint(1920, 0)); // config->outputs()[68]->setPrimary(true); qDebug() << "Setting config"; screen->setConfig(config); qDebug() << "setted"; XRRScreenResources* r = XRRGetScreenResources(QX11Info::display(), XRootWindow(QX11Info::display(), 0)); qDebug() << "RTime: " << r->timestamp; qDebug() << "Time: " << XRRTimes(QX11Info::display(), 0, &time); qDebug() << "Time: " << time; printConfig(); } void Loop::printConfig() { KScreen *screen = KScreen::self(); qDebug() << "Backend: " << screen->backend(); Config *config = screen->config(); OutputList outputs = config->outputs(); OutputList outputEnabled; Q_FOREACH(Output *output, outputs) { qDebug() << "Id: " << output->id(); qDebug() << "Name: " << output->name(); qDebug() << "Type: " << output->type(); qDebug() << "Connected: " << output->isConnected(); qDebug() << "Enabled: " << output->isEnabled(); qDebug() << "Primary: " << output->isPrimary(); qDebug() << "Pos: " << output->pos(); if (output->currentMode()) { qDebug() << "Size: " << output->mode(output->currentMode())->size(); } qDebug() << "Clones: " << output->clones().isEmpty(); qDebug() << "Mode: " << output->currentMode(); qDebug() << "Modes: "; ModeList modes = output->modes(); Q_FOREACH(Mode* mode, modes) { qDebug() << "\t" << mode->id() << " " << mode->name() << " " << mode->size() << " " << mode->refreshRate(); } if (output->isEnabled()) { outputEnabled.insert(output->id(), output); } qDebug() << "\n==================================================\n"; } } #include <loop.moc><commit_msg>QRandR removed, KScreen::config is working, setConfig yet to be ported<commit_after> #include "loop.h" #include "kscreen.h" #include "config.h" #include "output.h" #include "mode.h" #include <QX11Info> #include <QtCore/QDebug> #include <X11/X.h> #include <X11/Xlib.h> #include <X11/extensions/Xrandr.h> Loop::Loop(QObject* parent): QObject(parent) { QMetaObject::invokeMethod(this, "start"); } Loop::~Loop() { } void Loop::start() { qDebug() << "START"; // /*KScreen* screen = KScreen::self(); // Config* config = screen->config(); // Time time; // { // XRRScreenResources* r = XRRGetScreenResources(QX11Info::display(), XRootWindow(QX11Info::display(), 0)); // qDebug() << "RTime: " << r->timestamp; // } // qDebug() << "Time: " << XRRTimes(QX11Info::display(), 0, &time); // qDebug() << "Time: " << time; // // config->outputs()[65]->setEnabled(true); // // config->outputs()[65]->setPos(QPoint(0,0)); // // config->outputs()[65]->setPrimary(false); // // // config->outputs()[65]->setCurrentMode(70); // // // config->outputs()[68]->setEnabled(true); // // config->outputs()[68]->setCurrentMode(70); // config->outputs()[68]->setPos(QPoint(1920, 0)); // // config->outputs()[68]->setPrimary(true); // qDebug() << "Setting config"; // screen->setConfig(config); // qDebug() << "setted"; // XRRScreenResources* r = XRRGetScreenResources(QX11Info::display(), XRootWindow(QX11Info::display(), 0)); // qDebug() << "RTime: " << r->timestamp; // qDebug() << "Time: " << XRRTimes(QX11Info::display(), 0, &time); // qDebug() << "Time: " << time;*/ printConfig(); } void Loop::printConfig() { KScreen *screen = KScreen::self(); qDebug() << "Backend: " << screen->backend(); Config *config = screen->config(); OutputList outputs = config->outputs(); OutputList outputEnabled; Q_FOREACH(Output *output, outputs) { qDebug() << "Id: " << output->id(); qDebug() << "Name: " << output->name(); qDebug() << "Type: " << output->type(); qDebug() << "Connected: " << output->isConnected(); qDebug() << "Enabled: " << output->isEnabled(); qDebug() << "Primary: " << output->isPrimary(); qDebug() << "Pos: " << output->pos(); if (output->currentMode()) { qDebug() << "Size: " << output->mode(output->currentMode())->size(); } qDebug() << "Clones: " << output->clones().isEmpty(); qDebug() << "Mode: " << output->currentMode(); qDebug() << "Modes: "; ModeList modes = output->modes(); Q_FOREACH(Mode* mode, modes) { qDebug() << "\t" << mode->id() << " " << mode->name() << " " << mode->size() << " " << mode->refreshRate(); } if (output->isEnabled()) { outputEnabled.insert(output->id(), output); } qDebug() << "\n==================================================\n"; } } #include <loop.moc><|endoftext|>
<commit_before> #include "../../Flare.h" #include "FlareSubsystemStatus.h" #include "../Components/FlareRoundButton.h" #include "../../Spacecrafts/FlareWeapon.h" #include "../../Spacecrafts/FlareSpacecraft.h" #define LOCTEXT_NAMESPACE "FlareSubsystemStatus" /*---------------------------------------------------- Construct ----------------------------------------------------*/ void SFlareSubsystemStatus::Construct(const FArguments& InArgs) { // Args TargetShip = NULL; TargetComponent = NULL; SubsystemType = InArgs._Subsystem; // Settings Health = 1.0f; ComponentHealth = 0.0f; HealthDropFlashTime = 2.0f; TimeSinceFlash = HealthDropFlashTime; const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); // Icon const FSlateBrush* Icon = NULL; switch (SubsystemType) { case EFlareSubsystem::SYS_Temperature: Icon = FFlareStyleSet::GetIcon("HUD_Temperature"); break; case EFlareSubsystem::SYS_Propulsion: Icon = FFlareStyleSet::GetIcon("HUD_Propulsion"); break; case EFlareSubsystem::SYS_RCS: Icon = FFlareStyleSet::GetIcon("HUD_RCS"); break; case EFlareSubsystem::SYS_LifeSupport: Icon = FFlareStyleSet::GetIcon("HUD_LifeSupport"); break; case EFlareSubsystem::SYS_Power: Icon = FFlareStyleSet::GetIcon("HUD_Power"); break; case EFlareSubsystem::SYS_Weapon: Icon = FFlareStyleSet::GetIcon("HUD_Shell"); break; } // Structure ChildSlot .VAlign(VAlign_Top) .HAlign(HAlign_Center) [ SNew(SFlareRoundButton) .Clickable(false) .Icon(Icon) .Text(this, &SFlareSubsystemStatus::GetText) .HelpText(this, &SFlareSubsystemStatus::GetInfoText) .HighlightColor(this, &SFlareSubsystemStatus::GetHealthColor) .TextColor(this, &SFlareSubsystemStatus::GetFlashColor) ]; } /*---------------------------------------------------- Interaction ----------------------------------------------------*/ void SFlareSubsystemStatus::SetTargetShip(IFlareSpacecraftInterface* Target) { TargetShip = Target; } void SFlareSubsystemStatus::SetTargetComponent(UFlareSpacecraftComponent* Target) { TargetComponent = Target; } /*---------------------------------------------------- Callbacks ----------------------------------------------------*/ void SFlareSubsystemStatus::Tick(const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime) { SCompoundWidget::Tick(AllottedGeometry, InCurrentTime, InDeltaTime); if (TargetShip) { // Update health float NewHealth = TargetShip->GetDamageSystem()->GetSubsystemHealth(SubsystemType, true, false); ComponentHealth = TargetShip->GetDamageSystem()->GetSubsystemHealth(SubsystemType); // Update flash TimeSinceFlash += InDeltaTime; if (NewHealth < 0.98 * Health) { TimeSinceFlash = 0; Health = NewHealth; } } else { Health = 1; } } FText SFlareSubsystemStatus::GetText() const { return FText::Format(LOCTEXT("SubsystemInfoFormat", "{0}\n{1}%"), IFlareSpacecraftDamageSystemInterface::GetSubsystemName(SubsystemType), FText::AsNumber(100 * ComponentHealth)); } FText SFlareSubsystemStatus::GetInfoText() const { FText Text; switch (SubsystemType) { case EFlareSubsystem::SYS_Temperature: Text = LOCTEXT("SYS_TemperatureInfo", "The cooling subsystem ensures that your ship doesn't overheat and burn."); break; case EFlareSubsystem::SYS_Propulsion: Text = LOCTEXT("SYS_PropulsionInfo", "Orbital engines are required for orbital travel and can be used in combat to boost the spacecraft. They produce a lot of heat."); break; case EFlareSubsystem::SYS_RCS: Text = LOCTEXT("SYS_RCSInfo", "The Reaction Control System is responsible for moving and turning the ship around in space. They produce little heat."); break; case EFlareSubsystem::SYS_LifeSupport: Text = LOCTEXT("SYS_LifeSupportInfo", "The life support system needs to stay intact and powered in order for the crew to survive."); break; case EFlareSubsystem::SYS_Power: Text = LOCTEXT("SYS_PowerInfo", "The power subsystem feeds energy to every system on your ship, including propulsion, weapons or life support."); break; case EFlareSubsystem::SYS_Weapon: Text = LOCTEXT("SYS_WeaponInfo", "Weapons can be used to damage other spacecrafts. They produce a lot of heat."); break; } return Text; } FSlateColor SFlareSubsystemStatus::GetHealthColor() const { return FFlareStyleSet::GetHealthColor(ComponentHealth, false); } FSlateColor SFlareSubsystemStatus::GetFlashColor() const { const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); FLinearColor NormalColor = Theme.NeutralColor; FLinearColor DamageColor = Theme.EnemyColor; FLinearColor Color = FMath::Lerp(DamageColor, NormalColor, FMath::Clamp(TimeSinceFlash / HealthDropFlashTime, 0.0f, 1.0f)); Color.A *= Theme.DefaultAlpha; return Color; } #undef LOCTEXT_NAMESPACE <commit_msg>Fixed HUD<commit_after> #include "../../Flare.h" #include "FlareSubsystemStatus.h" #include "../Components/FlareRoundButton.h" #include "../../Spacecrafts/FlareWeapon.h" #include "../../Spacecrafts/FlareSpacecraft.h" #define LOCTEXT_NAMESPACE "FlareSubsystemStatus" /*---------------------------------------------------- Construct ----------------------------------------------------*/ void SFlareSubsystemStatus::Construct(const FArguments& InArgs) { // Args TargetShip = NULL; TargetComponent = NULL; SubsystemType = InArgs._Subsystem; // Settings Health = 1.0f; ComponentHealth = 0.0f; HealthDropFlashTime = 2.0f; TimeSinceFlash = HealthDropFlashTime; const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); // Icon const FSlateBrush* Icon = NULL; switch (SubsystemType) { case EFlareSubsystem::SYS_Temperature: Icon = FFlareStyleSet::GetIcon("HUD_Temperature"); break; case EFlareSubsystem::SYS_Propulsion: Icon = FFlareStyleSet::GetIcon("HUD_Propulsion"); break; case EFlareSubsystem::SYS_RCS: Icon = FFlareStyleSet::GetIcon("HUD_RCS"); break; case EFlareSubsystem::SYS_LifeSupport: Icon = FFlareStyleSet::GetIcon("HUD_LifeSupport"); break; case EFlareSubsystem::SYS_Power: Icon = FFlareStyleSet::GetIcon("HUD_Power"); break; case EFlareSubsystem::SYS_Weapon: Icon = FFlareStyleSet::GetIcon("HUD_Shell"); break; } // Structure ChildSlot .VAlign(VAlign_Top) .HAlign(HAlign_Center) [ SNew(SFlareRoundButton) .Clickable(false) .Icon(Icon) .Text(this, &SFlareSubsystemStatus::GetText) .HelpText(this, &SFlareSubsystemStatus::GetInfoText) .HighlightColor(this, &SFlareSubsystemStatus::GetHealthColor) .TextColor(this, &SFlareSubsystemStatus::GetFlashColor) ]; } /*---------------------------------------------------- Interaction ----------------------------------------------------*/ void SFlareSubsystemStatus::SetTargetShip(IFlareSpacecraftInterface* Target) { TargetShip = Target; } void SFlareSubsystemStatus::SetTargetComponent(UFlareSpacecraftComponent* Target) { TargetComponent = Target; } /*---------------------------------------------------- Callbacks ----------------------------------------------------*/ void SFlareSubsystemStatus::Tick(const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime) { SCompoundWidget::Tick(AllottedGeometry, InCurrentTime, InDeltaTime); if (TargetShip) { // Update health float NewHealth = TargetShip->GetDamageSystem()->GetSubsystemHealth(SubsystemType, true, false); ComponentHealth = TargetShip->GetDamageSystem()->GetSubsystemHealth(SubsystemType); // Update flash TimeSinceFlash += InDeltaTime; if (NewHealth < 0.98 * Health) { TimeSinceFlash = 0; Health = NewHealth; } } else { Health = 1; } } FText SFlareSubsystemStatus::GetText() const { return FText::Format(LOCTEXT("SubsystemInfoFormat", "{0}\n{1}%"), IFlareSpacecraftDamageSystemInterface::GetSubsystemName(SubsystemType), FText::AsNumber(FMath::RoundToInt(100 * ComponentHealth))); } FText SFlareSubsystemStatus::GetInfoText() const { FText Text; switch (SubsystemType) { case EFlareSubsystem::SYS_Temperature: Text = LOCTEXT("SYS_TemperatureInfo", "The cooling subsystem ensures that your ship doesn't overheat and burn."); break; case EFlareSubsystem::SYS_Propulsion: Text = LOCTEXT("SYS_PropulsionInfo", "Orbital engines are required for orbital travel and can be used in combat to boost the spacecraft. They produce a lot of heat."); break; case EFlareSubsystem::SYS_RCS: Text = LOCTEXT("SYS_RCSInfo", "The Reaction Control System is responsible for moving and turning the ship around in space. They produce little heat."); break; case EFlareSubsystem::SYS_LifeSupport: Text = LOCTEXT("SYS_LifeSupportInfo", "The life support system needs to stay intact and powered in order for the crew to survive."); break; case EFlareSubsystem::SYS_Power: Text = LOCTEXT("SYS_PowerInfo", "The power subsystem feeds energy to every system on your ship, including propulsion, weapons or life support."); break; case EFlareSubsystem::SYS_Weapon: Text = LOCTEXT("SYS_WeaponInfo", "Weapons can be used to damage other spacecrafts. They produce a lot of heat."); break; } return Text; } FSlateColor SFlareSubsystemStatus::GetHealthColor() const { return FFlareStyleSet::GetHealthColor(ComponentHealth, false); } FSlateColor SFlareSubsystemStatus::GetFlashColor() const { const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); FLinearColor NormalColor = Theme.NeutralColor; FLinearColor DamageColor = Theme.EnemyColor; FLinearColor Color = FMath::Lerp(DamageColor, NormalColor, FMath::Clamp(TimeSinceFlash / HealthDropFlashTime, 0.0f, 1.0f)); Color.A *= Theme.DefaultAlpha; return Color; } #undef LOCTEXT_NAMESPACE <|endoftext|>
<commit_before>/* This file is part of the Vc library. Copyright (C) 2009-2012 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 "unittest.h" #include <iostream> using namespace Vc; enum { VectorSizeFactor = short_v::Size / int_v::Size }; void testSigned() { for (int start = -32000; start < 32000; start += 5) { int_v a[VectorSizeFactor]; for (int i = 0; i < VectorSizeFactor; ++i) { a[i] = int_v(IndexesFromZero) + int_v::Size * i + start; } short_v b(a); COMPARE(b, short_v(IndexesFromZero) + start); // false positive: warning: ‘c’ is used uninitialized in this function int_v c[VectorSizeFactor]; b.expand(c); for (int i = 0; i < VectorSizeFactor; ++i) { COMPARE(c[i], int_v(IndexesFromZero) + int_v::Size * i + start); } } } void testUnsigned() { #if defined(VC_IMPL_SSE4_1) || defined(VC_IMPL_AVX) for (unsigned int start = 0; start < 64000; start += 5) { #else for (unsigned int start = 0; start < 32000; start += 5) { #endif uint_v a[VectorSizeFactor]; for (unsigned int i = 0; i < VectorSizeFactor; ++i) { a[i] = uint_v(IndexesFromZero) + uint_v::Size * i + start; } ushort_v b(a); COMPARE(b, ushort_v(IndexesFromZero) + start); // false positive: warning: ‘c’ is used uninitialized in this function uint_v c[VectorSizeFactor]; b.expand(c); for (unsigned int i = 0; i < VectorSizeFactor; ++i) { COMPARE(c[i], uint_v(IndexesFromZero) + uint_v::Size * i + start); } } for (unsigned int start = 32000; start < 64000; start += 5) { ushort_v b(IndexesFromZero); b += start; COMPARE(b, ushort_v(IndexesFromZero) + start); // false positive: warning: ‘c’ may be used uninitialized in this function uint_v c[VectorSizeFactor]; b.expand(c); for (unsigned int i = 0; i < VectorSizeFactor; ++i) { COMPARE(c[i], uint_v(IndexesFromZero) + uint_v::Size * i + start); } } } void testFloat() { enum { SizeFactor = float_v::Size / double_v::Size }; double_v d[SizeFactor]; for (int i = 0; i < SizeFactor; ++i) { d[i] = double_v::Random(); } float_v f(d); for (int i = 0; i < float_v::Size; ++i) { COMPARE(f[i], float(d[i / double_v::Size][i % double_v::Size])); } } int main() { runTest(testSigned); runTest(testUnsigned); runTest(testFloat); return 0; } <commit_msg>and a small test for float_v -> double_v expansion<commit_after>/* This file is part of the Vc library. Copyright (C) 2009-2012 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 "unittest.h" #include <iostream> using namespace Vc; enum { VectorSizeFactor = short_v::Size / int_v::Size }; void testSigned() { for (int start = -32000; start < 32000; start += 5) { int_v a[VectorSizeFactor]; for (int i = 0; i < VectorSizeFactor; ++i) { a[i] = int_v(IndexesFromZero) + int_v::Size * i + start; } short_v b(a); COMPARE(b, short_v(IndexesFromZero) + start); // false positive: warning: ‘c’ is used uninitialized in this function int_v c[VectorSizeFactor]; b.expand(c); for (int i = 0; i < VectorSizeFactor; ++i) { COMPARE(c[i], int_v(IndexesFromZero) + int_v::Size * i + start); } } } void testUnsigned() { #if defined(VC_IMPL_SSE4_1) || defined(VC_IMPL_AVX) for (unsigned int start = 0; start < 64000; start += 5) { #else for (unsigned int start = 0; start < 32000; start += 5) { #endif uint_v a[VectorSizeFactor]; for (unsigned int i = 0; i < VectorSizeFactor; ++i) { a[i] = uint_v(IndexesFromZero) + uint_v::Size * i + start; } ushort_v b(a); COMPARE(b, ushort_v(IndexesFromZero) + start); // false positive: warning: ‘c’ is used uninitialized in this function uint_v c[VectorSizeFactor]; b.expand(c); for (unsigned int i = 0; i < VectorSizeFactor; ++i) { COMPARE(c[i], uint_v(IndexesFromZero) + uint_v::Size * i + start); } } for (unsigned int start = 32000; start < 64000; start += 5) { ushort_v b(IndexesFromZero); b += start; COMPARE(b, ushort_v(IndexesFromZero) + start); // false positive: warning: ‘c’ may be used uninitialized in this function uint_v c[VectorSizeFactor]; b.expand(c); for (unsigned int i = 0; i < VectorSizeFactor; ++i) { COMPARE(c[i], uint_v(IndexesFromZero) + uint_v::Size * i + start); } } } void testFloat() { enum { SizeFactor = float_v::Size / double_v::Size }; double_v d[SizeFactor]; for (int i = 0; i < SizeFactor; ++i) { d[i] = double_v::Random(); } float_v f(d); for (int i = 0; i < float_v::Size; ++i) { COMPARE(f[i], float(d[i / double_v::Size][i % double_v::Size])); } f = float_v::Random(); f.expand(d); for (int i = 0; i < float_v::Size; ++i) { COMPARE(f[i], float(d[i / double_v::Size][i % double_v::Size])); } } int main() { runTest(testSigned); runTest(testUnsigned); runTest(testFloat); return 0; } <|endoftext|>
<commit_before>#ifndef ITER_REVERSE_HPP_ #define ITER_REVERSE_HPP_ #include "iterbase.hpp" #include <utility> #include <iterator> namespace iter { template <typename Container> class Reverser; template <typename Container> Reverser<Container> reversed(Container&&); template <typename Container> class Reverser { private: Container container; friend Reverser reversed<Container>(Container&&); Reverser(Container container) : container(std::forward<Container>(container)) { } Reverser() = delete; Reverser& operator=(const Reverser&) = delete; public: Reverser(const Reverser&) = default; class Iterator { private: reverse_iterator_type<Container> sub_iter; public: Iterator (reverse_iterator_type<Container> iter) : sub_iter{iter} { } reverse_iterator_deref<Container> operator*() { return *this->sub_iter; } Iterator& operator++() { ++this->sub_iter; return *this; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } }; Iterator begin() { return {this->container.rbegin()}; } Iterator end() { return {this->container.rend()}; } }; // Helper function to instantiate a Reverser template <typename Container> Reverser<Container> reversed(Container&& container) { return {std::forward<Container>(container)}; } // // specialization for statically allocated arrays // template <typename T, std::size_t N> Reverser<T[N]> reversed(T (&)[N]); template <typename T, std::size_t N> class Reverser<T[N]> { private: T *array; // The reversed function is the only thing allowed to create a // Reverser friend Reverser reversed<T, N>(T (&)[N]); // Value constructor for use only in the reversed function Reverser(T *array) : array{array} { } Reverser() = delete; Reverser& operator=(const Reverser&) = delete; public: Reverser(const Reverser&) = default; class Iterator { private: T *sub_iter; public: Iterator (T *iter) : sub_iter{iter} { } auto operator*() -> decltype(*array) { return *(this->sub_iter - 1); } Iterator& operator++() { --this->sub_iter; return *this; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } }; Iterator begin() { return {this->array + N}; } Iterator end() { return {this->array}; } }; template <typename T, std::size_t N> Reverser<T[N]> reversed(T (&array)[N]) { return {array}; } } #endif //ITER_REVERSE_HPP_ <commit_msg>reversed iter inherits from std::iterator<commit_after>#ifndef ITER_REVERSE_HPP_ #define ITER_REVERSE_HPP_ #include "iterbase.hpp" #include <utility> #include <iterator> namespace iter { template <typename Container> class Reverser; template <typename Container> Reverser<Container> reversed(Container&&); template <typename Container> class Reverser { private: Container container; friend Reverser reversed<Container>(Container&&); Reverser(Container container) : container(std::forward<Container>(container)) { } Reverser() = delete; Reverser& operator=(const Reverser&) = delete; public: Reverser(const Reverser&) = default; class Iterator : public std::iterator< std::input_iterator_tag, iterator_traits_deref<Container>> { private: reverse_iterator_type<Container> sub_iter; public: Iterator (reverse_iterator_type<Container> iter) : sub_iter{iter} { } reverse_iterator_deref<Container> operator*() { return *this->sub_iter; } Iterator& operator++() { ++this->sub_iter; return *this; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } }; Iterator begin() { return {this->container.rbegin()}; } Iterator end() { return {this->container.rend()}; } }; template <typename Container> Reverser<Container> reversed(Container&& container) { return {std::forward<Container>(container)}; } // // specialization for statically allocated arrays // template <typename T, std::size_t N> Reverser<T[N]> reversed(T (&)[N]); template <typename T, std::size_t N> class Reverser<T[N]> { private: T *array; friend Reverser reversed<T, N>(T (&)[N]); // Value constructor for use only in the reversed function Reverser(T *array) : array{array} { } Reverser() = delete; Reverser& operator=(const Reverser&) = delete; public: Reverser(const Reverser&) = default; class Iterator : public std::iterator<std::input_iterator_tag, T> { private: T *sub_iter; public: Iterator (T *iter) : sub_iter{iter} { } auto operator*() -> decltype(*array) { return *(this->sub_iter - 1); } Iterator& operator++() { --this->sub_iter; return *this; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } }; Iterator begin() { return {this->array + N}; } Iterator end() { return {this->array}; } }; template <typename T, std::size_t N> Reverser<T[N]> reversed(T (&array)[N]) { return {array}; } } #endif //ITER_REVERSE_HPP_ <|endoftext|>
<commit_before>#include "UnrealEnginePythonPrivatePCH.h" #include "PyCommandlet.h" #include "Regex.h" UPyCommandlet::UPyCommandlet(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { LogToConsole = 1; } int32 UPyCommandlet::Main(const FString& CommandLine) { TArray<FString> Tokens, Switches; TMap<FString, FString> Params; ParseCommandLine(*CommandLine, Tokens, Switches, Params); FString Filepath = Tokens[0]; if (!FPaths::FileExists(*Filepath)) { UE_LOG(LogPython, Error, TEXT("Python file could not be found: %s"), *Filepath); return -1; } FString RegexString = FString::Printf(TEXT("(?<=%s).*"), *(Filepath.Replace(TEXT("\\"), TEXT("\\\\")))); const FRegexPattern myPattern(RegexString); FRegexMatcher myMatcher(myPattern, *CommandLine); myMatcher.FindNext(); FString PyCommandLine = myMatcher.GetCaptureGroup(0).Trim().TrimTrailing(); TArray<FString> PyArgv = {FString()}; bool escaped = false; for (int i = 0; i < PyCommandLine.Len(); i++) { if(PyCommandLine[i] == ' ') { PyArgv.Add(FString()); continue; } else if(PyCommandLine[i] == '\"' && !escaped) { i++; while(i < PyCommandLine.Len() && !(PyCommandLine[i] == '"')) { PyArgv[PyArgv.Num() - 1].AppendChar(PyCommandLine[i]); i++; if (i == PyCommandLine.Len()) { PyArgv[PyArgv.Num() - 1].InsertAt(0, "\""); } } } else { if (PyCommandLine[i] == '\\') escaped = true; else escaped = false; PyArgv[PyArgv.Num() - 1].AppendChar(PyCommandLine[i]); } } PyArgv.Insert(Filepath, 0); #if PY_MAJOR_VERSION >= 3 wchar_t **argv = (wchar_t **)malloc(PyArgv.Num() * sizeof(void*)); #else char **argv = (char **)malloc(PyArgv.Num() * sizeof(void*)); #endif for (int i=0; i<PyArgv.Num(); i++) { #if PY_MAJOR_VERSION >= 3 argv[i] = (wchar_t*)malloc(PyArgv[i].Len()+1); #if UNREAL_ENGINE_PYTHON_ON_MAC || UNREAL_ENGINE_PYTHON_ON_LINUX wcsncpy(argv[i], *PyArgv[i].ReplaceEscapedCharWithChar(), PyArgv[i].Len() + 1); #else wcscpy_s(argv[i], PyArgv[i].Len() + 1, *PyArgv[i].ReplaceEscapedCharWithChar()); #endif #else argv[i] = (char*)malloc(PyArgv[i].Len() + 1); strcpy_s(argv[i], PyArgv[i].Len()+1, TCHAR_TO_UTF8(*PyArgv[i].ReplaceEscapedCharWithChar())); #endif } PySys_SetArgv(PyArgv.Num(), argv); FUnrealEnginePythonModule &PythonModule = FModuleManager::GetModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython"); PythonModule.RunFile(TCHAR_TO_UTF8(*Filepath)); return 0; } <commit_msg>fixed build for unreal 4.12<commit_after>#include "UnrealEnginePythonPrivatePCH.h" #include "PyCommandlet.h" #include "Regex.h" UPyCommandlet::UPyCommandlet(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { LogToConsole = 1; } int32 UPyCommandlet::Main(const FString& CommandLine) { TArray<FString> Tokens, Switches; TMap<FString, FString> Params; ParseCommandLine(*CommandLine, Tokens, Switches, Params); FString Filepath = Tokens[0]; if (!FPaths::FileExists(*Filepath)) { UE_LOG(LogPython, Error, TEXT("Python file could not be found: %s"), *Filepath); return -1; } FString RegexString = FString::Printf(TEXT("(?<=%s).*"), *(Filepath.Replace(TEXT("\\"), TEXT("\\\\")))); const FRegexPattern myPattern(RegexString); FRegexMatcher myMatcher(myPattern, *CommandLine); myMatcher.FindNext(); FString PyCommandLine = myMatcher.GetCaptureGroup(0).Trim().TrimTrailing(); TArray<FString> PyArgv; PyArgv.Add(FString()); bool escaped = false; for (int i = 0; i < PyCommandLine.Len(); i++) { if(PyCommandLine[i] == ' ') { PyArgv.Add(FString()); continue; } else if(PyCommandLine[i] == '\"' && !escaped) { i++; while(i < PyCommandLine.Len() && !(PyCommandLine[i] == '"')) { PyArgv[PyArgv.Num() - 1].AppendChar(PyCommandLine[i]); i++; if (i == PyCommandLine.Len()) { PyArgv[PyArgv.Num() - 1].InsertAt(0, "\""); } } } else { if (PyCommandLine[i] == '\\') escaped = true; else escaped = false; PyArgv[PyArgv.Num() - 1].AppendChar(PyCommandLine[i]); } } PyArgv.Insert(Filepath, 0); #if PY_MAJOR_VERSION >= 3 wchar_t **argv = (wchar_t **)malloc(PyArgv.Num() * sizeof(void*)); #else char **argv = (char **)malloc(PyArgv.Num() * sizeof(void*)); #endif for (int i=0; i<PyArgv.Num(); i++) { #if PY_MAJOR_VERSION >= 3 argv[i] = (wchar_t*)malloc(PyArgv[i].Len()+1); #if UNREAL_ENGINE_PYTHON_ON_MAC || UNREAL_ENGINE_PYTHON_ON_LINUX wcsncpy(argv[i], *PyArgv[i].ReplaceEscapedCharWithChar(), PyArgv[i].Len() + 1); #else wcscpy_s(argv[i], PyArgv[i].Len() + 1, *PyArgv[i].ReplaceEscapedCharWithChar()); #endif #else argv[i] = (char*)malloc(PyArgv[i].Len() + 1); strcpy_s(argv[i], PyArgv[i].Len()+1, TCHAR_TO_UTF8(*PyArgv[i].ReplaceEscapedCharWithChar())); #endif } PySys_SetArgv(PyArgv.Num(), argv); FUnrealEnginePythonModule &PythonModule = FModuleManager::GetModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython"); PythonModule.RunFile(TCHAR_TO_UTF8(*Filepath)); return 0; } <|endoftext|>
<commit_before>#include "MysqlDbConnection.h" namespace sf1r { MysqlDbConnection::MysqlDbConnection() :DB_NAME("SF1R"), PoolSize(16) { } MysqlDbConnection::~MysqlDbConnection() { close(); } void MysqlDbConnection::close() { mutex_.acquire_write_lock(); for(std::list<MYSQL*>::iterator it= pool_.begin(); it!=pool_.end(); it++ ) { mysql_close(*it); } pool_.clear(); //release it at last mysql_library_end(); mutex_.release_write_lock(); } bool MysqlDbConnection::init(const std::string& str ) { mysql_library_init(0, NULL, NULL); std::string host; uint32_t port = 3306; std::string username; std::string password; std::string schema = DB_NAME; std::string default_charset("utf8"); // std::string character_set_results("utf8"); std::string conn = str; std::size_t pos = conn.find(":"); if(pos==0 || pos == std::string::npos) return false; username = conn.substr(0, pos); conn = conn.substr(pos+1); pos = conn.find("@"); if(pos==0 || pos == std::string::npos) return false; password = conn.substr(0, pos); conn = conn.substr(pos+1); pos = conn.find(":"); if(pos==0 || pos == std::string::npos) return false; host = conn.substr(0, pos); conn = conn.substr(pos+1); try { port = boost::lexical_cast<uint32_t>(conn); } catch(std::exception& ex) { return false; } if(host=="localhost") host = "127.0.0.1"; int flags = CLIENT_MULTI_RESULTS; bool ret = true; mutex_.acquire_write_lock(); for(int i=0; i<PoolSize; i++) { MYSQL* mysql = mysql_init(NULL); if (!mysql) { std::cerr<<"mysql_init failed"<<std::endl; return false; } mysql_options(mysql, MYSQL_SET_CHARSET_NAME, default_charset.c_str()); if (!mysql_real_connect(mysql, host.c_str(), username.c_str(), password.c_str(), schema.c_str(), port, NULL, flags)) { printf("Couldn't connect mysql : %d:(%s) %s", mysql_errno(mysql), mysql_sqlstate(mysql), mysql_error(mysql)); mysql_close(mysql); return false; } pool_.push_back(mysql); } mutex_.release_write_lock(); if(!ret) close(); return ret; } MYSQL* MysqlDbConnection::getDb() { MYSQL* db = NULL; mutex_.acquire_write_lock(); if(!pool_.empty()) { db = pool_.front(); pool_.pop_front(); } mutex_.release_write_lock(); return db; } void MysqlDbConnection::putDb(MYSQL* db) { mutex_.acquire_write_lock(); pool_.push_back(db); mutex_.release_write_lock(); } bool MysqlDbConnection::exec(const std::string & sql, bool omitError) { bool ret = true; MYSQL* db = getDb(); if( db == NULL ) { std::cerr << "[LogManager] No available connection in pool" << std::endl; return false; } if( mysql_real_query(db, sql.c_str(), sql.length()) >0 && mysql_errno(db) ) { printf("Couldn't connect mysql : %d:(%s) %s", mysql_errno(db), mysql_sqlstate(db), mysql_error(db)); ret = false; } if(ret) { uint32_t field_count = mysql_field_count(db); std::cout<<"mysql exec field_count : "<<field_count<<std::endl; if ( field_count<= 0) ret = false; } putDb(db); return ret; } bool MysqlDbConnection::exec(const std::string & sql, std::list< std::map<std::string, std::string> > & results, bool omitError) { bool ret = true; MYSQL* db = getDb(); if( db == NULL ) { std::cerr << "[LogManager] No available connection in pool" << std::endl; return false; } if( mysql_real_query(db, sql.c_str(), sql.length()) >0 && mysql_errno(db) ) { printf("Couldn't connect mysql : %d:(%s) %s", mysql_errno(db), mysql_sqlstate(db), mysql_error(db)); ret = false; } else { MYSQL_RES* result = mysql_store_result(db); if(result==NULL) { printf("Error during store_result : %d:(%s) %s", mysql_errno(db), mysql_sqlstate(db), mysql_error(db)); ret = false; } else { uint32_t num_cols = mysql_num_fields(result); std::vector<std::string> col_nums(num_cols); for(uint32_t i=0;i<num_cols;i++) { MYSQL_FIELD* field = mysql_fetch_field_direct(result, i); col_nums[i] = field->name; } MYSQL_ROW row; while ((row = mysql_fetch_row(result))) { std::map<std::string, std::string> map; for(uint32_t i=0;i<num_cols;i++) { map.insert(std::make_pair(col_nums[i], row[i]) ); } results.push_back(map); } } } putDb(db); return ret; } } <commit_msg>add head files.<commit_after>#include "MysqlDbConnection.h" #include <vector> #include <boost/lexical_cast.hpp> #include <cstdio> namespace sf1r { MysqlDbConnection::MysqlDbConnection() :DB_NAME("SF1R"), PoolSize(16) { } MysqlDbConnection::~MysqlDbConnection() { close(); } void MysqlDbConnection::close() { mutex_.acquire_write_lock(); for(std::list<MYSQL*>::iterator it= pool_.begin(); it!=pool_.end(); it++ ) { mysql_close(*it); } pool_.clear(); //release it at last mysql_library_end(); mutex_.release_write_lock(); } bool MysqlDbConnection::init(const std::string& str ) { mysql_library_init(0, NULL, NULL); std::string host; uint32_t port = 3306; std::string username; std::string password; std::string schema = DB_NAME; std::string default_charset("utf8"); // std::string character_set_results("utf8"); std::string conn = str; std::size_t pos = conn.find(":"); if(pos==0 || pos == std::string::npos) return false; username = conn.substr(0, pos); conn = conn.substr(pos+1); pos = conn.find("@"); if(pos==0 || pos == std::string::npos) return false; password = conn.substr(0, pos); conn = conn.substr(pos+1); pos = conn.find(":"); if(pos==0 || pos == std::string::npos) return false; host = conn.substr(0, pos); conn = conn.substr(pos+1); try { port = boost::lexical_cast<uint32_t>(conn); } catch(std::exception& ex) { return false; } if(host=="localhost") host = "127.0.0.1"; int flags = CLIENT_MULTI_RESULTS; bool ret = true; mutex_.acquire_write_lock(); for(int i=0; i<PoolSize; i++) { MYSQL* mysql = mysql_init(NULL); if (!mysql) { std::cerr<<"mysql_init failed"<<std::endl; return false; } mysql_options(mysql, MYSQL_SET_CHARSET_NAME, default_charset.c_str()); if (!mysql_real_connect(mysql, host.c_str(), username.c_str(), password.c_str(), schema.c_str(), port, NULL, flags)) { printf("Couldn't connect mysql : %d:(%s) %s", mysql_errno(mysql), mysql_sqlstate(mysql), mysql_error(mysql)); mysql_close(mysql); return false; } pool_.push_back(mysql); } mutex_.release_write_lock(); if(!ret) close(); return ret; } MYSQL* MysqlDbConnection::getDb() { MYSQL* db = NULL; mutex_.acquire_write_lock(); if(!pool_.empty()) { db = pool_.front(); pool_.pop_front(); } mutex_.release_write_lock(); return db; } void MysqlDbConnection::putDb(MYSQL* db) { mutex_.acquire_write_lock(); pool_.push_back(db); mutex_.release_write_lock(); } bool MysqlDbConnection::exec(const std::string & sql, bool omitError) { bool ret = true; MYSQL* db = getDb(); if( db == NULL ) { std::cerr << "[LogManager] No available connection in pool" << std::endl; return false; } if( mysql_real_query(db, sql.c_str(), sql.length()) >0 && mysql_errno(db) ) { printf("Couldn't connect mysql : %d:(%s) %s", mysql_errno(db), mysql_sqlstate(db), mysql_error(db)); ret = false; } if(ret) { uint32_t field_count = mysql_field_count(db); std::cout<<"mysql exec field_count : "<<field_count<<std::endl; if ( field_count<= 0) ret = false; } putDb(db); return ret; } bool MysqlDbConnection::exec(const std::string & sql, std::list< std::map<std::string, std::string> > & results, bool omitError) { bool ret = true; MYSQL* db = getDb(); if( db == NULL ) { std::cerr << "[LogManager] No available connection in pool" << std::endl; return false; } if( mysql_real_query(db, sql.c_str(), sql.length()) >0 && mysql_errno(db) ) { printf("Couldn't connect mysql : %d:(%s) %s", mysql_errno(db), mysql_sqlstate(db), mysql_error(db)); ret = false; } else { MYSQL_RES* result = mysql_store_result(db); if(result==NULL) { printf("Error during store_result : %d:(%s) %s", mysql_errno(db), mysql_sqlstate(db), mysql_error(db)); ret = false; } else { uint32_t num_cols = mysql_num_fields(result); std::vector<std::string> col_nums(num_cols); for(uint32_t i=0;i<num_cols;i++) { MYSQL_FIELD* field = mysql_fetch_field_direct(result, i); col_nums[i] = field->name; } MYSQL_ROW row; while ((row = mysql_fetch_row(result))) { std::map<std::string, std::string> map; for(uint32_t i=0;i<num_cols;i++) { map.insert(std::make_pair(col_nums[i], row[i]) ); } results.push_back(map); } } } putDb(db); return ret; } } <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions 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. /// \file /// Tests for LoggerManager class. #include <gtest/gtest.h> #include "SurgSim/Framework/Log.h" #include <string> using SurgSim::Framework::Logger; using SurgSim::Framework::LoggerManager; using SurgSim::Framework::StreamOutput; class MockOutput : public SurgSim::Framework::LogOutput { public: MockOutput() { } ~MockOutput() { } bool writeMessage(const std::string& message) { logMessage = message; return true; } void reset() { logMessage.clear(); } std::string logMessage; }; TEST(LoggerManagerTest, Constructor) { EXPECT_NO_THROW({std::shared_ptr<LoggerManager> loggerManager(new LoggerManager());}); } TEST(LoggerManagerTest, DefaultOutput) { auto loggerManager = std::make_shared<LoggerManager>(); auto output = std::make_shared<StreamOutput>(std::cerr); loggerManager->setDefaultOutput(output); EXPECT_EQ(output, loggerManager->getDefaultOutput()); } TEST(LoggerManagerTest, DefaultLoggerTest) { auto loggerManager = std::make_shared<LoggerManager>(); auto defaultLogger = loggerManager->getDefaultLogger(); EXPECT_TRUE(nullptr != defaultLogger); EXPECT_EQ(loggerManager->getDefaultOutput(), defaultLogger->getOutput()); EXPECT_EQ(loggerManager->getThreshold(), defaultLogger->getThreshold()); } TEST(LoggerManagerTest, GetLogger) { auto loggerManager = std::make_shared<LoggerManager>(); /// getLogger() will create a new logger if a logger with given name is not found auto retrieved = loggerManager->getLogger("test"); EXPECT_TRUE(nullptr != retrieved); /// getLogger() guarantees to return a logger with given name { auto temp = loggerManager->getLogger("logger"); } EXPECT_TRUE(nullptr != loggerManager->getLogger("logger")); } TEST(LoggerManagerTest, Threshold) { auto loggerManager = std::make_shared<LoggerManager>(); /// Check default log level auto logger0 = loggerManager->getLogger("logger0"); EXPECT_EQ(SurgSim::Framework::LOG_LEVEL_WARNING, logger0->getThreshold()); /// setThreshold(level) will change log level of existing loggers /// and the default log level loggerManager->setThreshold(SurgSim::Framework::LOG_LEVEL_CRITICAL); EXPECT_EQ(SurgSim::Framework::LOG_LEVEL_CRITICAL, loggerManager->getThreshold()); EXPECT_EQ(SurgSim::Framework::LOG_LEVEL_CRITICAL, logger0->getThreshold()); /// setThreshold(level) will affect log level of newly created loggers auto logger1 = loggerManager->getLogger("logger1"); EXPECT_EQ(SurgSim::Framework::LOG_LEVEL_CRITICAL, logger1->getThreshold()); auto logger2 = loggerManager->getLogger("logger2"); auto logger3 = loggerManager->getLogger("logger3"); auto testLogger = loggerManager->getLogger("testLogger"); /// setThreshold(pattern, level) will change log level of existing loggers /// which match given name pattern /// Logger with different pattern will not be changed /// Default log level will not be affected loggerManager->setThreshold("logger", SurgSim::Framework::LOG_LEVEL_WARNING); EXPECT_EQ(SurgSim::Framework::LOG_LEVEL_WARNING, logger2->getThreshold()); EXPECT_EQ(SurgSim::Framework::LOG_LEVEL_WARNING, logger3->getThreshold()); EXPECT_NE(SurgSim::Framework::LOG_LEVEL_WARNING, testLogger->getThreshold()); EXPECT_NE(SurgSim::Framework::LOG_LEVEL_WARNING, loggerManager->getThreshold()); /// setThreshold(pattern, level) will not affect newly created loggers auto testLogger2 = loggerManager->getLogger("testLogger2"); EXPECT_NE(SurgSim::Framework::LOG_LEVEL_WARNING, testLogger2->getThreshold()); /// setThreshold(pattern, level) will not affect newly created loggers /// even the logger's name match the pattern auto logger5 = loggerManager->getLogger("logger5"); EXPECT_NE(SurgSim::Framework::LOG_LEVEL_WARNING, logger5->getThreshold()); }<commit_msg>UnitTest for LoggerManager to test if a manager owns a logger.<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions 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. /// \file /// Tests for LoggerManager class. #include "SurgSim/Framework/Log.h" #include <string> #include <memory> #include <gtest/gtest.h> using SurgSim::Framework::Logger; using SurgSim::Framework::LoggerManager; using SurgSim::Framework::StreamOutput; class MockOutput : public SurgSim::Framework::LogOutput { public: MockOutput() { } ~MockOutput() { } bool writeMessage(const std::string& message) { logMessage = message; return true; } void reset() { logMessage.clear(); } std::string logMessage; }; TEST(LoggerManagerTest, Constructor) { EXPECT_NO_THROW({std::shared_ptr<LoggerManager> loggerManager(new LoggerManager());}); } TEST(LoggerManagerTest, DefaultOutput) { auto loggerManager = std::make_shared<LoggerManager>(); auto output = std::make_shared<StreamOutput>(std::cerr); loggerManager->setDefaultOutput(output); EXPECT_EQ(output, loggerManager->getDefaultOutput()); } TEST(LoggerManagerTest, DefaultLoggerTest) { auto loggerManager = std::make_shared<LoggerManager>(); auto defaultLogger = loggerManager->getDefaultLogger(); EXPECT_TRUE(nullptr != defaultLogger); EXPECT_EQ(loggerManager->getDefaultOutput(), defaultLogger->getOutput()); EXPECT_EQ(loggerManager->getThreshold(), defaultLogger->getThreshold()); } TEST(LoggerManagerTest, GetLogger) { auto loggerManager = std::make_shared<LoggerManager>(); /// getLogger() will create a new logger if a logger with given name is not found auto retrieved = loggerManager->getLogger("test"); EXPECT_TRUE(nullptr != retrieved); /// getLogger() guarantees to return a logger with given name { auto temp = loggerManager->getLogger("logger"); } EXPECT_TRUE(nullptr != loggerManager->getLogger("logger")); } TEST(LoggerManagerTest, Threshold) { auto loggerManager = std::make_shared<LoggerManager>(); /// Check default log level auto logger0 = loggerManager->getLogger("logger0"); EXPECT_EQ(SurgSim::Framework::LOG_LEVEL_WARNING, logger0->getThreshold()); /// setThreshold(level) will change log level of existing loggers /// and the default log level loggerManager->setThreshold(SurgSim::Framework::LOG_LEVEL_CRITICAL); EXPECT_EQ(SurgSim::Framework::LOG_LEVEL_CRITICAL, loggerManager->getThreshold()); EXPECT_EQ(SurgSim::Framework::LOG_LEVEL_CRITICAL, logger0->getThreshold()); /// setThreshold(level) will affect log level of newly created loggers auto logger1 = loggerManager->getLogger("logger1"); EXPECT_EQ(SurgSim::Framework::LOG_LEVEL_CRITICAL, logger1->getThreshold()); auto logger2 = loggerManager->getLogger("logger2"); auto logger3 = loggerManager->getLogger("logger3"); auto testLogger = loggerManager->getLogger("testLogger"); /// setThreshold(pattern, level) will change log level of existing loggers /// which match given name pattern /// Logger with different pattern will not be changed /// Default log level will not be affected loggerManager->setThreshold("logger", SurgSim::Framework::LOG_LEVEL_WARNING); EXPECT_EQ(SurgSim::Framework::LOG_LEVEL_WARNING, logger2->getThreshold()); EXPECT_EQ(SurgSim::Framework::LOG_LEVEL_WARNING, logger3->getThreshold()); EXPECT_NE(SurgSim::Framework::LOG_LEVEL_WARNING, testLogger->getThreshold()); EXPECT_NE(SurgSim::Framework::LOG_LEVEL_WARNING, loggerManager->getThreshold()); /// setThreshold(pattern, level) will not affect newly created loggers auto testLogger2 = loggerManager->getLogger("testLogger2"); EXPECT_NE(SurgSim::Framework::LOG_LEVEL_WARNING, testLogger2->getThreshold()); /// setThreshold(pattern, level) will not affect newly created loggers /// even the logger's name match the pattern auto logger5 = loggerManager->getLogger("logger5"); EXPECT_NE(SurgSim::Framework::LOG_LEVEL_WARNING, logger5->getThreshold()); /// Logger manager should own the logger. loggerManager->getLogger("xxx")->setThreshold(SurgSim::Framework::LOG_LEVEL_DEBUG); EXPECT_EQ(SurgSim::Framework::LOG_LEVEL_DEBUG, loggerManager->getLogger("xxx")->getThreshold()); }<|endoftext|>
<commit_before>#include "text_renderer.h" #include "lib/bitmap.h" #include "lib/common.h" #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <limits.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> // **************************************************************************** // Glyph // **************************************************************************** typedef struct { unsigned startX; unsigned startY; unsigned runLen; } EncodedRun; class Glyph { public: unsigned m_width; int m_numRuns; EncodedRun *m_pixelRuns; Glyph(int w) { m_width = w; } }; // **************************************************************************** // Public Functions // **************************************************************************** static bool GetPixelFromBuffer(unsigned *buf, int w, int h, int x, int y) { return buf[(h - y - 1) * w + x] > 0; } TextRenderer *CreateTextRenderer(char const *fontName, int size, int weight) { if (size < 4 || size > 1000 || weight < 1 || weight > 9) return NULL; TextRenderer *tr = new TextRenderer; memset(tr, 0, sizeof(TextRenderer)); // Get the font from GDI HDC winDC = CreateDC("DISPLAY", NULL, NULL, NULL); HDC memDC = CreateCompatibleDC(winDC); int scaledSize = -MulDiv(size, GetDeviceCaps(memDC, LOGPIXELSY), 72); HFONT fontHandle = CreateFont(scaledSize, 0, 0, 0, weight * 100, false, false, false, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, NONANTIALIASED_QUALITY, DEFAULT_PITCH, fontName); ReleaseAssert(fontHandle != NULL, "Couldn't find Windows font '%s'", fontName); // Ask GDI about the font size and fixed-widthness SelectObject(memDC, fontHandle); TEXTMETRIC textMetrics; GetTextMetrics(memDC, &textMetrics); tr->charHeight = textMetrics.tmHeight; tr->maxCharWidth = textMetrics.tmMaxCharWidth; tr->fixedWidth = (textMetrics.tmAveCharWidth == textMetrics.tmMaxCharWidth); // Ask GDI about the name of the font char nameOfFontWeGot[256]; GetTextFace(memDC, 256, nameOfFontWeGot); ReleaseWarn(strnicmp(nameOfFontWeGot, fontName, 255) == 0, "Attempt to load font '%s' failed.\n" "'%s' will be used instead.", fontName, nameOfFontWeGot); // Create an off-screen bitmap BITMAPINFO bmpInfo = { 0 }; bmpInfo.bmiHeader.biBitCount = 32; bmpInfo.bmiHeader.biHeight = tr->charHeight; bmpInfo.bmiHeader.biWidth = tr->maxCharWidth; bmpInfo.bmiHeader.biPlanes = 1; bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); UINT *gdiPixels = 0; HBITMAP memBmp = CreateDIBSection(memDC, (BITMAPINFO *)&bmpInfo, DIB_RGB_COLORS, (void **)&gdiPixels, NULL, 0); HBITMAP prevBmp = (HBITMAP)SelectObject(memDC, memBmp); // Allocate enough EncodedRuns to store the worst case for a glyph of this size. // Worst case is if the whole glyph is encoded as runs of one pixel. There has // to be a gap of one pixel between each run, so there can only be half as many // runs as there are pixels. unsigned tempRunsSize = tr->charHeight * (tr->maxCharWidth / 2 + 1); EncodedRun *tempRuns = new EncodedRun [tempRunsSize]; // Setup stuff needed to render text with GDI SetTextColor(memDC, RGB(255,255,255)); SetBkColor(memDC, 0); RECT rect = { 0, 0, tr->maxCharWidth, tr->charHeight }; // Run-length encode each ASCII character for (int i = 0; i < 256; i++) { char buf[] = {(char)i}; // Get the size of this glyph SIZE glyphSize; GetTextExtentPoint32(memDC, buf, 1, &glyphSize); // if (glyphSize.cx > tr->maxCharWidth) // tr->maxCharWidth = glyphSize.cx; // if (glyphSize.cy > tr->charHeight) // tr->charHeight = glyphSize.cy; // Ask GDI to draw the character ExtTextOut(memDC, 0, 0, ETO_OPAQUE, &rect, buf, 1, 0); // Read back what GDI put in the bitmap and construct a run-length encoding memset(tempRuns, 0, tempRunsSize); EncodedRun *run = tempRuns; for (int y = 0; y < tr->charHeight; y++) { int x = 0; while (x < tr->maxCharWidth) { // Skip blank pixels while (!GetPixelFromBuffer(gdiPixels, tr->maxCharWidth, tr->charHeight, x, y)) { x++; if (x >= tr->maxCharWidth) break; } // Have we got to the end of the line? if (x >= tr->maxCharWidth) continue; run->startX = x; run->startY = y; run->runLen = 0; // Count non-blank pixels while (GetPixelFromBuffer(gdiPixels, tr->maxCharWidth, tr->charHeight, x, y)) { x++; run->runLen++; if (x >= tr->maxCharWidth) break; } run++; } } // Create the glyph to store the encoded runs we've made Glyph *glyph = new Glyph(glyphSize.cx); tr->glyphs[i] = glyph; // Copy the runs into the glyph glyph->m_numRuns = run - tempRuns; glyph->m_pixelRuns = new EncodedRun [glyph->m_numRuns]; memcpy(glyph->m_pixelRuns, tempRuns, glyph->m_numRuns * sizeof(EncodedRun)); } delete [] tempRuns; // Release the GDI resources DeleteDC(winDC); DeleteDC(memDC); DeleteObject(fontHandle); DeleteObject(memBmp); DeleteObject(prevBmp); return tr; } static int DrawTextSimpleClipped(TextRenderer *tr, RGBAColour col, BitmapRGBA *bmp, int _x, int y, char const *text) { int x = _x; RGBAColour *startRow = bmp->pixels + y * bmp->width; int width = bmp->width; if (y + tr->charHeight < 0 || y > (int)bmp->height) return 0; while (*text != '\0') { if (x + tr->maxCharWidth > (int)bmp->width) break; Glyph *glyph = tr->glyphs[(unsigned char)*text]; EncodedRun *rleBuf = glyph->m_pixelRuns; for (int i = 0; i < glyph->m_numRuns; i++) { int y3 = y + rleBuf->startY; if (y3 >= 0 && y3 < (int)bmp->height) { RGBAColour *thisRow = startRow + rleBuf->startY * width; for (unsigned i = 0; i < rleBuf->runLen; i++) { int x3 = x + rleBuf->startX + i; if (x3 >= 0 && x3 < width) thisRow[x3] = col; } } rleBuf++; } x += glyph->m_width; text++; } return _x - x; } int DrawTextSimple(TextRenderer *tr, RGBAColour col, BitmapRGBA *bmp, int _x, int y, char const *text) { int x = _x; int width = bmp->width; if (x < 0 || y < 0 || (y + tr->charHeight) > (int)bmp->height) return DrawTextSimpleClipped(tr, col, bmp, _x, y, text); RGBAColour *startRow = bmp->pixels + y * bmp->width; while (*text != '\0') { if (x + tr->glyphs[*text]->m_width > (int)bmp->width) break; // Copy the glyph onto the stack for better cache performance. This increased the // performance from 13.8 to 14.4 million chars per second. Madness. Glyph glyph = *tr->glyphs[(unsigned char)*text]; EncodedRun *rleBuf = glyph.m_pixelRuns; for (int i = 0; i < glyph.m_numRuns; i++) { RGBAColour *startPixel = startRow + rleBuf->startY * width + rleBuf->startX + x; // Loop unrolled for speed switch (rleBuf->runLen) { case 8: startPixel[7] = col; case 7: startPixel[6] = col; case 6: startPixel[5] = col; case 5: startPixel[4] = col; case 4: startPixel[3] = col; case 3: startPixel[2] = col; case 2: startPixel[1] = col; case 1: startPixel[0] = col; break; default: for (unsigned i = 0; i < rleBuf->runLen; i++) startPixel[i] = col; } rleBuf++; } x += glyph.m_width; text++; } return _x - x; } int DrawTextLeft(TextRenderer *tr, RGBAColour c, BitmapRGBA *bmp, int x, int y, char const *text, ...) { char buf[512]; va_list ap; va_start (ap, text); vsprintf(buf, text, ap); return DrawTextSimple(tr, c, bmp, x, y, buf); } int DrawTextRight(TextRenderer *tr, RGBAColour c, BitmapRGBA *bmp, int x, int y, char const *text, ...) { char buf[512]; va_list ap; va_start (ap, text); vsprintf(buf, text, ap); int width = GetTextWidth(tr, buf); return DrawTextSimple(tr, c, bmp, x - width, y, buf); } int DrawTextCentre(TextRenderer *tr, RGBAColour c, BitmapRGBA *bmp, int x, int y, char const *text, ...) { char buf[512]; va_list ap; va_start (ap, text); vsprintf(buf, text, ap); int width = GetTextWidth(tr, buf); return DrawTextSimple(tr, c, bmp, x - width/2, y, buf); } int GetTextWidth(TextRenderer *tr, char const *text, int len) { len = min((int)strlen(text), len); if (tr->fixedWidth) { return len * tr->maxCharWidth; } else { int width = 0; for (; len; len--) width += tr->glyphs[(int)text[len]]->m_width; return width; } } <commit_msg>Fixed a simple but serious bug in GetTextWidth.<commit_after>#include "text_renderer.h" #include "lib/bitmap.h" #include "lib/common.h" #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <limits.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> // **************************************************************************** // Glyph // **************************************************************************** typedef struct { unsigned startX; unsigned startY; unsigned runLen; } EncodedRun; class Glyph { public: unsigned m_width; int m_numRuns; EncodedRun *m_pixelRuns; Glyph(int w) { m_width = w; } }; // **************************************************************************** // Public Functions // **************************************************************************** static bool GetPixelFromBuffer(unsigned *buf, int w, int h, int x, int y) { return buf[(h - y - 1) * w + x] > 0; } TextRenderer *CreateTextRenderer(char const *fontName, int size, int weight) { if (size < 4 || size > 1000 || weight < 1 || weight > 9) return NULL; TextRenderer *tr = new TextRenderer; memset(tr, 0, sizeof(TextRenderer)); // Get the font from GDI HDC winDC = CreateDC("DISPLAY", NULL, NULL, NULL); HDC memDC = CreateCompatibleDC(winDC); int scaledSize = -MulDiv(size, GetDeviceCaps(memDC, LOGPIXELSY), 72); HFONT fontHandle = CreateFont(scaledSize, 0, 0, 0, weight * 100, false, false, false, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, NONANTIALIASED_QUALITY, DEFAULT_PITCH, fontName); ReleaseAssert(fontHandle != NULL, "Couldn't find Windows font '%s'", fontName); // Ask GDI about the font size and fixed-widthness SelectObject(memDC, fontHandle); TEXTMETRIC textMetrics; GetTextMetrics(memDC, &textMetrics); tr->charHeight = textMetrics.tmHeight; tr->maxCharWidth = textMetrics.tmMaxCharWidth; tr->fixedWidth = (textMetrics.tmAveCharWidth == textMetrics.tmMaxCharWidth); // Ask GDI about the name of the font char nameOfFontWeGot[256]; GetTextFace(memDC, 256, nameOfFontWeGot); ReleaseWarn(strnicmp(nameOfFontWeGot, fontName, 255) == 0, "Attempt to load font '%s' failed.\n" "'%s' will be used instead.", fontName, nameOfFontWeGot); // Create an off-screen bitmap BITMAPINFO bmpInfo = { 0 }; bmpInfo.bmiHeader.biBitCount = 32; bmpInfo.bmiHeader.biHeight = tr->charHeight; bmpInfo.bmiHeader.biWidth = tr->maxCharWidth; bmpInfo.bmiHeader.biPlanes = 1; bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); UINT *gdiPixels = 0; HBITMAP memBmp = CreateDIBSection(memDC, (BITMAPINFO *)&bmpInfo, DIB_RGB_COLORS, (void **)&gdiPixels, NULL, 0); HBITMAP prevBmp = (HBITMAP)SelectObject(memDC, memBmp); // Allocate enough EncodedRuns to store the worst case for a glyph of this size. // Worst case is if the whole glyph is encoded as runs of one pixel. There has // to be a gap of one pixel between each run, so there can only be half as many // runs as there are pixels. unsigned tempRunsSize = tr->charHeight * (tr->maxCharWidth / 2 + 1); EncodedRun *tempRuns = new EncodedRun [tempRunsSize]; // Setup stuff needed to render text with GDI SetTextColor(memDC, RGB(255,255,255)); SetBkColor(memDC, 0); RECT rect = { 0, 0, tr->maxCharWidth, tr->charHeight }; // Run-length encode each ASCII character for (int i = 0; i < 256; i++) { char buf[] = {(char)i}; // Get the size of this glyph SIZE glyphSize; GetTextExtentPoint32(memDC, buf, 1, &glyphSize); // if (glyphSize.cx > tr->maxCharWidth) // tr->maxCharWidth = glyphSize.cx; // if (glyphSize.cy > tr->charHeight) // tr->charHeight = glyphSize.cy; // Ask GDI to draw the character ExtTextOut(memDC, 0, 0, ETO_OPAQUE, &rect, buf, 1, 0); // Read back what GDI put in the bitmap and construct a run-length encoding memset(tempRuns, 0, tempRunsSize); EncodedRun *run = tempRuns; for (int y = 0; y < tr->charHeight; y++) { int x = 0; while (x < tr->maxCharWidth) { // Skip blank pixels while (!GetPixelFromBuffer(gdiPixels, tr->maxCharWidth, tr->charHeight, x, y)) { x++; if (x >= tr->maxCharWidth) break; } // Have we got to the end of the line? if (x >= tr->maxCharWidth) continue; run->startX = x; run->startY = y; run->runLen = 0; // Count non-blank pixels while (GetPixelFromBuffer(gdiPixels, tr->maxCharWidth, tr->charHeight, x, y)) { x++; run->runLen++; if (x >= tr->maxCharWidth) break; } run++; } } // Create the glyph to store the encoded runs we've made Glyph *glyph = new Glyph(glyphSize.cx); tr->glyphs[i] = glyph; // Copy the runs into the glyph glyph->m_numRuns = run - tempRuns; glyph->m_pixelRuns = new EncodedRun [glyph->m_numRuns]; memcpy(glyph->m_pixelRuns, tempRuns, glyph->m_numRuns * sizeof(EncodedRun)); } delete [] tempRuns; // Release the GDI resources DeleteDC(winDC); DeleteDC(memDC); DeleteObject(fontHandle); DeleteObject(memBmp); DeleteObject(prevBmp); return tr; } static int DrawTextSimpleClipped(TextRenderer *tr, RGBAColour col, BitmapRGBA *bmp, int _x, int y, char const *text) { int x = _x; RGBAColour *startRow = bmp->pixels + y * bmp->width; int width = bmp->width; if (y + tr->charHeight < 0 || y > (int)bmp->height) return 0; while (*text != '\0') { if (x + tr->maxCharWidth > (int)bmp->width) break; Glyph *glyph = tr->glyphs[(unsigned char)*text]; EncodedRun *rleBuf = glyph->m_pixelRuns; for (int i = 0; i < glyph->m_numRuns; i++) { int y3 = y + rleBuf->startY; if (y3 >= 0 && y3 < (int)bmp->height) { RGBAColour *thisRow = startRow + rleBuf->startY * width; for (unsigned i = 0; i < rleBuf->runLen; i++) { int x3 = x + rleBuf->startX + i; if (x3 >= 0 && x3 < width) thisRow[x3] = col; } } rleBuf++; } x += glyph->m_width; text++; } return _x - x; } int DrawTextSimple(TextRenderer *tr, RGBAColour col, BitmapRGBA *bmp, int _x, int y, char const *text) { int x = _x; int width = bmp->width; if (x < 0 || y < 0 || (y + tr->charHeight) > (int)bmp->height) return DrawTextSimpleClipped(tr, col, bmp, _x, y, text); RGBAColour *startRow = bmp->pixels + y * bmp->width; while (*text != '\0') { if (x + tr->glyphs[*text]->m_width > (int)bmp->width) break; // Copy the glyph onto the stack for better cache performance. This increased the // performance from 13.8 to 14.4 million chars per second. Madness. Glyph glyph = *tr->glyphs[(unsigned char)*text]; EncodedRun *rleBuf = glyph.m_pixelRuns; for (int i = 0; i < glyph.m_numRuns; i++) { RGBAColour *startPixel = startRow + rleBuf->startY * width + rleBuf->startX + x; // Loop unrolled for speed switch (rleBuf->runLen) { case 8: startPixel[7] = col; case 7: startPixel[6] = col; case 6: startPixel[5] = col; case 5: startPixel[4] = col; case 4: startPixel[3] = col; case 3: startPixel[2] = col; case 2: startPixel[1] = col; case 1: startPixel[0] = col; break; default: for (unsigned i = 0; i < rleBuf->runLen; i++) startPixel[i] = col; } rleBuf++; } x += glyph.m_width; text++; } return _x - x; } int DrawTextLeft(TextRenderer *tr, RGBAColour c, BitmapRGBA *bmp, int x, int y, char const *text, ...) { char buf[512]; va_list ap; va_start (ap, text); vsprintf(buf, text, ap); return DrawTextSimple(tr, c, bmp, x, y, buf); } int DrawTextRight(TextRenderer *tr, RGBAColour c, BitmapRGBA *bmp, int x, int y, char const *text, ...) { char buf[512]; va_list ap; va_start (ap, text); vsprintf(buf, text, ap); int width = GetTextWidth(tr, buf); return DrawTextSimple(tr, c, bmp, x - width, y, buf); } int DrawTextCentre(TextRenderer *tr, RGBAColour c, BitmapRGBA *bmp, int x, int y, char const *text, ...) { char buf[512]; va_list ap; va_start (ap, text); vsprintf(buf, text, ap); int width = GetTextWidth(tr, buf); return DrawTextSimple(tr, c, bmp, x - width/2, y, buf); } int GetTextWidth(TextRenderer *tr, char const *text, int len) { len = min((int)strlen(text), len); if (tr->fixedWidth) { return len * tr->maxCharWidth; } else { int width = 0; for (int i = 0; i < len; i++) width += tr->glyphs[(int)text[i]]->m_width; return width; } } <|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 <set> #include <string> #include "chrome/browser/download/download_util.h" #include "base/logging.h" #include "base/string_util.h" namespace download_util { // For file extensions taken from mozilla: /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code, released * March 31, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Doug Turner <dougt@netscape.com> * Dean Tessman <dean_tessman@hotmail.com> * Brodie Thiesfield <brofield@jellycan.com> * Jungshik Shin <jshin@i18nl10n.com> * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ static const char* const g_executables[] = { #if defined(OS_WIN) "ad", "ade", "adp", "app", "application", "asp", "asx", "bas", "bat", "chm", "cmd", "com", "cpl", "crt", "dll", "exe", "fxp", "hlp", "hta", "htm", "html", "htt", "inf", "ins", "isp", "jar", "js", "jse", "lnk", "mad", "maf", "mag", "mam", "maq", "mar", "mas", "mat", "mau", "mav", "maw", "mda", "mdb", "mde", "mdt", "mdw", "mdz", "mht", "mhtml", "msc", "msh", "mshxml", "msi", "msp", "mst", "ocx", "ops", "pcd", "pif", "plg", "prf", "prg", "pst", "reg", "scf", "scr", "sct", "shb", "shs", "shtm", "shtml", "svg", "url", "vb", "vbe", "vbs", "vsd", "vsmacros", "vss", "vst", "vsw", "ws", "wsc", "wsf", "wsh", "xht", "xhtm", "xhtml", "xml", "xsl", "xslt", #elif defined(OS_MACOSX) // TODO(thakis): Figure out what makes sense here -- crbug.com/19096 "dmg", #elif defined(OS_POSIX) // TODO(estade): lengthen this list. "exe", "pl", "py", "rb", "sh", "deb", "rpm", #endif }; bool IsExecutableExtension(const std::string& extension) { for (size_t i = 0; i < arraysize(g_executables); ++i) { if (LowerCaseEqualsASCII(extension, g_executables[i])) return true; } return false; } } // namespace download_util <commit_msg>Linux: Add several shell script extensions to the dangerous downloads list.<commit_after>// 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 <set> #include <string> #include "chrome/browser/download/download_util.h" #include "base/logging.h" #include "base/string_util.h" namespace download_util { // For file extensions taken from mozilla: /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code, released * March 31, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Doug Turner <dougt@netscape.com> * Dean Tessman <dean_tessman@hotmail.com> * Brodie Thiesfield <brofield@jellycan.com> * Jungshik Shin <jshin@i18nl10n.com> * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ static const char* const g_executables[] = { #if defined(OS_WIN) "ad", "ade", "adp", "app", "application", "asp", "asx", "bas", "bat", "chm", "cmd", "com", "cpl", "crt", "dll", "exe", "fxp", "hlp", "hta", "htm", "html", "htt", "inf", "ins", "isp", "jar", "js", "jse", "lnk", "mad", "maf", "mag", "mam", "maq", "mar", "mas", "mat", "mau", "mav", "maw", "mda", "mdb", "mde", "mdt", "mdw", "mdz", "mht", "mhtml", "msc", "msh", "mshxml", "msi", "msp", "mst", "ocx", "ops", "pcd", "pif", "plg", "prf", "prg", "pst", "reg", "scf", "scr", "sct", "shb", "shs", "shtm", "shtml", "svg", "url", "vb", "vbe", "vbs", "vsd", "vsmacros", "vss", "vst", "vsw", "ws", "wsc", "wsf", "wsh", "xht", "xhtm", "xhtml", "xml", "xsl", "xslt", #elif defined(OS_MACOSX) // TODO(thakis): Figure out what makes sense here -- crbug.com/19096 "dmg", #elif defined(OS_POSIX) // TODO(estade): lengthen this list. "bash", "csh", "deb", "exe", "ksh", "pl", "py", "rb", "rpm", "sh", "tcsh", #endif }; bool IsExecutableExtension(const std::string& extension) { for (size_t i = 0; i < arraysize(g_executables); ++i) { if (LowerCaseEqualsASCII(extension, g_executables[i])) return true; } return false; } } // namespace download_util <|endoftext|>
<commit_before> #include <gloperate/pipeline/Pipeline.h> #include <vector> #include <set> #include <cppassist/logging/logging.h> using namespace cppassist; namespace gloperate { Pipeline::Pipeline(ViewerContext * viewerContext, const std::string & name) : Stage(viewerContext, name) , m_sorted(false) { } Pipeline::~Pipeline() { } const std::vector<Stage *> Pipeline::stages() const { return m_stages; } Stage * Pipeline::stage(const std::string & name) const { return m_stagesMap.at(name); } void Pipeline::addStage(Stage * stage, cppexpose::PropertyOwnership ownership) { if (!stage) { return; } addProperty(stage, ownership); m_stages.push_back(stage); if (stage->name() != "") { m_stagesMap.insert(std::make_pair(stage->name(), stage)); } stageAdded(stage); // [TODO] Propagate change } bool Pipeline::removeStage(Stage * stage) { if (!stage) { return false; } auto it = std::find(m_stages.begin(), m_stages.end(), stage); if (it == m_stages.end()) { return false; } m_stages.erase(it); m_stagesMap.erase(stage->name()); stageRemoved(stage); // [TODO] Propagate change removeProperty(stage); return true; } bool Pipeline::destroyStage(Stage * stage) { if (!removeStage(stage)) { return false; } delete stage; return true; } bool Pipeline::isPipeline() const { return true; } void Pipeline::sortStages() { auto couldBeSorted = true; std::vector<Stage *> sorted; std::set<Stage *> touched; std::function<void(Stage *)> visit = [&] (Stage * stage) { if (!couldBeSorted) { sorted.push_back(stage); return; } if (touched.count(stage) > 0) { critical() << "Pipeline is not a directed acyclic graph" << std::endl; couldBeSorted = false; sorted.push_back(stage); return; } touched.insert(stage); for (auto stageIt = m_stages.begin(); stageIt != m_stages.end(); /* nop */) { if (!stage->requires(*stageIt, false)) { ++stageIt; continue; } auto nextStage = *stageIt; m_stages.erase(stageIt); visit(nextStage); stageIt = m_stages.begin(); } sorted.push_back(stage); }; while (!m_stages.empty()) { auto stageIt = m_stages.begin(); auto stage = *stageIt; m_stages.erase(stageIt); visit(stage); } m_stages = sorted; m_sorted = couldBeSorted; } void Pipeline::onContextInit(AbstractGLContext * context) { for (auto stage : m_stages) { stage->initContext(context); } } void Pipeline::onContextDeinit(AbstractGLContext * context) { for (auto stage : m_stages) { stage->deinitContext(context); } } void Pipeline::onProcess(AbstractGLContext * context) { if (!m_sorted) { sortStages(); } for (auto stage : m_stages) { if (stage->needsProcessing()) { stage->process(context); } } } void Pipeline::onInputValueChanged(AbstractSlot *) { // Not necessary for pipelines (handled by inner connections) } void Pipeline::onOutputRequiredChanged(AbstractSlot *) { // Not necessary for pipelines (handled by inner connections) } } // namespace gloperate <commit_msg>Add hint for pipeline invalidation<commit_after> #include <gloperate/pipeline/Pipeline.h> #include <vector> #include <set> #include <cppassist/logging/logging.h> using namespace cppassist; namespace gloperate { // [TODO] invalidate sorting when stages or connections change Pipeline::Pipeline(ViewerContext * viewerContext, const std::string & name) : Stage(viewerContext, name) , m_sorted(false) { } Pipeline::~Pipeline() { } const std::vector<Stage *> Pipeline::stages() const { return m_stages; } Stage * Pipeline::stage(const std::string & name) const { return m_stagesMap.at(name); } void Pipeline::addStage(Stage * stage, cppexpose::PropertyOwnership ownership) { if (!stage) { return; } addProperty(stage, ownership); m_stages.push_back(stage); if (stage->name() != "") { m_stagesMap.insert(std::make_pair(stage->name(), stage)); } stageAdded(stage); // [TODO] Propagate change } bool Pipeline::removeStage(Stage * stage) { if (!stage) { return false; } auto it = std::find(m_stages.begin(), m_stages.end(), stage); if (it == m_stages.end()) { return false; } m_stages.erase(it); m_stagesMap.erase(stage->name()); stageRemoved(stage); // [TODO] Propagate change removeProperty(stage); return true; } bool Pipeline::destroyStage(Stage * stage) { if (!removeStage(stage)) { return false; } delete stage; return true; } bool Pipeline::isPipeline() const { return true; } void Pipeline::sortStages() { auto couldBeSorted = true; std::vector<Stage *> sorted; std::set<Stage *> touched; std::function<void(Stage *)> visit = [&] (Stage * stage) { if (!couldBeSorted) { sorted.push_back(stage); return; } if (touched.count(stage) > 0) { critical() << "Pipeline is not a directed acyclic graph" << std::endl; couldBeSorted = false; sorted.push_back(stage); return; } touched.insert(stage); for (auto stageIt = m_stages.begin(); stageIt != m_stages.end(); /* nop */) { if (!stage->requires(*stageIt, false)) { ++stageIt; continue; } auto nextStage = *stageIt; m_stages.erase(stageIt); visit(nextStage); stageIt = m_stages.begin(); } sorted.push_back(stage); }; while (!m_stages.empty()) { auto stageIt = m_stages.begin(); auto stage = *stageIt; m_stages.erase(stageIt); visit(stage); } m_stages = sorted; m_sorted = couldBeSorted; } void Pipeline::onContextInit(AbstractGLContext * context) { for (auto stage : m_stages) { stage->initContext(context); } } void Pipeline::onContextDeinit(AbstractGLContext * context) { for (auto stage : m_stages) { stage->deinitContext(context); } } void Pipeline::onProcess(AbstractGLContext * context) { if (!m_sorted) { sortStages(); } for (auto stage : m_stages) { if (stage->needsProcessing()) { stage->process(context); } } } void Pipeline::onInputValueChanged(AbstractSlot *) { // Not necessary for pipelines (handled by inner connections) } void Pipeline::onOutputRequiredChanged(AbstractSlot *) { // Not necessary for pipelines (handled by inner connections) } } // namespace gloperate <|endoftext|>
<commit_before>/* This code is subject to the terms of the Mozilla Public License, v.2.0. http://mozilla.org/MPL/2.0/. */ #include "App.h" #include "Interface.h" #include "callbacks/ComputedOptions.h" #include "peer_server/MultiplexedSocketPool.h" #include "storage/FileStore.h" #include "storage/SimpleFileStore.h" #include "serialize/str.h" #include "socket/socket_address.h" #include "socket/UdpServer.h" #include "udt_socket/UdtServer.h" #include <functional> #include <vector> using namespace std::placeholders; namespace { // could be in a separate compilation unit. Point is: these are factory methods. ISocketServer* peerServer(const Turbopump::Options& opts, const socket_address& addr, std::function<void(ISocketWriter&, const char*, unsigned)> onPacket, std::function<bool(int)> onWriteReady) { if (opts.udt) return new UdtServer(addr, onPacket, onWriteReady, new MultiplexedSocketPool<udt_socket>()); else return new UdpServer(addr, onPacket, new MultiplexedSocketPool<udp_socket>()); } IStore* dataStore(const Turbopump::Options& opts) { std::string type; std::string path; std::vector<std::string> parts = turbo::str::split(opts.store, ':'); if ( !parts.empty() ) { type = parts.front(); if (parts.size() >= 2) path = parts[1]; } if (path.empty()) path = opts.home_dir + "/store"; else if (path.front() != '/') path = opts.home_dir + "/" + path; if (type == "file") return new SimpleFileStore(path); // default return new FileStore(path); } } namespace Turbopump { App::App(const Options& opts) : _store(dataStore(opts)) , _opts(opts, Interface{_turbopump.api, _turbopump.logger, *_store, _turbopump.membership, _turbopump.ring, _turbopump.keyLocator, _threadLockedKeyTabulator, _turbopump.corrector, _turbopump.synchronizer, _messenger, _writeSupervisor}) , _turbopump(_opts, *_store, _messenger, _writeSupervisor) , _peerServer(peerServer(opts, socket_address("127.0.0.1", opts.internal_port), std::bind(&PeerPacketHandler::onPacket, &_peerPacketHandler, _1, _2, _3), std::bind(&PartialTransfers::run, &_partialTransfers, _1))) , _messenger(_packer, *_peerServer) , _partialTransfers(*_peerServer) , _writeSupervisor(_packer, _partialTransfers, *_peerServer, _turbopump.store) , _peerCenter(_turbopump.api, _peerExecutor) , _peerPacketHandler(_turbopump.membership, _peerCenter, _turbopump.logger) , _threadLockedKeyTabulator(_turbopump.keyTabulator, _scheduler) { } bool App::run() { _turbopump.state.starting(); _turbopump.preStart(_opts); // start servers if (!_peerExecutor.start()) { _turbopump.logger.logError("failed to start wan handler threads. Abort."); return false; } if (!_peerServer->start()) { _turbopump.logger.logError("failed to start wan server. Abort. " + _peerServer->lastError()); _peerExecutor.stop(); return false; } _turbopump.postStart(_opts); _scheduler.schedule_repeat(std::bind(&Synchronizer::pingRandomPeer, &_turbopump.synchronizer), _opts.sync_interval_ms); _scheduler.schedule_repeat(std::bind(&Synchronizer::offloadUnwantedKeys, &_turbopump.synchronizer), _opts.offload_interval_ms); _turbopump.state.running(); _shutdown.wait(); _turbopump.state.stopping(); _scheduler.shutdown(); _peerServer->stop(); _peerExecutor.stop(); return true; } void App::shutdown() { // callable by signal handlers. // e.g. do not attempt to wait on mutexes. _shutdown.notify_all(); } const Api& App::api() const { return _turbopump.api; } }//namespace <commit_msg>Use new interface pattern.<commit_after>/* This code is subject to the terms of the Mozilla Public License, v.2.0. http://mozilla.org/MPL/2.0/. */ #include "App.h" #include "Interface.h" #include "callbacks/ComputedOptions.h" #include "peer_server/MultiplexedSocketPool.h" #include "storage/FileStore.h" #include "storage/SimpleFileStore.h" #include "serialize/str.h" #include "socket/socket_address.h" #include "socket/UdpServer.h" #include "udt_socket/UdtServer.h" #include <functional> #include <vector> using namespace std::placeholders; namespace { // could be in a separate compilation unit. Point is: these are factory methods. ISocketServer* peerServer(const Turbopump::Options& opts, const socket_address& addr) { if (opts.udt) return new UdtServer(addr, new MultiplexedSocketPool<udt_socket>()); else return new UdpServer(addr, new MultiplexedSocketPool<udp_socket>()); } IStore* dataStore(const Turbopump::Options& opts) { std::string type; std::string path; std::vector<std::string> parts = turbo::str::split(opts.store, ':'); if ( !parts.empty() ) { type = parts.front(); if (parts.size() >= 2) path = parts[1]; } if (path.empty()) path = opts.home_dir + "/store"; else if (path.front() != '/') path = opts.home_dir + "/" + path; if (type == "file") return new SimpleFileStore(path); // default return new FileStore(path); } } namespace Turbopump { App::App(const Options& opts) : _store(dataStore(opts)) , _opts(opts, Interface{_turbopump.api, _turbopump.logger, *_store, _turbopump.membership, _turbopump.ring, _turbopump.keyLocator, _threadLockedKeyTabulator, _turbopump.corrector, _turbopump.synchronizer, _messenger, _writeSupervisor}) , _turbopump(_opts, *_store, _messenger, _writeSupervisor) , _peerServer(peerServer(opts, socket_address("127.0.0.1", opts.internal_port))) , _messenger(_packer, *_peerServer) , _partialTransfers(*_peerServer) , _writeSupervisor(_packer, _partialTransfers, *_peerServer, _turbopump.store) , _peerCenter(_turbopump.api, _peerExecutor) , _peerPacketHandler(_turbopump.membership, _peerCenter, _turbopump.logger) , _threadLockedKeyTabulator(_turbopump.keyTabulator, _scheduler) { } bool App::run() { _turbopump.state.starting(); _turbopump.preStart(_opts); // start servers if (!_peerExecutor.start()) { _turbopump.logger.logError("failed to start wan handler threads. Abort."); return false; } if (!_peerServer->start(std::bind(&PeerPacketHandler::onPacket, &_peerPacketHandler, _1, _2, _3), std::bind(&PartialTransfers::run, &_partialTransfers, _1))) { _turbopump.logger.logError("failed to start wan server. Abort. " + _peerServer->lastError()); _peerExecutor.stop(); return false; } _turbopump.postStart(_opts); _scheduler.schedule_repeat(std::bind(&Synchronizer::pingRandomPeer, &_turbopump.synchronizer), _opts.sync_interval_ms); _scheduler.schedule_repeat(std::bind(&Synchronizer::offloadUnwantedKeys, &_turbopump.synchronizer), _opts.offload_interval_ms); _turbopump.state.running(); _shutdown.wait(); _turbopump.state.stopping(); _scheduler.shutdown(); _peerServer->stop(); _peerExecutor.stop(); return true; } void App::shutdown() { // callable by signal handlers. // e.g. do not attempt to wait on mutexes. _shutdown.notify_all(); } const Api& App::api() const { return _turbopump.api; } }//namespace <|endoftext|>
<commit_before>//============================================================================ // Name : TimeSeriesStatisticsDemo.cpp // Author : Dominik Skoda <skoda@d3s.mff.cuni.cz> // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <cstdlib> #include "TimeSeries.h" #include "StudentsDistribution.h" using namespace std; int main() { cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!! TimeSeries<10000,1000> s; for(size_t i = 0; i < 20; ++i){ s.addSample(i%5, i*300); } StudentsDistribution d = s.getMean(); cout << d.isLessThan(2, 0.95) << endl; return 0; } <commit_msg>Test of the tnc function.<commit_after>//============================================================================ // Name : TimeSeriesStatisticsDemo.cpp // Author : Dominik Skoda <skoda@d3s.mff.cuni.cz> // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <cstdlib> #include "TimeSeries.h" #include "StudentsDistribution.h" #include "TDistribution.h" using namespace std; int main() { cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!! TimeSeries<10000,1000> s; for(size_t i = 0; i < 20; ++i){ s.addSample(i%5, i*300); } StudentsDistribution d = s.getMean(); cout << d.isLessThan(2, 0.95) << endl; TDistribution td; int err; for(size_t i = 0; i < 100; ++i){ double t = td.tnc(0.975, i, 0, &err); if(err){ cout << "err " << err << endl; } cout << t << endl; } return 0; } <|endoftext|>
<commit_before>/*************************************************************************** ** ** ** Copyright (C) 2009-2011 Nokia Corporation. ** ** ** ** Author: Ilya Dogolazky <ilya.dogolazky@nokia.com> ** ** Author: Simo Piiroinen <simo.piiroinen@nokia.com> ** ** Author: Victor Portnov <ext-victor.portnov@nokia.com> ** ** ** ** This file is part of Timed ** ** ** ** Timed 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. ** ** ** ** Timed 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 Timed. If not, see http://www.gnu.org/licenses/ ** ** ** ***************************************************************************/ #include <timed/qmacro.h> #include <timed/wallclock> #include "timed/exception.h" #include "daemon/flags.h" #include "wall-settings.h" #include "nanotime.h" Maemo::Timed::WallClock::Settings::Settings() { p = new wall_settings_pimple_t ; } Maemo::Timed::WallClock::Settings::~Settings() { delete p ; } void Maemo::Timed::WallClock::Settings::setTimeNitz() { if(p->opcodes & WallOpcode::Op_Set_Time_Mask) p->valid = false ; p->opcodes |= WallOpcode::Op_Set_Time_Nitz ; } void Maemo::Timed::WallClock::Settings::setTimeManual() { if(p->opcodes & WallOpcode::Op_Set_Time_Mask) p->valid = false ; p->opcodes |= WallOpcode::Op_Set_Time_Manual ; } void Maemo::Timed::WallClock::Settings::setTimeManual(time_t value) { if(p->opcodes & WallOpcode::Op_Set_Time_Mask) p->valid = false ; if(value<=0) p->valid = false ; p->opcodes |= WallOpcode::Op_Set_Time_Manual_Val ; p->time_at_zero = nanotime_t::from_time_t(value)-nanotime_t::monotonic_now() ; } void Maemo::Timed::WallClock::Settings::setOffsetCellular() { if(p->opcodes & WallOpcode::Op_Set_Zone_Mask) p->valid = false ; p->opcodes |= WallOpcode::Op_Set_Offset_Cellular ; } void Maemo::Timed::WallClock::Settings::setOffsetManual() { if(p->opcodes & WallOpcode::Op_Set_Zone_Mask) p->valid = false ; p->opcodes |= WallOpcode::Op_Set_Offset_Manual ; } void Maemo::Timed::WallClock::Settings::setOffsetManual(int off) { if(p->opcodes & WallOpcode::Op_Set_Zone_Mask) p->valid = false ; p->opcodes |= WallOpcode::Op_Set_Offset_Manual_Val ; p->offset = off ; } void Maemo::Timed::WallClock::Settings::setTimezoneCellular() { if(p->opcodes & WallOpcode::Op_Set_Zone_Mask) p->valid = false ; p->opcodes |= WallOpcode::Op_Set_Timezone_Cellular ; } void Maemo::Timed::WallClock::Settings::setTimezoneCellular(const QString &fbz) { if(p->opcodes & WallOpcode::Op_Set_Zone_Mask) p->valid = false ; p->opcodes |= WallOpcode::Op_Set_Timezone_Cellular_Fbk ; p->zone = fbz ; } void Maemo::Timed::WallClock::Settings::setTimezoneManual(const QString &fbz) { if(p->opcodes & WallOpcode::Op_Set_Zone_Mask) p->valid = false ; p->opcodes |= WallOpcode::Op_Set_Timezone_Manual ; p->zone = fbz ; } void Maemo::Timed::WallClock::Settings::setFlag24(bool flag24) { if(p->opcodes & WallOpcode::Op_Set_Format_12_24_Mask) p->valid = false ; if(flag24) p->opcodes |= WallOpcode::Op_Set_24 ; else p->opcodes |= WallOpcode::Op_Set_12 ; } bool Maemo::Timed::WallClock::Settings::check() const { return p->opcodes != 0 && p->valid ; } QString Maemo::Timed::WallClock::Settings::str() const { if(p==NULL) return "{ NULL }" ; else return p->str() ; } QString Maemo::Timed::WallClock::wall_settings_pimple_t::str() const { QString res ; QTextStream os(&res) ; os << "{ opcodes='" ; bool first = true ; using namespace WallOpcode ; #define _x(x) if(opcodes&x){if(!first)os<<"+";first=false;os<<#x;} _x(Op_Set_Time_Nitz) ; _x(Op_Set_Time_Manual) ; _x(Op_Set_Time_Manual_Val) ; _x(Op_Set_Offset_Cellular) ; _x(Op_Set_Offset_Manual) ; _x(Op_Set_Offset_Manual_Val) ; _x(Op_Set_Timezone_Cellular) ; _x(Op_Set_Timezone_Cellular_Fbk) ; _x(Op_Set_Timezone_Manual) ; _x(Op_Set_24) ; _x(Op_Set_12) ; #undef _x os << "', " ; os << " time_at_zero=" << time_at_zero.sec() << "," << time_at_zero.nano() ; os << "', " ; os << " offset=" << offset << ", " ; os << " zone='" << zone << "'" ; os << " valid=" << valid << "}" << flush ; return res ; } QVariant Maemo::Timed::WallClock::Settings::dbus_output(const char *pretty) const { if(!p->valid) throw Maemo::Timed::Exception(pretty, "settings aren't valid") ; return QVariant::fromValue(*p) ; } QDBusArgument &operator<<(QDBusArgument &out, const Maemo::Timed::WallClock::wall_settings_pimple_t &x) { qdbusargument_structrure_wrapper o(out) ; return out << x.opcodes << x.time_at_zero << x.offset << x.zone ; } const QDBusArgument &operator>>(const QDBusArgument &in, Maemo::Timed::WallClock::wall_settings_pimple_t &x) { qdbusargument_structrure_wrapper_const i(in) ; return in >> x.opcodes >> x.time_at_zero >> x.offset >> x.zone ; } register_qtdbus_metatype(Maemo::Timed::WallClock::wall_settings_pimple_t, 0) ; <commit_msg>nice priniting<commit_after>/*************************************************************************** ** ** ** Copyright (C) 2009-2011 Nokia Corporation. ** ** ** ** Author: Ilya Dogolazky <ilya.dogolazky@nokia.com> ** ** Author: Simo Piiroinen <simo.piiroinen@nokia.com> ** ** Author: Victor Portnov <ext-victor.portnov@nokia.com> ** ** ** ** This file is part of Timed ** ** ** ** Timed 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. ** ** ** ** Timed 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 Timed. If not, see http://www.gnu.org/licenses/ ** ** ** ***************************************************************************/ #include <timed/qmacro.h> #include <timed/wallclock> #include "timed/exception.h" #include "daemon/flags.h" #include "wall-settings.h" #include "nanotime.h" Maemo::Timed::WallClock::Settings::Settings() { p = new wall_settings_pimple_t ; } Maemo::Timed::WallClock::Settings::~Settings() { delete p ; } void Maemo::Timed::WallClock::Settings::setTimeNitz() { if(p->opcodes & WallOpcode::Op_Set_Time_Mask) p->valid = false ; p->opcodes |= WallOpcode::Op_Set_Time_Nitz ; } void Maemo::Timed::WallClock::Settings::setTimeManual() { if(p->opcodes & WallOpcode::Op_Set_Time_Mask) p->valid = false ; p->opcodes |= WallOpcode::Op_Set_Time_Manual ; } void Maemo::Timed::WallClock::Settings::setTimeManual(time_t value) { if(p->opcodes & WallOpcode::Op_Set_Time_Mask) p->valid = false ; if(value<=0) p->valid = false ; p->opcodes |= WallOpcode::Op_Set_Time_Manual_Val ; p->time_at_zero = nanotime_t::from_time_t(value)-nanotime_t::monotonic_now() ; } void Maemo::Timed::WallClock::Settings::setOffsetCellular() { if(p->opcodes & WallOpcode::Op_Set_Zone_Mask) p->valid = false ; p->opcodes |= WallOpcode::Op_Set_Offset_Cellular ; } void Maemo::Timed::WallClock::Settings::setOffsetManual() { if(p->opcodes & WallOpcode::Op_Set_Zone_Mask) p->valid = false ; p->opcodes |= WallOpcode::Op_Set_Offset_Manual ; } void Maemo::Timed::WallClock::Settings::setOffsetManual(int off) { if(p->opcodes & WallOpcode::Op_Set_Zone_Mask) p->valid = false ; p->opcodes |= WallOpcode::Op_Set_Offset_Manual_Val ; p->offset = off ; } void Maemo::Timed::WallClock::Settings::setTimezoneCellular() { if(p->opcodes & WallOpcode::Op_Set_Zone_Mask) p->valid = false ; p->opcodes |= WallOpcode::Op_Set_Timezone_Cellular ; } void Maemo::Timed::WallClock::Settings::setTimezoneCellular(const QString &fbz) { if(p->opcodes & WallOpcode::Op_Set_Zone_Mask) p->valid = false ; p->opcodes |= WallOpcode::Op_Set_Timezone_Cellular_Fbk ; p->zone = fbz ; } void Maemo::Timed::WallClock::Settings::setTimezoneManual(const QString &fbz) { if(p->opcodes & WallOpcode::Op_Set_Zone_Mask) p->valid = false ; p->opcodes |= WallOpcode::Op_Set_Timezone_Manual ; p->zone = fbz ; } void Maemo::Timed::WallClock::Settings::setFlag24(bool flag24) { if(p->opcodes & WallOpcode::Op_Set_Format_12_24_Mask) p->valid = false ; if(flag24) p->opcodes |= WallOpcode::Op_Set_24 ; else p->opcodes |= WallOpcode::Op_Set_12 ; } bool Maemo::Timed::WallClock::Settings::check() const { return p->opcodes != 0 && p->valid ; } QString Maemo::Timed::WallClock::Settings::str() const { if(p==NULL) return "{ NULL }" ; else return p->str() ; } QString Maemo::Timed::WallClock::wall_settings_pimple_t::str() const { QString res ; QTextStream os(&res) ; os << "{opcodes='" ; bool first = true ; using namespace WallOpcode ; #define _x(x) if(opcodes&x){if(!first)os<<"+";first=false;os<<#x;} _x(Op_Set_Time_Nitz) ; _x(Op_Set_Time_Manual) ; _x(Op_Set_Time_Manual_Val) ; _x(Op_Set_Offset_Cellular) ; _x(Op_Set_Offset_Manual) ; _x(Op_Set_Offset_Manual_Val) ; _x(Op_Set_Timezone_Cellular) ; _x(Op_Set_Timezone_Cellular_Fbk) ; _x(Op_Set_Timezone_Manual) ; _x(Op_Set_24) ; _x(Op_Set_12) ; #undef _x os << "', " ; os << "time_at_zero=" << time_at_zero.str().c_str() << ", " ; os << "offset=" << offset << ", " ; os << "zone='" << zone << "', " ; os << "valid=" << valid << "}" << flush ; return res ; } QVariant Maemo::Timed::WallClock::Settings::dbus_output(const char *pretty) const { if(!p->valid) throw Maemo::Timed::Exception(pretty, "settings aren't valid") ; return QVariant::fromValue(*p) ; } QDBusArgument &operator<<(QDBusArgument &out, const Maemo::Timed::WallClock::wall_settings_pimple_t &x) { qdbusargument_structrure_wrapper o(out) ; return out << x.opcodes << x.time_at_zero << x.offset << x.zone ; } const QDBusArgument &operator>>(const QDBusArgument &in, Maemo::Timed::WallClock::wall_settings_pimple_t &x) { qdbusargument_structrure_wrapper_const i(in) ; return in >> x.opcodes >> x.time_at_zero >> x.offset >> x.zone ; } register_qtdbus_metatype(Maemo::Timed::WallClock::wall_settings_pimple_t, 0) ; <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkExtractImageTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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 <iostream> #include "itkImage.h" #include "itkImage.h" #include "itkImageRegionIterator.h" #include "itkExtractImageFilter.h" #include "itkFileOutputWindow.h" #include "itkStreamingImageFilter.h" int itkExtractImageTest(int, char* [] ) { itk::FileOutputWindow::Pointer fow = itk::FileOutputWindow::New(); fow->SetInstance(fow); int nextVal; // typedefs to simplify the syntax typedef itk::Image<short, 2> SimpleImage; SimpleImage::Pointer simpleImage = SimpleImage::New(); std::cout << "Simple image spacing: " << simpleImage->GetSpacing()[0] << ", " << simpleImage->GetSpacing()[1] << std::endl; // typedefs to simplify the syntax typedef itk::Image<short, 2> ShortImage; typedef itk::Image<short, 1> LineImage; // Test the creation of an image with native type ShortImage::Pointer if2 = ShortImage::New(); // fill in an image ShortImage::IndexType index = {{0, 0}}; ShortImage::SizeType size = {{8, 12}}; ShortImage::RegionType region; int row, column; region.SetSize( size ); region.SetIndex( index ); if2->SetLargestPossibleRegion( region ); if2->SetBufferedRegion( region ); if2->Allocate(); itk::ImageRegionIterator<ShortImage> iterator(if2, region); short i=0; for (; !iterator.IsAtEnd(); ++iterator, ++i) { iterator.Set( i ); } std::cout << "Input Image: " << if2 << std::endl; // Create a filter itk::ExtractImageFilter< ShortImage, ShortImage >::Pointer extract; extract = itk::ExtractImageFilter< ShortImage, ShortImage >::New(); extract->SetInput( if2 ); // fill in an image ShortImage::IndexType extractIndex = {{0, 0}}; ShortImage::SizeType extractSize = {{8, 12}}; ShortImage::RegionType extractRegion; extractRegion.SetSize( extractSize ); extractRegion.SetIndex( extractIndex ); extract->SetExtractionRegion(extractRegion); extract->UpdateLargestPossibleRegion(); std::cout << extract << std::endl; std::cout << "Input spacing: " << if2->GetSpacing()[0] << ", " << if2->GetSpacing()[1] << std::endl; std::cout << "Output spacing: " << extract->GetOutput()->GetSpacing()[0] << ", " << extract->GetOutput()->GetSpacing()[1] << std::endl; ShortImage::RegionType requestedRegion; bool passed; // CASE 1 extractIndex[0] = 1; extractIndex[1] = 2; extractSize[0] = 5; extractSize[1] = 6; extractRegion.SetSize( extractSize ); extractRegion.SetIndex( extractIndex ); extract->SetExtractionRegion(extractRegion); extract->UpdateLargestPossibleRegion(); requestedRegion = extract->GetOutput()->GetRequestedRegion(); itk::ImageRegionIterator<ShortImage> iteratorIn1(extract->GetOutput(), requestedRegion); passed = true; size = requestedRegion.GetSize(); index = requestedRegion.GetIndex(); if ((index[0] != extractIndex[0]) || (index[1] != extractIndex[1]) || (size[0] != extractSize[0]) || (size[1] != extractSize[1])) { passed = false; } else { for (; !iteratorIn1.IsAtEnd(); ++iteratorIn1) { row = iteratorIn1.GetIndex()[0]; column = iteratorIn1.GetIndex()[1]; if ((row < 0) || (row>7) || (column < 0) || (column > 11)) { if ( iteratorIn1.Get() != 13 ) { passed = false; } } else { nextVal = 8*column+row; if (iteratorIn1.Get() != nextVal) { std::cout << "Error: (" << row << ", " << column << "), expected " << nextVal << " got " << iteratorIn1.Get() << std::endl; passed = false; } } } } if (passed) { std::cout << "ExtractImageFilter case 1 passed." << std::endl; } else { std::cout << "ExtractImageFilter case 1 failed." << std::endl; return EXIT_FAILURE; } // CASE 2 extractIndex[0] = 1; extractIndex[1] = 1; extractSize[0] = 7; extractSize[1] = 11; extractRegion.SetSize( extractSize ); extractRegion.SetIndex( extractIndex ); extract->SetExtractionRegion(extractRegion); // Create a stream itk::StreamingImageFilter< ShortImage, ShortImage >::Pointer stream; stream = itk::StreamingImageFilter< ShortImage, ShortImage >::New(); stream->SetInput( extract->GetOutput() ); stream->SetNumberOfStreamDivisions(2); ShortImage::RegionType setRegion = extract->GetExtractionRegion(); size = setRegion.GetSize(); index = setRegion.GetIndex(); if ((index[0] != extractIndex[0]) || (index[1] != extractIndex[1]) || (size[0] != extractSize[0]) || (size[1] != extractSize[1])) { passed = false; } else { stream->UpdateLargestPossibleRegion(); requestedRegion = stream->GetOutput()->GetRequestedRegion(); itk::ImageRegionIterator<ShortImage> iteratorIn2(stream->GetOutput(), requestedRegion); nextVal = 0; passed = true; size = requestedRegion.GetSize(); index = requestedRegion.GetIndex(); if ((index[0] != extractIndex[0]) || (index[1] != extractIndex[1]) || (size[0] != extractSize[0]) || (size[1] != extractSize[1])) { passed = false; } else { for (; !iteratorIn2.IsAtEnd(); ++iteratorIn2) { row = iteratorIn2.GetIndex()[0]; column = iteratorIn2.GetIndex()[1]; if ((row < 0) || (row>7) || (column < 0) || (column > 11)) { if ( iteratorIn2.Get() != 13 ) { passed = false; } } else { nextVal = 8*column+row; if (iteratorIn2.Get() != nextVal) { std::cout << "Error: (" << row << ", " << column << "), expected " << nextVal << " got " << iteratorIn2.Get() << std::endl; passed = false; } } } } } // need to put in code to check whether the proper region was extracted. // if (passed) { std::cout << "ExtractImageFilter case 2 passed." << std::endl; } else { std::cout << "ExtractImageFilter case 2 failed." << std::endl; return EXIT_FAILURE; } //Case 3: Try extracting a single row itk::ExtractImageFilter<ShortImage, LineImage>::Pointer lineExtract; lineExtract = itk::ExtractImageFilter<ShortImage, LineImage>::New(); lineExtract->SetInput( if2 ); extractIndex[0] = 2; extractIndex[1] = 0; extractSize[0] = 0; extractSize[1] = 3; extractRegion.SetIndex( extractIndex ); extractRegion.SetSize( extractSize ); lineExtract->SetExtractionRegion( extractRegion ); lineExtract->UpdateLargestPossibleRegion(); std::cout << "After 1D extraction. " << std::endl; //test the dimension collapse LineImage::RegionType requestedLineRegion; requestedLineRegion = lineExtract->GetOutput()->GetRequestedRegion(); itk::ImageRegionIterator<LineImage> iteratorLineIn(lineExtract->GetOutput(), requestedLineRegion); ShortImage::IndexType testIndex; for (; !iteratorLineIn.IsAtEnd(); ++iteratorLineIn) { LineImage::PixelType linePixelValue = iteratorLineIn.Get(); testIndex[0] = extractIndex[0]; testIndex[1] = iteratorLineIn.GetIndex()[0]; if (linePixelValue != if2->GetPixel(testIndex)) { passed = false; } } if (passed) { std::cout << "ExtractImageFilter case 3 passed." << std::endl; } else { std::cout << "ExtractImageFilter case 3 failed." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>ERR: warning.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkExtractImageTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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 <iostream> #include "itkImage.h" #include "itkImage.h" #include "itkImageRegionIterator.h" #include "itkExtractImageFilter.h" #include "itkFileOutputWindow.h" #include "itkStreamingImageFilter.h" int itkExtractImageTest(int, char* [] ) { itk::FileOutputWindow::Pointer fow = itk::FileOutputWindow::New(); fow->SetInstance(fow); int nextVal; // typedefs to simplify the syntax typedef itk::Image<short, 2> SimpleImage; SimpleImage::Pointer simpleImage = SimpleImage::New(); std::cout << "Simple image spacing: " << simpleImage->GetSpacing()[0] << ", " << simpleImage->GetSpacing()[1] << std::endl; // typedefs to simplify the syntax typedef itk::Image<short, 2> ShortImage; typedef itk::Image<short, 1> LineImage; // Test the creation of an image with native type ShortImage::Pointer if2 = ShortImage::New(); // fill in an image ShortImage::IndexType index = {{0, 0}}; ShortImage::SizeType size = {{8, 12}}; ShortImage::RegionType region; int row, column; region.SetSize( size ); region.SetIndex( index ); if2->SetLargestPossibleRegion( region ); if2->SetBufferedRegion( region ); if2->Allocate(); itk::ImageRegionIterator<ShortImage> iterator(if2, region); short i=0; for (; !iterator.IsAtEnd(); ++iterator, ++i) { iterator.Set( i ); } std::cout << "Input Image: " << if2 << std::endl; // Create a filter itk::ExtractImageFilter< ShortImage, ShortImage >::Pointer extract; extract = itk::ExtractImageFilter< ShortImage, ShortImage >::New(); extract->SetInput( if2 ); // fill in an image ShortImage::IndexType extractIndex = {{0, 0}}; ShortImage::SizeType extractSize = {{8, 12}}; ShortImage::RegionType extractRegion; extractRegion.SetSize( extractSize ); extractRegion.SetIndex( extractIndex ); extract->SetExtractionRegion(extractRegion); extract->UpdateLargestPossibleRegion(); std::cout << extract << std::endl; std::cout << "Input spacing: " << if2->GetSpacing()[0] << ", " << if2->GetSpacing()[1] << std::endl; std::cout << "Output spacing: " << extract->GetOutput()->GetSpacing()[0] << ", " << extract->GetOutput()->GetSpacing()[1] << std::endl; ShortImage::RegionType requestedRegion; bool passed; // CASE 1 extractIndex[0] = 1; extractIndex[1] = 2; extractSize[0] = 5; extractSize[1] = 6; extractRegion.SetSize( extractSize ); extractRegion.SetIndex( extractIndex ); extract->SetExtractionRegion(extractRegion); extract->UpdateLargestPossibleRegion(); requestedRegion = extract->GetOutput()->GetRequestedRegion(); itk::ImageRegionIterator<ShortImage> iteratorIn1(extract->GetOutput(), requestedRegion); passed = true; size = requestedRegion.GetSize(); index = requestedRegion.GetIndex(); if ((index[0] != extractIndex[0]) || (index[1] != extractIndex[1]) || (size[0] != extractSize[0]) || (size[1] != extractSize[1])) { passed = false; } else { for (; !iteratorIn1.IsAtEnd(); ++iteratorIn1) { row = iteratorIn1.GetIndex()[0]; column = iteratorIn1.GetIndex()[1]; if ((row < 0) || (row>7) || (column < 0) || (column > 11)) { if ( iteratorIn1.Get() != 13 ) { passed = false; } } else { nextVal = 8*column+row; if (iteratorIn1.Get() != nextVal) { std::cout << "Error: (" << row << ", " << column << "), expected " << nextVal << " got " << iteratorIn1.Get() << std::endl; passed = false; } } } } if (passed) { std::cout << "ExtractImageFilter case 1 passed." << std::endl; } else { std::cout << "ExtractImageFilter case 1 failed." << std::endl; return EXIT_FAILURE; } // CASE 2 extractIndex[0] = 1; extractIndex[1] = 1; extractSize[0] = 7; extractSize[1] = 11; extractRegion.SetSize( extractSize ); extractRegion.SetIndex( extractIndex ); extract->SetExtractionRegion(extractRegion); // Create a stream itk::StreamingImageFilter< ShortImage, ShortImage >::Pointer stream; stream = itk::StreamingImageFilter< ShortImage, ShortImage >::New(); stream->SetInput( extract->GetOutput() ); stream->SetNumberOfStreamDivisions(2); ShortImage::RegionType setRegion = extract->GetExtractionRegion(); size = setRegion.GetSize(); index = setRegion.GetIndex(); if ((index[0] != extractIndex[0]) || (index[1] != extractIndex[1]) || (size[0] != extractSize[0]) || (size[1] != extractSize[1])) { passed = false; } else { stream->UpdateLargestPossibleRegion(); requestedRegion = stream->GetOutput()->GetRequestedRegion(); itk::ImageRegionIterator<ShortImage> iteratorIn2(stream->GetOutput(), requestedRegion); passed = true; size = requestedRegion.GetSize(); index = requestedRegion.GetIndex(); if ((index[0] != extractIndex[0]) || (index[1] != extractIndex[1]) || (size[0] != extractSize[0]) || (size[1] != extractSize[1])) { passed = false; } else { for (; !iteratorIn2.IsAtEnd(); ++iteratorIn2) { row = iteratorIn2.GetIndex()[0]; column = iteratorIn2.GetIndex()[1]; if ((row < 0) || (row>7) || (column < 0) || (column > 11)) { if ( iteratorIn2.Get() != 13 ) { passed = false; } } else { nextVal = 8*column+row; if (iteratorIn2.Get() != nextVal) { std::cout << "Error: (" << row << ", " << column << "), expected " << nextVal << " got " << iteratorIn2.Get() << std::endl; passed = false; } } } } } // need to put in code to check whether the proper region was extracted. // if (passed) { std::cout << "ExtractImageFilter case 2 passed." << std::endl; } else { std::cout << "ExtractImageFilter case 2 failed." << std::endl; return EXIT_FAILURE; } //Case 3: Try extracting a single row itk::ExtractImageFilter<ShortImage, LineImage>::Pointer lineExtract; lineExtract = itk::ExtractImageFilter<ShortImage, LineImage>::New(); lineExtract->SetInput( if2 ); extractIndex[0] = 2; extractIndex[1] = 0; extractSize[0] = 0; extractSize[1] = 3; extractRegion.SetIndex( extractIndex ); extractRegion.SetSize( extractSize ); lineExtract->SetExtractionRegion( extractRegion ); lineExtract->UpdateLargestPossibleRegion(); std::cout << "After 1D extraction. " << std::endl; //test the dimension collapse LineImage::RegionType requestedLineRegion; requestedLineRegion = lineExtract->GetOutput()->GetRequestedRegion(); itk::ImageRegionIterator<LineImage> iteratorLineIn(lineExtract->GetOutput(), requestedLineRegion); ShortImage::IndexType testIndex; for (; !iteratorLineIn.IsAtEnd(); ++iteratorLineIn) { LineImage::PixelType linePixelValue = iteratorLineIn.Get(); testIndex[0] = extractIndex[0]; testIndex[1] = iteratorLineIn.GetIndex()[0]; if (linePixelValue != if2->GetPixel(testIndex)) { passed = false; } } if (passed) { std::cout << "ExtractImageFilter case 3 passed." << std::endl; } else { std::cout << "ExtractImageFilter case 3 failed." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|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 "chrome/renderer/audio_message_filter.h" #include "base/message_loop.h" #include "chrome/common/render_messages.h" #include "ipc/ipc_logging.h" AudioMessageFilter::AudioMessageFilter(int32 route_id) : channel_(NULL), route_id_(route_id), message_loop_(NULL) { } AudioMessageFilter::~AudioMessageFilter() { } // Called on the IPC thread. bool AudioMessageFilter::Send(IPC::Message* message) { if (!channel_) { delete message; return false; } message->set_routing_id(route_id_); return channel_->Send(message); } bool AudioMessageFilter::OnMessageReceived(const IPC::Message& message) { if (message.routing_id() != route_id_) return false; bool handled = true; IPC_BEGIN_MESSAGE_MAP(AudioMessageFilter, message) IPC_MESSAGE_HANDLER(ViewMsg_RequestAudioPacket, OnRequestPacket) IPC_MESSAGE_HANDLER(ViewMsg_NotifyAudioStreamCreated, OnStreamCreated) IPC_MESSAGE_HANDLER(ViewMsg_NotifyLowLatencyAudioStreamCreated, OnLowLatencyStreamCreated) IPC_MESSAGE_HANDLER(ViewMsg_NotifyAudioStreamStateChanged, OnStreamStateChanged) IPC_MESSAGE_HANDLER(ViewMsg_NotifyAudioStreamVolume, OnStreamVolume) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void AudioMessageFilter::OnFilterAdded(IPC::Channel* channel) { // Captures the message loop for IPC. message_loop_ = MessageLoop::current(); channel_ = channel; } void AudioMessageFilter::OnFilterRemoved() { channel_ = NULL; } void AudioMessageFilter::OnChannelClosing() { channel_ = NULL; } void AudioMessageFilter::OnRequestPacket(const IPC::Message& msg, int stream_id, uint32 bytes_in_buffer, int64 message_timestamp) { Delegate* delegate = delegates_.Lookup(stream_id); if (!delegate) { DLOG(WARNING) << "Got audio packet request for a non-existent or removed" " audio renderer."; return; } delegate->OnRequestPacket(bytes_in_buffer, base::Time::FromInternalValue(message_timestamp)); } void AudioMessageFilter::OnStreamCreated(int stream_id, base::SharedMemoryHandle handle, uint32 length) { Delegate* delegate = delegates_.Lookup(stream_id); if (!delegate) { DLOG(WARNING) << "Got audio stream event for a non-existent or removed" " audio renderer."; return; } delegate->OnCreated(handle, length); } void AudioMessageFilter::OnLowLatencyStreamCreated( int stream_id, base::SharedMemoryHandle handle, #if defined(OS_WIN) base::SyncSocket::Handle socket_handle, #else base::FileDescriptor socket_descriptor, #endif uint32 length) { Delegate* delegate = delegates_.Lookup(stream_id); if (!delegate) { DLOG(WARNING) << "Got audio stream event for a non-existent or removed" " audio renderer."; return; } #if !defined(OS_WIN) base::SyncSocket::Handle socket_handle = socket_descriptor.fd; #endif delegate->OnLowLatencyCreated(handle, socket_handle, length); } void AudioMessageFilter::OnStreamStateChanged( int stream_id, const ViewMsg_AudioStreamState_Params& state) { Delegate* delegate = delegates_.Lookup(stream_id); if (!delegate) { DLOG(WARNING) << "Got audio stream event for a non-existent or removed" " audio renderer."; return; } delegate->OnStateChanged(state); } void AudioMessageFilter::OnStreamVolume(int stream_id, double volume) { Delegate* delegate = delegates_.Lookup(stream_id); if (!delegate) { DLOG(WARNING) << "Got audio stream event for a non-existent or removed" " audio renderer."; return; } delegate->OnVolume(volume); } int32 AudioMessageFilter::AddDelegate(Delegate* delegate) { return delegates_.Add(delegate); } void AudioMessageFilter::RemoveDelegate(int32 id) { delegates_.Remove(id); } <commit_msg>Fix thread safety issue in AudioMessageFilter. IPC::Channel can only be used on the IO thread. Review URL: http://codereview.chromium.org/600002<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 "chrome/renderer/audio_message_filter.h" #include "base/message_loop.h" #include "chrome/common/render_messages.h" #include "ipc/ipc_logging.h" AudioMessageFilter::AudioMessageFilter(int32 route_id) : channel_(NULL), route_id_(route_id), message_loop_(NULL) { } AudioMessageFilter::~AudioMessageFilter() { } // Called on the IPC thread. bool AudioMessageFilter::Send(IPC::Message* message) { if (!channel_) { delete message; return false; } if (MessageLoop::current() != message_loop_) { // Can only access the IPC::Channel on the IPC thread since it's not thread // safe. message_loop_->PostTask( FROM_HERE, NewRunnableMethod(this, &AudioMessageFilter::Send, message)); return true; } message->set_routing_id(route_id_); return channel_->Send(message); } bool AudioMessageFilter::OnMessageReceived(const IPC::Message& message) { if (message.routing_id() != route_id_) return false; bool handled = true; IPC_BEGIN_MESSAGE_MAP(AudioMessageFilter, message) IPC_MESSAGE_HANDLER(ViewMsg_RequestAudioPacket, OnRequestPacket) IPC_MESSAGE_HANDLER(ViewMsg_NotifyAudioStreamCreated, OnStreamCreated) IPC_MESSAGE_HANDLER(ViewMsg_NotifyLowLatencyAudioStreamCreated, OnLowLatencyStreamCreated) IPC_MESSAGE_HANDLER(ViewMsg_NotifyAudioStreamStateChanged, OnStreamStateChanged) IPC_MESSAGE_HANDLER(ViewMsg_NotifyAudioStreamVolume, OnStreamVolume) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void AudioMessageFilter::OnFilterAdded(IPC::Channel* channel) { // Captures the message loop for IPC. message_loop_ = MessageLoop::current(); channel_ = channel; } void AudioMessageFilter::OnFilterRemoved() { channel_ = NULL; } void AudioMessageFilter::OnChannelClosing() { channel_ = NULL; } void AudioMessageFilter::OnRequestPacket(const IPC::Message& msg, int stream_id, uint32 bytes_in_buffer, int64 message_timestamp) { Delegate* delegate = delegates_.Lookup(stream_id); if (!delegate) { DLOG(WARNING) << "Got audio packet request for a non-existent or removed" " audio renderer."; return; } delegate->OnRequestPacket(bytes_in_buffer, base::Time::FromInternalValue(message_timestamp)); } void AudioMessageFilter::OnStreamCreated(int stream_id, base::SharedMemoryHandle handle, uint32 length) { Delegate* delegate = delegates_.Lookup(stream_id); if (!delegate) { DLOG(WARNING) << "Got audio stream event for a non-existent or removed" " audio renderer."; return; } delegate->OnCreated(handle, length); } void AudioMessageFilter::OnLowLatencyStreamCreated( int stream_id, base::SharedMemoryHandle handle, #if defined(OS_WIN) base::SyncSocket::Handle socket_handle, #else base::FileDescriptor socket_descriptor, #endif uint32 length) { Delegate* delegate = delegates_.Lookup(stream_id); if (!delegate) { DLOG(WARNING) << "Got audio stream event for a non-existent or removed" " audio renderer."; return; } #if !defined(OS_WIN) base::SyncSocket::Handle socket_handle = socket_descriptor.fd; #endif delegate->OnLowLatencyCreated(handle, socket_handle, length); } void AudioMessageFilter::OnStreamStateChanged( int stream_id, const ViewMsg_AudioStreamState_Params& state) { Delegate* delegate = delegates_.Lookup(stream_id); if (!delegate) { DLOG(WARNING) << "Got audio stream event for a non-existent or removed" " audio renderer."; return; } delegate->OnStateChanged(state); } void AudioMessageFilter::OnStreamVolume(int stream_id, double volume) { Delegate* delegate = delegates_.Lookup(stream_id); if (!delegate) { DLOG(WARNING) << "Got audio stream event for a non-existent or removed" " audio renderer."; return; } delegate->OnVolume(volume); } int32 AudioMessageFilter::AddDelegate(Delegate* delegate) { return delegates_.Add(delegate); } void AudioMessageFilter::RemoveDelegate(int32 id) { delegates_.Remove(id); } <|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/platform_thread.h" #include "base/win_util.h" #include "chrome/installer/util/install_util.h" #include "chrome/test/mini_installer_test/mini_installer_test_constants.h" #include "testing/gtest/include/gtest/gtest.h" #include "chrome_mini_installer.h" namespace { class MiniInstallTest : public testing::Test { protected: void CleanTheSystem() { ChromeMiniInstaller userinstall(mini_installer_constants::kUserInstall); userinstall.UnInstall(); if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) { ChromeMiniInstaller systeminstall( mini_installer_constants::kSystemInstall); systeminstall.UnInstall(); } } virtual void SetUp() { CleanTheSystem(); } virtual void TearDown() { PlatformThread::Sleep(2000); CleanTheSystem(); } }; }; TEST_F(MiniInstallTest, FullInstallerTest) { ChromeMiniInstaller installer(mini_installer_constants::kUserInstall); installer.InstallFullInstaller(); } // Will enable this test after bug#9593 gets fixed. TEST_F(MiniInstallTest, DifferentialInstallerTest) { ChromeMiniInstaller installer(mini_installer_constants::kUserInstall); installer.InstallDifferentialInstaller(); } TEST_F(MiniInstallTest, DISABLED_StandaloneInstallerTest) { ChromeMiniInstaller installer(mini_installer_constants::kUserInstall); installer.InstallStandaloneIntaller(); } TEST_F(MiniInstallTest, DISABLED_MiniInstallerOverChromeMetaInstallerTest) { ChromeMiniInstaller installer(mini_installer_constants::kUserInstall); installer.OverInstall(); } TEST_F(MiniInstallTest, DISABLED_MiniInstallerSystemInstallTest) { if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) { ChromeMiniInstaller installer(mini_installer_constants::kSystemInstall); installer.Install(); } } TEST_F(MiniInstallTest, DISABLED_MiniInstallerUserInstallTest) { if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) { ChromeMiniInstaller installer(mini_installer_constants::kUserInstall); installer.Install(); } } TEST(InstallUtilTests, MiniInstallTestValidWindowsVersion) { // We run the tests on all supported OSes. // Make sure the code agrees. EXPECT_TRUE(InstallUtil::IsOSSupported()); } <commit_msg>Forgot to enable the test in last check-in. Enabled the test now. Review URL: http://codereview.chromium.org/99145<commit_after>// 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/platform_thread.h" #include "base/win_util.h" #include "chrome/installer/util/install_util.h" #include "chrome/test/mini_installer_test/mini_installer_test_constants.h" #include "testing/gtest/include/gtest/gtest.h" #include "chrome_mini_installer.h" namespace { class MiniInstallTest : public testing::Test { protected: void CleanTheSystem() { ChromeMiniInstaller userinstall(mini_installer_constants::kUserInstall); userinstall.UnInstall(); if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) { ChromeMiniInstaller systeminstall( mini_installer_constants::kSystemInstall); systeminstall.UnInstall(); } } virtual void SetUp() { CleanTheSystem(); } virtual void TearDown() { PlatformThread::Sleep(2000); CleanTheSystem(); } }; }; TEST_F(MiniInstallTest, FullInstallerTest) { ChromeMiniInstaller installer(mini_installer_constants::kUserInstall); installer.InstallFullInstaller(); } // Will enable this test after bug#9593 gets fixed. TEST_F(MiniInstallTest, DISABLED_DifferentialInstallerTest) { ChromeMiniInstaller installer(mini_installer_constants::kUserInstall); installer.InstallDifferentialInstaller(); } TEST_F(MiniInstallTest, DISABLED_StandaloneInstallerTest) { ChromeMiniInstaller installer(mini_installer_constants::kUserInstall); installer.InstallStandaloneIntaller(); } TEST_F(MiniInstallTest, MiniInstallerOverChromeMetaInstallerTest) { ChromeMiniInstaller installer(mini_installer_constants::kUserInstall); installer.OverInstall(); } TEST_F(MiniInstallTest, DISABLED_MiniInstallerSystemInstallTest) { if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) { ChromeMiniInstaller installer(mini_installer_constants::kSystemInstall); installer.Install(); } } TEST_F(MiniInstallTest, MiniInstallerUserInstallTest) { if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA) { ChromeMiniInstaller installer(mini_installer_constants::kUserInstall); installer.Install(); } } TEST(InstallUtilTests, MiniInstallTestValidWindowsVersion) { // We run the tests on all supported OSes. // Make sure the code agrees. EXPECT_TRUE(InstallUtil::IsOSSupported()); } <|endoftext|>
<commit_before>/* Author: Michael Schmidt Description: An a-star implementation to solve a sliding puzzle problem Assumptions: Board is N x N. */ #include "globals.h" #include "state.h" #include "pair.h" /* Prototypes */ void expand_state (StatePtr parent, set<StatePtr, ClosedPtrCompare> & closed_list, set<StatePtr, FrontierPtrCompare> & frontier); void init_board(Board & board, size_t & side); ////////////// /* INT MAIN */ ////////////// int main (int argc, char *argv[]) { assert(argc == 2 && "Supply heuristic as command line arguement."); /* Statistic Variables */ size_t v = 0; size_t n; size_t d; double b; /* Variables */ size_t side; // side length of puzzle Path path; Board board; StatePtr curr_state; set<StatePtr, ClosedPtrCompare> closed_list; set<StatePtr, FrontierPtrCompare> frontier; /* Create initial state */ init_board(board, side); try { curr_state = new State(board, side, Mode(atoi(argv[1]))); } catch (bad_alloc & ba) { cerr << "bad allocation: " << ba.what() << endl; } /* Perform a-star search */ while (!curr_state->is_goal()) { closed_list.insert(curr_state); expand_state(curr_state, closed_list, frontier); curr_state = *frontier.begin(); frontier.erase(frontier.begin()); v++; } /* Compute Stats */ n = frontier.size() + closed_list.size(); d = curr_state->get_depth(); b = pow(n, 1 / double(d)); /* Print Stats */ cout << "==================== STATS ====================" << endl; cout << v << " of " << n << " states visited." << endl; cout << "Solution is " << d << " levels deep in tree." << endl; cout << b << " average branching factor." << endl; cout << "=================== SOLUTION ==================" << endl << endl; /* Push states onto a stack for path */ while (curr_state != nullptr) { path.push(curr_state); curr_state = curr_state->get_parent(); } /* Print path/state history */ while (!path.empty()) { curr_state = path.top(); curr_state->print_board(); cout << endl; path.pop(); } /* Clean up heap allocations */ for (StatePtr p : frontier) if (p != nullptr) { delete p; p = nullptr; } for (StatePtr p : closed_list) if (p != nullptr) { delete p; p = nullptr; } for (int i = 0; i < side; i++) delete [] board[i]; delete [] board; /* Exit */ return 0; } /////////////// /* Functions */ /////////////// void expand_state (StatePtr parent, set<StatePtr, ClosedPtrCompare> & closed_list, set<StatePtr, FrontierPtrCompare> & frontier) { StatePtr expand[4]; /* Clone states from parent */ for (int i = 0; i < 4; i++) { try { expand[i] = new State(parent); } catch (bad_alloc& ba) { cerr << "bad allocation: " << ba.what() << endl; } } /* Modify states, to create new ones; remove ones that fail */ if (!expand[0]->move_down()) { delete expand[0]; expand[0] = nullptr; } if (!expand[1]->move_left()) { delete expand[1]; expand[1] = nullptr; } if (!expand[2]->move_up()) { delete expand[2]; expand[2] = nullptr; } if (!expand[3]->move_right()) { delete expand[3]; expand[3] = nullptr; } /* Add only new states now found in the frontier */ for (int i = 0; i < 4; i++) if (expand[i] != nullptr) { auto find = closed_list.find(expand[i]); if (find == closed_list.end()) { expand[i]->attach_parent(parent); frontier.insert(expand[i]); } } } /* Create board from STDIN` */ void init_board (Board & board, size_t & side) { Tile tile; vector<Tile> parse; while (cin >> tile) parse.push_back(tile); assert(ceil(sqrt(parse.size())) == sqrt(parse.size()) && "Assumes NxN puzzle."); side = sqrt(parse.size()); try { board = new TilePtr[side]; for (int r = 0, i = 0; r < side; r++) { board[r] = new Tile[side]; for (int c = 0; c < side; c++, i++) board[r][c] = parse[i]; } } catch (bad_alloc & ba) { cerr << "bad allocation: " << ba.what() << endl; } } <commit_msg>using stl pair class<commit_after>/* Author: Michael Schmidt Description: An a-star implementation to solve a sliding puzzle problem Assumptions: Board is N x N. */ #include "globals.h" #include "state.h" /* Prototypes */ void expand_state (StatePtr parent, set<StatePtr, ClosedPtrCompare> & closed_list, set<StatePtr, FrontierPtrCompare> & frontier); void init_board(Board & board, size_t & side); ////////////// /* INT MAIN */ ////////////// int main (int argc, char *argv[]) { assert(argc == 2 && "Supply heuristic as command line arguement."); /* Statistic Variables */ size_t v = 0; size_t n; size_t d; double b; /* Variables */ size_t side; // side length of puzzle Path path; Board board; StatePtr curr_state; set<StatePtr, ClosedPtrCompare> closed_list; set<StatePtr, FrontierPtrCompare> frontier; /* Create initial state */ init_board(board, side); try { curr_state = new State(board, side, Mode(atoi(argv[1]))); } catch (bad_alloc & ba) { cerr << "bad allocation: " << ba.what() << endl; } /* Perform a-star search */ while (!curr_state->is_goal()) { closed_list.insert(curr_state); expand_state(curr_state, closed_list, frontier); curr_state = *frontier.begin(); frontier.erase(frontier.begin()); v++; } /* Compute Stats */ n = frontier.size() + closed_list.size(); d = curr_state->get_depth(); b = pow(n, 1 / double(d)); /* Print Stats */ cout << "==================== STATS ====================" << endl; cout << v << " of " << n << " states visited." << endl; cout << "Solution is " << d << " levels deep in tree." << endl; cout << b << " average branching factor." << endl; cout << "=================== SOLUTION ==================" << endl << endl; /* Push states onto a stack for path */ while (curr_state != nullptr) { path.push(curr_state); curr_state = curr_state->get_parent(); } /* Print path/state history */ while (!path.empty()) { curr_state = path.top(); curr_state->print_board(); cout << endl; path.pop(); } /* Clean up heap allocations */ for (StatePtr p : frontier) if (p != nullptr) { delete p; p = nullptr; } for (StatePtr p : closed_list) if (p != nullptr) { delete p; p = nullptr; } for (int i = 0; i < side; i++) delete [] board[i]; delete [] board; /* Exit */ return 0; } /////////////// /* Functions */ /////////////// void expand_state (StatePtr parent, set<StatePtr, ClosedPtrCompare> & closed_list, set<StatePtr, FrontierPtrCompare> & frontier) { StatePtr expand[4]; /* Clone states from parent */ for (int i = 0; i < 4; i++) { try { expand[i] = new State(parent); } catch (bad_alloc& ba) { cerr << "bad allocation: " << ba.what() << endl; } } /* Modify states, to create new ones; remove ones that fail */ if (!expand[0]->move_down()) { delete expand[0]; expand[0] = nullptr; } if (!expand[1]->move_left()) { delete expand[1]; expand[1] = nullptr; } if (!expand[2]->move_up()) { delete expand[2]; expand[2] = nullptr; } if (!expand[3]->move_right()) { delete expand[3]; expand[3] = nullptr; } /* Add only new states now found in the frontier */ for (int i = 0; i < 4; i++) if (expand[i] != nullptr) { auto find = closed_list.find(expand[i]); if (find == closed_list.end()) { expand[i]->attach_parent(parent); frontier.insert(expand[i]); } } } /* Create board from STDIN` */ void init_board (Board & board, size_t & side) { Tile tile; vector<Tile> parse; while (cin >> tile) parse.push_back(tile); assert(ceil(sqrt(parse.size())) == sqrt(parse.size()) && "Assumes NxN puzzle."); side = sqrt(parse.size()); try { board = new TilePtr[side]; for (int r = 0, i = 0; r < side; r++) { board[r] = new Tile[side]; for (int c = 0; c < side; c++, i++) board[r][c] = parse[i]; } } catch (bad_alloc & ba) { cerr << "bad allocation: " << ba.what() << endl; } } <|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 "chrome/tools/convert_dict/dic_reader.h" #include <algorithm> #include <set> #include "base/file_util.h" #include "base/string_util.h" #include "chrome/tools/convert_dict/aff_reader.h" #include "chrome/tools/convert_dict/hunspell_reader.h" namespace convert_dict { namespace { // Maps each unique word to the unique affix group IDs associated with it. typedef std::map<std::string, std::set<int> > WordSet; void SplitDicLine(const std::string& line, std::vector<std::string>* output) { // We split the line on a slash not preceeded by a backslash. A slash at the // beginning of the line is not a separator either. size_t slash_index = line.size(); for (size_t i = 0; i < line.size(); i++) { if (line[i] == '/' && i > 0 && line[i - 1] != '\\') { slash_index = i; break; } } output->clear(); // Everything before the slash index is the first term. We also need to // convert all escaped slashes ("\/" sequences) to regular slashes. std::string word = line.substr(0, slash_index); ReplaceSubstringsAfterOffset(&word, 0, "\\/", "/"); output->push_back(word); // Everything (if anything) after the slash is the second. if (slash_index < line.size() - 1) output->push_back(line.substr(slash_index + 1)); } // This function reads words from a .dic file, or a .dic_delta file. Note that // we read 'all' the words in the file, irrespective of the word count given // in the first non empty line of a .dic file. Also note that, for a .dic_delta // file, the first line actually does _not_ have the number of words. In order // to control this, we use the |file_has_word_count_in_the_first_line| // parameter to tell this method whether the first non empty line in the file // contains the number of words or not. If it does, skip the first line. If it // does not, then the first line contains a word. bool PopulateWordSet(WordSet* word_set, FILE* file, AffReader* aff_reader, const char* file_type, const char* encoding, bool file_has_word_count_in_the_first_line) { int line_number = 0; while (!feof(file)) { std::string line = ReadLine(file); line_number++; StripComment(&line); if (line.empty()) continue; if (file_has_word_count_in_the_first_line) { // Skip the first nonempty line, this is the line count. We don't bother // with it and just read all the lines. file_has_word_count_in_the_first_line = false; continue; } std::vector<std::string> split; SplitDicLine(line, &split); if (split.size() == 0 || split.size() > 2) { printf("Line %d has extra slashes in the %s file\n", line_number, file_type); return false; } // The first part is the word, the second (optional) part is the affix. We // always use UTF-8 as the encoding to simplify life. std::string utf8word; std::string encoding_string(encoding); if (encoding_string == "UTF-8") { utf8word = split[0]; } else if (!aff_reader->EncodingToUTF8(split[0], &utf8word)) { printf("Unable to convert line %d from %s to UTF-8 in the %s file\n", line_number, encoding, file_type); return false; } // We always convert the affix to an index. 0 means no affix. int affix_index = 0; if (split.size() == 2) { // Got a rule, which is the stuff after the slash. The line may also have // an optional term separated by a tab. This is the morphological // description. We don't care about this (it is used in the tests to // generate a nice dump), so we remove it. size_t split1_tab_offset = split[1].find('\t'); if (split1_tab_offset != std::string::npos) split[1] = split[1].substr(0, split1_tab_offset); if (aff_reader->has_indexed_affixes()) affix_index = atoi(split[1].c_str()); else affix_index = aff_reader->GetAFIndexForAFString(split[1]); } // Discard the morphological description if it is attached to the first // token. (It is attached to the first token if a word doesn't have affix // rules.) size_t word_tab_offset = utf8word.find('\t'); if (word_tab_offset != std::string::npos) utf8word = utf8word.substr(0, word_tab_offset); WordSet::iterator found = word_set->find(utf8word); if (found == word_set->end()) { std::set<int> affix_vector; affix_vector.insert(affix_index); word_set->insert(std::make_pair(utf8word, affix_vector)); } else { found->second.insert(affix_index); } } return true; } } // namespace DicReader::DicReader(const std::string& filename) { FilePath path = FilePath::FromWStringHack(ASCIIToWide(filename)); file_ = file_util::OpenFile(path, "r"); additional_words_file_ = file_util::OpenFile(FilePath(path.InsertBeforeExtension("_delta")), "r"); } DicReader::~DicReader() { if (file_) file_util::CloseFile(file_); if (additional_words_file_) file_util::CloseFile(additional_words_file_); } bool DicReader::Read(AffReader* aff_reader) { if (!file_) return false; WordSet word_set; // Add words from the dic file to the word set. // Note that the first line is the word count in the file. if (!PopulateWordSet(&word_set, file_, aff_reader, "dic", aff_reader->encoding(), true)) return false; // Add words from the .dic_delta file to the word set, if it exists. // The first line is the first word to add. Word count line is not present. // NOTE: These additional words should be encoded as UTF-8. if (additional_words_file_ != NULL) { PopulateWordSet(&word_set, additional_words_file_, aff_reader, "dic delta", "UTF-8", false); } // Make sure the words are sorted, they may be unsorted in the input. for (WordSet::iterator word = word_set.begin(); word != word_set.end(); ++word) { std::vector<int> affixes; for (std::set<int>::iterator aff = word->second.begin(); aff != word->second.end(); ++aff) affixes.push_back(*aff); // Double check that the affixes are sorted. This isn't strictly necessary // but it's nice for the file to have a fixed layout. std::sort(affixes.begin(), affixes.end()); words_.push_back(std::make_pair(word->first, affixes)); } // Double-check that the words are sorted. std::sort(words_.begin(), words_.end()); return true; } } // namespace convert_dict <commit_msg>Fix build.<commit_after>// 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 "chrome/tools/convert_dict/dic_reader.h" #include <algorithm> #include <set> #include "base/file_util.h" #include "base/string_util.h" #include "chrome/tools/convert_dict/aff_reader.h" #include "chrome/tools/convert_dict/hunspell_reader.h" namespace convert_dict { namespace { // Maps each unique word to the unique affix group IDs associated with it. typedef std::map<std::string, std::set<int> > WordSet; void SplitDicLine(const std::string& line, std::vector<std::string>* output) { // We split the line on a slash not preceeded by a backslash. A slash at the // beginning of the line is not a separator either. size_t slash_index = line.size(); for (size_t i = 0; i < line.size(); i++) { if (line[i] == '/' && i > 0 && line[i - 1] != '\\') { slash_index = i; break; } } output->clear(); // Everything before the slash index is the first term. We also need to // convert all escaped slashes ("\/" sequences) to regular slashes. std::string word = line.substr(0, slash_index); ReplaceSubstringsAfterOffset(&word, 0, "\\/", "/"); output->push_back(word); // Everything (if anything) after the slash is the second. if (slash_index < line.size() - 1) output->push_back(line.substr(slash_index + 1)); } // This function reads words from a .dic file, or a .dic_delta file. Note that // we read 'all' the words in the file, irrespective of the word count given // in the first non empty line of a .dic file. Also note that, for a .dic_delta // file, the first line actually does _not_ have the number of words. In order // to control this, we use the |file_has_word_count_in_the_first_line| // parameter to tell this method whether the first non empty line in the file // contains the number of words or not. If it does, skip the first line. If it // does not, then the first line contains a word. bool PopulateWordSet(WordSet* word_set, FILE* file, AffReader* aff_reader, const char* file_type, const char* encoding, bool file_has_word_count_in_the_first_line) { int line_number = 0; while (!feof(file)) { std::string line = ReadLine(file); line_number++; StripComment(&line); if (line.empty()) continue; if (file_has_word_count_in_the_first_line) { // Skip the first nonempty line, this is the line count. We don't bother // with it and just read all the lines. file_has_word_count_in_the_first_line = false; continue; } std::vector<std::string> split; SplitDicLine(line, &split); if (split.size() == 0 || split.size() > 2) { printf("Line %d has extra slashes in the %s file\n", line_number, file_type); return false; } // The first part is the word, the second (optional) part is the affix. We // always use UTF-8 as the encoding to simplify life. std::string utf8word; std::string encoding_string(encoding); if (encoding_string == "UTF-8") { utf8word = split[0]; } else if (!aff_reader->EncodingToUTF8(split[0], &utf8word)) { printf("Unable to convert line %d from %s to UTF-8 in the %s file\n", line_number, encoding, file_type); return false; } // We always convert the affix to an index. 0 means no affix. int affix_index = 0; if (split.size() == 2) { // Got a rule, which is the stuff after the slash. The line may also have // an optional term separated by a tab. This is the morphological // description. We don't care about this (it is used in the tests to // generate a nice dump), so we remove it. size_t split1_tab_offset = split[1].find('\t'); if (split1_tab_offset != std::string::npos) split[1] = split[1].substr(0, split1_tab_offset); if (aff_reader->has_indexed_affixes()) affix_index = atoi(split[1].c_str()); else affix_index = aff_reader->GetAFIndexForAFString(split[1]); } // Discard the morphological description if it is attached to the first // token. (It is attached to the first token if a word doesn't have affix // rules.) size_t word_tab_offset = utf8word.find('\t'); if (word_tab_offset != std::string::npos) utf8word = utf8word.substr(0, word_tab_offset); WordSet::iterator found = word_set->find(utf8word); if (found == word_set->end()) { std::set<int> affix_vector; affix_vector.insert(affix_index); word_set->insert(std::make_pair(utf8word, affix_vector)); } else { found->second.insert(affix_index); } } return true; } } // namespace DicReader::DicReader(const std::string& filename) { FilePath path = FilePath::FromWStringHack(ASCIIToWide(filename)); file_ = file_util::OpenFile(path, "r"); FilePath additional_path = path.InsertBeforeExtension(FILE_PATH_LITERAL("_delta")); additional_words_file_ = file_util::OpenFile(additional_path, "r"); } DicReader::~DicReader() { if (file_) file_util::CloseFile(file_); if (additional_words_file_) file_util::CloseFile(additional_words_file_); } bool DicReader::Read(AffReader* aff_reader) { if (!file_) return false; WordSet word_set; // Add words from the dic file to the word set. // Note that the first line is the word count in the file. if (!PopulateWordSet(&word_set, file_, aff_reader, "dic", aff_reader->encoding(), true)) return false; // Add words from the .dic_delta file to the word set, if it exists. // The first line is the first word to add. Word count line is not present. // NOTE: These additional words should be encoded as UTF-8. if (additional_words_file_ != NULL) { PopulateWordSet(&word_set, additional_words_file_, aff_reader, "dic delta", "UTF-8", false); } // Make sure the words are sorted, they may be unsorted in the input. for (WordSet::iterator word = word_set.begin(); word != word_set.end(); ++word) { std::vector<int> affixes; for (std::set<int>::iterator aff = word->second.begin(); aff != word->second.end(); ++aff) affixes.push_back(*aff); // Double check that the affixes are sorted. This isn't strictly necessary // but it's nice for the file to have a fixed layout. std::sort(affixes.begin(), affixes.end()); words_.push_back(std::make_pair(word->first, affixes)); } // Double-check that the words are sorted. std::sort(words_.begin(), words_.end()); return true; } } // namespace convert_dict <|endoftext|>