<commit_before>/* Copyright 2021 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

#include "dng_color_space.h"
#include "dng_date_time.h"
#include "dng_exceptions.h"
#include "dng_file_stream.h"
#include "dng_globals.h"
#include "dng_host.h"
#include "dng_ifd.h"
#include "dng_image_writer.h"
#include "dng_info.h"
#include "dng_linearization_info.h"
#include "dng_mosaic_info.h"
#include "dng_negative.h"
#include "dng_preview.h"
#include "dng_render.h"
#include "dng_simple_image.h"
#include "dng_tag_codes.h"
#include "dng_tag_types.h"
#include "dng_tag_values.h"
#include "dng_camera_profile.h"

// Run a set of the operations high-level operations on the dng_sdk
// This code is inspired by dng_validate.cpp and performs many of the same
// operations in a simplified manner.
void runFuzzerWithVariableHost(char *filename, uint32_t dng_version,
                               bool linear, bool preview, bool should_proxy,
                               bool KeepOriginalFile, bool NeedsMeta,
                               bool NeedsImage, int do_color_coding,
                               bool setFuji) {
  dng_host host;
  host.SetPreferredSize(0);
  host.SetMinimumSize(0);
  host.SetMaximumSize(0);
  host.SetSaveDNGVersion(dng_version);
  host.SetSaveLinearDNG(linear);
  host.SetForPreview(preview);
  host.ValidateSizes();
  host.SetKeepOriginalFile(KeepOriginalFile);
  host.SetNeedsMeta(NeedsMeta);
  host.SetNeedsImage(NeedsImage);

  AutoPtr<dng_camera_profile> customCameraProfile (new dng_camera_profile ());
  customCameraProfile->SetName("custom profile");

  AutoPtr<dng_negative> negative;
  try {
    dng_info info;
    dng_file_stream stream((const char *)filename);
    info.Parse(host, stream);
    info.PostParse(host);

    if (setFuji && info.fIFDCount > 0) {
      info.fIFD[0]->CanRead();
    }

    if (info.IsValidDNG()) {
      negative.Reset(host.Make_dng_negative());
      negative->AddProfile(customCameraProfile);

      if (do_color_coding == 1) {
        negative->SetDefaultCropSize((uint32)100,(uint32)100);
        negative->SetDefaultCropOrigin((uint32)50,(uint32)100);
      }
      else if (do_color_coding == 2) {
        negative->ResetDefaultUserCrop();
      }
      else {
        negative->SetDefaultUserCropT(dng_urational(0, 1));
      }

      negative->SetStage3Gain(2);
      negative->SetIsPreview(true);

      negative->Parse(host, stream, info);
      negative->PostParse(host, stream, info);
      negative->ReadStage1Image(host, stream, info);
      if (info.fMaskIndex != -1) {
        negative->ReadTransparencyMask(host, stream, info);
      }

      negative->SynchronizeMetadata();
      negative->SetFourColorBayer();
      if (do_color_coding == 1) {
        negative->SetRGB();
      }
      else if (do_color_coding == 2) {
        negative->SetCMY();
      }
      else if (do_color_coding == 3) {
        negative->SetGMCY();
      }
      negative->BuildStage2Image(host);
      negative->BuildStage3Image(host, 1);

      if (should_proxy) {
        dng_image_writer writer;
        negative->ConvertToProxy(host, writer, 1);
      }

      if (negative->NeedFlattenTransparency(host)) {
        negative->FlattenTransparency(host);
      }

      // Write DNG
      dng_file_stream stream3("/tmp/randdng1", true);
      dng_image_writer writer3;
      dng_preview_list previewList;
      writer3.WriteDNG(host, stream3, *negative.Get(), &previewList,
                       dng_version, false);

      // Write TIFF
      uint32_t compression_arr[8] = { ccUncompressed, ccLZW, ccOldJPEG, ccJPEG,
        ccDeflate, ccPackBits, ccOldDeflate, ccLossyJPEG};
      for (int c = 0; c < 8; c++) {
        dng_file_stream stream2("/tmp/randpng", true);
        const dng_image &stage3 = *negative->Stage3Image();
        dng_image_writer writer2;
        writer2.WriteTIFF(host, stream2, stage3,
                          stage3.Planes() >= 3 ? piRGB : piBlackIsZero, compression_arr[c]);
      }

      // Create a renderer
      dng_render render(host, *negative);
      AutoPtr<dng_image> finalImage;
      finalImage.Reset(render.Render());

      // Use a random var to determine if we should clear profiles from disk.
      if (do_color_coding == 3) {
      negative->ClearProfiles(true, true);
      }
    }
  } catch (dng_exception &e) {
    // dng_sdk throws C++ exceptions on errors
    // catch them here to prevent libFuzzer from crashing.
  }
}

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  char filename[256];
  sprintf(filename, "/tmp/libfuzzer.%d", getpid());
  FILE *fp = fopen(filename, "wb");
  if (!fp) {
    return 0;
  }
  fwrite(data, size, 1, fp);
  fclose(fp);

  // parse the data using a variable set of options for dng_host
  runFuzzerWithVariableHost(filename, dngVersion_None, true, false, false, true, true, true, 1, true);
  runFuzzerWithVariableHost(filename, dngVersion_1_0_0_0, true, true, false, true, true, true, 2, false);
  runFuzzerWithVariableHost(filename, dngVersion_1_1_0_0, true, true, false, true, true, true, 3, true);
  runFuzzerWithVariableHost(filename, dngVersion_1_2_0_0, true, true, false, true, true, true, 4, false);
  runFuzzerWithVariableHost(filename, dngVersion_1_3_0_0, true, true, false, true, true, true, 1, true);
  runFuzzerWithVariableHost(filename, dngVersion_1_4_0_0, true, true, false, true, true, true, 2, false);
  runFuzzerWithVariableHost(filename, dngVersion_1_4_0_0, false, false, true, true, true, true, 3, false);
  runFuzzerWithVariableHost(filename, dngVersion_1_4_0_0, false, false, true, true, true, true, 3, true);

  unlink(filename);
  return 0;
}
<commit_msg>dng_sdk: extend stage fuzzer (#6897)<commit_after>/* Copyright 2021 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

#include "dng_color_space.h"
#include "dng_date_time.h"
#include "dng_exceptions.h"
#include "dng_file_stream.h"
#include "dng_globals.h"
#include "dng_host.h"
#include "dng_ifd.h"
#include "dng_image_writer.h"
#include "dng_info.h"
#include "dng_linearization_info.h"
#include "dng_mosaic_info.h"
#include "dng_negative.h"
#include "dng_preview.h"
#include "dng_render.h"
#include "dng_simple_image.h"
#include "dng_tag_codes.h"
#include "dng_tag_types.h"
#include "dng_tag_values.h"
#include "dng_camera_profile.h"

// Run a set of the operations high-level operations on the dng_sdk
// This code is inspired by dng_validate.cpp and performs many of the same
// operations in a simplified manner.
void runFuzzerWithVariableHost(char *filename, uint32_t dng_version,
                               bool linear, bool preview, bool should_proxy,
                               bool KeepOriginalFile, bool NeedsMeta,
                               bool NeedsImage, int do_color_coding,
                               bool setFuji) {
  dng_host host;
  host.SetPreferredSize(0);
  host.SetMinimumSize(0);
  host.SetMaximumSize(0);
  host.SetSaveDNGVersion(dng_version);
  host.SetSaveLinearDNG(linear);
  host.SetForPreview(preview);
  host.ValidateSizes();
  host.SetKeepOriginalFile(KeepOriginalFile);
  host.SetNeedsMeta(NeedsMeta);
  host.SetNeedsImage(NeedsImage);

  AutoPtr<dng_camera_profile> customCameraProfile (new dng_camera_profile ());
  customCameraProfile->SetName("custom profile");

  AutoPtr<dng_negative> negative;
  try {
    dng_info info;
    dng_file_stream stream((const char *)filename);
    info.Parse(host, stream);
    info.PostParse(host);

    if (setFuji && info.fIFDCount > 0) {
      info.fIFD[0]->CanRead();
    }

    if (info.IsValidDNG()) {
      negative.Reset(host.Make_dng_negative());
      negative->AddProfile(customCameraProfile);

      if (do_color_coding == 1) {
        negative->SetDefaultCropSize((uint32)100,(uint32)100);
        negative->SetDefaultCropOrigin((uint32)50,(uint32)100);
      }
      else if (do_color_coding == 2) {
        negative->ResetDefaultUserCrop();
      }
      else {
        negative->SetDefaultUserCropT(dng_urational(0, 1));
      }

      negative->SetStage3Gain(2);
      negative->SetIsPreview(true);

      negative->Parse(host, stream, info);
      negative->PostParse(host, stream, info);
      negative->ReadStage1Image(host, stream, info);
      if (info.fMaskIndex != -1) {
        negative->ReadTransparencyMask(host, stream, info);
      }

      if (do_color_coding == 2) {
        const char fingerprint_raw[32] = { 'a', 'a','a','a','a','a',
          'a','a','a','a','a','a','a','a','a','a','a','a','a',
          'a','a','a','a','a','a','a','a','a','a','a','a','a'};

        dng_fingerprint fp;
        fp.FromUtf8HexString(fingerprint_raw);
        dng_camera_profile_id dcpi("random id", fp);
        negative->ProfileByID(dcpi, true);
      }
      negative->SynchronizeMetadata();
      negative->SetFourColorBayer();
      if (do_color_coding == 1) {
        negative->SetRGB();
      }
      else if (do_color_coding == 2) {
        negative->SetCMY();
      }
      else if (do_color_coding == 3) {
        negative->SetGMCY();
      }
      negative->BuildStage2Image(host);
      negative->BuildStage3Image(host, 1);

      if (should_proxy) {
        dng_image_writer writer;
        negative->ConvertToProxy(host, writer, 1);
      }

      if (negative->NeedFlattenTransparency(host)) {
        negative->FlattenTransparency(host);
      }

      // Write DNG
      dng_file_stream stream3("/tmp/randdng1", true);
      dng_image_writer writer3;
      dng_preview_list previewList;
      writer3.WriteDNG(host, stream3, *negative.Get(), &previewList,
                       dng_version, false);

      // Write TIFF
      uint32_t compression_arr[8] = { ccUncompressed, ccLZW, ccOldJPEG, ccJPEG,
        ccDeflate, ccPackBits, ccOldDeflate, ccLossyJPEG};
      for (int c = 0; c < 8; c++) {
        dng_file_stream stream2("/tmp/randpng", true);
        const dng_image &stage3 = *negative->Stage3Image();
        dng_image_writer writer2;
        writer2.WriteTIFF(host, stream2, stage3,
                          stage3.Planes() >= 3 ? piRGB : piBlackIsZero, compression_arr[c]);
      }

      // Create a renderer
      dng_render render(host, *negative);
      AutoPtr<dng_image> finalImage;
      finalImage.Reset(render.Render());

      // Use a random var to determine if we should clear profiles from disk.
      if (do_color_coding == 3) {
      negative->ClearProfiles(true, true);
      }
    }
  } catch (dng_exception &e) {
    // dng_sdk throws C++ exceptions on errors
    // catch them here to prevent libFuzzer from crashing.
  }
}

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  char filename[256];
  sprintf(filename, "/tmp/libfuzzer.%d", getpid());
  FILE *fp = fopen(filename, "wb");
  if (!fp) {
    return 0;
  }
  fwrite(data, size, 1, fp);
  fclose(fp);

  // parse the data using a variable set of options for dng_host
  runFuzzerWithVariableHost(filename, dngVersion_None, true, false, false, true, true, true, 1, true);
  runFuzzerWithVariableHost(filename, dngVersion_1_0_0_0, true, true, false, true, true, true, 2, false);
  runFuzzerWithVariableHost(filename, dngVersion_1_1_0_0, true, true, false, true, true, true, 3, true);
  runFuzzerWithVariableHost(filename, dngVersion_1_2_0_0, true, true, false, true, true, true, 4, false);
  runFuzzerWithVariableHost(filename, dngVersion_1_3_0_0, true, true, false, true, true, true, 1, true);
  runFuzzerWithVariableHost(filename, dngVersion_1_4_0_0, true, true, false, true, true, true, 2, false);
  runFuzzerWithVariableHost(filename, dngVersion_1_4_0_0, false, false, true, true, true, true, 3, false);
  runFuzzerWithVariableHost(filename, dngVersion_1_4_0_0, false, false, true, true, true, true, 3, true);

  unlink(filename);
  return 0;
}
<|endoftext|>


<commit_before><commit_msg>Bin obsolete conditional compilation<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: XMLEmptyContext.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-23 12:49:01 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef SC_XMLEMPTYCONTEXT_HXX
#define SC_XMLEMPTYCONTEXT_HXX

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif

class ScXMLImport;

class ScXMLEmptyContext : public SvXMLImportContext
{
    rtl::OUString   sPrintRanges;
    sal_Bool        bStartFormPage;

    const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); }
    ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); }

public:

    ScXMLEmptyContext( ScXMLImport& rImport, USHORT nPrfx,
                        const ::rtl::OUString& rLName);

    virtual ~ScXMLEmptyContext();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
                                     const ::rtl::OUString& rLocalName,
                                     const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList );

    virtual void EndElement();
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.116); FILE MERGED 2005/09/05 15:03:22 rt 1.2.116.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLEmptyContext.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 19:53:20 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef SC_XMLEMPTYCONTEXT_HXX
#define SC_XMLEMPTYCONTEXT_HXX

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif

class ScXMLImport;

class ScXMLEmptyContext : public SvXMLImportContext
{
    rtl::OUString   sPrintRanges;
    sal_Bool        bStartFormPage;

    const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); }
    ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); }

public:

    ScXMLEmptyContext( ScXMLImport& rImport, USHORT nPrfx,
                        const ::rtl::OUString& rLName);

    virtual ~ScXMLEmptyContext();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
                                     const ::rtl::OUString& rLocalName,
                                     const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList );

    virtual void EndElement();
};

#endif
<|endoftext|>


<commit_before>#include "vr_wrapper.h"
#include "texture.h"

#include <memory>

#include <Windows.h>
// uh, weird this is manual
#define OVR_OS_WIN32
#include "OVR_CAPI.h"
#include "OVR_CAPI_GL.h"

#include <GL/freeglut.h>

#include "glhelper.h"
#include "win32_platform.h"
#include "../common/fourmath.h"
#include "../common/camera.h"

namespace fd {

bool VRWrapper::s_Initialized = false;
bool VRWrapper::s_UsingVR = false;

// TODO: move this to like ovr_vr_wrapper.cpp or something
class OVRWrapper : public VRWrapper {
public:
  PlatformWindow* m_pWindow;
  ovrHmd m_HMD; // actually a pointer...

  Texture* m_eyeRenderTex[2];
  Texture* m_eyeDepthTex[2];

  ovrEyeRenderDesc m_eyeDesc[2];
  ovrPosef m_eyeRenderPose[2];

  const Mat4f* m_debugHeadPose;

  OVRWrapper() : m_HMD(NULL), m_debugHeadPose(NULL) {
    for(int e = 0; e < 2; e++) {
      m_eyeRenderTex[e] = NULL;
      m_eyeDepthTex[e] = NULL;
    }
  }
  ~OVRWrapper() {
    for(int e = 0; e < 2; e++) {
      delete m_eyeRenderTex[e];
      delete m_eyeDepthTex[e];
    }
    ovr_Shutdown();
  }

  bool Initialize(PlatformWindow* pWindow) {
    if (!ovr_Initialize()) {
      printf("Couldn't init ovr\n");
      return false;
    }

    m_pWindow = pWindow;

    int ovrIndex = ovrHmd_Detect();

    if (ovrIndex == 0 || (NULL == (m_HMD = ovrHmd_Create(0)))) {
      printf("Oculus device not found\n"
          "Trying to create debug oculus device...\n");
      // do we want to #ifdef DEBUG this?
      m_HMD = ovrHmd_CreateDebug(ovrHmd_DK2);
    }

    if (m_HMD == NULL) {
      printf("Oculus device not created:\n");
      return false;
    }
    WasGLErrorPlusPrint();

    const float pixelsPerDisplayPixel = 1.0f; //0.25f; // 1.0f;
    bool createSuccess = true;
    for (int e = 0; e < 2; e++) {
      ovrSizei recommendedFovTexSize = ovrHmd_GetFovTextureSize(
          m_HMD, (ovrEyeType)e, m_HMD->DefaultEyeFov[e],
          pixelsPerDisplayPixel);
      WasGLErrorPlusPrint();
      m_eyeRenderTex[e] = new Texture();
      createSuccess &= m_eyeRenderTex[e]->CreateRenderTarget(
          recommendedFovTexSize.w, recommendedFovTexSize.h);
      m_eyeDepthTex[e] = new Texture();
      createSuccess &= m_eyeDepthTex[e]->CreateDepthTarget(
          recommendedFovTexSize.w, recommendedFovTexSize.h);
    }
    if(!createSuccess) {
      printf("VR Render/depth target creation failed\n");
      return false;
    }

    ovrGLConfig config;
    config.OGL.Header.API = ovrRenderAPI_OpenGL;
    config.OGL.Header.BackBufferSize = m_HMD->Resolution;
    config.OGL.Header.Multisample = 0;
    config.OGL.Window = pWindow->m_hWnd;

    int ovrDistortionCaps = ovrDistortionCap_Vignette
        | ovrDistortionCap_Chromatic
        | ovrDistortionCap_TimeWarp
        | ovrDistortionCap_Overdrive;
    ovrHmd_ConfigureRendering(m_HMD, &config.Config, ovrDistortionCaps,
        m_HMD->DefaultEyeFov, m_eyeDesc);

    int ovrCaps = ovrHmdCap_DynamicPrediction | ovrHmdCap_LowPersistence;
    ovrHmd_SetEnabledCaps(m_HMD, ovrCaps);

    ovrHmd_AttachToWindow(m_HMD, pWindow->m_hWnd,
        NULL /*destRect*/, NULL /*srcRect*/);

    int trackingCaps = ovrTrackingCap_Orientation
        | ovrTrackingCap_MagYawCorrection
        | ovrTrackingCap_Position;
    ovrHmd_ConfigureTracking(m_HMD, trackingCaps, 0);

    ovrHmd_DismissHSWDisplay(m_HMD);

    s_Initialized = true;
    //s_UsingVR = true;

    return true;
  }

  virtual void StartFrame() {
    ovrHmd_BeginFrame(m_HMD, 0);

    ovrVector3f viewOffsets[2] = {
        m_eyeDesc[0].HmdToEyeViewOffset,
        m_eyeDesc[1].HmdToEyeViewOffset };

    ovrHmd_GetEyePoses(m_HMD, 0, viewOffsets, m_eyeRenderPose,
        NULL /*trackingState*/);
  }

  void StartEye(int eye) {
    glBindFramebuffer(GL_FRAMEBUFFER, m_eyeRenderTex[eye]->m_framebuffer_id);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
        GL_TEXTURE_2D, m_eyeRenderTex[eye]->m_texture_id, 0);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
        GL_TEXTURE_2D, m_eyeDepthTex[eye]->m_texture_id, 0);

    glViewport(0, 0,
        m_eyeRenderTex[eye]->m_width, m_eyeRenderTex[eye]->m_height);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  }

  virtual void SetDebugHeadOrientation(const Mat4f* matrix) {
    m_debugHeadPose = matrix;
  }

  void UpdateCameraRenderMatrix(int eye, Camera* pCamera) {

    const ovrVector3f& localPosOvr = m_eyeRenderPose[eye].Position;

    const float worldScale = 20.0f;

    const ovrQuatf& localQuatOvr = m_eyeRenderPose[eye].Orientation;
    Quatf localEyeQuat(localQuatOvr.w, localQuatOvr.x, localQuatOvr.y, localQuatOvr.z);
    Mat4f localEye;
    localEye.storeQuat3dRotation(localEyeQuat);

    if(m_debugHeadPose) {
      localEye = *m_debugHeadPose;
    }

    pCamera->_renderMatrix = localEye * pCamera->_cameraMatrix;
    //pCamera->_renderMatrix = pCamera->_cameraMatrix;

    Vec4f localOffset(localPosOvr.x, localPosOvr.z, localPosOvr.y, 0.0f);
    //Vec4f localOffset(localPosOvr.x, localPosOvr.y, -localPosOvr.z, 0.0f);
    localOffset *= worldScale;

    Vec4f eyeSpaceOffset = localEye.transform(localOffset);
    Vec4f worldSpaceOffset = pCamera->_cameraMatrix.transpose().transform(eyeSpaceOffset);

    Vec4f offset = pCamera->_cameraMatrix.transpose().transform(localOffset);
    //Vec4f offset = pCamera->_cameraMatrix.transpose().transform(localOffset);
    //offset = localEye.transform(offset);
    //Vec4f offset = pCamera->_renderMatrix.transform(localOffset);
    pCamera->_renderPos = pCamera->_cameraPos + offset;

    static int framecount = 0;
    if(eye == 0) {
      framecount++;
    }
    if(framecount > 100) {
      printf("Eye %d\n", eye);
      printf("Localoffset: \t");
      localOffset.printIt();
      printf("\neyespace: \t");
      eyeSpaceOffset.printIt();
      printf("\neyeworld: \t");
      worldSpaceOffset.printIt();
      printf("\nlocalworld: \t");
      offset.printIt();
      printf("\ncamerapos: \t");
      pCamera->_cameraPos.printIt();
      printf("\nlocalEyeMat: \n");
      localEye.printIt();
      printf("\ncamera: \n");
      pCamera->_cameraMatrix.printIt();
      printf("\nrender: \n");
      pCamera->_renderMatrix.printIt();
      printf("\n");
      if(eye != 0) {
        framecount = 0;
      }
    }

    ovrMatrix4f ovrProj = ovrMatrix4f_Projection(m_HMD->DefaultEyeFov[eye],
      0.2f /*zNear*/, 1000.0f /*zFar*/, true /*rightHanded*/);
    pCamera->_zProjectionMatrix.storeFromTransposedArray(&ovrProj.M[0][0]);
  }

  virtual void StartLeftEye(Camera* pCamera) {
    const int eye = 0;
    StartEye(eye);
    UpdateCameraRenderMatrix(eye, pCamera);
  }

  virtual void StartRightEye(Camera* pCamera) {
    const int eye = 1;
    StartEye(eye);
    UpdateCameraRenderMatrix(eye, pCamera);
  }

  virtual void FinishFrame() {
    ovrGLTexture eyeTex[2];
    for(int e = 0; e < 2; e++) {
      eyeTex[e].OGL.Header.API = ovrRenderAPI_OpenGL;
      eyeTex[e].OGL.Header.TextureSize.w = m_eyeRenderTex[e]->m_width;
      eyeTex[e].OGL.Header.TextureSize.h = m_eyeRenderTex[e]->m_height;
      eyeTex[e].OGL.Header.RenderViewport.Pos.x = 0;
      eyeTex[e].OGL.Header.RenderViewport.Pos.y = 0;
      eyeTex[e].OGL.Header.RenderViewport.Size = eyeTex[e].OGL.Header.TextureSize;
      eyeTex[e].OGL.TexId = m_eyeRenderTex[e]->m_texture_id;
    }
    //ovrTexture eyeTexStruct[2];
    //eyeTexStruct[0] = eyeTex[0].Texture;
    // uh this seems weird.... but parallel to sample so far
    ovrHmd_EndFrame(m_HMD, m_eyeRenderPose, &eyeTex[0].Texture);
  }

  virtual void SetIsUsingVR(bool usingVR) {
    if(!s_Initialized) return;
    if(s_UsingVR == usingVR) return;

    if(s_UsingVR) {
      s_UsingVR = false;
      glBindFramebuffer(GL_FRAMEBUFFER, 0);
      int restoreWidth;
      int restoreHeight;
      m_pWindow->GetWidthHeight(&restoreWidth, &restoreHeight);
      glViewport(0, 0, restoreWidth, restoreHeight);

    } else {
      s_UsingVR = true;
    }
  }

  virtual void ToggleFullscreen() {
    if(!m_HMD) return;
    //if(!(m_HMD->HmdCaps & ovrHmdCap_ExtendDesktop)) return;

    m_pWindow->ToggleFullscreenByMonitorName(m_HMD->DisplayDeviceName);
  }

  virtual void Recenter() {
    if(!m_HMD) return;
    ovrHmd_RecenterPose(m_HMD);
  }
};

VRWrapper* VRWrapper::CreateVR(PlatformWindow* pWindow) {
  std::unique_ptr<OVRWrapper> vrWrapper(new OVRWrapper);

  if(!vrWrapper->Initialize(pWindow)) {
    return NULL;
  }

  return vrWrapper.release();
}

}; // namespace fd<commit_msg>Added a simple eye offset mode, which always works. Position tracking is behaving badly, so added a fair bit of debug info to no avail.<commit_after>#include "vr_wrapper.h"
#include "texture.h"

#include <memory>

#include <Windows.h>
// uh, weird this is manual
#define OVR_OS_WIN32
#include "OVR_CAPI.h"
#include "OVR_CAPI_GL.h"

#include <GL/freeglut.h>

#include "glhelper.h"
#include "win32_platform.h"
#include "../common/fourmath.h"
#include "../common/camera.h"

namespace fd {

bool VRWrapper::s_Initialized = false;
bool VRWrapper::s_UsingVR = false;

// TODO: move this to like ovr_vr_wrapper.cpp or something
class OVRWrapper : public VRWrapper {
public:
  PlatformWindow* m_pWindow;
  ovrHmd m_HMD; // actually a pointer...

  Texture* m_eyeRenderTex[2];
  Texture* m_eyeDepthTex[2];

  ovrEyeRenderDesc m_eyeDesc[2];
  ovrPosef m_eyeRenderPose[2];

  const Mat4f* m_debugHeadPose;

  OVRWrapper() : m_HMD(NULL), m_debugHeadPose(NULL) {
    for(int e = 0; e < 2; e++) {
      m_eyeRenderTex[e] = NULL;
      m_eyeDepthTex[e] = NULL;
    }
  }
  ~OVRWrapper() {
    for(int e = 0; e < 2; e++) {
      delete m_eyeRenderTex[e];
      delete m_eyeDepthTex[e];
    }
    ovr_Shutdown();
  }

  bool Initialize(PlatformWindow* pWindow) {
    if (!ovr_Initialize()) {
      printf("Couldn't init ovr\n");
      return false;
    }

    m_pWindow = pWindow;

    int ovrIndex = ovrHmd_Detect();

    if (ovrIndex == 0 || (NULL == (m_HMD = ovrHmd_Create(0)))) {
      printf("Oculus device not found\n"
          "Trying to create debug oculus device...\n");
      // do we want to #ifdef DEBUG this?
      m_HMD = ovrHmd_CreateDebug(ovrHmd_DK2);
    }

    if (m_HMD == NULL) {
      printf("Oculus device not created:\n");
      return false;
    }
    WasGLErrorPlusPrint();

    const float pixelsPerDisplayPixel = 1.0f; //0.25f; // 1.0f;
    bool createSuccess = true;
    for (int e = 0; e < 2; e++) {
      ovrSizei recommendedFovTexSize = ovrHmd_GetFovTextureSize(
          m_HMD, (ovrEyeType)e, m_HMD->DefaultEyeFov[e],
          pixelsPerDisplayPixel);
      WasGLErrorPlusPrint();
      m_eyeRenderTex[e] = new Texture();
      createSuccess &= m_eyeRenderTex[e]->CreateRenderTarget(
          recommendedFovTexSize.w, recommendedFovTexSize.h);
      m_eyeDepthTex[e] = new Texture();
      createSuccess &= m_eyeDepthTex[e]->CreateDepthTarget(
          recommendedFovTexSize.w, recommendedFovTexSize.h);
    }
    if(!createSuccess) {
      printf("VR Render/depth target creation failed\n");
      return false;
    }

    ovrGLConfig config;
    config.OGL.Header.API = ovrRenderAPI_OpenGL;
    config.OGL.Header.BackBufferSize = m_HMD->Resolution;
    config.OGL.Header.Multisample = 0;
    config.OGL.Window = pWindow->m_hWnd;

    int ovrDistortionCaps = ovrDistortionCap_Vignette
        | ovrDistortionCap_Chromatic
        | ovrDistortionCap_TimeWarp
        | ovrDistortionCap_Overdrive;
    ovrHmd_ConfigureRendering(m_HMD, &config.Config, ovrDistortionCaps,
        m_HMD->DefaultEyeFov, m_eyeDesc);

    int ovrCaps = ovrHmdCap_DynamicPrediction | ovrHmdCap_LowPersistence;
    ovrHmd_SetEnabledCaps(m_HMD, ovrCaps);

    ovrHmd_AttachToWindow(m_HMD, pWindow->m_hWnd,
        NULL /*destRect*/, NULL /*srcRect*/);

    int trackingCaps = ovrTrackingCap_Orientation
        | ovrTrackingCap_MagYawCorrection
        | ovrTrackingCap_Position;
    ovrHmd_ConfigureTracking(m_HMD, trackingCaps, 0);

    ovrHmd_DismissHSWDisplay(m_HMD);

    s_Initialized = true;
    //s_UsingVR = true;

    return true;
  }

  virtual void StartFrame() {
    ovrHmd_BeginFrame(m_HMD, 0);

    ovrVector3f viewOffsets[2] = {
        m_eyeDesc[0].HmdToEyeViewOffset,
        m_eyeDesc[1].HmdToEyeViewOffset };

    ovrHmd_GetEyePoses(m_HMD, 0, viewOffsets, m_eyeRenderPose,
        NULL /*trackingState*/);
  }

  void StartEye(int eye) {
    glBindFramebuffer(GL_FRAMEBUFFER, m_eyeRenderTex[eye]->m_framebuffer_id);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
        GL_TEXTURE_2D, m_eyeRenderTex[eye]->m_texture_id, 0);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
        GL_TEXTURE_2D, m_eyeDepthTex[eye]->m_texture_id, 0);

    glViewport(0, 0,
        m_eyeRenderTex[eye]->m_width, m_eyeRenderTex[eye]->m_height);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  }

  virtual void SetDebugHeadOrientation(const Mat4f* matrix) {
    m_debugHeadPose = matrix;
  }

  void UpdateCameraRenderMatrix(int eye, Camera* pCamera) {

    const ovrQuatf& localQuatOvr = m_eyeRenderPose[eye].Orientation;
    Quatf localEyeQuat(localQuatOvr.w, localQuatOvr.x, localQuatOvr.y, localQuatOvr.z);
    Mat4f localEye;
    localEye.storeQuat3dRotation(localEyeQuat);

    if(m_debugHeadPose) {
      localEye = *m_debugHeadPose;
    }
    pCamera->_renderMatrix = localEye * pCamera->_cameraMatrix;

    const float worldScale = 20.0f;
    static bool simpleEyeOffset = true;
    if(simpleEyeOffset) {
      const ovrVector3f& localPosOvr = m_eyeDesc[eye].HmdToEyeViewOffset;
      Vec4f ovrEyePos(-localPosOvr.x, localPosOvr.y, localPosOvr.z, 0.0f);
      ovrEyePos *= worldScale;
      ovrEyePos = pCamera->_renderMatrix.transpose().transform(ovrEyePos);
      pCamera->_renderPos = pCamera->_cameraPos + ovrEyePos;
    } else {
      const ovrVector3f& localPosOvr = m_eyeRenderPose[eye].Position;
      static int transposer[3] = {0, 1, 2};
      static Vec4f sign(1.0f, 1.0f, 1.0f, 1.0f);
      Vec4f ovrEyePos(localPosOvr.x, localPosOvr.y, localPosOvr.z, 0.0f);
      ovrEyePos *= worldScale;
      Vec4f localOffset(
          ovrEyePos[transposer[0]] * sign.x,
          ovrEyePos[transposer[1]] * sign.y,
          ovrEyePos[transposer[2]] * sign.z,
          0.0f);

      static int doLocalTrans = 1; // 0
      Vec4f eyeSpaceOffset = localOffset;
      if(doLocalTrans > 0) {
        eyeSpaceOffset = localEye.transform(eyeSpaceOffset);
      } else if(doLocalTrans < 0) {
        eyeSpaceOffset = localEye.transpose().transform(eyeSpaceOffset);
      } else {
        // do nothing
      }

      static int doCameraTrans = -1;
      Vec4f worldSpaceOffset = eyeSpaceOffset;
      if(doCameraTrans > 0) {
        worldSpaceOffset = pCamera->_cameraMatrix.transform(worldSpaceOffset);
      } else if(doCameraTrans < 0) {
        worldSpaceOffset = pCamera->_cameraMatrix.transpose().transform(worldSpaceOffset);
      } else {
        // do nothing
      }

      static int doRenderTrans = 0; // -1;
      Vec4f renderOffset = worldSpaceOffset;
      if(doRenderTrans > 0) {
        renderOffset = pCamera->_renderMatrix.transform(renderOffset);
      } else if(doRenderTrans < 0) {
        renderOffset = pCamera->_renderMatrix.transpose().transform(renderOffset);
      } else {
        // do nothing
      }

      static int finalTransposer[4] = {0, 1, 2, 3};
      static Vec4f finalSign(1.0f, 1.0f, 1.0f, 1.0f);

      Vec4f finalOffset(
          renderOffset[finalTransposer[0]] * finalSign.x,
          renderOffset[finalTransposer[1]] * finalSign.y,
          renderOffset[finalTransposer[2]] * finalSign.z,
          renderOffset[finalTransposer[3]] * finalSign.w);

      const float derpEyes[2] = { -0.6f, 0.6f };
      Vec4f derpEye = (pCamera->_renderMatrix[Camera::RIGHT] * (derpEyes[eye]));

      pCamera->_renderPos = pCamera->_cameraPos + finalOffset;

      static int framecount = 0;
      if(eye == 0) {
        framecount++;
      }
      if(framecount > 100) {
        printf("Eye %d\n", eye);
        printf("pristine ovr: \t");   ovrEyePos.printIt();
        printf("\neyespace: \t"); eyeSpaceOffset.printIt();
        printf("\neyecamera: \t"); worldSpaceOffset.printIt();
        printf("\neyerender: \t"); renderOffset.printIt();
        printf("\nfinal: \t"); finalOffset.printIt();
        printf("\nderp: \t"); derpEye.printIt();
        printf("\ncamerapos: \t"); pCamera->_cameraPos.printIt();
        printf("\nlocalEyeMat: \n"); localEye.printIt();
        printf("\ncamera: \n"); pCamera->_cameraMatrix.printIt();
        printf("\nrender: \n"); pCamera->_renderMatrix.printIt();
        printf("\n");
        if(eye != 0) {
          framecount = 0;
        }
      }
    }

    ovrMatrix4f ovrProj = ovrMatrix4f_Projection(m_HMD->DefaultEyeFov[eye],
      0.2f /*zNear*/, 1000.0f /*zFar*/, true /*rightHanded*/);
    pCamera->_zProjectionMatrix.storeFromTransposedArray(&ovrProj.M[0][0]);
  }

  virtual void StartLeftEye(Camera* pCamera) {
    const int eye = 0;
    StartEye(eye);
    UpdateCameraRenderMatrix(eye, pCamera);
  }

  virtual void StartRightEye(Camera* pCamera) {
    const int eye = 1;
    StartEye(eye);
    UpdateCameraRenderMatrix(eye, pCamera);
  }

  virtual void FinishFrame() {
    ovrGLTexture eyeTex[2];
    for(int e = 0; e < 2; e++) {
      eyeTex[e].OGL.Header.API = ovrRenderAPI_OpenGL;
      eyeTex[e].OGL.Header.TextureSize.w = m_eyeRenderTex[e]->m_width;
      eyeTex[e].OGL.Header.TextureSize.h = m_eyeRenderTex[e]->m_height;
      eyeTex[e].OGL.Header.RenderViewport.Pos.x = 0;
      eyeTex[e].OGL.Header.RenderViewport.Pos.y = 0;
      eyeTex[e].OGL.Header.RenderViewport.Size = eyeTex[e].OGL.Header.TextureSize;
      eyeTex[e].OGL.TexId = m_eyeRenderTex[e]->m_texture_id;
    }
    //ovrTexture eyeTexStruct[2];
    //eyeTexStruct[0] = eyeTex[0].Texture;
    // uh this seems weird.... but parallel to sample so far
    ovrHmd_EndFrame(m_HMD, m_eyeRenderPose, &eyeTex[0].Texture);
  }

  virtual void SetIsUsingVR(bool usingVR) {
    if(!s_Initialized) return;
    if(s_UsingVR == usingVR) return;

    if(s_UsingVR) {
      s_UsingVR = false;
      glBindFramebuffer(GL_FRAMEBUFFER, 0);
      int restoreWidth;
      int restoreHeight;
      m_pWindow->GetWidthHeight(&restoreWidth, &restoreHeight);
      glViewport(0, 0, restoreWidth, restoreHeight);

    } else {
      s_UsingVR = true;
    }
  }

  virtual void ToggleFullscreen() {
    if(!m_HMD) return;
    //if(!(m_HMD->HmdCaps & ovrHmdCap_ExtendDesktop)) return;

    m_pWindow->ToggleFullscreenByMonitorName(m_HMD->DisplayDeviceName);
  }

  virtual void Recenter() {
    if(!m_HMD) return;
    ovrHmd_RecenterPose(m_HMD);
  }
};

VRWrapper* VRWrapper::CreateVR(PlatformWindow* pWindow) {
  std::unique_ptr<OVRWrapper> vrWrapper(new OVRWrapper);

  if(!vrWrapper->Initialize(pWindow)) {
    return NULL;
  }

  return vrWrapper.release();
}

}; // namespace fd<|endoftext|>


<commit_before>#define BOOST_TEST_MODULE direct_Threaded_SWORD
#include <metaSMT/DirectSolver_Context.hpp>
#include <metaSMT/UnpackFuture_Context.hpp>
#include <metaSMT/Threaded_Context.hpp>
#include <metaSMT/backend/SWORD_Backend.hpp>
#include <metaSMT/API/Stack.hpp>
#include <metaSMT/API/Comment.hpp>
#include <metaSMT/API/Group.hpp>
#include <metaSMT/Instantiate.hpp>

using namespace metaSMT::solver;
using namespace metaSMT;
struct Solver_Fixture {
  typedef DirectSolver_Context<  UnpackFuture_Context< Stack< SWORD_Backend > >  > ContextType1;
  typedef Threaded_Context< ContextType1, ContextType1 > ContextType;
  ContextType ctx ;
};

namespace std {
  //std::ostream & operator<< (std::ostream & o, Solver_Fixture::ContextType::result_type const & r) {
  //  return (o << "(Threaded result_type " << &r << ")");
  //}
  template <typename T>
  std::ostream & operator<< (std::ostream & o, boost::shared_future<T> const & f) {
    return (o << "(shared_future@" << &f << ")");
  }
} /* std */

#include "test_solver.cpp"
#include "test_QF_BV.cpp"
//#include "test_Array.cpp"
//#include "test_group.cpp"
#include "test_stack.cpp"
#include "test_unsat.cpp"
#include "test_fmi.cpp"
//#include "test_cardinality.cpp"
#include "test_lazy.cpp"
//#include "test_annotate.cpp"
<commit_msg>removed unused header from direct_Threaded_SWORD test<commit_after>#define BOOST_TEST_MODULE direct_Threaded_SWORD
#include <metaSMT/DirectSolver_Context.hpp>
#include <metaSMT/UnpackFuture_Context.hpp>
#include <metaSMT/Threaded_Context.hpp>
#include <metaSMT/backend/SWORD_Backend.hpp>
#include <metaSMT/API/Stack.hpp>
#include <metaSMT/API/Comment.hpp>
#include <metaSMT/API/Group.hpp>

using namespace metaSMT::solver;
using namespace metaSMT;
struct Solver_Fixture {
  typedef DirectSolver_Context<  UnpackFuture_Context< Stack< SWORD_Backend > >  > ContextType1;
  typedef Threaded_Context< ContextType1, ContextType1 > ContextType;
  ContextType ctx ;
};

namespace std {
  //std::ostream & operator<< (std::ostream & o, Solver_Fixture::ContextType::result_type const & r) {
  //  return (o << "(Threaded result_type " << &r << ")");
  //}
  template <typename T>
  std::ostream & operator<< (std::ostream & o, boost::shared_future<T> const & f) {
    return (o << "(shared_future@" << &f << ")");
  }
} /* std */

#include "test_solver.cpp"
#include "test_QF_BV.cpp"
//#include "test_Array.cpp"
//#include "test_group.cpp"
#include "test_stack.cpp"
#include "test_unsat.cpp"
#include "test_fmi.cpp"
//#include "test_cardinality.cpp"
#include "test_lazy.cpp"
//#include "test_annotate.cpp"
<|endoftext|>


<commit_before>/**
 * Position Engine provides dead reckoning engine to obtain position
 * information based on fusion of different kind of sensors.
 *
 * Copyright 2017 Pavlo Kleymonov <pavlo.kleymonov@gmail.com>
 *
 * Distributed under the OSI-approved BSD License (the "License");
 * see accompanying file LICENSE.txt for details.
 *
 * This software is distributed WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the License for more information.
 */

/**
 * Unit test of the PECalibrationTest class.
 *
 * Code under test:
 *
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "mock_PENormalisation.h"
#include "PECalibrationEx.h"

using ::testing::_;
using ::testing::Eq;
using ::testing::ByRef;

class PECalibrationExTest : public ::testing::Test
{
public:
   virtual void SetUp()
   {}
   virtual void TearDown()
   {}
};

/**
* tests 6 sensors 2 valid reference
*/
TEST_F(PECalibrationExTest, _6_sensors_2_valid_ref_test)
{
   PE::Mock_normalisation mock;

   PE::calibration_ex calib(mock,10); //10 meters accuracy

   calib.add_sensor(1000); //has to be ignored before first valid ref
   calib.add_sensor(1000); //has to be ignored before first valid ref

   calib.add_reference(100,5); //added 100 meters with accuracy +/-5meters
   calib.add_sensor(500);
   calib.add_sensor(500);
   calib.add_reference(100,5); //added 100 meters with accuracy +/-5meters
   EXPECT_CALL(mock,add_sensor(_));

   calib.add_sensor(500);
   calib.add_sensor(500);
}

int main(int argc, char *argv[])
{
   ::testing::InitGoogleTest(&argc, argv);
   return RUN_ALL_TESTS();
}

<commit_msg>added simple test for class calibration_ex<commit_after>/**
 * Position Engine provides dead reckoning engine to obtain position
 * information based on fusion of different kind of sensors.
 *
 * Copyright 2017 Pavlo Kleymonov <pavlo.kleymonov@gmail.com>
 *
 * Distributed under the OSI-approved BSD License (the "License");
 * see accompanying file LICENSE.txt for details.
 *
 * This software is distributed WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the License for more information.
 */

/**
 * Unit test of the PECalibrationTest class.
 *
 * Code under test:
 *
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "mock_PENormalisation.h"
#include "PECalibrationEx.h"

using ::testing::_;
using ::testing::Eq;
using ::testing::ByRef;

class PECalibrationExTest : public ::testing::Test
{
public:
   virtual void SetUp()
   {}
   virtual void TearDown()
   {}
};

/**
* tests 6 sensors 2 valid reference
*/
TEST_F(PECalibrationExTest, _6_sensors_2_valid_ref_test)
{
   PE::normalisation norm;
   PE::calibration_ex calib(norm,10); //10 meters accuracy

   calib.add_sensor(1000); //has to be ignored before first valid ref
   calib.add_sensor(1000); //has to be ignored before first valid ref

   calib.add_reference(100,5); //added 100 meters with accuracy +/-5meters
   calib.add_sensor(500);
   calib.add_sensor(500);
   calib.add_reference(100,5); //added 100 meters with accuracy +/-5meters
   calib.add_sensor(500);
   calib.add_sensor(500);
   calib.add_reference(100,5); //added 100 meters with accuracy +/-5meters

   EXPECT_EQ(10, calib.get_scale());
   EXPECT_EQ(0, calib.get_accuracy());
   EXPECT_EQ(100, calib.get_calibration());
   calib.add_sensor(500);
   calib.add_sensor(500);

/*
   PE::Mock_normalisation mock;

   PE::calibration_ex calib(mock,10); //10 meters accuracy

   calib.add_sensor(1000); //has to be ignored before first valid ref
   calib.add_sensor(1000); //has to be ignored before first valid ref

   calib.add_reference(100,5); //added 100 meters with accuracy +/-5meters
   calib.add_sensor(500);
   calib.add_sensor(500);
   calib.add_reference(100,5); //added 100 meters with accuracy +/-5meters
   EXPECT_CALL(mock,add_sensor(_));

   calib.add_sensor(500);
   calib.add_sensor(500);
   */
}

int main(int argc, char *argv[])
{
   ::testing::InitGoogleTest(&argc, argv);
   return RUN_ALL_TESTS();
}

<|endoftext|>


<commit_before>
#include "Module.h"
#include "ModuleWindow.h"
#include "ModuleRender.h"
#include "ModuleTextures.h"
#include "ModuleFonts.h"
#include "ModuleInput.h"
#include "ModuleAudio.h"
#include "ModulePlayer.h"
#include "ModulePhysics.h"
#include "ModuleSceneIntro.h"
#include "ModuleSceneGameOver.h"

#include "Application.h"

Application::Application()
{
	renderer = new ModuleRender(this);
	window = new ModuleWindow(this);
	textures = new ModuleTextures(this);
	fonts = new ModuleFonts(this);
	input = new ModuleInput(this);
	audio = new ModuleAudio(this, true);
	player = new ModulePlayer(this);
	scene_intro = new ModuleSceneIntro(this);
	physics = new ModulePhysics(this);
	scene_game_over = new ModuleSceneGameOver(this);

	// The order of calls is very important!
	// Modules will Init() Start() and Update in this order
	// They will CleanUp() in reverse order

	// Main Modules
	AddModule(window);
	AddModule(physics);
	AddModule(renderer);
	AddModule(textures);
	AddModule(input);
	AddModule(audio);

	//Fonts
	AddModule(fonts);
	// Scenes
	AddModule(scene_intro);
	AddModule(scene_game_over);

	// Player
	AddModule(player);
}

Application::~Application()
{
	p2List_item<Module*>* item = list_modules.getLast();

	while(item != NULL)
	{
		delete item->data;
		item = item->prev;
	}
}

bool Application::Init()
{
	bool ret = true;

	// Call Init() in all modules
	p2List_item<Module*>* item = list_modules.getFirst();

	while(item != NULL && ret == true)
	{
		ret = item->data->Init();
		item = item->next;
	}

	// After all Init calls we call Start() in all modules
	LOG("Application Start --------------");
	item = list_modules.getFirst();

	while(item != NULL && ret == true)
	{
		if(item->data->IsEnabled())
			ret = item->data->Start();
		item = item->next;
	}

	return ret;
}

// Call PreUpdate, Update and PostUpdate on all modules
update_status Application::Update()
{
	update_status ret = UPDATE_CONTINUE;
	p2List_item<Module*>* item = list_modules.getFirst();

	while(item != NULL && ret == UPDATE_CONTINUE)
	{
		if(item->data->IsEnabled())
			ret = item->data->PreUpdate();
		item = item->next;
	}

	item = list_modules.getFirst();

	while(item != NULL && ret == UPDATE_CONTINUE)
	{
		if(item->data->IsEnabled())
  			ret = item->data->Update();
		item = item->next;
	}

	item = list_modules.getFirst();

	while(item != NULL && ret == UPDATE_CONTINUE)
	{
		if(item->data->IsEnabled())
			ret = item->data->PostUpdate();
		item = item->next;
	}

	return ret;
}

bool Application::CleanUp()
{
	bool ret = true;
	p2List_item<Module*>* item = list_modules.getLast();

	while(item != NULL && ret == true)
	{
		ret = item->data->CleanUp();
		item = item->prev;
	}
	return ret;
}

void Application::AddModule(Module* mod)
{
	list_modules.add(mod);
}<commit_msg>Scene game over disable start<commit_after>
#include "Module.h"
#include "ModuleWindow.h"
#include "ModuleRender.h"
#include "ModuleTextures.h"
#include "ModuleFonts.h"
#include "ModuleInput.h"
#include "ModuleAudio.h"
#include "ModulePlayer.h"
#include "ModulePhysics.h"
#include "ModuleSceneIntro.h"
#include "ModuleSceneGameOver.h"

#include "Application.h"

Application::Application()
{
	renderer = new ModuleRender(this);
	window = new ModuleWindow(this);
	textures = new ModuleTextures(this);
	fonts = new ModuleFonts(this);
	input = new ModuleInput(this);
	audio = new ModuleAudio(this, true);
	player = new ModulePlayer(this);
	scene_intro = new ModuleSceneIntro(this);
	physics = new ModulePhysics(this);
	scene_game_over = new ModuleSceneGameOver(this);

	// The order of calls is very important!
	// Modules will Init() Start() and Update in this order
	// They will CleanUp() in reverse order

	// Main Modules
	AddModule(window);
	AddModule(physics);
	AddModule(renderer);
	AddModule(textures);
	AddModule(input);
	AddModule(audio);

	//Fonts
	AddModule(fonts);
	// Scenes
	AddModule(scene_intro);
	AddModule(scene_game_over);

	// Player
	AddModule(player);
	scene_game_over->Disable();
}

Application::~Application()
{
	p2List_item<Module*>* item = list_modules.getLast();

	while(item != NULL)
	{
		delete item->data;
		item = item->prev;
	}
}

bool Application::Init()
{
	bool ret = true;

	// Call Init() in all modules
	p2List_item<Module*>* item = list_modules.getFirst();

	while(item != NULL && ret == true)
	{
		ret = item->data->Init();
		item = item->next;
	}

	// After all Init calls we call Start() in all modules
	LOG("Application Start --------------");
	item = list_modules.getFirst();

	while(item != NULL && ret == true)
	{
		if(item->data->IsEnabled())
			ret = item->data->Start();
		item = item->next;
	}

	return ret;
}

// Call PreUpdate, Update and PostUpdate on all modules
update_status Application::Update()
{
	update_status ret = UPDATE_CONTINUE;
	p2List_item<Module*>* item = list_modules.getFirst();

	while(item != NULL && ret == UPDATE_CONTINUE)
	{
		if(item->data->IsEnabled())
			ret = item->data->PreUpdate();
		item = item->next;
	}

	item = list_modules.getFirst();

	while(item != NULL && ret == UPDATE_CONTINUE)
	{
		if(item->data->IsEnabled())
  			ret = item->data->Update();
		item = item->next;
	}

	item = list_modules.getFirst();

	while(item != NULL && ret == UPDATE_CONTINUE)
	{
		if(item->data->IsEnabled())
			ret = item->data->PostUpdate();
		item = item->next;
	}

	return ret;
}

bool Application::CleanUp()
{
	bool ret = true;
	p2List_item<Module*>* item = list_modules.getLast();

	while(item != NULL && ret == true)
	{
		ret = item->data->CleanUp();
		item = item->prev;
	}
	return ret;
}

void Application::AddModule(Module* mod)
{
	list_modules.add(mod);
}<|endoftext|>


<commit_before>#include <iostream>

#define MAX_PIECE_NUM 64

using namespace std;

typedef struct {
  unsigned long curr_grp;
  unsigned long visited;

  int curr_sum;
  int rest_sum;
} Record;

int pieces[MAX_PIECE_NUM];
int piece_num;
int piece_len_sum;
unsigned long all_visited;

void solve();
void solve_helper(int tgt_value, int curr_sum, int rest_sum,
    int idx, int curr_grp, int visited, bool& res);

void solve_helper(int tgt_value, Record& record, int idx, bool& res);

void print();
unsigned long get_all_visited(int piece_num);

int main() {
  int n;

  int res;
  while (cin >> n && n != 0) {
    piece_num = n;
    piece_len_sum = 0;

    all_visited = get_all_visited(piece_num);

    for (int i = 0; i < piece_num; i++) {
      cin >> n;
      pieces[i] = n;
      piece_len_sum += n;
    }

    solve();

    cout << res << endl;
    //print();
  }
}

unsigned long get_all_visited(int piece_num) {
  unsigned long res = 0;

  for (int i = 0; i < piece_num; i++)
    res = res || (1 << i);

  return res;
}

void solve() {
  sort(pieces, pieces + piece_num);

  int tgt_value = pieces[piece_num - 1];
  bool res = false;
  for (int tgt_value = pieces[piece_num - 1]; tgt_value < piece_len_sum;
      tgt_value++) {

    if (piece_len_sum % tgt_value)
      continue;

    solve_helper(tgt_value, 0, piece_len_sum, 0, 0, 0, res);
    if (res) {
      cout << tgt_value << endl;
      break;
    }
  }

  return;
}

void solve_helper(int tgt_value, Record& record, int idx, bool& res) {
  // find a legal solution
  if (record.rest_sum == 0 && record.visited == all_visited) {
    res = true;
    return;
  }

  // find a legal subset, whose sum equals to the target value
  if (record.curr_sum == tgt_value) {
    record.rest_sum -= tgt_value;

    // merge the subset into the visited set
    record.visited = (record.visited | record.curr_grp);

    // start to search another possible subset
    solve_helper(tgt_value, record, 0, res);
  }
}

void solve_helper(int tgt_value, int curr_sum, int rest_sum,
    int idx, int curr_grp, int visited, bool& res) {

  if (rest_sum == 0 && visited == all_visited) {
    res = true;
    return;
  }

  if (idx >= piece_num) {
    return;
  }

  return;
}

void print() {
  for (int i = 0; i < piece_num; i++)
    cout << pieces[i] << " ";

  cout << endl;
}
<commit_msg>p1011 solving<commit_after>#include <iostream>

#define MAX_PIECE_NUM 64

using namespace std;

typedef struct {
  unsigned long curr_grp;
  unsigned long visited;

  int curr_sum;
  int rest_sum;
} Record;

int pieces[MAX_PIECE_NUM];
int piece_num;
int piece_len_sum;
unsigned long all_visited;

void solve();
void solve_helper(int tgt_value, int curr_sum, int rest_sum,
    int idx, int curr_grp, int visited, bool& res);

void solve_helper(int tgt_value, Record& record, int idx, bool& res);

void print();
unsigned long get_all_visited(int piece_num);

int main() {
  int n;

  int res;
  while (cin >> n && n != 0) {
    piece_num = n;
    piece_len_sum = 0;

    all_visited = get_all_visited(piece_num);

    for (int i = 0; i < piece_num; i++) {
      cin >> n;
      pieces[i] = n;
      piece_len_sum += n;
    }

    solve();

    cout << res << endl;
    //print();
  }
}

unsigned long get_all_visited(int piece_num) {
  unsigned long res = 0;

  for (int i = 0; i < piece_num; i++)
    res = res || (1 << i);

  return res;
}

void solve() {
  sort(pieces, pieces + piece_num);

  int tgt_value = pieces[piece_num - 1];
  bool res = false;
  for (int tgt_value = pieces[piece_num - 1]; tgt_value < piece_len_sum;
      tgt_value++) {

    if (piece_len_sum % tgt_value)
      continue;

    solve_helper(tgt_value, 0, piece_len_sum, 0, 0, 0, res);
    if (res) {
      cout << tgt_value << endl;
      break;
    }
  }

  return;
}

void solve_helper(int tgt_value, Record& record, int idx, bool& res) {
  // find a legal solution
  if (record.rest_sum == 0 && record.visited == all_visited) {
    res = true;
    return;
  }

  // find a legal subset, whose sum equals to the target value
  if (record.curr_sum == tgt_value) {
    record.rest_sum -= tgt_value;
    record.curr_sum = 0;

    // merge the subset into the visited set
    record.visited = (record.visited | record.curr_grp);

    // start to search another possible subset from index#0
    solve_helper(tgt_value, record, 0, res);

    return;
  }

  // idx exceeds piece_num, while the sum of current group is not equal to
  // the target value
  // 1) ? then start new search, reseting the current group
  // 2) return immediately
  if (idx >= piece_num) {
    return;
  }

  // don't select the piece to which the idx points
  solve_helper(tgt_value, record, idx + 1, res);

  // select the piece indexed by idx
}

void solve_helper(int tgt_value, int curr_sum, int rest_sum,
    int idx, int curr_grp, int visited, bool& res) {

  if (rest_sum == 0 && visited == all_visited) {
    res = true;
    return;
  }

  if (idx >= piece_num) {
    return;
  }

  return;
}

void print() {
  for (int i = 0; i < piece_num; i++)
    cout << pieces[i] << " ";

  cout << endl;
}
<|endoftext|>


<commit_before><commit_msg>don't try to use Inf for axes calculation fdo#43703<commit_after><|endoftext|>


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

#include "chrome/browser/autofill/data_driven_test.h"

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/common/chrome_paths.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

// Reads |file| into |content|, and converts Windows line-endings to Unix ones.
// Returns true on success.
bool ReadFile(const FilePath& file, std::string* content) {
  if (!file_util::ReadFileToString(file, content))
    return false;

  ReplaceSubstringsAfterOffset(content, 0, "\r\n", "\n");
  return true;
}

// Write |content| to |file|. Returns true on success.
bool WriteFile(const FilePath& file, const std::string& content) {
  int write_size = file_util::WriteFile(file, content.c_str(),
                                        content.length());
  return write_size == static_cast<int>(content.length());
}

}  // namespace

void DataDrivenTest::RunDataDrivenTest(
    const FilePath& input_directory,
    const FilePath& output_directory,
    const FilePath::StringType& file_name_pattern) {
  file_util::FileEnumerator input_files(input_directory,
                                        false,
                                        file_util::FileEnumerator::FILES,
                                        file_name_pattern);

  for (FilePath input_file = input_files.Next();
       !input_file.empty();
       input_file = input_files.Next()) {
    std::string input;
    ASSERT_TRUE(ReadFile(input_file, &input));

    std::string output;
    GenerateResults(input, &output);

    FilePath output_file = output_directory.Append(
        input_file.BaseName().StripTrailingSeparators().ReplaceExtension(
            FILE_PATH_LITERAL(".out")));

    std::string output_file_contents;
    if (ReadFile(output_file, &output_file_contents))
      EXPECT_EQ(output_file_contents, output);
    else
      ASSERT_TRUE(WriteFile(output_file, output));
  }
}

FilePath DataDrivenTest::GetInputDirectory(
    const FilePath::StringType& test_name) {
  FilePath test_data_dir_;
  PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_);
  test_data_dir_ = test_data_dir_.AppendASCII("autofill")
                                 .Append(test_name)
                                 .AppendASCII("input");
  return test_data_dir_;
}

FilePath DataDrivenTest::GetOutputDirectory(
    const FilePath::StringType& test_name) {
  FilePath test_data_dir_;
  PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_);
  test_data_dir_ = test_data_dir_.AppendASCII("autofill")
                                 .Append(test_name)
                                 .AppendASCII("output");
  return test_data_dir_;
}

DataDrivenTest::DataDrivenTest() {
}

DataDrivenTest::~DataDrivenTest() {
}
<commit_msg>Add SCOPED_TRACE to data driven tests.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/autofill/data_driven_test.h"

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/common/chrome_paths.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

// Reads |file| into |content|, and converts Windows line-endings to Unix ones.
// Returns true on success.
bool ReadFile(const FilePath& file, std::string* content) {
  if (!file_util::ReadFileToString(file, content))
    return false;

  ReplaceSubstringsAfterOffset(content, 0, "\r\n", "\n");
  return true;
}

// Write |content| to |file|. Returns true on success.
bool WriteFile(const FilePath& file, const std::string& content) {
  int write_size = file_util::WriteFile(file, content.c_str(),
                                        content.length());
  return write_size == static_cast<int>(content.length());
}

}  // namespace

void DataDrivenTest::RunDataDrivenTest(
    const FilePath& input_directory,
    const FilePath& output_directory,
    const FilePath::StringType& file_name_pattern) {
  file_util::FileEnumerator input_files(input_directory,
                                        false,
                                        file_util::FileEnumerator::FILES,
                                        file_name_pattern);

  for (FilePath input_file = input_files.Next();
       !input_file.empty();
       input_file = input_files.Next()) {
    SCOPED_TRACE(input_file.BaseName().value());

    std::string input;
    ASSERT_TRUE(ReadFile(input_file, &input));

    std::string output;
    GenerateResults(input, &output);

    FilePath output_file = output_directory.Append(
        input_file.BaseName().StripTrailingSeparators().ReplaceExtension(
            FILE_PATH_LITERAL(".out")));

    std::string output_file_contents;
    if (ReadFile(output_file, &output_file_contents))
      EXPECT_EQ(output_file_contents, output);
    else
      ASSERT_TRUE(WriteFile(output_file, output));
  }
}

FilePath DataDrivenTest::GetInputDirectory(
    const FilePath::StringType& test_name) {
  FilePath test_data_dir_;
  PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_);
  test_data_dir_ = test_data_dir_.AppendASCII("autofill")
                                 .Append(test_name)
                                 .AppendASCII("input");
  return test_data_dir_;
}

FilePath DataDrivenTest::GetOutputDirectory(
    const FilePath::StringType& test_name) {
  FilePath test_data_dir_;
  PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_);
  test_data_dir_ = test_data_dir_.AppendASCII("autofill")
                                 .Append(test_name)
                                 .AppendASCII("output");
  return test_data_dir_;
}

DataDrivenTest::DataDrivenTest() {
}

DataDrivenTest::~DataDrivenTest() {
}
<|endoftext|>


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

#include "chrome/browser/chrome_browser_main_posix.h"

#include <errno.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <sys/resource.h>
#include <unistd.h>

#include <string>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/eintr_wrapper.h"
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/common/chrome_switches.h"
#include "content/public/browser/browser_thread.h"

#if defined(TOOLKIT_USES_GTK) && !defined(OS_CHROMEOS)
#include "chrome/browser/printing/print_dialog_gtk.h"
#endif

using content::BrowserThread;

namespace {

// See comment in |PreEarlyInitialization()|, where sigaction is called.
void SIGCHLDHandler(int signal) {
}

int g_shutdown_pipe_write_fd = -1;
int g_shutdown_pipe_read_fd = -1;

// Common code between SIG{HUP, INT, TERM}Handler.
void GracefulShutdownHandler(int signal) {
  // Reinstall the default handler.  We had one shot at graceful shutdown.
  struct sigaction action;
  memset(&action, 0, sizeof(action));
  action.sa_handler = SIG_DFL;
  RAW_CHECK(sigaction(signal, &action, NULL) == 0);

  RAW_CHECK(g_shutdown_pipe_write_fd != -1);
  RAW_CHECK(g_shutdown_pipe_read_fd != -1);
  size_t bytes_written = 0;
  do {
    int rv = HANDLE_EINTR(
        write(g_shutdown_pipe_write_fd,
              reinterpret_cast<const char*>(&signal) + bytes_written,
              sizeof(signal) - bytes_written));
    RAW_CHECK(rv >= 0);
    bytes_written += rv;
  } while (bytes_written < sizeof(signal));
}

// See comment in |PostMainMessageLoopStart()|, where sigaction is called.
void SIGHUPHandler(int signal) {
  RAW_CHECK(signal == SIGHUP);
  GracefulShutdownHandler(signal);
}

// See comment in |PostMainMessageLoopStart()|, where sigaction is called.
void SIGINTHandler(int signal) {
  RAW_CHECK(signal == SIGINT);
  GracefulShutdownHandler(signal);
}

// See comment in |PostMainMessageLoopStart()|, where sigaction is called.
void SIGTERMHandler(int signal) {
  RAW_CHECK(signal == SIGTERM);
  GracefulShutdownHandler(signal);
}

class ShutdownDetector : public base::PlatformThread::Delegate {
 public:
  explicit ShutdownDetector(int shutdown_fd);

  virtual void ThreadMain();

 private:
  const int shutdown_fd_;

  DISALLOW_COPY_AND_ASSIGN(ShutdownDetector);
};

ShutdownDetector::ShutdownDetector(int shutdown_fd)
    : shutdown_fd_(shutdown_fd) {
  CHECK_NE(shutdown_fd_, -1);
}

// These functions are used to help us diagnose crash dumps that happen
// during the shutdown process.
NOINLINE void ShutdownFDReadError() {
  // Ensure function isn't optimized away.
  asm("");
  sleep(UINT_MAX);
}

NOINLINE void ShutdownFDClosedError() {
  // Ensure function isn't optimized away.
  asm("");
  sleep(UINT_MAX);
}

NOINLINE void ExitPosted() {
  // Ensure function isn't optimized away.
  asm("");
  sleep(UINT_MAX);
}

void ShutdownDetector::ThreadMain() {
  base::PlatformThread::SetName("CrShutdownDetector");

  int signal;
  size_t bytes_read = 0;
  ssize_t ret;
  do {
    ret = HANDLE_EINTR(
        read(shutdown_fd_,
             reinterpret_cast<char*>(&signal) + bytes_read,
             sizeof(signal) - bytes_read));
    if (ret < 0) {
      NOTREACHED() << "Unexpected error: " << strerror(errno);
      ShutdownFDReadError();
      break;
    } else if (ret == 0) {
      NOTREACHED() << "Unexpected closure of shutdown pipe.";
      ShutdownFDClosedError();
      break;
    }
    bytes_read += ret;
  } while (bytes_read < sizeof(signal));
  VLOG(1) << "Handling shutdown for signal " << signal << ".";
#if defined(OS_CHROMEOS)
  // On ChromeOS, exiting on signal should be always clean.
  base::Closure task = base::Bind(&BrowserList::ExitCleanly);
#else
  base::Closure task = base::Bind(&BrowserList::AttemptExit);
#endif

  if (!BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, task)) {
    // Without a UI thread to post the exit task to, there aren't many
    // options.  Raise the signal again.  The default handler will pick it up
    // and cause an ungraceful exit.
    RAW_LOG(WARNING, "No UI thread, exiting ungracefully.");
    kill(getpid(), signal);

    // The signal may be handled on another thread.  Give that a chance to
    // happen.
    sleep(3);

    // We really should be dead by now.  For whatever reason, we're not. Exit
    // immediately, with the exit status set to the signal number with bit 8
    // set.  On the systems that we care about, this exit status is what is
    // normally used to indicate an exit by this signal's default handler.
    // This mechanism isn't a de jure standard, but even in the worst case, it
    // should at least result in an immediate exit.
    RAW_LOG(WARNING, "Still here, exiting really ungracefully.");
    _exit(signal | (1 << 7));
  }
  ExitPosted();
}

// Sets the file descriptor soft limit to |max_descriptors| or the OS hard
// limit, whichever is lower.
void SetFileDescriptorLimit(unsigned int max_descriptors) {
  struct rlimit limits;
  if (getrlimit(RLIMIT_NOFILE, &limits) == 0) {
    unsigned int new_limit = max_descriptors;
    if (limits.rlim_max > 0 && limits.rlim_max < max_descriptors) {
      new_limit = limits.rlim_max;
    }
    limits.rlim_cur = new_limit;
    if (setrlimit(RLIMIT_NOFILE, &limits) != 0) {
      PLOG(INFO) << "Failed to set file descriptor limit";
    }
  } else {
    PLOG(INFO) << "Failed to get file descriptor limit";
  }
}

}  // namespace

// ChromeBrowserMainPartsPosix -------------------------------------------------

ChromeBrowserMainPartsPosix::ChromeBrowserMainPartsPosix(
    const content::MainFunctionParams& parameters)
    : ChromeBrowserMainParts(parameters) {
}

void ChromeBrowserMainPartsPosix::PreEarlyInitialization() {
  ChromeBrowserMainParts::PreEarlyInitialization();

  // We need to accept SIGCHLD, even though our handler is a no-op because
  // otherwise we cannot wait on children. (According to POSIX 2001.)
  struct sigaction action;
  memset(&action, 0, sizeof(action));
  action.sa_handler = SIGCHLDHandler;
  CHECK(sigaction(SIGCHLD, &action, NULL) == 0);

  const std::string fd_limit_string =
      parsed_command_line().GetSwitchValueASCII(
          switches::kFileDescriptorLimit);
  int fd_limit = 0;
  if (!fd_limit_string.empty()) {
    base::StringToInt(fd_limit_string, &fd_limit);
  }
#if defined(OS_MACOSX)
  // We use quite a few file descriptors for our IPC, and the default limit on
  // the Mac is low (256), so bump it up if there is no explicit override.
  if (fd_limit == 0) {
    fd_limit = 1024;
  }
#endif  // OS_MACOSX
  if (fd_limit > 0)
    SetFileDescriptorLimit(fd_limit);
}

void ChromeBrowserMainPartsPosix::PostMainMessageLoopStart() {
  ChromeBrowserMainParts::PostMainMessageLoopStart();

  int pipefd[2];
  int ret = pipe(pipefd);
  if (ret < 0) {
    PLOG(DFATAL) << "Failed to create pipe";
  } else {
    g_shutdown_pipe_read_fd = pipefd[0];
    g_shutdown_pipe_write_fd = pipefd[1];
    const size_t kShutdownDetectorThreadStackSize = PTHREAD_STACK_MIN;
    // TODO(viettrungluu,willchan): crbug.com/29675 - This currently leaks, so
    // if you change this, you'll probably need to change the suppression.
    if (!base::PlatformThread::CreateNonJoinable(
            kShutdownDetectorThreadStackSize,
            new ShutdownDetector(g_shutdown_pipe_read_fd))) {
      LOG(DFATAL) << "Failed to create shutdown detector task.";
    }
  }
  // Setup signal handlers for shutdown AFTER shutdown pipe is setup because
  // it may be called right away after handler is set.

  // If adding to this list of signal handlers, note the new signal probably
  // needs to be reset in child processes. See
  // base/process_util_posix.cc:LaunchProcess.

  // We need to handle SIGTERM, because that is how many POSIX-based distros ask
  // processes to quit gracefully at shutdown time.
  struct sigaction action;
  memset(&action, 0, sizeof(action));
  action.sa_handler = SIGTERMHandler;
  CHECK(sigaction(SIGTERM, &action, NULL) == 0);
  // Also handle SIGINT - when the user terminates the browser via Ctrl+C. If
  // the browser process is being debugged, GDB will catch the SIGINT first.
  action.sa_handler = SIGINTHandler;
  CHECK(sigaction(SIGINT, &action, NULL) == 0);
  // And SIGHUP, for when the terminal disappears. On shutdown, many Linux
  // distros send SIGHUP, SIGTERM, and then SIGKILL.
  action.sa_handler = SIGHUPHandler;
  CHECK(sigaction(SIGHUP, &action, NULL) == 0);

#if defined(TOOLKIT_USES_GTK) && !defined(OS_CHROMEOS)
  printing::PrintingContextGtk::SetCreatePrintDialogFunction(
      &PrintDialogGtk::CreatePrintDialog);
#endif
}
<commit_msg>Fix android build of sync_unit_tests after http://crrev.com/122182<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chrome_browser_main_posix.h"

#include <errno.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <sys/resource.h>
#include <unistd.h>

#include <string>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/eintr_wrapper.h"
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/common/chrome_switches.h"
#include "content/public/browser/browser_thread.h"

#if defined(OS_ANDROID)
#include <asm/page.h>  // for PAGE_SIZE needed by PTHREAD_STACK_MIN
#endif

#if defined(TOOLKIT_USES_GTK) && !defined(OS_CHROMEOS)
#include "chrome/browser/printing/print_dialog_gtk.h"
#endif

using content::BrowserThread;

namespace {

// See comment in |PreEarlyInitialization()|, where sigaction is called.
void SIGCHLDHandler(int signal) {
}

int g_shutdown_pipe_write_fd = -1;
int g_shutdown_pipe_read_fd = -1;

// Common code between SIG{HUP, INT, TERM}Handler.
void GracefulShutdownHandler(int signal) {
  // Reinstall the default handler.  We had one shot at graceful shutdown.
  struct sigaction action;
  memset(&action, 0, sizeof(action));
  action.sa_handler = SIG_DFL;
  RAW_CHECK(sigaction(signal, &action, NULL) == 0);

  RAW_CHECK(g_shutdown_pipe_write_fd != -1);
  RAW_CHECK(g_shutdown_pipe_read_fd != -1);
  size_t bytes_written = 0;
  do {
    int rv = HANDLE_EINTR(
        write(g_shutdown_pipe_write_fd,
              reinterpret_cast<const char*>(&signal) + bytes_written,
              sizeof(signal) - bytes_written));
    RAW_CHECK(rv >= 0);
    bytes_written += rv;
  } while (bytes_written < sizeof(signal));
}

// See comment in |PostMainMessageLoopStart()|, where sigaction is called.
void SIGHUPHandler(int signal) {
  RAW_CHECK(signal == SIGHUP);
  GracefulShutdownHandler(signal);
}

// See comment in |PostMainMessageLoopStart()|, where sigaction is called.
void SIGINTHandler(int signal) {
  RAW_CHECK(signal == SIGINT);
  GracefulShutdownHandler(signal);
}

// See comment in |PostMainMessageLoopStart()|, where sigaction is called.
void SIGTERMHandler(int signal) {
  RAW_CHECK(signal == SIGTERM);
  GracefulShutdownHandler(signal);
}

class ShutdownDetector : public base::PlatformThread::Delegate {
 public:
  explicit ShutdownDetector(int shutdown_fd);

  virtual void ThreadMain();

 private:
  const int shutdown_fd_;

  DISALLOW_COPY_AND_ASSIGN(ShutdownDetector);
};

ShutdownDetector::ShutdownDetector(int shutdown_fd)
    : shutdown_fd_(shutdown_fd) {
  CHECK_NE(shutdown_fd_, -1);
}

// These functions are used to help us diagnose crash dumps that happen
// during the shutdown process.
NOINLINE void ShutdownFDReadError() {
  // Ensure function isn't optimized away.
  asm("");
  sleep(UINT_MAX);
}

NOINLINE void ShutdownFDClosedError() {
  // Ensure function isn't optimized away.
  asm("");
  sleep(UINT_MAX);
}

NOINLINE void ExitPosted() {
  // Ensure function isn't optimized away.
  asm("");
  sleep(UINT_MAX);
}

void ShutdownDetector::ThreadMain() {
  base::PlatformThread::SetName("CrShutdownDetector");

  int signal;
  size_t bytes_read = 0;
  ssize_t ret;
  do {
    ret = HANDLE_EINTR(
        read(shutdown_fd_,
             reinterpret_cast<char*>(&signal) + bytes_read,
             sizeof(signal) - bytes_read));
    if (ret < 0) {
      NOTREACHED() << "Unexpected error: " << strerror(errno);
      ShutdownFDReadError();
      break;
    } else if (ret == 0) {
      NOTREACHED() << "Unexpected closure of shutdown pipe.";
      ShutdownFDClosedError();
      break;
    }
    bytes_read += ret;
  } while (bytes_read < sizeof(signal));
  VLOG(1) << "Handling shutdown for signal " << signal << ".";
#if defined(OS_CHROMEOS)
  // On ChromeOS, exiting on signal should be always clean.
  base::Closure task = base::Bind(&BrowserList::ExitCleanly);
#else
  base::Closure task = base::Bind(&BrowserList::AttemptExit);
#endif

  if (!BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, task)) {
    // Without a UI thread to post the exit task to, there aren't many
    // options.  Raise the signal again.  The default handler will pick it up
    // and cause an ungraceful exit.
    RAW_LOG(WARNING, "No UI thread, exiting ungracefully.");
    kill(getpid(), signal);

    // The signal may be handled on another thread.  Give that a chance to
    // happen.
    sleep(3);

    // We really should be dead by now.  For whatever reason, we're not. Exit
    // immediately, with the exit status set to the signal number with bit 8
    // set.  On the systems that we care about, this exit status is what is
    // normally used to indicate an exit by this signal's default handler.
    // This mechanism isn't a de jure standard, but even in the worst case, it
    // should at least result in an immediate exit.
    RAW_LOG(WARNING, "Still here, exiting really ungracefully.");
    _exit(signal | (1 << 7));
  }
  ExitPosted();
}

// Sets the file descriptor soft limit to |max_descriptors| or the OS hard
// limit, whichever is lower.
void SetFileDescriptorLimit(unsigned int max_descriptors) {
  struct rlimit limits;
  if (getrlimit(RLIMIT_NOFILE, &limits) == 0) {
    unsigned int new_limit = max_descriptors;
    if (limits.rlim_max > 0 && limits.rlim_max < max_descriptors) {
      new_limit = limits.rlim_max;
    }
    limits.rlim_cur = new_limit;
    if (setrlimit(RLIMIT_NOFILE, &limits) != 0) {
      PLOG(INFO) << "Failed to set file descriptor limit";
    }
  } else {
    PLOG(INFO) << "Failed to get file descriptor limit";
  }
}

}  // namespace

// ChromeBrowserMainPartsPosix -------------------------------------------------

ChromeBrowserMainPartsPosix::ChromeBrowserMainPartsPosix(
    const content::MainFunctionParams& parameters)
    : ChromeBrowserMainParts(parameters) {
}

void ChromeBrowserMainPartsPosix::PreEarlyInitialization() {
  ChromeBrowserMainParts::PreEarlyInitialization();

  // We need to accept SIGCHLD, even though our handler is a no-op because
  // otherwise we cannot wait on children. (According to POSIX 2001.)
  struct sigaction action;
  memset(&action, 0, sizeof(action));
  action.sa_handler = SIGCHLDHandler;
  CHECK(sigaction(SIGCHLD, &action, NULL) == 0);

  const std::string fd_limit_string =
      parsed_command_line().GetSwitchValueASCII(
          switches::kFileDescriptorLimit);
  int fd_limit = 0;
  if (!fd_limit_string.empty()) {
    base::StringToInt(fd_limit_string, &fd_limit);
  }
#if defined(OS_MACOSX)
  // We use quite a few file descriptors for our IPC, and the default limit on
  // the Mac is low (256), so bump it up if there is no explicit override.
  if (fd_limit == 0) {
    fd_limit = 1024;
  }
#endif  // OS_MACOSX
  if (fd_limit > 0)
    SetFileDescriptorLimit(fd_limit);
}

void ChromeBrowserMainPartsPosix::PostMainMessageLoopStart() {
  ChromeBrowserMainParts::PostMainMessageLoopStart();

  int pipefd[2];
  int ret = pipe(pipefd);
  if (ret < 0) {
    PLOG(DFATAL) << "Failed to create pipe";
  } else {
    g_shutdown_pipe_read_fd = pipefd[0];
    g_shutdown_pipe_write_fd = pipefd[1];
    const size_t kShutdownDetectorThreadStackSize = PTHREAD_STACK_MIN;
    // TODO(viettrungluu,willchan): crbug.com/29675 - This currently leaks, so
    // if you change this, you'll probably need to change the suppression.
    if (!base::PlatformThread::CreateNonJoinable(
            kShutdownDetectorThreadStackSize,
            new ShutdownDetector(g_shutdown_pipe_read_fd))) {
      LOG(DFATAL) << "Failed to create shutdown detector task.";
    }
  }
  // Setup signal handlers for shutdown AFTER shutdown pipe is setup because
  // it may be called right away after handler is set.

  // If adding to this list of signal handlers, note the new signal probably
  // needs to be reset in child processes. See
  // base/process_util_posix.cc:LaunchProcess.

  // We need to handle SIGTERM, because that is how many POSIX-based distros ask
  // processes to quit gracefully at shutdown time.
  struct sigaction action;
  memset(&action, 0, sizeof(action));
  action.sa_handler = SIGTERMHandler;
  CHECK(sigaction(SIGTERM, &action, NULL) == 0);
  // Also handle SIGINT - when the user terminates the browser via Ctrl+C. If
  // the browser process is being debugged, GDB will catch the SIGINT first.
  action.sa_handler = SIGINTHandler;
  CHECK(sigaction(SIGINT, &action, NULL) == 0);
  // And SIGHUP, for when the terminal disappears. On shutdown, many Linux
  // distros send SIGHUP, SIGTERM, and then SIGKILL.
  action.sa_handler = SIGHUPHandler;
  CHECK(sigaction(SIGHUP, &action, NULL) == 0);

#if defined(TOOLKIT_USES_GTK) && !defined(OS_CHROMEOS)
  printing::PrintingContextGtk::SetCreatePrintDialogFunction(
      &PrintDialogGtk::CreatePrintDialog);
#endif
}
<|endoftext|>


<commit_before><commit_msg>Removed a stray string. Review URL: http://codereview.chromium.org/18317<commit_after><|endoftext|>


<commit_before><commit_msg>Fix issue 34343: "Tab to search" hint on omnibox disappears on drag dropped tab.<commit_after><|endoftext|>