<commit_before>// __BEGIN_LICENSE__
//  Copyright (c) 2009-2013, United States Government as represented by the
//  Administrator of the National Aeronautics and Space Administration. All
//  rights reserved.
//
//  The NGT platform is 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.
// __END_LICENSE__

#include <vw/Math/Matrix.h>
#include <asp/IsisIO/IsisInterfaceFrame.h>

#include <algorithm>
#include <vector>

#include <Camera.h>
#include <CameraDetectorMap.h>
#include <CameraDistortionMap.h>
#include <CameraFocalPlaneMap.h>

using namespace vw;
using namespace asp;
using namespace asp::isis;

// Constructor
IsisInterfaceFrame::IsisInterfaceFrame( std::string const& filename ) :
  IsisInterface(filename), m_alphacube( *m_label ) {

  // Gutting Isis::Camera
  m_distortmap = m_camera->DistortionMap();
  m_focalmap   = m_camera->FocalPlaneMap();
  m_detectmap  = m_camera->DetectorMap();

  // Calculating Center (just once)
  m_camera->instrumentPosition(&m_center[0]);
  m_center *= 1000;

  // Calculating Pose (just once)
  std::vector<double> rot_inst = m_camera->instrumentRotation()->Matrix();
  std::vector<double> rot_body = m_camera->bodyRotation()->Matrix();
  MatrixProxy<double,3,3> R_inst(&(rot_inst[0]));
  MatrixProxy<double,3,3> R_body(&(rot_body[0]));

  // Instrument Rotation = Spacecraft to Camera's Frame
  // Body Rotation = Spacecraft to World Frame
  m_pose = Quat(R_body*transpose(R_inst));
}

Vector2
IsisInterfaceFrame::point_to_pixel( Vector3 const& point ) const {

  Vector3 look = normalize( point - m_center );
  std::vector<double> lookB_copy(3);
  std::copy( look.begin(), look.end(), lookB_copy.begin() );
  lookB_copy = m_camera->bodyRotation()->J2000Vector(lookB_copy);
  lookB_copy = m_camera->instrumentRotation()->ReferenceVector(lookB_copy);
  std::copy( lookB_copy.begin(), lookB_copy.end(), look.begin() );
  look = m_camera->FocalLength() * ( look / look[2] );

  // Back Projecting
  m_distortmap->SetUndistortedFocalPlane( look[0], look[1] );
  m_focalmap->SetFocalPlane( m_distortmap->FocalPlaneX(),
                             m_distortmap->FocalPlaneY() );
  m_detectmap->SetDetector( m_focalmap->DetectorSample(),
                            m_focalmap->DetectorLine() );
  return Vector2( m_alphacube.BetaSample( m_detectmap->ParentSample() ) - 1,
                  m_alphacube.BetaLine( m_detectmap->ParentLine() ) - 1 );
}

Vector3
IsisInterfaceFrame::pixel_to_vector( Vector2 const& px ) const {
  m_detectmap->SetParent( m_alphacube.AlphaSample(px[0]+1),
                          m_alphacube.AlphaLine(px[1]+1));
  m_focalmap->SetDetector( m_detectmap->DetectorSample(),
                           m_detectmap->DetectorLine() );
  m_distortmap->SetFocalPlane( m_focalmap->FocalPlaneX(),
                               m_focalmap->FocalPlaneY() );
  std::vector<double> look(3);
  look[0] = m_distortmap->UndistortedFocalPlaneX();
  look[1] = m_distortmap->UndistortedFocalPlaneY();
  look[2] = m_distortmap->UndistortedFocalPlaneZ();
  VectorProxy<double,3> result( &look[0] );
  result = normalize( result );
  look = m_camera->instrumentRotation()->J2000Vector(look);
  look = m_camera->bodyRotation()->ReferenceVector(look);
  return result;
}

Vector3
IsisInterfaceFrame::camera_center( Vector2 const& /*pix*/ ) const {
  return m_center;
}

Quat
IsisInterfaceFrame::camera_pose( Vector2 const& /*pix*/ ) const {
  return m_pose;
}
<commit_msg>IsisInterfaceFrame: Bug fix in point_to_pixel<commit_after>// __BEGIN_LICENSE__
//  Copyright (c) 2009-2013, United States Government as represented by the
//  Administrator of the National Aeronautics and Space Administration. All
//  rights reserved.
//
//  The NGT platform is 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.
// __END_LICENSE__

#include <vw/Math/Matrix.h>
#include <asp/IsisIO/IsisInterfaceFrame.h>

#include <algorithm>
#include <vector>

#include <Camera.h>
#include <CameraDetectorMap.h>
#include <CameraDistortionMap.h>
#include <CameraFocalPlaneMap.h>

using namespace vw;
using namespace asp;
using namespace asp::isis;

// Constructor
IsisInterfaceFrame::IsisInterfaceFrame( std::string const& filename ) :
  IsisInterface(filename), m_alphacube( *m_label ) {

  // Gutting Isis::Camera
  m_distortmap = m_camera->DistortionMap();
  m_focalmap   = m_camera->FocalPlaneMap();
  m_detectmap  = m_camera->DetectorMap();

  // Calculating Center (just once)
  m_camera->instrumentPosition(&m_center[0]);
  m_center *= 1000;

  // Calculating Pose (just once)
  std::vector<double> rot_inst = m_camera->instrumentRotation()->Matrix();
  std::vector<double> rot_body = m_camera->bodyRotation()->Matrix();
  MatrixProxy<double,3,3> R_inst(&(rot_inst[0]));
  MatrixProxy<double,3,3> R_body(&(rot_body[0]));

  // Instrument Rotation = Spacecraft to Camera's Frame
  // Body Rotation = Spacecraft to World Frame
  m_pose = Quat(R_body*transpose(R_inst));
}

Vector2
IsisInterfaceFrame::point_to_pixel( Vector3 const& point ) const {

  Vector3 look = normalize( point - m_center );
  std::vector<double> lookB_copy(3);
  std::copy( look.begin(), look.end(), lookB_copy.begin() );
  lookB_copy = m_camera->bodyRotation()->J2000Vector(lookB_copy);
  lookB_copy = m_camera->instrumentRotation()->ReferenceVector(lookB_copy);
  std::copy( lookB_copy.begin(), lookB_copy.end(), look.begin() );
  look = m_camera->FocalLength() * ( look / std::abs(look[2]) );

  // Back Projecting
  m_distortmap->SetUndistortedFocalPlane( look[0], look[1] );
  m_focalmap->SetFocalPlane( m_distortmap->FocalPlaneX(),
                             m_distortmap->FocalPlaneY() );
  m_detectmap->SetDetector( m_focalmap->DetectorSample(),
                            m_focalmap->DetectorLine() );
  return Vector2( m_alphacube.BetaSample( m_detectmap->ParentSample() ) - 1,
                  m_alphacube.BetaLine( m_detectmap->ParentLine() ) - 1 );
}

Vector3
IsisInterfaceFrame::pixel_to_vector( Vector2 const& px ) const {
  m_detectmap->SetParent( m_alphacube.AlphaSample(px[0]+1),
                          m_alphacube.AlphaLine(px[1]+1));
  m_focalmap->SetDetector( m_detectmap->DetectorSample(),
                           m_detectmap->DetectorLine() );
  m_distortmap->SetFocalPlane( m_focalmap->FocalPlaneX(),
                               m_focalmap->FocalPlaneY() );
  std::vector<double> look(3);
  look[0] = m_distortmap->UndistortedFocalPlaneX();
  look[1] = m_distortmap->UndistortedFocalPlaneY();
  look[2] = m_distortmap->UndistortedFocalPlaneZ();
  VectorProxy<double,3> result( &look[0] );
  result = normalize( result );
  look = m_camera->instrumentRotation()->J2000Vector(look);
  look = m_camera->bodyRotation()->ReferenceVector(look);
  return result;
}

Vector3
IsisInterfaceFrame::camera_center( Vector2 const& /*pix*/ ) const {
  return m_center;
}

Quat
IsisInterfaceFrame::camera_pose( Vector2 const& /*pix*/ ) const {
  return m_pose;
}
<|endoftext|>


<commit_before>// Dear ImGui: standalone example application for SDL2 + OpenGL
// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs

#include "imgui.h"
#include "imgui_impl_sdl.h"
#include "imgui_impl_opengl3.h"
#include <stdio.h>
#include <SDL.h>
#include <SDL_opengl.h>
#if defined(IMGUI_IMPL_OPENGL_ES2)
#include <SDL_opengles2.h>
#endif

// Main code
int main(int, char**)
{
    // Setup SDL
    // (Some versions of SDL before <2.0.10 appears to have performance/stalling issues on a minority of Windows systems,
    // depending on whether SDL_INIT_GAMECONTROLLER is enabled or disabled.. updating to latest version of SDL is recommended!)
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0)
    {
        printf("Error: %s\n", SDL_GetError());
        return -1;
    }

    // Decide GL+GLSL versions
#if defined(IMGUI_IMPL_OPENGL_ES2)
    // GL ES 2.0 + GLSL 100
    const char* glsl_version = "#version 100";
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
#elif defined(__APPLE__)
    // GL 3.2 Core + GLSL 150
    const char* glsl_version = "#version 150";
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); // Always required on Mac
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
#else
    // GL 3.0 + GLSL 130
    const char* glsl_version = "#version 130";
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
#endif

    // Create window with graphics context
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
    SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
    SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
    SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL3 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags);
    SDL_GLContext gl_context = SDL_GL_CreateContext(window);
    SDL_GL_MakeCurrent(window, gl_context);
    SDL_GL_SetSwapInterval(1); // Enable vsync

    // Setup Dear ImGui context
    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO(); (void)io;
    //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;     // Enable Keyboard Controls
    //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;      // Enable Gamepad Controls

    // Setup Dear ImGui style
    ImGui::StyleColorsDark();
    //ImGui::StyleColorsClassic();

    // Setup Platform/Renderer backends
    ImGui_ImplSDL2_InitForOpenGL(window, gl_context);
    ImGui_ImplOpenGL3_Init(glsl_version);

    // Load Fonts
    // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
    // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
    // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
    // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
    // - Read 'docs/FONTS.md' for more instructions and details.
    // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
    //io.Fonts->AddFontDefault();
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
    //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
    //IM_ASSERT(font != NULL);

    // Our state
    bool show_demo_window = true;
    bool show_another_window = false;
    ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);

    // Main loop
    bool done = false;
    while (!done)
    {
        // Poll and handle events (inputs, window resize, etc.)
        // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
        // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
        // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
        // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            ImGui_ImplSDL2_ProcessEvent(&event);
            if (event.type == SDL_QUIT)
                done = true;
            if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window))
                done = true;
        }

        // Start the Dear ImGui frame
        ImGui_ImplOpenGL3_NewFrame();
        ImGui_ImplSDL2_NewFrame();
        ImGui::NewFrame();

        // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
        if (show_demo_window)
            ImGui::ShowDemoWindow(&show_demo_window);

        // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
        {
            static float f = 0.0f;
            static int counter = 0;

            ImGui::Begin("Hello, world!");                          // Create a window called "Hello, world!" and append into it.

            ImGui::Text("This is some useful text.");               // Display some text (you can use a format strings too)
            ImGui::Checkbox("Demo Window", &show_demo_window);      // Edit bools storing our window open/close state
            ImGui::Checkbox("Another Window", &show_another_window);

            ImGui::SliderFloat("float", &f, 0.0f, 1.0f);            // Edit 1 float using a slider from 0.0f to 1.0f
            ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color

            if (ImGui::Button("Button"))                            // Buttons return true when clicked (most widgets return true when edited/activated)
                counter++;
            ImGui::SameLine();
            ImGui::Text("counter = %d", counter);

            ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
            ImGui::End();
        }

        // 3. Show another simple window.
        if (show_another_window)
        {
            ImGui::Begin("Another Window", &show_another_window);   // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
            ImGui::Text("Hello from another window!");
            if (ImGui::Button("Close Me"))
                show_another_window = false;
            ImGui::End();
        }

        // Rendering
        ImGui::Render();
        glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
        glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w);
        glClear(GL_COLOR_BUFFER_BIT);
        ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
        SDL_GL_SwapWindow(window);
    }

    // Cleanup
    ImGui_ImplOpenGL3_Shutdown();
    ImGui_ImplSDL2_Shutdown();
    ImGui::DestroyContext();

    SDL_GL_DeleteContext(gl_context);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}
<commit_msg>Examples: SDL+OpenGL3: fixed build on ES2 target. (#4492)<commit_after>// Dear ImGui: standalone example application for SDL2 + OpenGL
// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs

#include "imgui.h"
#include "imgui_impl_sdl.h"
#include "imgui_impl_opengl3.h"
#include <stdio.h>
#include <SDL.h>
#if defined(IMGUI_IMPL_OPENGL_ES2)
#include <SDL_opengles2.h>
#else
#include <SDL_opengl.h>
#endif

// Main code
int main(int, char**)
{
    // Setup SDL
    // (Some versions of SDL before <2.0.10 appears to have performance/stalling issues on a minority of Windows systems,
    // depending on whether SDL_INIT_GAMECONTROLLER is enabled or disabled.. updating to latest version of SDL is recommended!)
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0)
    {
        printf("Error: %s\n", SDL_GetError());
        return -1;
    }

    // Decide GL+GLSL versions
#if defined(IMGUI_IMPL_OPENGL_ES2)
    // GL ES 2.0 + GLSL 100
    const char* glsl_version = "#version 100";
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
#elif defined(__APPLE__)
    // GL 3.2 Core + GLSL 150
    const char* glsl_version = "#version 150";
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG); // Always required on Mac
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
#else
    // GL 3.0 + GLSL 130
    const char* glsl_version = "#version 130";
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
#endif

    // Create window with graphics context
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
    SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
    SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
    SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL3 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags);
    SDL_GLContext gl_context = SDL_GL_CreateContext(window);
    SDL_GL_MakeCurrent(window, gl_context);
    SDL_GL_SetSwapInterval(1); // Enable vsync

    // Setup Dear ImGui context
    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO(); (void)io;
    //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;     // Enable Keyboard Controls
    //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;      // Enable Gamepad Controls

    // Setup Dear ImGui style
    ImGui::StyleColorsDark();
    //ImGui::StyleColorsClassic();

    // Setup Platform/Renderer backends
    ImGui_ImplSDL2_InitForOpenGL(window, gl_context);
    ImGui_ImplOpenGL3_Init(glsl_version);

    // Load Fonts
    // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
    // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
    // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
    // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
    // - Read 'docs/FONTS.md' for more instructions and details.
    // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
    //io.Fonts->AddFontDefault();
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
    //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
    //IM_ASSERT(font != NULL);

    // Our state
    bool show_demo_window = true;
    bool show_another_window = false;
    ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);

    // Main loop
    bool done = false;
    while (!done)
    {
        // Poll and handle events (inputs, window resize, etc.)
        // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
        // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
        // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
        // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            ImGui_ImplSDL2_ProcessEvent(&event);
            if (event.type == SDL_QUIT)
                done = true;
            if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window))
                done = true;
        }

        // Start the Dear ImGui frame
        ImGui_ImplOpenGL3_NewFrame();
        ImGui_ImplSDL2_NewFrame();
        ImGui::NewFrame();

        // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
        if (show_demo_window)
            ImGui::ShowDemoWindow(&show_demo_window);

        // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
        {
            static float f = 0.0f;
            static int counter = 0;

            ImGui::Begin("Hello, world!");                          // Create a window called "Hello, world!" and append into it.

            ImGui::Text("This is some useful text.");               // Display some text (you can use a format strings too)
            ImGui::Checkbox("Demo Window", &show_demo_window);      // Edit bools storing our window open/close state
            ImGui::Checkbox("Another Window", &show_another_window);

            ImGui::SliderFloat("float", &f, 0.0f, 1.0f);            // Edit 1 float using a slider from 0.0f to 1.0f
            ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color

            if (ImGui::Button("Button"))                            // Buttons return true when clicked (most widgets return true when edited/activated)
                counter++;
            ImGui::SameLine();
            ImGui::Text("counter = %d", counter);

            ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
            ImGui::End();
        }

        // 3. Show another simple window.
        if (show_another_window)
        {
            ImGui::Begin("Another Window", &show_another_window);   // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
            ImGui::Text("Hello from another window!");
            if (ImGui::Button("Close Me"))
                show_another_window = false;
            ImGui::End();
        }

        // Rendering
        ImGui::Render();
        glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
        glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w);
        glClear(GL_COLOR_BUFFER_BIT);
        ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
        SDL_GL_SwapWindow(window);
    }

    // Cleanup
    ImGui_ImplOpenGL3_Shutdown();
    ImGui_ImplSDL2_Shutdown();
    ImGui::DestroyContext();

    SDL_GL_DeleteContext(gl_context);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}
<|endoftext|>


<commit_before>/*
 * This program is just for personal experiments here on AVR features and C++ stuff
 * to check compilation and link of FastArduino port and pin API.
 * It does not do anything interesting as far as hardware is concerned.
 */

#include <fastarduino/analog_input.h>
#include <fastarduino/time.h>
#include <fastarduino/timer.h>
#include <fastarduino/pwm.h>

template<	board::Timer TIMER, typename timer::Calculator<TIMER>::TIMER_PRESCALER PRESCALER,
			typename T = typename board_traits::Timer_trait<TIMER>::TYPE>
class PulseTimer: public timer::Timer<TIMER>
{
public:
	PulseTimer(UNUSED uint16_t pulse_frequency):timer::Timer<TIMER>{0, 0} {}
	inline void begin() {}
	inline void _begin() {}
};

constexpr const board::Timer TIMER = board::Timer::TIMER0;
using TCALC = timer::Calculator<TIMER>;
using TPRESCALER = TCALC::TIMER_PRESCALER;

constexpr const uint16_t MAX_PULSE_US = 2000;
constexpr const uint16_t PULSE_FREQUENCY = 50;
constexpr const TPRESCALER PRESCALER = TCALC::PulseTimer_prescaler(MAX_PULSE_US, PULSE_FREQUENCY);

using PULSE_TIMER = PulseTimer<TIMER, PRESCALER>;

static PULSE_TIMER my_timer{PULSE_FREQUENCY};

//template<board::Timer TIMER, board::DigitalPin PIN>
//class Servo
//{
//public:
//	//TODO remove eventually
//	Servo(timer::PulseTimer<TIMER>& timer)
//		:	timer_{timer}, out_{timer, timer::TimerOutputMode::NON_INVERTING},
//			neutral_{}, minimum_{}, maximum_{}
//	{
//	}
//
//	Servo(timer::PulseTimer<TIMER>& timer, uint16_t neutral, uint16_t minimum, uint16_t maximum)
//		:	timer_{timer}, out_{timer, timer::TimerOutputMode::NON_INVERTING},
//			neutral_{int16_t(neutral)}, minimum_{int16_t(minimum)}, maximum_{int16_t(maximum)}
//	{
//	}
//
//	~Servo()
//	{
//	}
//
//	inline void set(uint16_t value)
//	{
//		out_.set_duty(value);
//	}
//
//	inline void rotate(int8_t angle)
//	{
//		uint16_t duty;
//		if (angle > 0)
//			duty = angle * (maximum_ - neutral_) / (MAX - 0) + neutral_;
//		else if (angle < 0)
//			duty = angle * (neutral_ - minimum_) / (0 - MIN) + neutral_;
//		else
//			duty = neutral_;
//		out_.set_duty(duty);
//	}
//
//private:
//	static const int8_t MAX = 127;
//	static const int8_t MIN = -128;
//
//	timer::PulseTimer<TIMER>& timer_;
//	PIN_TYPE out_;
//	const int16_t neutral_;
//	const int16_t minimum_;
//	const int16_t maximum_;
//};

int main()
{
}
<commit_msg>Experimenting on how to define one unique PulseTimer that would delegate to either PulseTimer8 or PulseTimer16.<commit_after>/*
 * This program is just for personal experiments here on AVR features and C++ stuff
 * to check compilation and link of FastArduino port and pin API.
 * It does not do anything interesting as far as hardware is concerned.
 */

#include <fastarduino/analog_input.h>
#include <fastarduino/time.h>
#include <fastarduino/timer.h>
#include <fastarduino/pwm.h>

template<	board::Timer TIMER, typename timer::Calculator<TIMER>::TIMER_PRESCALER PRESCALER,
			typename T = typename board_traits::Timer_trait<TIMER>::TYPE>
class PulseTimer: public timer::Timer<TIMER>
{
public:
	PulseTimer(UNUSED uint16_t pulse_frequency):timer::Timer<TIMER>{0, 0} {}
	inline void begin() {}
	inline void _begin() {}
};

template<board::Timer TIMER, typename timer::Calculator<TIMER>::TIMER_PRESCALER PRESCALER>
class PulseTimer<TIMER, PRESCALER, uint8_t>: public timer::PulseTimer8<TIMER, PRESCALER>
{
public:
	PulseTimer(uint16_t pulse_frequency):timer::PulseTimer8<TIMER, PRESCALER>{pulse_frequency} {}
};

template<board::Timer TIMER, typename timer::Calculator<TIMER>::TIMER_PRESCALER PRESCALER>
class PulseTimer<TIMER, PRESCALER, uint16_t>: public timer::PulseTimer16<TIMER, PRESCALER>
{
public:
	PulseTimer(uint16_t pulse_frequency):timer::PulseTimer16<TIMER, PRESCALER>{pulse_frequency} {}
};

constexpr const board::Timer TIMER0 = board::Timer::TIMER0;
using TCALC0 = timer::Calculator<TIMER0>;
using TPRESCALER0 = TCALC0::TIMER_PRESCALER;

constexpr const board::Timer TIMER1 = board::Timer::TIMER1;
using TCALC1 = timer::Calculator<TIMER1>;
using TPRESCALER1 = TCALC1::TIMER_PRESCALER;

constexpr const uint16_t MAX_PULSE_US = 2000;
constexpr const uint16_t PULSE_FREQUENCY = 50;
constexpr const TPRESCALER0 PRESCALER0 = TCALC0::PulseTimer_prescaler(MAX_PULSE_US, PULSE_FREQUENCY);
constexpr const TPRESCALER1 PRESCALER1 = TCALC1::PulseTimer_prescaler(MAX_PULSE_US, PULSE_FREQUENCY);

using PULSE_TIMER0 = PulseTimer<TIMER0, PRESCALER0>;
using PULSE_TIMER1 = PulseTimer<TIMER1, PRESCALER1>;

//template<board::Timer TIMER, board::DigitalPin PIN>
//class Servo
//{
//public:
//	//TODO remove eventually
//	Servo(timer::PulseTimer<TIMER>& timer)
//		:	timer_{timer}, out_{timer, timer::TimerOutputMode::NON_INVERTING},
//			neutral_{}, minimum_{}, maximum_{}
//	{
//	}
//
//	Servo(timer::PulseTimer<TIMER>& timer, uint16_t neutral, uint16_t minimum, uint16_t maximum)
//		:	timer_{timer}, out_{timer, timer::TimerOutputMode::NON_INVERTING},
//			neutral_{int16_t(neutral)}, minimum_{int16_t(minimum)}, maximum_{int16_t(maximum)}
//	{
//	}
//
//	~Servo()
//	{
//	}
//
//	inline void set(uint16_t value)
//	{
//		out_.set_duty(value);
//	}
//
//	inline void rotate(int8_t angle)
//	{
//		uint16_t duty;
//		if (angle > 0)
//			duty = angle * (maximum_ - neutral_) / (MAX - 0) + neutral_;
//		else if (angle < 0)
//			duty = angle * (neutral_ - minimum_) / (0 - MIN) + neutral_;
//		else
//			duty = neutral_;
//		out_.set_duty(duty);
//	}
//
//private:
//	static const int8_t MAX = 127;
//	static const int8_t MIN = -128;
//
//	timer::PulseTimer<TIMER>& timer_;
//	PIN_TYPE out_;
//	const int16_t neutral_;
//	const int16_t minimum_;
//	const int16_t maximum_;
//};

int main() __attribute__((OS_main));
int main()
{
//	PULSE_TIMER0 timer0{PULSE_FREQUENCY};
//	timer0._begin();
	PULSE_TIMER1 timer1{PULSE_FREQUENCY};
	timer1._begin();
	sei();
	while (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 "browser/net_log.h"

#include "browser/browser_context.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "content/public/common/content_switches.h"
#include "net/log/net_log_util.h"
#include "net/url_request/url_request_context.h"

namespace {

base::Value* GetConstants() {
  scoped_ptr<base::DictionaryValue> constants = net::GetNetConstants();

  // Adding client information to constants dictionary.
  base::DictionaryValue* client_info = new base::DictionaryValue();

  client_info->SetString("command_line",
      base::CommandLine::ForCurrentProcess()->GetCommandLineString());

  constants->Set("clientInfo", client_info);

  return constants.release();
}

}  // namespace

namespace brightray {

NetLog::NetLog(net::URLRequestContext* context)
    : added_events_(false),
      context_(context) {
  auto command_line = base::CommandLine::ForCurrentProcess();
  base::FilePath log_path =
      command_line->GetSwitchValuePath(switches::kLogNetLog);

  #if defined(OS_WIN)
    log_file_.reset(_wfopen(log_path.value().c_str(), L"w"));
  #elif defined(OS_POSIX)
    log_file_.reset(fopen(log_path.value().c_str(), "w"));
  #endif

  if (!log_file_) {
    LOG(ERROR) << "Could not open file: " << log_path.value()
               << "for net logging";
  } else {
    std::string json;
    base::JSONWriter::Write(GetConstants(), &json);
    fprintf(log_file_.get(), "{\"constants\": %s, \n", json.c_str());
    fprintf(log_file_.get(), "\"events\": [\n");

    if (context_) {
      DCHECK(context_->CalledOnValidThread());

      std::set<net::URLRequestContext*> contexts;
      contexts.insert(context_);

      net::CreateNetLogEntriesForActiveObjects(contexts, this);
    }

    DeprecatedAddObserver(this, net::NetLog::LogLevel::LOG_STRIP_PRIVATE_DATA);
  }
}

NetLog::~NetLog() {
  DeprecatedRemoveObserver(this);

  // Ending events array.
  fprintf(log_file_.get(), "]}");
  log_file_.reset();
}

void NetLog::OnAddEntry(const net::NetLog::Entry& entry) {
  std::string json;
  base::JSONWriter::Write(entry.ToValue(), &json);

  fprintf(log_file_.get(), "%s%s", (added_events_ ? ",\n" : ""), json.c_str());
  added_events_ = true;
}

}  // namespace brightray
<commit_msg>fix memory leak<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 "browser/net_log.h"

#include "browser/browser_context.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "content/public/common/content_switches.h"
#include "net/log/net_log_util.h"
#include "net/url_request/url_request_context.h"

namespace {

base::Value* GetConstants() {
  scoped_ptr<base::DictionaryValue> constants = net::GetNetConstants();

  // Adding client information to constants dictionary.
  base::DictionaryValue* client_info = new base::DictionaryValue();

  client_info->SetString("command_line",
      base::CommandLine::ForCurrentProcess()->GetCommandLineString());

  constants->Set("clientInfo", client_info);

  return constants.release();
}

}  // namespace

namespace brightray {

NetLog::NetLog(net::URLRequestContext* context)
    : added_events_(false),
      context_(context) {
  auto command_line = base::CommandLine::ForCurrentProcess();
  base::FilePath log_path =
      command_line->GetSwitchValuePath(switches::kLogNetLog);

  #if defined(OS_WIN)
    log_file_.reset(_wfopen(log_path.value().c_str(), L"w"));
  #elif defined(OS_POSIX)
    log_file_.reset(fopen(log_path.value().c_str(), "w"));
  #endif

  if (!log_file_) {
    LOG(ERROR) << "Could not open file: " << log_path.value()
               << "for net logging";
  } else {
    std::string json;
    scoped_ptr<base::Value> constants(GetConstants());
    base::JSONWriter::Write(constants.get(), &json);
    fprintf(log_file_.get(), "{\"constants\": %s, \n", json.c_str());
    fprintf(log_file_.get(), "\"events\": [\n");

    if (context_) {
      DCHECK(context_->CalledOnValidThread());

      std::set<net::URLRequestContext*> contexts;
      contexts.insert(context_);

      net::CreateNetLogEntriesForActiveObjects(contexts, this);
    }

    DeprecatedAddObserver(this, net::NetLog::LogLevel::LOG_STRIP_PRIVATE_DATA);
  }
}

NetLog::~NetLog() {
  DeprecatedRemoveObserver(this);

  // Ending events array.
  fprintf(log_file_.get(), "]}");
  log_file_.reset();
}

void NetLog::OnAddEntry(const net::NetLog::Entry& entry) {
  std::string json;
  base::JSONWriter::Write(entry.ToValue(), &json);

  fprintf(log_file_.get(), "%s%s", (added_events_ ? ",\n" : ""), json.c_str());
  added_events_ = true;
}

}  // namespace brightray
<|endoftext|>


<commit_before>//#include "mvcc.h"
#include "txn.h"
#include "row.h"
#include "manager.h"
#include "row_mvcc.h"
#include "mem_alloc.h"
#include <mm_malloc.h>

#if CC_ALG == MVCC

void Row_mvcc::init(row_t * row) {
	_row = row;
	_his_len = 4;
	_req_len = _his_len;

	_write_history = (WriteHisEntry *) _mm_malloc(sizeof(WriteHisEntry) * _his_len, 64);
	_requests = (ReqEntry *) _mm_malloc(sizeof(ReqEntry) * _req_len, 64);
	for (uint32_t i = 0; i < _his_len; i++) {
		_requests[i].valid = false;
		_write_history[i].valid = false;
		_write_history[i].row = NULL;
	}
	_latest_row = _row;
	_latest_wts = 0;
	_oldest_wts = 0;

	_num_versions = 0;
	_exists_prewrite = false;
	_max_served_rts = 0;

	blatch = false;
	latch = (pthread_mutex_t *) _mm_malloc(sizeof(pthread_mutex_t), 64);
	pthread_mutex_init(latch, NULL);
}

void Row_mvcc::buffer_req(TsType type, txn_man * txn, bool served)
{
	uint32_t access_num = 1;
	while (true) {
		for (uint32_t i = 0; i < _req_len; i++) {
			// TODO No need to keep all read history.
			// in some sense, only need to keep the served read request with the max ts.
			//
			if (!_requests[i].valid) {
				_requests[i].valid = true;
				_requests[i].type = type;
				_requests[i].ts = txn->get_ts();
				_requests[i].txn = txn;
				_requests[i].time = get_sys_clock();
				return;
			}
		}
		assert(access_num == 1);
		double_list(1);
		access_num ++;
	}
}

void
Row_mvcc::double_list(uint32_t list)
{
	if (list == 0) {
		WriteHisEntry * temp = (WriteHisEntry *) _mm_malloc(sizeof(WriteHisEntry) * _his_len * 2, 64);
		for (uint32_t i = 0; i < _his_len; i++) {
			temp[i].valid = _write_history[i].valid;
			temp[i].reserved = _write_history[i].reserved;
			temp[i].ts = _write_history[i].ts;
			temp[i].row = _write_history[i].row;
		}
		for (uint32_t i = _his_len; i < _his_len * 2; i++) {
			temp[i].valid = false;
			temp[i].reserved = false;
			temp[i].row = NULL;
		}
		_mm_free(_write_history);
		_write_history = temp;
		_his_len = _his_len * 2;
	} else {
		assert(list == 1);
		ReqEntry * temp = (ReqEntry *) _mm_malloc(sizeof(ReqEntry) * _req_len * 2, 64);
		for (uint32_t i = 0; i < _req_len; i++) {
			temp[i].valid = _requests[i].valid;
			temp[i].type = _requests[i].type;
			temp[i].ts = _requests[i].ts;
			temp[i].txn = _requests[i].txn;
			temp[i].time = _requests[i].time;
		}
		for (uint32_t i = _req_len; i < _req_len * 2; i++)
			temp[i].valid = false;
		_mm_free(_requests);
		_requests = temp;
		_req_len = _req_len * 2;
	}
}

RC Row_mvcc::access(txn_man * txn, TsType type, row_t * row) {
	RC rc = RCOK;
	ts_t ts = txn->get_ts();
uint64_t t1 = get_sys_clock();
	if (g_central_man)
		glob_manager->lock_row(_row);
	else
		while (!ATOM_CAS(blatch, false, true))
			PAUSE
		//pthread_mutex_lock( latch );
uint64_t t2 = get_sys_clock();
INC_STATS(txn->get_thd_id(), debug4, t2 - t1);

#if DEBUG_CC
	for (uint32_t i = 0; i < _req_len; i++)
		if (_requests[i].valid) {
			assert(_requests[i].ts > _latest_wts);
			if (_exists_prewrite)
				assert(_prewrite_ts < _requests[i].ts);
		}
#endif
	if (type == R_REQ) {
		if (ts < _oldest_wts)
			// the version was already recycled... This should be very rare
			rc = Abort;
		else if (ts > _latest_wts) {
			if (_exists_prewrite && _prewrite_ts < ts)
			{
				// exists a pending prewrite request before the current read. should wait.
				rc = WAIT;
				buffer_req(R_REQ, txn, false);
				txn->ts_ready = false;
			} else {
				// should just read
				rc = RCOK;
				txn->cur_row = _latest_row;
				if (ts > _max_served_rts)
					_max_served_rts = ts;
			}
		} else {
			rc = RCOK;
			// ts is between _oldest_wts and _latest_wts, should find the correct version
			uint32_t the_ts = 0;
		   	uint32_t the_i = _his_len;
	   		for (uint32_t i = 0; i < _his_len; i++) {
		   		if (_write_history[i].valid
					&& _write_history[i].ts < ts
			   		&& _write_history[i].ts > the_ts)
	   			{
		   			the_ts = _write_history[i].ts;
			  		the_i = i;
				}
			}
			if (the_i == _his_len)
				txn->cur_row = _row;
   			else
	   			txn->cur_row = _write_history[the_i].row;
		}
	} else if (type == P_REQ) {
		if (ts < _latest_wts || ts < _max_served_rts || (_exists_prewrite && _prewrite_ts > ts))
			rc = Abort;
		else if (_exists_prewrite) {  // _prewrite_ts < ts
			rc = WAIT;
			buffer_req(P_REQ, txn, false);
			txn->ts_ready = false;
		} else {
			rc = RCOK;
			row_t * res_row = reserveRow(ts, txn);
			assert(res_row);
			res_row->copy(_latest_row);
			txn->cur_row = res_row;
		}
	} else if (type == W_REQ) {
		rc = RCOK;
		assert(ts > _latest_wts);
		assert(row == _write_history[_prewrite_his_id].row);
		_write_history[_prewrite_his_id].valid = true;
		_write_history[_prewrite_his_id].ts = ts;
		_latest_wts = ts;
		_latest_row = row;
		_exists_prewrite = false;
		_num_versions ++;
		update_buffer(txn, W_REQ);
	} else if (type == XP_REQ) {
		assert(row == _write_history[_prewrite_his_id].row);
		_write_history[_prewrite_his_id].valid = false;
		_write_history[_prewrite_his_id].reserved = false;
		_exists_prewrite = false;
		update_buffer(txn, XP_REQ);
	} else
		assert(false);
INC_STATS(txn->get_thd_id(), debug3, get_sys_clock() - t2);
	if (g_central_man)
		glob_manager->release_row(_row);
	else
		blatch = false;
		//pthread_mutex_unlock( latch );

	return rc;
}

row_t *
Row_mvcc::reserveRow(ts_t ts, txn_man * txn)
{
	assert(!_exists_prewrite);

	// Garbage Collection
	ts_t min_ts = glob_manager->get_min_ts(txn->get_thd_id());
	if (_oldest_wts < min_ts &&
		_num_versions == _his_len)
	{
		ts_t max_recycle_ts = 0;
		ts_t idx = _his_len;
		for (uint32_t i = 0; i < _his_len; i++) {
			if (_write_history[i].valid
				&& _write_history[i].ts < min_ts
				&& _write_history[i].ts > max_recycle_ts)
			{
				max_recycle_ts = _write_history[i].ts;
				idx = i;
			}
		}
		// some entries can be garbage collected.
		if (idx != _his_len) {
			row_t * temp = _row;
			_row = _write_history[idx].row;
			_write_history[idx].row = temp;
			_oldest_wts = max_recycle_ts;
			for (uint32_t i = 0; i < _his_len; i++) {
				if (_write_history[i].valid
					&& _write_history[i].ts <= max_recycle_ts)
				{
					_write_history[i].valid = false;
					_write_history[i].reserved = false;
					assert(_write_history[i].row);
					_num_versions --;
				}
			}
		}
	}

#if DEBUG_CC
	uint32_t his_size = 0;
	uint64_t max_ts = 0;
	for (uint32_t i = 0; i < _his_len; i++)
		if (_write_history[i].valid) {
			his_size ++;
			if (_write_history[i].ts > max_ts)
				max_ts = _write_history[i].ts;
		}
	assert(his_size == _num_versions);
	if (_num_versions > 0)
		assert(max_ts == _latest_wts);
#endif
	uint32_t idx = _his_len;
	// _write_history is not full, find an unused entry for P_REQ.
	if (_num_versions < _his_len) {
		for (uint32_t i = 0; i < _his_len; i++) {
			if (!_write_history[i].valid
				&& !_write_history[i].reserved
				&& _write_history[i].row != NULL)
			{
				idx = i;
				break;
			}
			else if (!_write_history[i].valid
				 	 && !_write_history[i].reserved)
				idx = i;
		}
		assert(idx < _his_len);
	}
	row_t * row;
	if (idx == _his_len) {
		if (_his_len >= g_thread_cnt) {
			// all entries are taken. recycle the oldest version if _his_len is too long already
			ts_t min_ts = UINT64_MAX;
			for (uint32_t i = 0; i < _his_len; i++) {
				if (_write_history[i].valid && _write_history[i].ts < min_ts) {
					min_ts = _write_history[i].ts;
					idx = i;
				}
			}
			assert(min_ts > _oldest_wts);
			assert(_write_history[idx].row);
			row = _row;
			_row = _write_history[idx].row;
			_write_history[idx].row = row;
			_oldest_wts = min_ts;
			_num_versions --;
		} else {
			// double the history size.
			double_list(0);
			_prewrite_ts = ts;
#if DEBUG_CC
			for (uint32_t i = 0; i < _his_len / 2; i++)
				assert(_write_history[i].valid);
			assert(!_write_history[_his_len / 2].valid);
#endif
			idx = _his_len / 2;
		}
	}
	assert(idx != _his_len);
	// some entries are not taken. But the row of that entry is NULL.
	if (!_write_history[idx].row) {
		_write_history[idx].row = (row_t *) _mm_malloc(sizeof(row_t), 64);
		_write_history[idx].row->init(MAX_TUPLE_SIZE);
	}
	_write_history[idx].valid = false;
	_write_history[idx].reserved = true;
	_write_history[idx].ts = ts;
	_exists_prewrite = true;
	_prewrite_his_id = idx;
	_prewrite_ts = ts;
	return _write_history[idx].row;
}

void Row_mvcc::update_buffer(txn_man * txn, TsType type) {
	// the current txn performs WR or XP.
	// immediate following R_REQ and P_REQ should return.
	ts_t ts = txn->get_ts();
	// figure out the ts for the next pending P_REQ
	ts_t next_pre_ts = UINT64_MAX ;
	for (uint32_t i = 0; i < _req_len; i++)
		if (_requests[i].valid && _requests[i].type == P_REQ
			&& _requests[i].ts > ts
			&& _requests[i].ts < next_pre_ts)
			next_pre_ts = _requests[i].ts;
	// return all pending quests between txn->ts and next_pre_ts
	for (uint32_t i = 0; i < _req_len; i++)	{
		if (_requests[i].valid)
			assert(_requests[i].ts > ts);
		// return pending R_REQ
		if (_requests[i].valid && _requests[i].type == R_REQ && _requests[i].ts < next_pre_ts) {
			if (_requests[i].ts > _max_served_rts)
				_max_served_rts = _requests[i].ts;
			_requests[i].valid = false;
			_requests[i].txn->cur_row = _latest_row;
			_requests[i].txn->ts_ready = true;
		}
		// return one pending P_REQ
		else if (_requests[i].valid && _requests[i].ts == next_pre_ts) {
			assert(_requests[i].type == P_REQ);
			row_t * res_row = reserveRow(_requests[i].ts, txn);
			assert(res_row);
			res_row->copy(_latest_row);
			_requests[i].valid = false;
			_requests[i].txn->cur_row = res_row;
			_requests[i].txn->ts_ready = true;
		}
	}
}

#endif
<commit_msg>Update row_mvcc.cpp<commit_after>//#include "mvcc.h"
#include "txn.h"
#include "row.h"
#include "manager.h"
#include "row_mvcc.h"
#include "mem_alloc.h"
#include <mm_malloc.h>

#if CC_ALG == MVCC

void Row_mvcc::init(row_t * row) {
	_row = row;
	_his_len = 4;
	_req_len = _his_len;

	_write_history = (WriteHisEntry *) _mm_malloc(sizeof(WriteHisEntry) * _his_len, 64);
	_requests = (ReqEntry *) _mm_malloc(sizeof(ReqEntry) * _req_len, 64);
	for (uint32_t i = 0; i < _his_len; i++) {
		_requests[i].valid = false;
		_write_history[i].valid = false;
		_write_history[i].reserved = false;
		_write_history[i].row = NULL;
	}
	_latest_row = _row;
	_latest_wts = 0;
	_oldest_wts = 0;

	_num_versions = 0;
	_exists_prewrite = false;
	_max_served_rts = 0;

	blatch = false;
	latch = (pthread_mutex_t *) _mm_malloc(sizeof(pthread_mutex_t), 64);
	pthread_mutex_init(latch, NULL);
}

void Row_mvcc::buffer_req(TsType type, txn_man * txn, bool served)
{
	uint32_t access_num = 1;
	while (true) {
		for (uint32_t i = 0; i < _req_len; i++) {
			// TODO No need to keep all read history.
			// in some sense, only need to keep the served read request with the max ts.
			//
			if (!_requests[i].valid) {
				_requests[i].valid = true;
				_requests[i].type = type;
				_requests[i].ts = txn->get_ts();
				_requests[i].txn = txn;
				_requests[i].time = get_sys_clock();
				return;
			}
		}
		assert(access_num == 1);
		double_list(1);
		access_num ++;
	}
}

void
Row_mvcc::double_list(uint32_t list)
{
	if (list == 0) {
		WriteHisEntry * temp = (WriteHisEntry *) _mm_malloc(sizeof(WriteHisEntry) * _his_len * 2, 64);
		for (uint32_t i = 0; i < _his_len; i++) {
			temp[i].valid = _write_history[i].valid;
			temp[i].reserved = _write_history[i].reserved;
			temp[i].ts = _write_history[i].ts;
			temp[i].row = _write_history[i].row;
		}
		for (uint32_t i = _his_len; i < _his_len * 2; i++) {
			temp[i].valid = false;
			temp[i].reserved = false;
			temp[i].row = NULL;
		}
		_mm_free(_write_history);
		_write_history = temp;
		_his_len = _his_len * 2;
	} else {
		assert(list == 1);
		ReqEntry * temp = (ReqEntry *) _mm_malloc(sizeof(ReqEntry) * _req_len * 2, 64);
		for (uint32_t i = 0; i < _req_len; i++) {
			temp[i].valid = _requests[i].valid;
			temp[i].type = _requests[i].type;
			temp[i].ts = _requests[i].ts;
			temp[i].txn = _requests[i].txn;
			temp[i].time = _requests[i].time;
		}
		for (uint32_t i = _req_len; i < _req_len * 2; i++)
			temp[i].valid = false;
		_mm_free(_requests);
		_requests = temp;
		_req_len = _req_len * 2;
	}
}

RC Row_mvcc::access(txn_man * txn, TsType type, row_t * row) {
	RC rc = RCOK;
	ts_t ts = txn->get_ts();
uint64_t t1 = get_sys_clock();
	if (g_central_man)
		glob_manager->lock_row(_row);
	else
		while (!ATOM_CAS(blatch, false, true))
			PAUSE
		//pthread_mutex_lock( latch );
uint64_t t2 = get_sys_clock();
INC_STATS(txn->get_thd_id(), debug4, t2 - t1);

#if DEBUG_CC
	for (uint32_t i = 0; i < _req_len; i++)
		if (_requests[i].valid) {
			assert(_requests[i].ts > _latest_wts);
			if (_exists_prewrite)
				assert(_prewrite_ts < _requests[i].ts);
		}
#endif
	if (type == R_REQ) {
		if (ts < _oldest_wts)
			// the version was already recycled... This should be very rare
			rc = Abort;
		else if (ts > _latest_wts) {
			if (_exists_prewrite && _prewrite_ts < ts)
			{
				// exists a pending prewrite request before the current read. should wait.
				rc = WAIT;
				buffer_req(R_REQ, txn, false);
				txn->ts_ready = false;
			} else {
				// should just read
				rc = RCOK;
				txn->cur_row = _latest_row;
				if (ts > _max_served_rts)
					_max_served_rts = ts;
			}
		} else {
			rc = RCOK;
			// ts is between _oldest_wts and _latest_wts, should find the correct version
			uint32_t the_ts = 0;
		   	uint32_t the_i = _his_len;
	   		for (uint32_t i = 0; i < _his_len; i++) {
		   		if (_write_history[i].valid
					&& _write_history[i].ts < ts
			   		&& _write_history[i].ts > the_ts)
	   			{
		   			the_ts = _write_history[i].ts;
			  		the_i = i;
				}
			}
			if (the_i == _his_len)
				txn->cur_row = _row;
   			else
	   			txn->cur_row = _write_history[the_i].row;
		}
	} else if (type == P_REQ) {
		if (ts < _latest_wts || ts < _max_served_rts || (_exists_prewrite && _prewrite_ts > ts))
			rc = Abort;
		else if (_exists_prewrite) {  // _prewrite_ts < ts
			rc = WAIT;
			buffer_req(P_REQ, txn, false);
			txn->ts_ready = false;
		} else {
			rc = RCOK;
			row_t * res_row = reserveRow(ts, txn);
			assert(res_row);
			res_row->copy(_latest_row);
			txn->cur_row = res_row;
		}
	} else if (type == W_REQ) {
		rc = RCOK;
		assert(ts > _latest_wts);
		assert(row == _write_history[_prewrite_his_id].row);
		_write_history[_prewrite_his_id].valid = true;
		_write_history[_prewrite_his_id].ts = ts;
		_latest_wts = ts;
		_latest_row = row;
		_exists_prewrite = false;
		_num_versions ++;
		update_buffer(txn, W_REQ);
	} else if (type == XP_REQ) {
		assert(row == _write_history[_prewrite_his_id].row);
		_write_history[_prewrite_his_id].valid = false;
		_write_history[_prewrite_his_id].reserved = false;
		_exists_prewrite = false;
		update_buffer(txn, XP_REQ);
	} else
		assert(false);
INC_STATS(txn->get_thd_id(), debug3, get_sys_clock() - t2);
	if (g_central_man)
		glob_manager->release_row(_row);
	else
		blatch = false;
		//pthread_mutex_unlock( latch );

	return rc;
}

row_t *
Row_mvcc::reserveRow(ts_t ts, txn_man * txn)
{
	assert(!_exists_prewrite);

	// Garbage Collection
	ts_t min_ts = glob_manager->get_min_ts(txn->get_thd_id());
	if (_oldest_wts < min_ts &&
		_num_versions == _his_len)
	{
		ts_t max_recycle_ts = 0;
		ts_t idx = _his_len;
		for (uint32_t i = 0; i < _his_len; i++) {
			if (_write_history[i].valid
				&& _write_history[i].ts < min_ts
				&& _write_history[i].ts > max_recycle_ts)
			{
				max_recycle_ts = _write_history[i].ts;
				idx = i;
			}
		}
		// some entries can be garbage collected.
		if (idx != _his_len) {
			row_t * temp = _row;
			_row = _write_history[idx].row;
			_write_history[idx].row = temp;
			_oldest_wts = max_recycle_ts;
			for (uint32_t i = 0; i < _his_len; i++) {
				if (_write_history[i].valid
					&& _write_history[i].ts <= max_recycle_ts)
				{
					_write_history[i].valid = false;
					_write_history[i].reserved = false;
					assert(_write_history[i].row);
					_num_versions --;
				}
			}
		}
	}

#if DEBUG_CC
	uint32_t his_size = 0;
	uint64_t max_ts = 0;
	for (uint32_t i = 0; i < _his_len; i++)
		if (_write_history[i].valid) {
			his_size ++;
			if (_write_history[i].ts > max_ts)
				max_ts = _write_history[i].ts;
		}
	assert(his_size == _num_versions);
	if (_num_versions > 0)
		assert(max_ts == _latest_wts);
#endif
	uint32_t idx = _his_len;
	// _write_history is not full, find an unused entry for P_REQ.
	if (_num_versions < _his_len) {
		for (uint32_t i = 0; i < _his_len; i++) {
			if (!_write_history[i].valid
				&& !_write_history[i].reserved
				&& _write_history[i].row != NULL)
			{
				idx = i;
				break;
			}
			else if (!_write_history[i].valid
				 	 && !_write_history[i].reserved)
				idx = i;
		}
		assert(idx < _his_len);
	}
	row_t * row;
	if (idx == _his_len) {
		if (_his_len >= g_thread_cnt) {
			// all entries are taken. recycle the oldest version if _his_len is too long already
			ts_t min_ts = UINT64_MAX;
			for (uint32_t i = 0; i < _his_len; i++) {
				if (_write_history[i].valid && _write_history[i].ts < min_ts) {
					min_ts = _write_history[i].ts;
					idx = i;
				}
			}
			assert(min_ts > _oldest_wts);
			assert(_write_history[idx].row);
			row = _row;
			_row = _write_history[idx].row;
			_write_history[idx].row = row;
			_oldest_wts = min_ts;
			_num_versions --;
		} else {
			// double the history size.
			double_list(0);
			_prewrite_ts = ts;
#if DEBUG_CC
			for (uint32_t i = 0; i < _his_len / 2; i++)
				assert(_write_history[i].valid);
			assert(!_write_history[_his_len / 2].valid);
#endif
			idx = _his_len / 2;
		}
	}
	assert(idx != _his_len);
	// some entries are not taken. But the row of that entry is NULL.
	if (!_write_history[idx].row) {
		_write_history[idx].row = (row_t *) _mm_malloc(sizeof(row_t), 64);
		_write_history[idx].row->init(MAX_TUPLE_SIZE);
	}
	_write_history[idx].valid = false;
	_write_history[idx].reserved = true;
	_write_history[idx].ts = ts;
	_exists_prewrite = true;
	_prewrite_his_id = idx;
	_prewrite_ts = ts;
	return _write_history[idx].row;
}

void Row_mvcc::update_buffer(txn_man * txn, TsType type) {
	// the current txn performs WR or XP.
	// immediate following R_REQ and P_REQ should return.
	ts_t ts = txn->get_ts();
	// figure out the ts for the next pending P_REQ
	ts_t next_pre_ts = UINT64_MAX ;
	for (uint32_t i = 0; i < _req_len; i++)
		if (_requests[i].valid && _requests[i].type == P_REQ
			&& _requests[i].ts > ts
			&& _requests[i].ts < next_pre_ts)
			next_pre_ts = _requests[i].ts;
	// return all pending quests between txn->ts and next_pre_ts
	for (uint32_t i = 0; i < _req_len; i++)	{
		if (_requests[i].valid)
			assert(_requests[i].ts > ts);
		// return pending R_REQ
		if (_requests[i].valid && _requests[i].type == R_REQ && _requests[i].ts < next_pre_ts) {
			if (_requests[i].ts > _max_served_rts)
				_max_served_rts = _requests[i].ts;
			_requests[i].valid = false;
			_requests[i].txn->cur_row = _latest_row;
			_requests[i].txn->ts_ready = true;
		}
		// return one pending P_REQ
		else if (_requests[i].valid && _requests[i].ts == next_pre_ts) {
			assert(_requests[i].type == P_REQ);
			row_t * res_row = reserveRow(_requests[i].ts, txn);
			assert(res_row);
			res_row->copy(_latest_row);
			_requests[i].valid = false;
			_requests[i].txn->cur_row = res_row;
			_requests[i].txn->ts_ready = true;
		}
	}
}

#endif
<|endoftext|>


<commit_before>//===- TableGen.cpp - Top-Level TableGen implementation for LLVM ----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the main function for LLVM's TableGen.
//
//===----------------------------------------------------------------------===//

#include "TableGenBackends.h" // Declares all backends.
#include "SetTheory.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Main.h"
#include "llvm/TableGen/Record.h"

using namespace llvm;

enum ActionType {
  PrintRecords,
  GenEmitter,
  GenRegisterInfo,
  GenInstrInfo,
  GenAsmWriter,
  GenAsmMatcher,
  GenDisassembler,
  GenPseudoLowering,
  GenCallingConv,
  GenDAGISel,
  GenDFAPacketizer,
  GenFastISel,
  GenSubtarget,
  GenIntrinsic,
  GenTgtIntrinsic,
  PrintEnums,
  PrintSets,
  GenOptParserDefs,
  GenCTags
};

namespace {
  cl::opt<ActionType>
  Action(cl::desc("Action to perform:"),
         cl::values(clEnumValN(PrintRecords, "print-records",
                               "Print all records to stdout (default)"),
                    clEnumValN(GenEmitter, "gen-emitter",
                               "Generate machine code emitter"),
                    clEnumValN(GenRegisterInfo, "gen-register-info",
                               "Generate registers and register classes info"),
                    clEnumValN(GenInstrInfo, "gen-instr-info",
                               "Generate instruction descriptions"),
                    clEnumValN(GenCallingConv, "gen-callingconv",
                               "Generate calling convention descriptions"),
                    clEnumValN(GenAsmWriter, "gen-asm-writer",
                               "Generate assembly writer"),
                    clEnumValN(GenDisassembler, "gen-disassembler",
                               "Generate disassembler"),
                    clEnumValN(GenPseudoLowering, "gen-pseudo-lowering",
                               "Generate pseudo instruction lowering"),
                    clEnumValN(GenAsmMatcher, "gen-asm-matcher",
                               "Generate assembly instruction matcher"),
                    clEnumValN(GenDAGISel, "gen-dag-isel",
                               "Generate a DAG instruction selector"),
                    clEnumValN(GenDFAPacketizer, "gen-dfa-packetizer",
                               "Generate DFA Packetizer for VLIW targets"),
                    clEnumValN(GenFastISel, "gen-fast-isel",
                               "Generate a \"fast\" instruction selector"),
                    clEnumValN(GenSubtarget, "gen-subtarget",
                               "Generate subtarget enumerations"),
                    clEnumValN(GenIntrinsic, "gen-intrinsic",
                               "Generate intrinsic information"),
                    clEnumValN(GenTgtIntrinsic, "gen-tgt-intrinsic",
                               "Generate target intrinsic information"),
                    clEnumValN(PrintEnums, "print-enums",
                               "Print enum values for a class"),
                    clEnumValN(PrintSets, "print-sets",
                               "Print expanded sets for testing DAG exprs"),
                    clEnumValN(GenOptParserDefs, "gen-opt-parser-defs",
                               "Generate option definitions"),
                    clEnumValN(GenCTags, "gen-ctags",
                               "Generate ctags-compatible index"),
                    clEnumValEnd));

  cl::opt<std::string>
  Class("class", cl::desc("Print Enum list for this class"),
          cl::value_desc("class name"));

bool LLVMTableGenMain(raw_ostream &OS, RecordKeeper &Records) {
  switch (Action) {
  case PrintRecords:
    OS << Records;           // No argument, dump all contents
    break;
  case GenEmitter:
    EmitCodeEmitter(Records, OS);
    break;
  case GenRegisterInfo:
    EmitRegisterInfo(Records, OS);
    break;
  case GenInstrInfo:
    EmitInstrInfo(Records, OS);
    break;
  case GenCallingConv:
    EmitCallingConv(Records, OS);
    break;
  case GenAsmWriter:
    EmitAsmWriter(Records, OS);
    break;
  case GenAsmMatcher:
    EmitAsmMatcher(Records, OS);
    break;
  case GenDisassembler:
    EmitDisassembler(Records, OS);
    break;
  case GenPseudoLowering:
    EmitPseudoLowering(Records, OS);
    break;
  case GenDAGISel:
    EmitDAGISel(Records, OS);
    break;
  case GenDFAPacketizer:
    EmitDFAPacketizer(Records, OS);
    break;
  case GenFastISel:
    EmitFastISel(Records, OS);
    break;
  case GenSubtarget:
    EmitSubtarget(Records, OS);
    break;
  case GenIntrinsic:
    EmitIntrinsics(Records, OS);
    break;
  case GenTgtIntrinsic:
    EmitIntrinsics(Records, OS, true);
    break;
  case GenOptParserDefs:
    EmitOptParser(Records, OS);
    break;
  case PrintEnums:
  {
    std::vector<Record*> Recs = Records.getAllDerivedDefinitions(Class);
    for (unsigned i = 0, e = Recs.size(); i != e; ++i)
      OS << Recs[i]->getName() << ", ";
    OS << "\n";
    break;
  }
  case PrintSets:
  {
    SetTheory Sets;
    Sets.addFieldExpander("Set", "Elements");
    std::vector<Record*> Recs = Records.getAllDerivedDefinitions("Set");
    for (unsigned i = 0, e = Recs.size(); i != e; ++i) {
      OS << Recs[i]->getName() << " = [";
      const std::vector<Record*> *Elts = Sets.expand(Recs[i]);
      assert(Elts && "Couldn't expand Set instance");
      for (unsigned ei = 0, ee = Elts->size(); ei != ee; ++ei)
        OS << ' ' << (*Elts)[ei]->getName();
      OS << " ]\n";
    }
    break;
  }
  case GenCTags:
    EmitCTags(Records, OS);
    break;
  }

  return false;
}
}

int main(int argc, char **argv) {
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);
  cl::ParseCommandLineOptions(argc, argv);

  return TableGenMain(argv[0], &LLVMTableGenMain);
}
<commit_msg>Disable LeakSanitizer in TableGen binaries, see PR18325<commit_after>//===- TableGen.cpp - Top-Level TableGen implementation for LLVM ----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the main function for LLVM's TableGen.
//
//===----------------------------------------------------------------------===//

#include "TableGenBackends.h" // Declares all backends.
#include "SetTheory.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Main.h"
#include "llvm/TableGen/Record.h"

using namespace llvm;

enum ActionType {
  PrintRecords,
  GenEmitter,
  GenRegisterInfo,
  GenInstrInfo,
  GenAsmWriter,
  GenAsmMatcher,
  GenDisassembler,
  GenPseudoLowering,
  GenCallingConv,
  GenDAGISel,
  GenDFAPacketizer,
  GenFastISel,
  GenSubtarget,
  GenIntrinsic,
  GenTgtIntrinsic,
  PrintEnums,
  PrintSets,
  GenOptParserDefs,
  GenCTags
};

namespace {
  cl::opt<ActionType>
  Action(cl::desc("Action to perform:"),
         cl::values(clEnumValN(PrintRecords, "print-records",
                               "Print all records to stdout (default)"),
                    clEnumValN(GenEmitter, "gen-emitter",
                               "Generate machine code emitter"),
                    clEnumValN(GenRegisterInfo, "gen-register-info",
                               "Generate registers and register classes info"),
                    clEnumValN(GenInstrInfo, "gen-instr-info",
                               "Generate instruction descriptions"),
                    clEnumValN(GenCallingConv, "gen-callingconv",
                               "Generate calling convention descriptions"),
                    clEnumValN(GenAsmWriter, "gen-asm-writer",
                               "Generate assembly writer"),
                    clEnumValN(GenDisassembler, "gen-disassembler",
                               "Generate disassembler"),
                    clEnumValN(GenPseudoLowering, "gen-pseudo-lowering",
                               "Generate pseudo instruction lowering"),
                    clEnumValN(GenAsmMatcher, "gen-asm-matcher",
                               "Generate assembly instruction matcher"),
                    clEnumValN(GenDAGISel, "gen-dag-isel",
                               "Generate a DAG instruction selector"),
                    clEnumValN(GenDFAPacketizer, "gen-dfa-packetizer",
                               "Generate DFA Packetizer for VLIW targets"),
                    clEnumValN(GenFastISel, "gen-fast-isel",
                               "Generate a \"fast\" instruction selector"),
                    clEnumValN(GenSubtarget, "gen-subtarget",
                               "Generate subtarget enumerations"),
                    clEnumValN(GenIntrinsic, "gen-intrinsic",
                               "Generate intrinsic information"),
                    clEnumValN(GenTgtIntrinsic, "gen-tgt-intrinsic",
                               "Generate target intrinsic information"),
                    clEnumValN(PrintEnums, "print-enums",
                               "Print enum values for a class"),
                    clEnumValN(PrintSets, "print-sets",
                               "Print expanded sets for testing DAG exprs"),
                    clEnumValN(GenOptParserDefs, "gen-opt-parser-defs",
                               "Generate option definitions"),
                    clEnumValN(GenCTags, "gen-ctags",
                               "Generate ctags-compatible index"),
                    clEnumValEnd));

  cl::opt<std::string>
  Class("class", cl::desc("Print Enum list for this class"),
          cl::value_desc("class name"));

bool LLVMTableGenMain(raw_ostream &OS, RecordKeeper &Records) {
  switch (Action) {
  case PrintRecords:
    OS << Records;           // No argument, dump all contents
    break;
  case GenEmitter:
    EmitCodeEmitter(Records, OS);
    break;
  case GenRegisterInfo:
    EmitRegisterInfo(Records, OS);
    break;
  case GenInstrInfo:
    EmitInstrInfo(Records, OS);
    break;
  case GenCallingConv:
    EmitCallingConv(Records, OS);
    break;
  case GenAsmWriter:
    EmitAsmWriter(Records, OS);
    break;
  case GenAsmMatcher:
    EmitAsmMatcher(Records, OS);
    break;
  case GenDisassembler:
    EmitDisassembler(Records, OS);
    break;
  case GenPseudoLowering:
    EmitPseudoLowering(Records, OS);
    break;
  case GenDAGISel:
    EmitDAGISel(Records, OS);
    break;
  case GenDFAPacketizer:
    EmitDFAPacketizer(Records, OS);
    break;
  case GenFastISel:
    EmitFastISel(Records, OS);
    break;
  case GenSubtarget:
    EmitSubtarget(Records, OS);
    break;
  case GenIntrinsic:
    EmitIntrinsics(Records, OS);
    break;
  case GenTgtIntrinsic:
    EmitIntrinsics(Records, OS, true);
    break;
  case GenOptParserDefs:
    EmitOptParser(Records, OS);
    break;
  case PrintEnums:
  {
    std::vector<Record*> Recs = Records.getAllDerivedDefinitions(Class);
    for (unsigned i = 0, e = Recs.size(); i != e; ++i)
      OS << Recs[i]->getName() << ", ";
    OS << "\n";
    break;
  }
  case PrintSets:
  {
    SetTheory Sets;
    Sets.addFieldExpander("Set", "Elements");
    std::vector<Record*> Recs = Records.getAllDerivedDefinitions("Set");
    for (unsigned i = 0, e = Recs.size(); i != e; ++i) {
      OS << Recs[i]->getName() << " = [";
      const std::vector<Record*> *Elts = Sets.expand(Recs[i]);
      assert(Elts && "Couldn't expand Set instance");
      for (unsigned ei = 0, ee = Elts->size(); ei != ee; ++ei)
        OS << ' ' << (*Elts)[ei]->getName();
      OS << " ]\n";
    }
    break;
  }
  case GenCTags:
    EmitCTags(Records, OS);
    break;
  }

  return false;
}
}

int main(int argc, char **argv) {
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);
  cl::ParseCommandLineOptions(argc, argv);

  return TableGenMain(argv[0], &LLVMTableGenMain);
}

extern "C" {
// Disable LeakSanitizer for this binary as it has too many leaks that are not
// very interesting to fix. __lsan_is_turned_off is explained in
// compiler-rt/include/sanitizer/lsan_interface.h
int __lsan_is_turned_off() { return 1; }
}  // extern "C"
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "glwidget.h"
#include <math.h>

#include "cube.h"

#include <QGLPixelBuffer>

#ifndef GL_MULTISAMPLE
#define GL_MULTISAMPLE  0x809D
#endif

static GLfloat colorArray[][4] = {
    {0.243f, 0.423f, 0.125f, 1.0f},
    {0.176f, 0.31f, 0.09f, 1.0f},
    {0.4f, 0.69f, 0.212f, 1.0f},
    {0.317f, 0.553f, 0.161f, 1.0f}
};

GLWidget::GLWidget(QWidget *parent)
    : QGLWidget(QGLFormat(QGL::SampleBuffers), parent)
    , geom(0)
    , cube(0)
{
    // create the pbuffer
    pbuffer = new QGLPixelBuffer(QSize(512, 512), format(), this);
    setWindowTitle(tr("OpenGL pbuffers"));
    initializeGeometry();
}

GLWidget::~GLWidget()
{
    pbuffer->releaseFromDynamicTexture();
    glDeleteTextures(1, &dynamicTexture);
    delete pbuffer;

    qDeleteAll(cubes);
    qDeleteAll(tiles);
    delete cube;
}

void GLWidget::initializeGL()
{
    initCommon();
    glShadeModel(GL_SMOOTH);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    static GLfloat lightPosition[4] = { 0.5, 5.0, 7.0, 1.0 };
    glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
    initPbuffer();
    cube->startAnimation();
    connect(cube, SIGNAL(changed()), this, SLOT(update()));
    for (int i = 0; i < 3; ++i)
    {
        cubes[i]->startAnimation();
        connect(cubes[i], SIGNAL(changed()), this, SLOT(update()));
    }
}

void GLWidget::paintGL()
{
    pbuffer->makeCurrent();
    drawPbuffer();
    // On direct render platforms, drawing onto the pbuffer context above
    // automatically updates the dynamic texture.  For cases where rendering
    // directly to a texture is not supported, explicitly copy.
    if (!hasDynamicTextureUpdate)
        pbuffer->updateDynamicTexture(dynamicTexture);
    makeCurrent();

    // Use the pbuffer as a texture to render the scene
    glBindTexture(GL_TEXTURE_2D, dynamicTexture);

    // set up to render the scene
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    glTranslatef(0.0f, 0.0f, -10.0f);

    // draw the background
    glPushMatrix();
    glScalef(aspect, 1.0f, 1.0f);
    for (int i = 0; i < tiles.count(); ++i)
        tiles[i]->draw();
    glPopMatrix();

    // draw the bouncing cubes
    for (int i = 0; i < cubes.count(); ++i)
        cubes[i]->draw();
}

void GLWidget::initializeGeometry()
{
    geom = new Geometry();
    CubeBuilder cBuilder(geom, 0.5);
    cBuilder.setColor(QColor(255, 255, 255, 212));
    // build the 3 bouncing, spinning cubes
    for (int i = 0; i < 3; ++i)
        cubes.append(cBuilder.newCube(QVector3D((float)(i-1), -1.5f, 5 - i)));

    // build the spinning cube which goes in the dynamic texture
    cube = cBuilder.newCube();
    cube->removeBounce();

    // build the background tiles
    TileBuilder tBuilder(geom);
    tBuilder.setColor(QColor(Qt::white));
    for (int c = -2; c <= +2; ++c)
        for (int r = -2; r <= +2; ++r)
            tiles.append(tBuilder.newTile(QVector3D(c, r, 0)));

    // graded backdrop for the pbuffer scene
    TileBuilder bBuilder(geom, 0.0f, 2.0f);
    bBuilder.setColor(QColor(102, 176, 54, 210));
    backdrop = bBuilder.newTile(QVector3D(0.0f, 0.0f, -1.5f));
    backdrop->setColors(colorArray);
}

void GLWidget::initCommon()
{
    qglClearColor(QColor(Qt::darkGray));

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glEnable(GL_MULTISAMPLE);

    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);

    glEnable(GL_TEXTURE_2D);

    geom->loadArrays();
}

void GLWidget::perspectiveProjection()
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glFrustum(-aspect, +aspect, -1.0, +1.0, 4.0, 15.0);
    glMatrixMode(GL_MODELVIEW);
}

void GLWidget::orthographicProjection()
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-1.0, +1.0, -1.0, +1.0, -90.0, +90.0);
    glMatrixMode(GL_MODELVIEW);
}

void GLWidget::resizeGL(int width, int height)
{
    glViewport(0, 0, width, height);
    aspect = (qreal)width / (qreal)(height ? height : 1);
    perspectiveProjection();
}

void GLWidget::drawPbuffer()
{
    orthographicProjection();

    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glDisable(GL_TEXTURE_2D);
    backdrop->draw();
    glEnable(GL_TEXTURE_2D);

    glBindTexture(GL_TEXTURE_2D, cubeTexture);
    glDisable(GL_CULL_FACE);
    cube->draw();
    glEnable(GL_CULL_FACE);

    glFlush();
}

void GLWidget::initPbuffer()
{
    pbuffer->makeCurrent();

    cubeTexture = bindTexture(QImage(":res/cubelogo.png"));

    initCommon();

    // generate a texture that has the same size/format as the pbuffer
    dynamicTexture = pbuffer->generateDynamicTexture();

    // bind the dynamic texture to the pbuffer - this is a no-op under X11
    hasDynamicTextureUpdate = pbuffer->bindToDynamicTexture(dynamicTexture);
    makeCurrent();
}

void GLWidget::setAnimationPaused(bool enable)
{
    cube->setAnimationPaused(enable);
    for (int i = 0; i < 3; ++i)
        cubes[i]->setAnimationPaused(enable);
}
<commit_msg>Make pbuffers example compile under OpenGL/ES 1.1<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "glwidget.h"
#include <math.h>

#include "cube.h"

#include <QGLPixelBuffer>

#ifndef GL_MULTISAMPLE
#define GL_MULTISAMPLE  0x809D
#endif

static GLfloat colorArray[][4] = {
    {0.243f, 0.423f, 0.125f, 1.0f},
    {0.176f, 0.31f, 0.09f, 1.0f},
    {0.4f, 0.69f, 0.212f, 1.0f},
    {0.317f, 0.553f, 0.161f, 1.0f}
};

GLWidget::GLWidget(QWidget *parent)
    : QGLWidget(QGLFormat(QGL::SampleBuffers), parent)
    , geom(0)
    , cube(0)
{
    // create the pbuffer
    pbuffer = new QGLPixelBuffer(QSize(512, 512), format(), this);
    setWindowTitle(tr("OpenGL pbuffers"));
    initializeGeometry();
}

GLWidget::~GLWidget()
{
    pbuffer->releaseFromDynamicTexture();
    glDeleteTextures(1, &dynamicTexture);
    delete pbuffer;

    qDeleteAll(cubes);
    qDeleteAll(tiles);
    delete cube;
}

void GLWidget::initializeGL()
{
    initCommon();
    glShadeModel(GL_SMOOTH);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    static GLfloat lightPosition[4] = { 0.5, 5.0, 7.0, 1.0 };
    glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
    initPbuffer();
    cube->startAnimation();
    connect(cube, SIGNAL(changed()), this, SLOT(update()));
    for (int i = 0; i < 3; ++i)
    {
        cubes[i]->startAnimation();
        connect(cubes[i], SIGNAL(changed()), this, SLOT(update()));
    }
}

void GLWidget::paintGL()
{
    pbuffer->makeCurrent();
    drawPbuffer();
    // On direct render platforms, drawing onto the pbuffer context above
    // automatically updates the dynamic texture.  For cases where rendering
    // directly to a texture is not supported, explicitly copy.
    if (!hasDynamicTextureUpdate)
        pbuffer->updateDynamicTexture(dynamicTexture);
    makeCurrent();

    // Use the pbuffer as a texture to render the scene
    glBindTexture(GL_TEXTURE_2D, dynamicTexture);

    // set up to render the scene
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    glTranslatef(0.0f, 0.0f, -10.0f);

    // draw the background
    glPushMatrix();
    glScalef(aspect, 1.0f, 1.0f);
    for (int i = 0; i < tiles.count(); ++i)
        tiles[i]->draw();
    glPopMatrix();

    // draw the bouncing cubes
    for (int i = 0; i < cubes.count(); ++i)
        cubes[i]->draw();
}

void GLWidget::initializeGeometry()
{
    geom = new Geometry();
    CubeBuilder cBuilder(geom, 0.5);
    cBuilder.setColor(QColor(255, 255, 255, 212));
    // build the 3 bouncing, spinning cubes
    for (int i = 0; i < 3; ++i)
        cubes.append(cBuilder.newCube(QVector3D((float)(i-1), -1.5f, 5 - i)));

    // build the spinning cube which goes in the dynamic texture
    cube = cBuilder.newCube();
    cube->removeBounce();

    // build the background tiles
    TileBuilder tBuilder(geom);
    tBuilder.setColor(QColor(Qt::white));
    for (int c = -2; c <= +2; ++c)
        for (int r = -2; r <= +2; ++r)
            tiles.append(tBuilder.newTile(QVector3D(c, r, 0)));

    // graded backdrop for the pbuffer scene
    TileBuilder bBuilder(geom, 0.0f, 2.0f);
    bBuilder.setColor(QColor(102, 176, 54, 210));
    backdrop = bBuilder.newTile(QVector3D(0.0f, 0.0f, -1.5f));
    backdrop->setColors(colorArray);
}

void GLWidget::initCommon()
{
    qglClearColor(QColor(Qt::darkGray));

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glEnable(GL_MULTISAMPLE);

    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);

    glEnable(GL_TEXTURE_2D);

    geom->loadArrays();
}

void GLWidget::perspectiveProjection()
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
#ifdef QT_OPENGL_ES
    glFrustumf(-aspect, +aspect, -1.0, +1.0, 4.0, 15.0);
#else
    glFrustum(-aspect, +aspect, -1.0, +1.0, 4.0, 15.0);
#endif
    glMatrixMode(GL_MODELVIEW);
}

void GLWidget::orthographicProjection()
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
#ifdef QT_OPENGL_ES
    glOrthof(-1.0, +1.0, -1.0, +1.0, -90.0, +90.0);
#else
    glOrtho(-1.0, +1.0, -1.0, +1.0, -90.0, +90.0);
#endif
    glMatrixMode(GL_MODELVIEW);
}

void GLWidget::resizeGL(int width, int height)
{
    glViewport(0, 0, width, height);
    aspect = (qreal)width / (qreal)(height ? height : 1);
    perspectiveProjection();
}

void GLWidget::drawPbuffer()
{
    orthographicProjection();

    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glDisable(GL_TEXTURE_2D);
    backdrop->draw();
    glEnable(GL_TEXTURE_2D);

    glBindTexture(GL_TEXTURE_2D, cubeTexture);
    glDisable(GL_CULL_FACE);
    cube->draw();
    glEnable(GL_CULL_FACE);

    glFlush();
}

void GLWidget::initPbuffer()
{
    pbuffer->makeCurrent();

    cubeTexture = bindTexture(QImage(":res/cubelogo.png"));

    initCommon();

    // generate a texture that has the same size/format as the pbuffer
    dynamicTexture = pbuffer->generateDynamicTexture();

    // bind the dynamic texture to the pbuffer - this is a no-op under X11
    hasDynamicTextureUpdate = pbuffer->bindToDynamicTexture(dynamicTexture);
    makeCurrent();
}

void GLWidget::setAnimationPaused(bool enable)
{
    cube->setAnimationPaused(enable);
    for (int i = 0; i < 3; ++i)
        cubes[i]->setAnimationPaused(enable);
}
<|endoftext|>


<commit_before>#include "stoptasksdialog.h"

WARNINGS_DISABLE
#include <QAction>
#include <QMenu>
#include <QPushButton>
WARNINGS_ENABLE

StopTasksDialog::StopTasksDialog(QWidget *parent)
    : QMessageBox(parent),
      _actionButton(new QPushButton(this)),
      _actionMenu(new QMenu(_actionButton))
{
}

void StopTasksDialog::display(bool backupTaskRunning, int runningTasks,
                              int queuedTasks, bool aboutToQuit)
{
    _aboutToQuit = aboutToQuit;

    // Overall setup.
    setText(tr("There are %1 running tasks and %2 queued.")
                .arg(runningTasks)
                .arg(queuedTasks));
    setInformativeText(tr("What do you want to do?"));

    _actionButton->setText(tr("Choose action"));

    // interrupt
    _interruptBackup = nullptr;
    if(backupTaskRunning)
    {
        if(_aboutToQuit)
            _interruptBackup =
                _actionMenu->addAction(tr("Interrupt backup and clear queue"));
        else
            _interruptBackup = _actionMenu->addAction(tr("Interrupt backup"));
        _interruptBackup->setCheckable(true);
    }
    // stopRunning
    _stopRunning = nullptr;
    if(runningTasks && !_aboutToQuit)
    {
        _stopRunning = _actionMenu->addAction(tr("Stop running"));
        _stopRunning->setCheckable(true);
    }
    // stopQueued
    _stopQueued = nullptr;
    if(queuedTasks && !_aboutToQuit)
    {
        _stopQueued = _actionMenu->addAction(tr("Cancel queued"));
        _stopQueued->setCheckable(true);
    }
    // stopAll
    _stopAll = nullptr;
    if(runningTasks || queuedTasks)
    {
        _stopAll = _actionMenu->addAction(tr("Stop all"));
        _stopAll->setCheckable(true);
    }
    // proceedBackground
    _proceedBackground = nullptr;
    if((runningTasks || queuedTasks) && _aboutToQuit)
    {
        _proceedBackground =
            _actionMenu->addAction(tr("Proceed in background"));
        _proceedBackground->setCheckable(true);
    }
    _cancel = addButton(QMessageBox::Cancel);
    setDefaultButton(_cancel);
    connect(_actionMenu, &QMenu::triggered, this, &QDialog::accept,
            Qt::QueuedConnection);
    _actionButton->setMenu(_actionMenu);
    addButton(_actionButton, QMessageBox::ActionRole);

    // Launch dialog.
    int res = exec();

    // Bail (if applicable).
    // QMessageBox::finished() is not documented as diverging from
    // QDialog::finished().  However, it does differ, similar to
    // QMessageBox::exec() -- it can return a QMessageBox::StandardButton
    // value.  That said, if the QMessageBox is closed with an
    // ->accept(), ->reject(), or ->close(), it will still provide a
    // QDialog::Accepted or QDialog::Rejected.
    if((res != QDialog::Accepted) || (clickedButton() == _cancel))
    {
        if(_aboutToQuit)
        {
            _aboutToQuit = false;
            emit cancelAboutToQuit();
        }
        return;
    }

    // Signal that we can quit now.
    if(_aboutToQuit)
    {
        emit quitOk();
    }

    // Stop tasks.
    if(_interruptBackup && _interruptBackup->isChecked())
        emit stopTasks(true, false, _aboutToQuit);
    else if(_stopQueued && _stopQueued->isChecked())
        emit stopTasks(false, false, true);
    else if(_stopRunning && _stopRunning->isChecked())
        emit stopTasks(false, true, false);
    else if(_stopAll && _stopAll->isChecked())
        emit stopTasks(false, true, true);
    else if(_proceedBackground && _proceedBackground->isChecked())
    {
        // Do nothing; it will happen due to code elsewhere
    }
}
<commit_msg>StopTasksDialog: move initialization into constructor<commit_after>#include "stoptasksdialog.h"

WARNINGS_DISABLE
#include <QAction>
#include <QMenu>
#include <QPushButton>
WARNINGS_ENABLE

StopTasksDialog::StopTasksDialog(QWidget *parent)
    : QMessageBox(parent),
      _actionButton(new QPushButton(this)),
      _actionMenu(new QMenu(_actionButton))
{
    // Set up text.
    setInformativeText(tr("What do you want to do?"));
    _actionButton->setText(tr("Choose action"));

    // Set up buttons.
    _cancel = addButton(QMessageBox::Cancel);
    setDefaultButton(_cancel);
    connect(_actionMenu, &QMenu::triggered, this, &QDialog::accept,
            Qt::QueuedConnection);
    _actionButton->setMenu(_actionMenu);
    addButton(_actionButton, QMessageBox::ActionRole);
}

void StopTasksDialog::display(bool backupTaskRunning, int runningTasks,
                              int queuedTasks, bool aboutToQuit)
{
    _aboutToQuit = aboutToQuit;

    // Overall setup.
    setText(tr("There are %1 running tasks and %2 queued.")
                .arg(runningTasks)
                .arg(queuedTasks));
    _actionMenu->clear();

    // interrupt
    _interruptBackup = nullptr;
    if(backupTaskRunning)
    {
        if(_aboutToQuit)
            _interruptBackup =
                _actionMenu->addAction(tr("Interrupt backup and clear queue"));
        else
            _interruptBackup = _actionMenu->addAction(tr("Interrupt backup"));
        _interruptBackup->setCheckable(true);
    }
    // stopRunning
    _stopRunning = nullptr;
    if(runningTasks && !_aboutToQuit)
    {
        _stopRunning = _actionMenu->addAction(tr("Stop running"));
        _stopRunning->setCheckable(true);
    }
    // stopQueued
    _stopQueued = nullptr;
    if(queuedTasks && !_aboutToQuit)
    {
        _stopQueued = _actionMenu->addAction(tr("Cancel queued"));
        _stopQueued->setCheckable(true);
    }
    // stopAll
    _stopAll = nullptr;
    if(runningTasks || queuedTasks)
    {
        _stopAll = _actionMenu->addAction(tr("Stop all"));
        _stopAll->setCheckable(true);
    }
    // proceedBackground
    _proceedBackground = nullptr;
    if((runningTasks || queuedTasks) && _aboutToQuit)
    {
        _proceedBackground =
            _actionMenu->addAction(tr("Proceed in background"));
        _proceedBackground->setCheckable(true);
    }

    // Launch dialog.
    int res = exec();

    // Bail (if applicable).
    // QMessageBox::finished() is not documented as diverging from
    // QDialog::finished().  However, it does differ, similar to
    // QMessageBox::exec() -- it can return a QMessageBox::StandardButton
    // value.  That said, if the QMessageBox is closed with an
    // ->accept(), ->reject(), or ->close(), it will still provide a
    // QDialog::Accepted or QDialog::Rejected.
    if((res != QDialog::Accepted) || (clickedButton() == _cancel))
    {
        if(_aboutToQuit)
        {
            _aboutToQuit = false;
            emit cancelAboutToQuit();
        }
        return;
    }

    // Signal that we can quit now.
    if(_aboutToQuit)
    {
        emit quitOk();
    }

    // Stop tasks.
    if(_interruptBackup && _interruptBackup->isChecked())
        emit stopTasks(true, false, _aboutToQuit);
    else if(_stopQueued && _stopQueued->isChecked())
        emit stopTasks(false, false, true);
    else if(_stopRunning && _stopRunning->isChecked())
        emit stopTasks(false, true, false);
    else if(_stopAll && _stopAll->isChecked())
        emit stopTasks(false, true, true);
    else if(_proceedBackground && _proceedBackground->isChecked())
    {
        // Do nothing; it will happen due to code elsewhere
    }
}
<|endoftext|>


<commit_before>#include "jitpp/arm/Disassembler.h"
#include "jitpp/ppc/Disassembler.h"

#include "binary/Binary.h"

#include <getopt.h>

#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>

const char *binary_type_str = nullptr;
const char *machine_type_str = nullptr;

const char *binary_name = nullptr;

std::vector<std::string> symbol_files;

remu::binary::BinaryOptions binary_options = {
	.load_addr   = remu::binary::UNKNOWN_LOAD_ADDR,
	.entry_point = remu::binary::UNKNOWN_ENTRY_POINT,
	.machine     = remu::binary::MachineType::UNKNOWN,
};

std::unique_ptr<remu::jitpp::Disassembler> disassembler;

static void parse_args( int argc, char **argv )
{
	int option_index = 0;

	static struct option long_options[] = {
		{ "binary-type",  required_argument, 0, 'b' },
		{ "machine-type", required_argument, 0, 'm' },
		{ "symbol-file",  required_argument, 0, 's' },
	};

	while( true ) {
		int c = getopt_long(argc, argv, "b:m:", long_options, &option_index);

		if( c == -1 ) {
			break;
		}

		switch( c ) {
		case 'b': binary_type_str = optarg;       break;
		case 'm': machine_type_str = optarg;      break;
		case 's': symbol_files.push_back(optarg); break;

		case '?': exit( 1 );
		default:  exit( 1 );
		}
	}

	while( optind < argc ) {
		if( nullptr == binary_name ) {
			binary_name = argv[optind++];
		}
		else {
			fprintf( stderr, "Error:  Multiple binary files specified\n" );
			exit( 1 );
		}
	}
}

static void print_header( remu::binary::Binary* binary )
{
	printf( "\n" );
	printf( "%s:     file format %s\n", binary_name, binary->formatName().c_str() );
	printf( "\n" );
}

static size_t count_zeros( const remu::util::memslice& slice )
{
	size_t num_zeros = 0;

	while( (num_zeros < slice.size) && (slice.data[num_zeros] == 0) ) {
		num_zeros++;
	}

	return num_zeros;
}

static void disassemble_file( remu::binary::Binary* binary )
{
	print_header( binary );

	auto segment_list = binary->getSectionSegments();

	auto symbol_db = binary->getSymbolDB();

	char dis[64];

	for( const auto& segment : segment_list ) {
		if( !segment.executable ) {
			continue;
		}

		printf( "\n" );
		printf( "Disassembly of section %s:\n", segment.name.c_str() );

		uint64_t cur_off = segment.base;
		const uint64_t end = segment.base + segment.size;
		std::vector<uint8_t> cur_section = binary->readSegment( segment );
		remu::util::memslice slice = { cur_section.data(), cur_section.size() };

		while( cur_off < end ) {
			const auto num_zeros = count_zeros( slice );

			if( count_zeros(slice) >= 8 ) {
				printf( "\t...\n" );
				const auto bytes_to_consume = num_zeros - (num_zeros % 4);

				cur_off += bytes_to_consume;

				slice.data += bytes_to_consume;
				slice.size -= bytes_to_consume;
			}
			else {
				const auto symbol = symbol_db.getSymbolExact( cur_off );
				if( symbol ) {
					printf( "\n" );
					printf( "%lx <%s>:\n", cur_off, symbol->name.c_str() );
				}
				else if( cur_off == segment.base ) {
					printf( "\n" );
					printf( "%lx <%s>:\n", cur_off, segment.name.c_str() );
				}

				size_t instr_size = disassembler->disassemble( slice, cur_off, dis, 64 );
				printf( "%lx:\t", cur_off );
				size_t ii = 0;
				for( ; ii < instr_size; ii++ ) {
					printf( "%02x ", slice.data[ii] );
				}
				for( ; ii < 4; ii++ ) {
					printf( "   " );
				}
				printf( "\t%s\n", dis );

				cur_off += instr_size;

				slice.data += instr_size;
				slice.size -= instr_size;
			}
		}
	}
}

int main( int argc, char **argv )
{
	parse_args( argc, argv );

	if( nullptr == binary_name ) {
		fprintf( stderr, "Error:  No binary specified\n" );
		exit( 1 );
	}

	remu::oshal::File file( binary_name );
	if( !file.isOpen() ) {
		fprintf( stderr, "Error:  Unable to open file \"%s\"\n", binary_name );
		exit( 1 );
	}

	auto binary = remu::binary::binaryForFile( file, binary_options );

	if( !binary ) {
		fprintf( stderr, "Error:  Unable to divine filetype for file \"%s\"\n", binary_name );
		exit( 1 );
	}

	if( binary->machineType() == remu::binary::MachineType::UNKNOWN ) {
	}

	switch( binary->machineType() ) {
		case remu::binary::MachineType::UNKNOWN: {
			fprintf( stderr, "Error: Unknown machine type in file \"%s\"\n", binary_name );
			exit( 1 );
		}
		break;

		case remu::binary::MachineType::PPC: {
			disassembler = std::unique_ptr<remu::jitpp::Disassembler>( new remu::jitpp::ppc::Disassembler() );
		}
		break;

		case remu::binary::MachineType::ARM: {
			disassembler = std::unique_ptr<remu::jitpp::Disassembler>( new remu::jitpp::arm::Disassembler() );
		}
		break;
	}

	disassemble_file( binary.get() );

	return 0;
}

<commit_msg>Spacing on jitpp-dis to match objdump in 32-bit mode<commit_after>#include "jitpp/arm/Disassembler.h"
#include "jitpp/ppc/Disassembler.h"

#include "binary/Binary.h"

#include <getopt.h>

#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>

const char *binary_type_str = nullptr;
const char *machine_type_str = nullptr;

const char *binary_name = nullptr;

std::vector<std::string> symbol_files;

remu::binary::BinaryOptions binary_options = {
	.load_addr   = remu::binary::UNKNOWN_LOAD_ADDR,
	.entry_point = remu::binary::UNKNOWN_ENTRY_POINT,
	.machine     = remu::binary::MachineType::UNKNOWN,
};

std::unique_ptr<remu::jitpp::Disassembler> disassembler;

static void parse_args( int argc, char **argv )
{
	int option_index = 0;

	static struct option long_options[] = {
		{ "binary-type",  required_argument, 0, 'b' },
		{ "machine-type", required_argument, 0, 'm' },
		{ "symbol-file",  required_argument, 0, 's' },
	};

	while( true ) {
		int c = getopt_long(argc, argv, "b:m:", long_options, &option_index);

		if( c == -1 ) {
			break;
		}

		switch( c ) {
		case 'b': binary_type_str = optarg;       break;
		case 'm': machine_type_str = optarg;      break;
		case 's': symbol_files.push_back(optarg); break;

		case '?': exit( 1 );
		default:  exit( 1 );
		}
	}

	while( optind < argc ) {
		if( nullptr == binary_name ) {
			binary_name = argv[optind++];
		}
		else {
			fprintf( stderr, "Error:  Multiple binary files specified\n" );
			exit( 1 );
		}
	}
}

static void print_header( remu::binary::Binary* binary )
{
	printf( "\n" );
	printf( "%s:     file format %s\n", binary_name, binary->formatName().c_str() );
	printf( "\n" );
}

static size_t count_zeros( const remu::util::memslice& slice )
{
	size_t num_zeros = 0;

	while( (num_zeros < slice.size) && (slice.data[num_zeros] == 0) ) {
		num_zeros++;
	}

	return num_zeros;
}

static void disassemble_file( remu::binary::Binary* binary )
{
	print_header( binary );

	auto segment_list = binary->getSectionSegments();

	auto symbol_db = binary->getSymbolDB();

	char dis[64];

	for( const auto& segment : segment_list ) {
		if( !segment.executable ) {
			continue;
		}

		printf( "\n" );
		printf( "Disassembly of section %s:\n", segment.name.c_str() );

		uint64_t cur_off = segment.base;
		const uint64_t end = segment.base + segment.size;
		std::vector<uint8_t> cur_section = binary->readSegment( segment );
		remu::util::memslice slice = { cur_section.data(), cur_section.size() };

		while( cur_off < end ) {
			const auto num_zeros = count_zeros( slice );

			const auto symbol = symbol_db.getSymbolExact( cur_off );
			if( symbol ) {
				printf( "\n" );
				printf( "%08lx <%s>:\n", cur_off, symbol->name.c_str() );
			}
			else if( cur_off == segment.base ) {
				printf( "\n" );
				printf( "%08lx <%s>:\n", cur_off, segment.name.c_str() );
			}

			if( count_zeros(slice) >= 8 ) {
				printf( "\t...\n" );
				const auto bytes_to_consume = num_zeros - (num_zeros % 4);

				cur_off += bytes_to_consume;

				slice.data += bytes_to_consume;
				slice.size -= bytes_to_consume;
			}
			else {

				size_t instr_size = disassembler->disassemble( slice, cur_off, dis, 64 );
				printf( "%8lx:\t", cur_off );
				size_t ii = 0;
				for( ; ii < instr_size; ii++ ) {
					printf( "%02x ", slice.data[ii] );
				}
				for( ; ii < 4; ii++ ) {
					printf( "   " );
				}
				printf( "\t%s\n", dis );

				cur_off += instr_size;

				slice.data += instr_size;
				slice.size -= instr_size;
			}
		}
	}
}

int main( int argc, char **argv )
{
	parse_args( argc, argv );

	if( nullptr == binary_name ) {
		fprintf( stderr, "Error:  No binary specified\n" );
		exit( 1 );
	}

	remu::oshal::File file( binary_name );
	if( !file.isOpen() ) {
		fprintf( stderr, "Error:  Unable to open file \"%s\"\n", binary_name );
		exit( 1 );
	}

	auto binary = remu::binary::binaryForFile( file, binary_options );

	if( !binary ) {
		fprintf( stderr, "Error:  Unable to divine filetype for file \"%s\"\n", binary_name );
		exit( 1 );
	}

	if( binary->machineType() == remu::binary::MachineType::UNKNOWN ) {
	}

	switch( binary->machineType() ) {
		case remu::binary::MachineType::UNKNOWN: {
			fprintf( stderr, "Error: Unknown machine type in file \"%s\"\n", binary_name );
			exit( 1 );
		}
		break;

		case remu::binary::MachineType::PPC: {
			disassembler = std::unique_ptr<remu::jitpp::Disassembler>( new remu::jitpp::ppc::Disassembler() );
		}
		break;

		case remu::binary::MachineType::ARM: {
			disassembler = std::unique_ptr<remu::jitpp::Disassembler>( new remu::jitpp::arm::Disassembler() );
		}
		break;
	}

	disassemble_file( binary.get() );

	return 0;
}

<|endoftext|>