<commit_before>// @(#)root/base:$Name:  $:$Id: TVirtualViewer3D.cxx,v 1.9 2007/01/29 15:10:48 brun Exp $
// Author: Olivier Couet 05/10/2004

/*************************************************************************
 * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TVirtualViewer3D                                                     //
//                                                                      //
// Abstract 3D shapes viewer. The concrete implementations are:         //
//                                                                      //
// TViewerX3D   : X3d viewer                                            //
// TGLViewer    : OpenGL viewer                                         //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
//BEGIN_HTML

3D Viewer Infrastructure Overview

The 3D Viewer infrastructure consists of:

 TVirtualViewer3D interface: An abstract handle to the viewer, allowing
    client to test preferences, add objects, control the viewer via scripting
    (to be added) etc.

TBuffer3D class hierarchy: Used to describe 3D objects
    ("shapes")
    - filled /added by negotiation with viewer via TVirtualViewer3D.

Together these allow clients to publish objects to any one of the 3D viewers
  (currently OpenGL/x3d,TPad), free of viewer specific drawing code. They allow
  our simple x3d viewer, and considerably more sophisticated OpenGL one to both
  work with both geometry libraries (g3d and geom) efficiently.

Publishing to a viewer consists of the following steps:

 Create / obtain viewer handle

Begin scene on viewer

Fill mandatory parts of TBuffer3D describing object

Add to viewer

Fill optional parts of TBuffer3D if requested by viewer, and add again

     ... repeat 3/4/5
  as required

End scene on viewer

Creating / Obtaining Viewer

Create/obtain the viewer handle via local/global pad - the viewer is always
  bound to a TPad object at present [This may be removed as a restriction in
  the future] . You should perform the publishing to the viewer described below
  in the Paint() method of the object you attach to the pad (via Draw())

TVirtualViewer3D * v = gPad->GetViewer3D("xxxx");

" xxxx" is viewer type: OpenGL "ogl", X3D "x3d" or
  Pad "pad" (default). The viewer is created via the plugin manager,
  attached to pad, and the interface returned.

 Begin / End Scene

Objects must be added to viewer between BeginScene/EndScene calls e.g.

v->BeginScene();
.....
v->AddObject(....);
v->AddObject(....);
.....
v->EndScene();

The BeginScene call will cause the viewer to suspend redraws etc, and after
  the EndScene the viewer will reset the camera to frame the new scene and redraw.

[x3d viewer does not support changing of scenes - objects added after the
  first Open/CloseScene pair will be ignored.]

Filling TBuffer3D and Adding to Viewer

The viewers behind the TVirtualViewer3D interface differ greatly in their
  capabilities e.g.

 Some know how to draw certain shapes natively (e.g. spheres/tubes in
    OpenGL) - others always require a raw tessellation description of points/lines/segments.

Some
      need the 3D object positions in the global frame, others can cope with
    local frames + a translation matrix - which can give considerable performance
      benefits.

To cope with these situations the object buffer is filled out in negotiation
  with the viewer. TBuffer3D classes are conceptually divided into enumerated
  sections Core, BoundingBox, Raw etc (see TBuffer3D.h for more details).

The SectionsValid() / SetSectionsValid / ClearSectionsValid() methods of TBuffer3D
    are used to test/set/clear these section valid flags.

The sections found in TBuffer3D (Core/BoundingBox/Raw Sizes/Raw)
  are sufficient to describe any tessellated shape in a generic fashion. An additional ShapeSpecific  section
  in derived shape specific classes allows a more abstract shape description
  ("a sphere of inner radius x, outer radius y"). This enables a viewer
  which knows how to draw (tessellate) the shape itself to do so, which can bring
  considerable performance and quality benefits, while providing a generic fallback
  suitable for all viewers.

The rules for client negotiation with the viewer are:

 If suitable specialized TBuffer3D class exists, use it, otherwise use
    TBuffer3D.

Complete the mandatory Core section.

Complete the ShapeSpecific section
      if applicable.

Complete the BoundingBox if you can.

Pass this buffer to the viewer using
      one of the AddObject() methods - see below.

If the viewer requires more sections to be completed (Raw/RawSizes) AddObject()
  will return flags indicating which ones, otherwise it returns kNone. You must
  fill the buffer and mark these sections valid, and pass the buffer again. A
  typical code snippet would be:

TBuffer3DSphere sphereBuffer;
// Fill out kCore...
// Fill out kBoundingBox...
// Fill out kShapeSpecific for TBuffer3DSphere
// Try first add to viewer
Int_t reqSections = viewer->AddObject(buffer);
if (reqSections != TBuffer3D::kNone) {
  if (reqSections & TBuffer3D::kRawSizes) {
     // Fill out kRawSizes...
  }
  if (reqSections & TBuffer3D::kRaw) {
     // Fill out kRaw...
  }
  // Add second time to viewer - ignore return cannot do more
  viewer->AddObject(buffer);
  }
}

ShapeSpecific: If the viewer can directly display the buffer without
  filling of the kRaw/kRawSizes section it will not need to request client side
  tessellation.
  Currently we provide the following various shape specific classes, which the
  OpenGL viewer can take advantage of (see TBuffer3D.h and TBuffer3DTypes.h)

TBuffer3DSphere - solid, hollow and cut spheres*

TBuffer3DTubeSeg - angle tube segment

TBuffer3DCutTube - angle tube segment with plane cut ends.

*OpenGL only supports solid spheres at present - cut/hollow ones will be
    requested tessellated.

Anyone is free to add new TBuffer3D classes, but it should be clear that the
  viewers require updating to be able to take advantage of them. The number of
  native shapes in OpenGL will be expanded over time.

BoundingBox: You are not obliged to complete this, as any viewer
  requiring one internally (OpenGL) will build one for you if you do not provide.
  However
  to do this the viewer will force you to provide the raw tessellation, and the
  resulting box will be axis aligned with the overall scene, which is non-ideal
  for rotated shapes.

As we need to support orientated (rotated) bounding boxes, TBuffer3D requires
  the 6 vertices of the box. We also provide a convenience function, SetAABoundingBox(),
  for simpler case of setting an axis aligned bounding box.

  Master/Local Reference Frames

The Core section of TBuffer3D contains two members relating to reference
  frames:
fLocalFrame & fLocalMaster. fLocalFrame indicates
  if any positions in the buffer (bounding box and tessellation vertexes) are
  in local or master (world
  frame). fLocalMaster is a standard 4x4 translation matrix (OpenGL
  colum major ordering) for placing the object into the 3D master frame.

If fLocalFrame is kFALSE, fLocalMaster should contain an
  identity matrix. This is set by default, and can be reset using SetLocalMasterIdentity() function.

Logical & Physical Objects

There are two cases of object addition:

 Add this object as a single independent entity in the world reference
    frame.

Add
        a physical placement (copy) of this logical object (described in local
    reference frame).

The second case is very typical in geometry packages, GEANT4, where we have
  very large number repeated placements of relatively few logical (unique) shapes.
  Some viewers (OpenGL only at present) are able to take advantage of this by
  identifying unique logical shapes from the fID logical ID member of
  TBuffer3D. If repeated addition of the same fID is found, the shape
  is cached already - and the costly tessellation does not need to be sent again.
  The viewer can
  also perform internal GL specific caching with considerable performance gains
  in these cases.

For this to work correctly the logical object in must be described in TBuffer3D
  in the local reference frame, complete with the local/master translation. The
  viewer indicates this through the interface method

PreferLocalFrame()

If this returns kTRUE you can make repeated calls to AddObject(), with TBuffer3D
  containing the same fID, and different fLocalMaster placements.

For viewers supporting logical/physical objects, the TBuffer3D content refers
  to the properties of logical object, with the fLocalMaster transform and the
  fColor and fTransparency attributes, which can be varied for each physical
  object.

As a minimum requirement all clients must be capable of filling the raw tessellation
  of the object buffer, in the master reference frame. Conversely viewers must
  always be capable of displaying the object described by this buffer.

  Scene Rebuilds

It should be understood that AddObject is not an explicit command to the viewer
  - it may for various reasons decide to ignore it:

 It already has the object internally cached .

The object falls outside
    some 'interest' limits of the viewer camera.

The object is too small to
      be worth drawing.

In all these cases AddObject() returns kNone, as it does for successful addition,
  simply indicating it does not require you to provide further information about
  this object. You should
  not try to make any assumptions about what the viewer did with it.

This enables the viewer to be connected to a client which sends potentially
  millions of objects, and only accept those that are of interest at a certain
  time, caching the relatively small number of CPU/memory costly logical shapes,
  and retaining/discarding the physical placements as required. The viewer may
  decide to force the client to rebuild (republish) the scene (via
  a TPad
  repaint
  at
  present),
  and
  thus
  collect
  these
  objects if
  the
  internal viewer state changes. It does this presently by forcing a repaint
  on the attached TPad object - hence the reason for putting all publishing to
  the viewer in the attached pad objects Paint() method. We will likely remove
  this requirement in the future, indicating the rebuild request via a normal
ROOT signal, which the client can detect.

  Physical IDs

TVirtualViewer3D provides for two methods of object addition:virtual Int_t AddObject(const
TBuffer3D & buffer, Bool_t * addChildren = 0)

virtual Int_t AddObject(UInt_t physicalID, const TBuffer3D & buffer, Bool_t * addChildren = 0)

If you use the first (simple) case a viewer using logical/physical pairs
    will generate IDs for each physical object internally. In the second you
    can specify
      a unique identifier from the client, which allows the viewer to be more
    efficient. It can now cache both logical and physical objects, and only discard
    physical
  objects no longer of interest as part of scene rebuilds.

  Child Objects

In many geometries there is a rigid containment hierarchy, and so if the viewer
  is not interested in a certain object due to limits/size then it will also
  not be interest in any of the contained branch of descendents. Both AddObject()
  methods have an addChildren parameter. The viewer will complete this (if passed)
indicating if children (contained within the one just sent) are worth adding.

  Recyling TBuffer3D

Once add AddObject() has been called, the contents are copied to the viewer
  internally. You are free to destroy this object, or recycle it for the next
  object if suitable.

END_HTML

#include "TVirtualViewer3D.h"
#include "TVirtualPad.h"
#include "TPluginManager.h"
#include "TError.h"
#include "TROOT.h"
#include "TClass.h"

ClassImp(TVirtualViewer3D)

//______________________________________________________________________________
TVirtualViewer3D* TVirtualViewer3D::Viewer3D(TVirtualPad *pad, Option_t *type)
{
   // Create a Viewer 3D of specified type
   TVirtualViewer3D *viewer = 0;
   TPluginHandler *h;
   if ((h = gROOT->GetPluginManager()->FindHandler("TVirtualViewer3D", type))) {
      if (h->LoadPlugin() == -1) return 0;

      if (!pad) {
         viewer = (TVirtualViewer3D *) h->ExecPlugin(1, gPad);
      } else {
         viewer = (TVirtualViewer3D *) h->ExecPlugin(1, pad);
      }
   }
   return viewer;
}
<commit_msg>remove now unused TROOT.h include.<commit_after>// @(#)root/base:$Name:  $:$Id: TVirtualViewer3D.cxx,v 1.10 2007/06/11 19:56:33 brun Exp $
// Author: Olivier Couet 05/10/2004

/*************************************************************************
 * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TVirtualViewer3D                                                     //
//                                                                      //
// Abstract 3D shapes viewer. The concrete implementations are:         //
//                                                                      //
// TViewerX3D   : X3d viewer                                            //
// TGLViewer    : OpenGL viewer                                         //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
//BEGIN_HTML

3D Viewer Infrastructure Overview

The 3D Viewer infrastructure consists of:

 TVirtualViewer3D interface: An abstract handle to the viewer, allowing
    client to test preferences, add objects, control the viewer via scripting
    (to be added) etc.

TBuffer3D class hierarchy: Used to describe 3D objects
    ("shapes")
    - filled /added by negotiation with viewer via TVirtualViewer3D.

Together these allow clients to publish objects to any one of the 3D viewers
  (currently OpenGL/x3d,TPad), free of viewer specific drawing code. They allow
  our simple x3d viewer, and considerably more sophisticated OpenGL one to both
  work with both geometry libraries (g3d and geom) efficiently.

Publishing to a viewer consists of the following steps:

 Create / obtain viewer handle

Begin scene on viewer

Fill mandatory parts of TBuffer3D describing object

Add to viewer

Fill optional parts of TBuffer3D if requested by viewer, and add again

     ... repeat 3/4/5
  as required

End scene on viewer

Creating / Obtaining Viewer

Create/obtain the viewer handle via local/global pad - the viewer is always
  bound to a TPad object at present [This may be removed as a restriction in
  the future] . You should perform the publishing to the viewer described below
  in the Paint() method of the object you attach to the pad (via Draw())

TVirtualViewer3D * v = gPad->GetViewer3D("xxxx");

" xxxx" is viewer type: OpenGL "ogl", X3D "x3d" or
  Pad "pad" (default). The viewer is created via the plugin manager,
  attached to pad, and the interface returned.

 Begin / End Scene

Objects must be added to viewer between BeginScene/EndScene calls e.g.

v->BeginScene();
.....
v->AddObject(....);
v->AddObject(....);
.....
v->EndScene();

The BeginScene call will cause the viewer to suspend redraws etc, and after
  the EndScene the viewer will reset the camera to frame the new scene and redraw.

[x3d viewer does not support changing of scenes - objects added after the
  first Open/CloseScene pair will be ignored.]

Filling TBuffer3D and Adding to Viewer

The viewers behind the TVirtualViewer3D interface differ greatly in their
  capabilities e.g.

 Some know how to draw certain shapes natively (e.g. spheres/tubes in
    OpenGL) - others always require a raw tessellation description of points/lines/segments.

Some
      need the 3D object positions in the global frame, others can cope with
    local frames + a translation matrix - which can give considerable performance
      benefits.

To cope with these situations the object buffer is filled out in negotiation
  with the viewer. TBuffer3D classes are conceptually divided into enumerated
  sections Core, BoundingBox, Raw etc (see TBuffer3D.h for more details).

The SectionsValid() / SetSectionsValid / ClearSectionsValid() methods of TBuffer3D
    are used to test/set/clear these section valid flags.

The sections found in TBuffer3D (Core/BoundingBox/Raw Sizes/Raw)
  are sufficient to describe any tessellated shape in a generic fashion. An additional ShapeSpecific  section
  in derived shape specific classes allows a more abstract shape description
  ("a sphere of inner radius x, outer radius y"). This enables a viewer
  which knows how to draw (tessellate) the shape itself to do so, which can bring
  considerable performance and quality benefits, while providing a generic fallback
  suitable for all viewers.

The rules for client negotiation with the viewer are:

 If suitable specialized TBuffer3D class exists, use it, otherwise use
    TBuffer3D.

Complete the mandatory Core section.

Complete the ShapeSpecific section
      if applicable.

Complete the BoundingBox if you can.

Pass this buffer to the viewer using
      one of the AddObject() methods - see below.

If the viewer requires more sections to be completed (Raw/RawSizes) AddObject()
  will return flags indicating which ones, otherwise it returns kNone. You must
  fill the buffer and mark these sections valid, and pass the buffer again. A
  typical code snippet would be:

TBuffer3DSphere sphereBuffer;
// Fill out kCore...
// Fill out kBoundingBox...
// Fill out kShapeSpecific for TBuffer3DSphere
// Try first add to viewer
Int_t reqSections = viewer->AddObject(buffer);
if (reqSections != TBuffer3D::kNone) {
  if (reqSections & TBuffer3D::kRawSizes) {
     // Fill out kRawSizes...
  }
  if (reqSections & TBuffer3D::kRaw) {
     // Fill out kRaw...
  }
  // Add second time to viewer - ignore return cannot do more
  viewer->AddObject(buffer);
  }
}

ShapeSpecific: If the viewer can directly display the buffer without
  filling of the kRaw/kRawSizes section it will not need to request client side
  tessellation.
  Currently we provide the following various shape specific classes, which the
  OpenGL viewer can take advantage of (see TBuffer3D.h and TBuffer3DTypes.h)

TBuffer3DSphere - solid, hollow and cut spheres*

TBuffer3DTubeSeg - angle tube segment

TBuffer3DCutTube - angle tube segment with plane cut ends.

*OpenGL only supports solid spheres at present - cut/hollow ones will be
    requested tessellated.

Anyone is free to add new TBuffer3D classes, but it should be clear that the
  viewers require updating to be able to take advantage of them. The number of
  native shapes in OpenGL will be expanded over time.

BoundingBox: You are not obliged to complete this, as any viewer
  requiring one internally (OpenGL) will build one for you if you do not provide.
  However
  to do this the viewer will force you to provide the raw tessellation, and the
  resulting box will be axis aligned with the overall scene, which is non-ideal
  for rotated shapes.

As we need to support orientated (rotated) bounding boxes, TBuffer3D requires
  the 6 vertices of the box. We also provide a convenience function, SetAABoundingBox(),
  for simpler case of setting an axis aligned bounding box.

  Master/Local Reference Frames

The Core section of TBuffer3D contains two members relating to reference
  frames:
fLocalFrame & fLocalMaster. fLocalFrame indicates
  if any positions in the buffer (bounding box and tessellation vertexes) are
  in local or master (world
  frame). fLocalMaster is a standard 4x4 translation matrix (OpenGL
  colum major ordering) for placing the object into the 3D master frame.

If fLocalFrame is kFALSE, fLocalMaster should contain an
  identity matrix. This is set by default, and can be reset using SetLocalMasterIdentity() function.

Logical & Physical Objects

There are two cases of object addition:

 Add this object as a single independent entity in the world reference
    frame.

Add
        a physical placement (copy) of this logical object (described in local
    reference frame).

The second case is very typical in geometry packages, GEANT4, where we have
  very large number repeated placements of relatively few logical (unique) shapes.
  Some viewers (OpenGL only at present) are able to take advantage of this by
  identifying unique logical shapes from the fID logical ID member of
  TBuffer3D. If repeated addition of the same fID is found, the shape
  is cached already - and the costly tessellation does not need to be sent again.
  The viewer can
  also perform internal GL specific caching with considerable performance gains
  in these cases.

For this to work correctly the logical object in must be described in TBuffer3D
  in the local reference frame, complete with the local/master translation. The
  viewer indicates this through the interface method

PreferLocalFrame()

If this returns kTRUE you can make repeated calls to AddObject(), with TBuffer3D
  containing the same fID, and different fLocalMaster placements.

For viewers supporting logical/physical objects, the TBuffer3D content refers
  to the properties of logical object, with the fLocalMaster transform and the
  fColor and fTransparency attributes, which can be varied for each physical
  object.

As a minimum requirement all clients must be capable of filling the raw tessellation
  of the object buffer, in the master reference frame. Conversely viewers must
  always be capable of displaying the object described by this buffer.

  Scene Rebuilds

It should be understood that AddObject is not an explicit command to the viewer
  - it may for various reasons decide to ignore it:

 It already has the object internally cached .

The object falls outside
    some 'interest' limits of the viewer camera.

The object is too small to
      be worth drawing.

In all these cases AddObject() returns kNone, as it does for successful addition,
  simply indicating it does not require you to provide further information about
  this object. You should
  not try to make any assumptions about what the viewer did with it.

This enables the viewer to be connected to a client which sends potentially
  millions of objects, and only accept those that are of interest at a certain
  time, caching the relatively small number of CPU/memory costly logical shapes,
  and retaining/discarding the physical placements as required. The viewer may
  decide to force the client to rebuild (republish) the scene (via
  a TPad
  repaint
  at
  present),
  and
  thus
  collect
  these
  objects if
  the
  internal viewer state changes. It does this presently by forcing a repaint
  on the attached TPad object - hence the reason for putting all publishing to
  the viewer in the attached pad objects Paint() method. We will likely remove
  this requirement in the future, indicating the rebuild request via a normal
ROOT signal, which the client can detect.

  Physical IDs

TVirtualViewer3D provides for two methods of object addition:virtual Int_t AddObject(const
TBuffer3D & buffer, Bool_t * addChildren = 0)

virtual Int_t AddObject(UInt_t physicalID, const TBuffer3D & buffer, Bool_t * addChildren = 0)

If you use the first (simple) case a viewer using logical/physical pairs
    will generate IDs for each physical object internally. In the second you
    can specify
      a unique identifier from the client, which allows the viewer to be more
    efficient. It can now cache both logical and physical objects, and only discard
    physical
  objects no longer of interest as part of scene rebuilds.

  Child Objects

In many geometries there is a rigid containment hierarchy, and so if the viewer
  is not interested in a certain object due to limits/size then it will also
  not be interest in any of the contained branch of descendents. Both AddObject()
  methods have an addChildren parameter. The viewer will complete this (if passed)
indicating if children (contained within the one just sent) are worth adding.

  Recyling TBuffer3D

Once add AddObject() has been called, the contents are copied to the viewer
  internally. You are free to destroy this object, or recycle it for the next
  object if suitable.

END_HTML

#include "TVirtualViewer3D.h"
#include "TVirtualPad.h"
#include "TPluginManager.h"
#include "TError.h"
#include "TClass.h"

ClassImp(TVirtualViewer3D)

//______________________________________________________________________________
TVirtualViewer3D* TVirtualViewer3D::Viewer3D(TVirtualPad *pad, Option_t *type)
{
   // Create a Viewer 3D of specified type.

   TVirtualViewer3D *viewer = 0;
   TPluginHandler *h;
   if ((h = gPluginMgr->FindHandler("TVirtualViewer3D", type))) {
      if (h->LoadPlugin() == -1)
         return 0;

      if (!pad) {
         viewer = (TVirtualViewer3D *) h->ExecPlugin(1, gPad);
      } else {
         viewer = (TVirtualViewer3D *) h->ExecPlugin(1, pad);
      }
   }
   return viewer;
}
<|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.

// This file contains unit tests for PEImage.

#include "testing/gtest/include/gtest/gtest.h"
#include "base/win/pe_image.h"
#include "base/win/windows_version.h"

namespace base {
namespace win {

// Just counts the number of invocations.
bool ExportsCallback(const PEImage &image,
                     DWORD ordinal,
                     DWORD hint,
                     LPCSTR name,
                     PVOID function,
                     LPCSTR forward,
                     PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool ImportsCallback(const PEImage &image,
                     LPCSTR module,
                     DWORD ordinal,
                     LPCSTR name,
                     DWORD hint,
                     PIMAGE_THUNK_DATA iat,
                     PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool SectionsCallback(const PEImage &image,
                       PIMAGE_SECTION_HEADER header,
                       PVOID section_start,
                       DWORD section_size,
                       PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool RelocsCallback(const PEImage &image,
                    WORD type,
                    PVOID address,
                    PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool ImportChunksCallback(const PEImage &image,
                          LPCSTR module,
                          PIMAGE_THUNK_DATA name_table,
                          PIMAGE_THUNK_DATA iat,
                          PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool DelayImportChunksCallback(const PEImage &image,
                               PImgDelayDescr delay_descriptor,
                               LPCSTR module,
                               PIMAGE_THUNK_DATA name_table,
                               PIMAGE_THUNK_DATA iat,
                               PIMAGE_THUNK_DATA bound_iat,
                               PIMAGE_THUNK_DATA unload_iat,
                               PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// We'll be using some known values for the tests.
enum Value {
  sections = 0,
  imports_dlls,
  delay_dlls,
  exports,
  imports,
  delay_imports,
  relocs
};

// Retrieves the expected value from advapi32.dll based on the OS.
int GetExpectedValue(Value value, DWORD os) {
  const int xp_delay_dlls = 2;
  const int xp_exports = 675;
  const int xp_imports = 422;
  const int xp_delay_imports = 8;
  const int xp_relocs = 9180;
  const int vista_delay_dlls = 4;
  const int vista_exports = 799;
  const int vista_imports = 476;
  const int vista_delay_imports = 24;
  const int vista_relocs = 10188;
  const int w2k_delay_dlls = 0;
  const int w2k_exports = 566;
  const int w2k_imports = 357;
  const int w2k_delay_imports = 0;
  const int w2k_relocs = 7388;
  const int win7_delay_dlls = 7;
  const int win7_exports = 806;
  const int win7_imports = 568;
  const int win7_delay_imports = 71;
  const int win7_relocs = 7812;
  const int win8_delay_dlls = 9;
  const int win8_exports = 806;
  const int win8_imports = 568;
  const int win8_delay_imports = 113;
  const int win8_relocs = 9478;

  // Contains the expected value, for each enumerated property (Value), and the
  // OS version: [Value][os_version]
  const int expected[][5] = {
    {4, 4, 4, 4, 5},
    {3, 3, 3, 13, 19},
    {w2k_delay_dlls, xp_delay_dlls, vista_delay_dlls, win7_delay_dlls,
     win8_delay_dlls},
    {w2k_exports, xp_exports, vista_exports, win7_exports, win8_exports},
    {w2k_imports, xp_imports, vista_imports, win7_imports, win8_imports},
    {w2k_delay_imports, xp_delay_imports,
     vista_delay_imports, win7_delay_imports, win8_delay_imports},
    {w2k_relocs, xp_relocs, vista_relocs, win7_relocs, win8_relocs}
  };

  if (value > relocs)
    return 0;
  if (50 == os)
    os = 0;  // 5.0
  else if (51 == os || 52 == os)
    os = 1;
  else if (os == 60)
    os = 2;  // 6.x
  else if (os == 61)
    os = 3;
  else if (os >= 62)
    os = 4;
  else
    return 0;

  return expected[value][os];
}

// Tests that we are able to enumerate stuff from a PE file, and that
// the actual number of items found is within the expected range.
TEST(PEImageTest, EnumeratesPE) {
  // Windows Server 2003 is not supported as a test environment for this test.
  if (base::win::GetVersion() == base::win::VERSION_SERVER_2003)
    return;
  HMODULE module = LoadLibrary(L"advapi32.dll");
  ASSERT_TRUE(NULL != module);

  PEImage pe(module);
  int count = 0;
  EXPECT_TRUE(pe.VerifyMagic());

  DWORD os = pe.GetNTHeaders()->OptionalHeader.MajorOperatingSystemVersion;
  os = os * 10 + pe.GetNTHeaders()->OptionalHeader.MinorOperatingSystemVersion;

  pe.EnumSections(SectionsCallback, &count);
  EXPECT_EQ(GetExpectedValue(sections, os), count);

  count = 0;
  pe.EnumImportChunks(ImportChunksCallback, &count);
  EXPECT_EQ(GetExpectedValue(imports_dlls, os), count);

  count = 0;
  pe.EnumDelayImportChunks(DelayImportChunksCallback, &count);
  EXPECT_EQ(GetExpectedValue(delay_dlls, os), count);

  count = 0;
  pe.EnumExports(ExportsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(exports, os) - 20);
  EXPECT_LT(count, GetExpectedValue(exports, os) + 100);

  count = 0;
  pe.EnumAllImports(ImportsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(imports, os) - 20);
  EXPECT_LT(count, GetExpectedValue(imports, os) + 100);

  count = 0;
  pe.EnumAllDelayImports(ImportsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(delay_imports, os) - 2);
  EXPECT_LT(count, GetExpectedValue(delay_imports, os) + 8);

  count = 0;
  pe.EnumRelocs(RelocsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(relocs, os) - 150);
  EXPECT_LT(count, GetExpectedValue(relocs, os) + 1500);

  FreeLibrary(module);
}

// Tests that we can locate an specific exported symbol, by name and by ordinal.
TEST(PEImageTest, RetrievesExports) {
  HMODULE module = LoadLibrary(L"advapi32.dll");
  ASSERT_TRUE(NULL != module);

  PEImage pe(module);
  WORD ordinal;

  EXPECT_TRUE(pe.GetProcOrdinal("RegEnumKeyExW", &ordinal));

  FARPROC address1 = pe.GetProcAddress("RegEnumKeyExW");
  FARPROC address2 = pe.GetProcAddress(reinterpret_cast<char*>(ordinal));
  EXPECT_TRUE(address1 != NULL);
  EXPECT_TRUE(address2 != NULL);
  EXPECT_TRUE(address1 == address2);

  FreeLibrary(module);
}

}  // namespace win
}  // namespace base
<commit_msg>Fixes for the EnumeratesPE base_unittest failures seen on Windows 8 X64. The values used by this test for sections and import dlls, needed to be changed. These values are different for X86 and X64.<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.

// This file contains unit tests for PEImage.

#include "testing/gtest/include/gtest/gtest.h"
#include "base/win/pe_image.h"
#include "base/win/windows_version.h"

namespace base {
namespace win {

// Just counts the number of invocations.
bool ExportsCallback(const PEImage &image,
                     DWORD ordinal,
                     DWORD hint,
                     LPCSTR name,
                     PVOID function,
                     LPCSTR forward,
                     PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool ImportsCallback(const PEImage &image,
                     LPCSTR module,
                     DWORD ordinal,
                     LPCSTR name,
                     DWORD hint,
                     PIMAGE_THUNK_DATA iat,
                     PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool SectionsCallback(const PEImage &image,
                       PIMAGE_SECTION_HEADER header,
                       PVOID section_start,
                       DWORD section_size,
                       PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool RelocsCallback(const PEImage &image,
                    WORD type,
                    PVOID address,
                    PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool ImportChunksCallback(const PEImage &image,
                          LPCSTR module,
                          PIMAGE_THUNK_DATA name_table,
                          PIMAGE_THUNK_DATA iat,
                          PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// Just counts the number of invocations.
bool DelayImportChunksCallback(const PEImage &image,
                               PImgDelayDescr delay_descriptor,
                               LPCSTR module,
                               PIMAGE_THUNK_DATA name_table,
                               PIMAGE_THUNK_DATA iat,
                               PIMAGE_THUNK_DATA bound_iat,
                               PIMAGE_THUNK_DATA unload_iat,
                               PVOID cookie) {
  int* count = reinterpret_cast<int*>(cookie);
  (*count)++;
  return true;
}

// We'll be using some known values for the tests.
enum Value {
  sections = 0,
  imports_dlls,
  delay_dlls,
  exports,
  imports,
  delay_imports,
  relocs
};

// Retrieves the expected value from advapi32.dll based on the OS.
int GetExpectedValue(Value value, DWORD os) {
  const int xp_delay_dlls = 2;
  const int xp_exports = 675;
  const int xp_imports = 422;
  const int xp_delay_imports = 8;
  const int xp_relocs = 9180;
  const int vista_delay_dlls = 4;
  const int vista_exports = 799;
  const int vista_imports = 476;
  const int vista_delay_imports = 24;
  const int vista_relocs = 10188;
  const int w2k_delay_dlls = 0;
  const int w2k_exports = 566;
  const int w2k_imports = 357;
  const int w2k_delay_imports = 0;
  const int w2k_relocs = 7388;
  const int win7_delay_dlls = 7;
  const int win7_exports = 806;
  const int win7_imports = 568;
  const int win7_delay_imports = 71;
  const int win7_relocs = 7812;
  const int win8_delay_dlls = 9;
  const int win8_exports = 806;
  const int win8_imports = 568;
  const int win8_delay_imports = 113;
  const int win8_relocs = 9478;
  int win8_sections = 4;
  int win8_import_dlls = 17;

  base::win::OSInfo* os_info = base::win::OSInfo::GetInstance();
  if (os_info->architecture() == base::win::OSInfo::X86_ARCHITECTURE) {
    win8_sections = 5;
    win8_import_dlls = 19;
  }

  // Contains the expected value, for each enumerated property (Value), and the
  // OS version: [Value][os_version]
  const int expected[][5] = {
    {4, 4, 4, 4, win8_sections},
    {3, 3, 3, 13, win8_import_dlls},
    {w2k_delay_dlls, xp_delay_dlls, vista_delay_dlls, win7_delay_dlls,
     win8_delay_dlls},
    {w2k_exports, xp_exports, vista_exports, win7_exports, win8_exports},
    {w2k_imports, xp_imports, vista_imports, win7_imports, win8_imports},
    {w2k_delay_imports, xp_delay_imports,
     vista_delay_imports, win7_delay_imports, win8_delay_imports},
    {w2k_relocs, xp_relocs, vista_relocs, win7_relocs, win8_relocs}
  };

  if (value > relocs)
    return 0;
  if (50 == os)
    os = 0;  // 5.0
  else if (51 == os || 52 == os)
    os = 1;
  else if (os == 60)
    os = 2;  // 6.x
  else if (os == 61)
    os = 3;
  else if (os >= 62)
    os = 4;
  else
    return 0;

  return expected[value][os];
}

// Tests that we are able to enumerate stuff from a PE file, and that
// the actual number of items found is within the expected range.
TEST(PEImageTest, EnumeratesPE) {
  // Windows Server 2003 is not supported as a test environment for this test.
  if (base::win::GetVersion() == base::win::VERSION_SERVER_2003)
    return;
  HMODULE module = LoadLibrary(L"advapi32.dll");
  ASSERT_TRUE(NULL != module);

  PEImage pe(module);
  int count = 0;
  EXPECT_TRUE(pe.VerifyMagic());

  DWORD os = pe.GetNTHeaders()->OptionalHeader.MajorOperatingSystemVersion;
  os = os * 10 + pe.GetNTHeaders()->OptionalHeader.MinorOperatingSystemVersion;

  pe.EnumSections(SectionsCallback, &count);
  EXPECT_EQ(GetExpectedValue(sections, os), count);

  count = 0;
  pe.EnumImportChunks(ImportChunksCallback, &count);
  EXPECT_EQ(GetExpectedValue(imports_dlls, os), count);

  count = 0;
  pe.EnumDelayImportChunks(DelayImportChunksCallback, &count);
  EXPECT_EQ(GetExpectedValue(delay_dlls, os), count);

  count = 0;
  pe.EnumExports(ExportsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(exports, os) - 20);
  EXPECT_LT(count, GetExpectedValue(exports, os) + 100);

  count = 0;
  pe.EnumAllImports(ImportsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(imports, os) - 20);
  EXPECT_LT(count, GetExpectedValue(imports, os) + 100);

  count = 0;
  pe.EnumAllDelayImports(ImportsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(delay_imports, os) - 2);
  EXPECT_LT(count, GetExpectedValue(delay_imports, os) + 8);

  count = 0;
  pe.EnumRelocs(RelocsCallback, &count);
  EXPECT_GT(count, GetExpectedValue(relocs, os) - 150);
  EXPECT_LT(count, GetExpectedValue(relocs, os) + 1500);

  FreeLibrary(module);
}

// Tests that we can locate an specific exported symbol, by name and by ordinal.
TEST(PEImageTest, RetrievesExports) {
  HMODULE module = LoadLibrary(L"advapi32.dll");
  ASSERT_TRUE(NULL != module);

  PEImage pe(module);
  WORD ordinal;

  EXPECT_TRUE(pe.GetProcOrdinal("RegEnumKeyExW", &ordinal));

  FARPROC address1 = pe.GetProcAddress("RegEnumKeyExW");
  FARPROC address2 = pe.GetProcAddress(reinterpret_cast<char*>(ordinal));
  EXPECT_TRUE(address1 != NULL);
  EXPECT_TRUE(address2 != NULL);
  EXPECT_TRUE(address1 == address2);

  FreeLibrary(module);
}

}  // namespace win
}  // namespace base
<|endoftext|>


<commit_before>#include <db_cxx.h>

#include <iostream>
using namespace std;
int main()
{
    Dbt dbt;
    dbt.set_size(3);
    cout << "Hello World!" << endl;   cout << "Welcome to C++ Programming" << endl;
    return 0;
}
<commit_msg>Added Dbt.get_ulen and Dbt.set_ulen Modified test1 to test new functions and some of the older ones. Addresses #197<commit_after>#include <db_cxx.h>

#include <iostream>
using namespace std;
int main()
{
    u_int32_t size  = 3;
    u_int32_t flags = 5;
    u_int32_t ulen  = 7;
    void*     data  = &size;
    Dbt dbt;

    dbt.set_size(size);
    dbt.set_flags(flags);
    dbt.set_data(data);
    dbt.set_ulen(ulen);
    assert(dbt.get_size()  == size);
    assert(dbt.get_flags() == flags);
    assert(dbt.get_data()  == data);
    assert(dbt.get_ulen()  == ulen);
    cout << "Hello World!" << endl;   cout << "Welcome to C++ Programming" << endl;
    return 0;
}
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015-2016 André Netzeband
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

/**
 * @file main.cpp
 * @brief This example creates a simple Irrlicht scene with background and a simple IMGUI window.
 */

// standard library includes
#include <exception>
#include <iostream>

// library includes
#include <IrrIMGUI/IncludeIrrlicht.h>
#include <IrrIMGUI/IncludeIMGUI.h>
#include <IrrIMGUI/IrrIMGUI.h>
#include <IrrIMGUI/IrrIMGUIDebug.h>

// helper macros for reacting on unexpected states
#define _TOSTR(x) #x
#define TOSTR(x) _TOSTR(x)
#define FASSERT(expr) if (!(expr)) { throw IrrIMGUI::Debug::ExAssert(__FILE__ "[" TOSTR(__LINE__) "] Assertion failed: \'" TOSTR(expr) "'\n"); }

// builds up the Irrlicht scene
void runScene(void)
{
  using namespace IrrIMGUI;
  using namespace irr;

  // Create standard event receiver for the IrrIMGUI
  CIMGUIEventReceiver EventReceiver;

  // Irrlicht Settings
  SIrrlichtCreationParameters IrrlichtParams;
  IrrlichtParams.DriverType    = video::EDT_OPENGL;
  IrrlichtParams.WindowSize    = core::dimension2d<u32>(1024, 800);
  IrrlichtParams.Bits          = 32;
  IrrlichtParams.Fullscreen    = false;
  IrrlichtParams.Stencilbuffer = true;
  IrrlichtParams.AntiAlias     = 16;
  IrrlichtParams.Vsync         = false;
  IrrlichtParams.EventReceiver = &EventReceiver;

  IrrlichtDevice * const pDevice = createDeviceEx(IrrlichtParams);
  FASSERT(pDevice);

  // Create GUI object
  CIMGUIHandle GUI(pDevice, &EventReceiver);

  video::IVideoDriver  * const pDriver       = pDevice->getVideoDriver();
  scene::ISceneManager * const pSceneManager = pDevice->getSceneManager();

  scene::ISceneNode    * const pMainScreen   = pSceneManager->addEmptySceneNode();
  scene::ISceneNode    * const pMoonScreen   = pSceneManager->addEmptySceneNode();

  pDriver->setTextureCreationFlag(irr::video::ETCF_CREATE_MIP_MAPS, false);
  irr::scene::ISceneNode * const pSkybox = pSceneManager->addSkyBoxSceneNode(
      pDriver->getTexture("../../media/Background.jpg"),
      pDriver->getTexture("../../media/Background.jpg"),
      pDriver->getTexture("../../media/Background.jpg"),
      pDriver->getTexture("../../media/Background.jpg"),
      pDriver->getTexture("../../media/Background.jpg"),
      pDriver->getTexture("../../media/Background.jpg"),
      pMainScreen);
  pDriver->setTextureCreationFlag(irr::video::ETCF_CREATE_MIP_MAPS, true);

  // Create Planet object
  scene::IMeshSceneNode * const pMoon = pSceneManager->addSphereSceneNode(5.0f, 128, pMoonScreen);
  FASSERT(pMoon);
  pMoon->setPosition(irr::core::vector3df(0,0,25));
  pMoon->setMaterialTexture(0, pDriver->getTexture("../../media/Phobos.jpg"));
  pMoon->setMaterialFlag(irr::video::EMF_LIGHTING, false);

  // Add camera object
  irr::scene::ICameraSceneNode * const pMainCam = pSceneManager->addCameraSceneNode(pMainScreen, core::vector3df(0, 0, 0), core::vector3df(0,0,5));
  irr::scene::ICameraSceneNode * const pMoonCam = pSceneManager->addCameraSceneNode(pMoonScreen, core::vector3df(0, 0,15), core::vector3df(0,0,25));

  u32 LastTime = pDevice->getTimer()->getRealTime();
  f32 Rotation = 0.0;
  f32 RotPerSec = 0.01f;
  bool IsFirstLoop = true;
  int RotationDirection = 1;
  f32 Color[3] = {0.0f/256.0f, 43.0f/256.0f, 56.0f/256.0f};

  // Prepare double rendering
  video::ITexture * const pRenderTarget = pDriver->addRenderTargetTexture(core::dimension2d<u32>(384, 300), "Moon");
  IGUITexture * const pRenderTextureID  = GUI.createTexture(pRenderTarget);

  // Start main loop
  while(pDevice->run())
  {
    pDriver->beginScene(true, true, irr::video::SColor(255,100,101,140));

    // ****************************
    // Render Moon Scene
    // ****************************
    pDriver->setRenderTarget(pRenderTarget, true, true, video::SColor(255,(u32)(Color[0]*255.0f),(u32)(Color[1]*255.0f),(u32)(Color[2]*255.0f)));
    pMoonScreen->setVisible(true);
    pMainScreen->setVisible(false);
    pSceneManager->setActiveCamera(pMoonCam);

    pSceneManager->drawAll();

    pDriver->setRenderTarget(0, true, true, video::SColor(255,100,101,140));

    // ****************************
    // Render Main Scene
    // ****************************
    pMoonScreen->setVisible(false);
    pMainScreen->setVisible(true);
    pSceneManager->setActiveCamera(pMainCam);

    GUI.startGUI();

    // create first window with picture sources
    if (IsFirstLoop)
    {
      ImGui::SetNextWindowPos(ImVec2(20.0f, 20.0f));
      ImGui::SetNextWindowSize(ImVec2(500.0f, 100.0f));
    }
    ImGui::Begin("Picture sources");
    ImGui::Text("Background picture from Manuel Tellur / pixelio.de (Image-ID: 642831)");
    ImGui::Text("Moon (Phobos) texture from http://nasa3d.arc.nasa.gov");
    if (ImGui::Button("Exit", ImVec2(40, 20)))
    {
      pDevice->closeDevice();
    }
    ImGui::End();

    GUI.updateTexture(pRenderTextureID, pRenderTarget);

    if (IsFirstLoop)
    {
      ImGui::SetNextWindowPos(ImVec2(300.0f, 200.0f));
      ImGui::SetNextWindowSize(ImVec2(400.0f, 450.0f));
    }
    ImGui::Begin("Moon Window", NULL, ImGuiWindowFlags_ShowBorders);
    ImGui::Text("%.1f FPS", ImGui::GetIO().Framerate);
    ImGui::Image(*pRenderTextureID, ImVec2(384, 300));
    ImGui::BeginGroup();
    ImGui::RadioButton("Left",  &RotationDirection, 1);
    ImGui::RadioButton("Stop",  &RotationDirection, 0);
    ImGui::RadioButton("Right", &RotationDirection, -1);
    ImGui::EndGroup();
    ImGui::SameLine(0.0f, 10.0f);
    ImGui::BeginGroup();
    ImGui::SliderFloat("Speed", &RotPerSec, 0.001f, 0.5f);
    ImGui::SliderFloat("Angle",     &Rotation,  0.0f, 360.0f);
    ImGui::ColorEdit3("Color", Color);
    ImGui::EndGroup();
    ImGui::End();

    pSceneManager->drawAll();
    GUI.drawAll();

    pDriver->endScene();

    u32 const Time = pDevice->getTimer()->getRealTime();
    u32 const DeltaTime = Time - LastTime;
    if (DeltaTime > 0)
    {
      Rotation += (360.0f * RotPerSec * ((float)RotationDirection)) * (DeltaTime / 1000.0f);
      if (Rotation > 360.0f)
      {
        Rotation -= 360.0f;
      }
      else if (Rotation < 0.0f)
      {
        Rotation += 360.0f;
      }
      LastTime = Time;
    }
    pMoon->setRotation(irr::core::vector3df(0,Rotation,0));
    IsFirstLoop = false;
  }

  GUI.deleteTexture(pRenderTextureID);
  pDevice->drop();

}

int main(void)
{
  try
  {
    runScene();
  }
  catch(std::exception &rEx)
  {
    std::cout << rEx.what() << std::flush;
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
  }

  return 0;
}
<commit_msg>Add FPS print out at window caption.<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015-2016 André Netzeband
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

/**
 * @file main.cpp
 * @brief This example creates a simple Irrlicht scene with background and a simple IMGUI window.
 */

// standard library includes
#include <exception>
#include <iostream>

// library includes
#include <IrrIMGUI/IncludeIrrlicht.h>
#include <IrrIMGUI/IncludeIMGUI.h>
#include <IrrIMGUI/IrrIMGUI.h>
#include <IrrIMGUI/IrrIMGUIDebug.h>

// helper macros for reacting on unexpected states
#define _TOSTR(x) #x
#define TOSTR(x) _TOSTR(x)
#define FASSERT(expr) if (!(expr)) { throw IrrIMGUI::Debug::ExAssert(__FILE__ "[" TOSTR(__LINE__) "] Assertion failed: \'" TOSTR(expr) "'\n"); }

// builds up the Irrlicht scene
void runScene(void)
{
  using namespace IrrIMGUI;
  using namespace irr;

  // Create standard event receiver for the IrrIMGUI
  CIMGUIEventReceiver EventReceiver;

  // Irrlicht Settings
  SIrrlichtCreationParameters IrrlichtParams;
  IrrlichtParams.DriverType    = video::EDT_OPENGL;
  IrrlichtParams.WindowSize    = core::dimension2d<u32>(1024, 800);
  IrrlichtParams.Bits          = 32;
  IrrlichtParams.Fullscreen    = false;
  IrrlichtParams.Stencilbuffer = true;
  IrrlichtParams.AntiAlias     = 16;
  IrrlichtParams.Vsync         = false;
  IrrlichtParams.EventReceiver = &EventReceiver;

  IrrlichtDevice * const pDevice = createDeviceEx(IrrlichtParams);
  FASSERT(pDevice);

  // Create GUI object
  CIMGUIHandle GUI(pDevice, &EventReceiver);

  video::IVideoDriver  * const pDriver       = pDevice->getVideoDriver();
  scene::ISceneManager * const pSceneManager = pDevice->getSceneManager();

  scene::ISceneNode    * const pMainScreen   = pSceneManager->addEmptySceneNode();
  scene::ISceneNode    * const pMoonScreen   = pSceneManager->addEmptySceneNode();

  pDriver->setTextureCreationFlag(irr::video::ETCF_CREATE_MIP_MAPS, false);
  irr::scene::ISceneNode * const pSkybox = pSceneManager->addSkyBoxSceneNode(
      pDriver->getTexture("../../media/Background.jpg"),
      pDriver->getTexture("../../media/Background.jpg"),
      pDriver->getTexture("../../media/Background.jpg"),
      pDriver->getTexture("../../media/Background.jpg"),
      pDriver->getTexture("../../media/Background.jpg"),
      pDriver->getTexture("../../media/Background.jpg"),
      pMainScreen);
  pDriver->setTextureCreationFlag(irr::video::ETCF_CREATE_MIP_MAPS, true);

  // Create Planet object
  scene::IMeshSceneNode * const pMoon = pSceneManager->addSphereSceneNode(5.0f, 128, pMoonScreen);
  FASSERT(pMoon);
  pMoon->setPosition(irr::core::vector3df(0,0,25));
  pMoon->setMaterialTexture(0, pDriver->getTexture("../../media/Phobos.jpg"));
  pMoon->setMaterialFlag(irr::video::EMF_LIGHTING, false);

  // Add camera object
  irr::scene::ICameraSceneNode * const pMainCam = pSceneManager->addCameraSceneNode(pMainScreen, core::vector3df(0, 0, 0), core::vector3df(0,0,5));
  irr::scene::ICameraSceneNode * const pMoonCam = pSceneManager->addCameraSceneNode(pMoonScreen, core::vector3df(0, 0,15), core::vector3df(0,0,25));

  u32 LastTime = pDevice->getTimer()->getRealTime();
  s32 LastFPS = 0;
  f32 Rotation = 0.0;
  f32 RotPerSec = 0.01f;
  bool IsFirstLoop = true;
  int RotationDirection = 1;
  f32 Color[3] = {0.0f/256.0f, 43.0f/256.0f, 56.0f/256.0f};

  // Prepare double rendering
  video::ITexture * const pRenderTarget = pDriver->addRenderTargetTexture(core::dimension2d<u32>(384, 300), "Moon");
  IGUITexture * const pRenderTextureID  = GUI.createTexture(pRenderTarget);

  // Start main loop
  while(pDevice->run())
  {
    pDriver->beginScene(true, true, irr::video::SColor(255,100,101,140));

    // ****************************
    // Render Moon Scene
    // ****************************
    pDriver->setRenderTarget(pRenderTarget, true, true, video::SColor(255,(u32)(Color[0]*255.0f),(u32)(Color[1]*255.0f),(u32)(Color[2]*255.0f)));
    pMoonScreen->setVisible(true);
    pMainScreen->setVisible(false);
    pSceneManager->setActiveCamera(pMoonCam);

    pSceneManager->drawAll();

    pDriver->setRenderTarget(0, true, true, video::SColor(255,100,101,140));

    // ****************************
    // Render Main Scene
    // ****************************
    pMoonScreen->setVisible(false);
    pMainScreen->setVisible(true);
    pSceneManager->setActiveCamera(pMainCam);

    GUI.startGUI();

    // create first window with picture sources
    if (IsFirstLoop)
    {
      ImGui::SetNextWindowPos(ImVec2(20.0f, 20.0f));
      ImGui::SetNextWindowSize(ImVec2(500.0f, 100.0f));
    }
    ImGui::Begin("Picture sources");
    ImGui::Text("Background picture from Manuel Tellur / pixelio.de (Image-ID: 642831)");
    ImGui::Text("Moon (Phobos) texture from http://nasa3d.arc.nasa.gov");
    if (ImGui::Button("Exit", ImVec2(40, 20)))
    {
      pDevice->closeDevice();
    }
    ImGui::End();

    GUI.updateTexture(pRenderTextureID, pRenderTarget);

    if (IsFirstLoop)
    {
      ImGui::SetNextWindowPos(ImVec2(300.0f, 200.0f));
      ImGui::SetNextWindowSize(ImVec2(400.0f, 450.0f));
    }
    ImGui::Begin("Moon Window", NULL, ImGuiWindowFlags_ShowBorders);
    ImGui::Text("%.1f FPS", ImGui::GetIO().Framerate);
    ImGui::Image(*pRenderTextureID, ImVec2(384, 300));
    ImGui::BeginGroup();
    ImGui::RadioButton("Left",  &RotationDirection, 1);
    ImGui::RadioButton("Stop",  &RotationDirection, 0);
    ImGui::RadioButton("Right", &RotationDirection, -1);
    ImGui::EndGroup();
    ImGui::SameLine(0.0f, 10.0f);
    ImGui::BeginGroup();
    ImGui::SliderFloat("Speed", &RotPerSec, 0.001f, 0.5f);
    ImGui::SliderFloat("Angle",     &Rotation,  0.0f, 360.0f);
    ImGui::ColorEdit3("Color", Color);
    ImGui::EndGroup();
    ImGui::End();

    pSceneManager->drawAll();
    GUI.drawAll();

    pDriver->endScene();

    u32 const Time = pDevice->getTimer()->getRealTime();
    u32 const DeltaTime = Time - LastTime;
    if (DeltaTime > 0)
    {
      Rotation += (360.0f * RotPerSec * ((float)RotationDirection)) * (DeltaTime / 1000.0f);
      if (Rotation > 360.0f)
      {
        Rotation -= 360.0f;
      }
      else if (Rotation < 0.0f)
      {
        Rotation += 360.0f;
      }
      LastTime = Time;
    }
    pMoon->setRotation(irr::core::vector3df(0,Rotation,0));
    IsFirstLoop = false;

    s32 const FPS = pDriver->getFPS();
    if (FPS != LastFPS)
    {
      LastFPS = FPS;
      core::stringw TempString = L"Using a render target texture with IMGUI - FPS: ";
      TempString += LastFPS;
      pDevice->setWindowCaption(TempString.c_str());
    }
  }

  GUI.deleteTexture(pRenderTextureID);
  pDevice->drop();

}

int main(void)
{
  try
  {
    runScene();
  }
  catch(std::exception &rEx)
  {
    std::cout << rEx.what() << std::flush;
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
  }

  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: macropg_impl.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 19:05:39 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _MACROPG_IMPL_HXX
#define _MACROPG_IMPL_HXX

class _SfxMacroTabPage_Impl
{
public:
                                    _SfxMacroTabPage_Impl( void );
                                    ~_SfxMacroTabPage_Impl();

    String                          maStaticMacroLBLabel;
    PushButton*                     pAssignPB;
    PushButton*                     pDeletePB;
    String*                         pStrEvent;
    String*                         pAssignedMacro;
    ListBox*                        pScriptTypeLB;
    _HeaderTabListBox*              pEventLB;
    SfxConfigGroupListBox_Impl*     pGroupLB;
    FixedText*                      pFT_MacroLBLabel;
    SfxConfigFunctionListBox_Impl*  pMacroLB;

    FixedText*                      pMacroFT;
    String*                         pMacroStr;
    FNGetRangeHdl                   fnGetRange;
    FNGetMacrosOfRangeHdl           fnGetMacroOfRange;

    BOOL                            bReadOnly;
};

#endif
<commit_msg>INTEGRATION: CWS fwk48 (1.2.326); FILE MERGED 2006/09/13 10:42:42 pb 1.2.326.1: fix: #125845# new member: maFillGroupTimer<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: macropg_impl.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-13 09:47:09 $
 *
 *  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 _MACROPG_IMPL_HXX
#define _MACROPG_IMPL_HXX

class _SfxMacroTabPage_Impl
{
public:
    _SfxMacroTabPage_Impl( void );
    ~_SfxMacroTabPage_Impl();

    String                          maStaticMacroLBLabel;
    PushButton*                     pAssignPB;
    PushButton*                     pDeletePB;
    String*                         pStrEvent;
    String*                         pAssignedMacro;
    ListBox*                        pScriptTypeLB;
    _HeaderTabListBox*              pEventLB;
    SfxConfigGroupListBox_Impl*     pGroupLB;
    FixedText*                      pFT_MacroLBLabel;
    SfxConfigFunctionListBox_Impl*  pMacroLB;

    FixedText*                      pMacroFT;
    String*                         pMacroStr;
    FNGetRangeHdl                   fnGetRange;
    FNGetMacrosOfRangeHdl           fnGetMacroOfRange;

    BOOL                            bReadOnly;
    Timer                           maFillGroupTimer;
};

#endif

<|endoftext|>


<commit_before>// RUN: %clang_cc1 -g -triple %itanium_abi_triple -emit-llvm -o - %s | FileCheck %s

// Make sure that clang outputs distinct debug info for a function
// that is inlined twice on the same line. Otherwise it would appear
// as if the function was only inlined once.

#define INLINE inline __attribute__((always_inline))

int i;

INLINE void sum(int a, int b) {
  i = a + b;
}

void noinline(int x, int y) {
  i = x + y;
}

#define CALLS sum(9, 10), sum(11, 12)

inline void inlsum(int t, int u) {
  i = t + u;
}

int main() {
  sum(1, 2), sum(3, 4);
  noinline(5, 6), noinline(7, 8);
  CALLS;
  inlsum(13, 14), inlsum(15, 16);
}

// CHECK-LABEL: @main
// CHECK: = add {{.*}} !dbg [[FIRST_INLINE:![0-9]*]]
// CHECK: = add {{.*}} !dbg [[SECOND_INLINE:![0-9]*]]

// Check that we don't give column information (and thus end up with distinct
// line entries) for two non-inlined calls on the same line.
// CHECK: call {{.*}}noinline{{.*}}({{i32[ ]?[a-z]*}} 5, {{i32[ ]?[a-z]*}} 6), !dbg [[NOINLINE:![0-9]*]]
// CHECK: call {{.*}}noinline{{.*}}({{i32[ ]?[a-z]*}} 7, {{i32[ ]?[a-z]*}} 8), !dbg [[NOINLINE]]

// FIXME: These should be separate locations but because the two calls have the
// same line /and/ column, they get coalesced into a single inlined call by
// accident. We need discriminators or some other changes to LLVM to cope with
// this. (this is, unfortunately, an LLVM test disguised as a Clang test - since
// inlining is forced to happen here). It's possible this could be fixed in
// Clang, but I doubt it'll be the right place for the fix.
// CHECK: = add {{.*}} !dbg [[FIRST_MACRO_INLINE:![0-9]*]]
// CHECK: = add {{.*}} !dbg [[FIRST_MACRO_INLINE]]

// Even if the functions are marked inline but do not get inlined, they
// shouldn't use column information, and thus should be at the same debug
// location.
// CHECK: call {{.*}}inlsum{{.*}}({{i32[ ]?[a-z]*}} 13, {{i32[ ]?[a-z]*}} 14), !dbg [[INL_FIRST:![0-9]*]]
// CHECK: call {{.*}}inlsum{{.*}}({{i32[ ]?[a-z]*}} 15, {{i32[ ]?[a-z]*}} 16), !dbg [[INL_SECOND:![0-9]*]]

// [[FIRST_INLINE]] =
// [[SECOND_INLINE]] =

// FIXME: These should be the same location since the functions appear on the
// same line and were not inlined - they needlessly have column information
// intended to disambiguate inlined calls, which is going to confuse GDB as it
// doesn't cope well with column information.
// [[INL_FIRST]] =
// [[INL_SECOND]] =
<commit_msg>DebugInfo: Remove distinct-call-inlining test case as this is being fixed in LLVM.<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *                                                                       *
 *  I|*j^3Cl|a   "+!*%                  qt          Nd   gW              *
 *  l]{y+l?MM*  !#Wla\NNP               NW          MM   I|              *
 *        PW    ?E|    tWg              Wg  sC!     AW           ~@v~    *
 *       NC     ?M!    yN|  WW     MK   MW@K1Y%M@   RM   #Q    QP@tim    *
 *     CM|      |WQCljAE|   MD     Mg   RN     cM~  NM   WQ   MQ         *
 *    #M        aQ?         MW     M3   Mg      Q(  HQ   YR  IM|         *
 *   Dq         {Ql         MH    iMX   Mg     MM   QP   QM   Eg         *
 * !EWNaPRag2$  +M"          $WNaHaN%   MQE$%EXW    QQ   CM    %M%a$D    *
 *                                                                       *
 *               Website: https://github.com/zpublic/zpublic             *
 *                                                                       *
 ************************************************************************/

/**
 * @file
 * @brief ļͼ
 */

#pragma once
#include "win_utils_header.h"
#include <ShlObj.h>

namespace zl
{
namespace WinUtils
{

    class ZLFileIcon
    {
    public:
        ZLFileIcon(HICON hIcon = NULL) : m_icon(hIcon) {}
        virtual ~ZLFileIcon() { reset(); }
        void reset()
        {
            if (m_icon != NULL)
            {
                ::DestroyIcon(m_icon);
                m_icon = NULL;
            }
        }
        BOOL Load(LPCTSTR szFilePath, BOOL bLargeIcon = TRUE)
        {
            reset();
            BOOL bRet = FALSE;
            SHFILEINFO fileInfo = {0};
            DWORD dwStyle = SHGFI_ICON | SHGFI_USEFILEATTRIBUTES;
            if (bLargeIcon)
                dwStyle |= SHGFI_LARGEICON;
            else
                dwStyle |= SHGFI_SMALLICON;

            if (::SHGetFileInfo(szFilePath, 0, &fileInfo, sizeof(fileInfo), dwStyle))
            {
                m_icon = fileInfo.hIcon;
                bRet = TRUE;
            }
            return bRet;
        }
        BOOL LoadEx(LPCTSTR szFilePath, UINT uSize = 48, UINT uIndex = 0)
        {
            reset();
            if (::SHDefExtractIcon(szFilePath, uIndex, 0, &m_icon, NULL, uSize) == S_OK)
            {
                return TRUE;
            }
            else
            {
                return FALSE;
            }
        }
        HICON GetHandle()
        {
            return m_icon;
        }

    protected:
        HICON m_icon;
    };

}
}
<commit_msg>*file_icon文件注释<commit_after>/*************************************************************************
 *                                                                       *
 *  I|*j^3Cl|a   "+!*%                  qt          Nd   gW              *
 *  l]{y+l?MM*  !#Wla\NNP               NW          MM   I|              *
 *        PW    ?E|    tWg              Wg  sC!     AW           ~@v~    *
 *       NC     ?M!    yN|  WW     MK   MW@K1Y%M@   RM   #Q    QP@tim    *
 *     CM|      |WQCljAE|   MD     Mg   RN     cM~  NM   WQ   MQ         *
 *    #M        aQ?         MW     M3   Mg      Q(  HQ   YR  IM|         *
 *   Dq         {Ql         MH    iMX   Mg     MM   QP   QM   Eg         *
 * !EWNaPRag2$  +M"          $WNaHaN%   MQE$%EXW    QQ   CM    %M%a$D    *
 *                                                                       *
 *               Website: https://github.com/zpublic/zpublic             *
 *                                                                       *
 ************************************************************************/

/**
 * @file
 * @brief ļͼ
 */

#pragma once
#include "win_utils_header.h"
#include <ShlObj.h>

namespace zl
{
namespace WinUtils
{
	/**
	* @brief ȡļͼ
	*/
    class ZLFileIcon
    {
    public:
        ZLFileIcon(HICON hIcon = NULL) : m_icon(hIcon) {}
        virtual ~ZLFileIcon() { reset(); }
        void reset()
        {
            if (m_icon != NULL)
            {
                ::DestroyIcon(m_icon);
                m_icon = NULL;
            }
        }
		/**
		 * @brief ȡļͼ
		 * @param[in]   szFilePath ļ·
		 * @param[in]   bLargeIcon ǷΪͼ꣬ĬTRUE
		 * @return ɹTRUEʧܷFALSE
		 * @see SHGetFileInfo
		 */
        BOOL Load(LPCTSTR szFilePath, BOOL bLargeIcon = TRUE)
        {
            reset();
            BOOL bRet = FALSE;
            SHFILEINFO fileInfo = {0};
            DWORD dwStyle = SHGFI_ICON | SHGFI_USEFILEATTRIBUTES;
            if (bLargeIcon)
                dwStyle |= SHGFI_LARGEICON;
            else
                dwStyle |= SHGFI_SMALLICON;

            if (::SHGetFileInfo(szFilePath, 0, &fileInfo, sizeof(fileInfo), dwStyle))
            {
                m_icon = fileInfo.hIcon;
                bRet = TRUE;
            }
            return bRet;
        }
		/**
		 * @brief ļȡͼ
		 * @param[in]   szFilePath ļ·
		 * @param[in]   uSize ͼĴС
		 * @param[in]   uIndex szFilePathļͼ
		 * @return ɹTRUEʧܷFALSE
		 * @see SHDefExtractIcon
		 */
        BOOL LoadEx(LPCTSTR szFilePath, UINT uSize = 48, UINT uIndex = 0)
        {
            reset();
            if (::SHDefExtractIcon(szFilePath, uIndex, 0, &m_icon, NULL, uSize) == S_OK)
            {
                return TRUE;
            }
            else
            {
                return FALSE;
            }
        }
        HICON GetHandle()
        {
            return m_icon;
        }

    protected:
        HICON m_icon;
    };

}
}
<|endoftext|>


<commit_before>#ifdef __linux__
# include <sys/sendfile.h>
#endif

#include <cerrno>
#include <algorithm>
#include <limits>

#include "direct-fd-stream.hh"
#include "copy.hh"

namespace mimosa
{
  namespace stream
  {
    DirectFdStream::DirectFdStream(int fd, bool own_fd)
      : fd_(fd),
        own_fd_(own_fd),
        mode_(0)
    {
    }

    DirectFdStream::~DirectFdStream()
    {
      if (own_fd_ && fd_ >= 0)
      {
        ::close(fd_);
        fd_ = -1;
      }
    }

    int64_t
    DirectFdStream::write(const char * data, uint64_t nbytes)
    {
      return ::write(fd_, data, nbytes);
    }

    int64_t
    DirectFdStream::writev(const struct iovec *iov, int iovcnt)
    {
      return ::writev(fd_, iov, iovcnt < IOV_MAX ? iovcnt : IOV_MAX);
    }

    int64_t
    DirectFdStream::read(char * data, uint64_t nbytes)
    {
      return ::read(fd_, data, nbytes);
    }

    int64_t
    DirectFdStream::readv(const struct iovec *iov, int iovcnt)
    {
      return ::readv(fd_, iov, iovcnt < IOV_MAX ? iovcnt : IOV_MAX);
    }

    void
    DirectFdStream::close()
    {
      assert(own_fd_);
      if (own_fd_ && fd_ >= 0)
      {
        int fd = fd_;
        fd_    = -1;
        ::close(fd);
      }
    }

    bool
    DirectFdStream::stat() const
    {
      struct ::stat st;
      if (::fstat(fd_, &st))
        return false;
      mode_ = st.st_mode;
      return true;
    }

#ifdef __linux__
    static int64_t copySendfile(DirectFdStream & input,
                                DirectFdStream & output,
                                int64_t          max_bytes)
    {
      int64_t total = 0;

      while (total < max_bytes || max_bytes == 0) {
        int64_t limit;

        if (max_bytes == 0)
          limit = std::numeric_limits<int64_t>::max();
        else
          limit = max_bytes - total;

        ssize_t bytes = ::sendfile(output.fd(), input.fd(), nullptr, limit);
        if (bytes <= 0) {
          if (errno == EAGAIN)
            continue;
          return total;
        }
        total += bytes;
      }
      return total;
    }

    static int64_t copySplice(DirectFdStream & input,
                              DirectFdStream & output,
                              int64_t          max_bytes)
    {
      int64_t total = 0;

      while (total < max_bytes || max_bytes == 0) {
        int64_t limit;

        if (max_bytes == 0)
          limit = std::numeric_limits<int64_t>::max();
        else
          limit = max_bytes - total;

        ssize_t bytes = ::splice(input.fd(), nullptr, output.fd(), nullptr, limit, 0);
        if (bytes <= 0) {
          if (errno == EAGAIN)
            continue;
          return total;
        }
        total += bytes;
      }
      return total;
    }

    static int64_t copySpliceAny(DirectFdStream & input,
                                 DirectFdStream & output,
                                 int64_t          max_bytes)
    {
      int     pfd[2];
      int64_t total = 0;

      if (::pipe2(pfd, O_CLOEXEC | O_NONBLOCK))
        return -1;

      while (total < max_bytes || max_bytes == 0) {
        int64_t limit;

        if (max_bytes == 0)
          limit = std::numeric_limits<int64_t>::max();
        else
          limit = max_bytes - total;

        ssize_t rbytes = ::splice(input.fd(), nullptr, pfd[1], nullptr, limit, 0);
        if (bytes <= 0) {
          if (errno == EAGAIN)
            continue;
          goto end;
        }

        while (rbytes > 0) {
          ssize_t wbytes = ::splice(pfd[0], nullptr, output.fd(), nullptr, rbytes, 0);
          if (wbytes < 0) {
            if (errno == EAGAIN)
              continue;
            total = -1;
            goto end;
          }

          total  += wbytes;
          rbytes -= wbytes;
        }
      }

      end:
      ::close(pfd[0]);
      ::close(pfd[1]);
      return total;
    }
#endif // __linux__

    int64_t copy(DirectFdStream & input,
                 DirectFdStream & output,
                 int64_t          max_bytes)
    {

#ifdef __linux__
      // disk to fd
      if (S_ISREG(input.fdMode()))
        return copySendfile(input, output, max_bytes);

      // from a pipe or to a pipe
      if (S_ISFIFO(input.fdMode()) || S_ISFIFO(output.fdMode()))
        return copySplice(input, output, max_bytes);

      // splice: input -> pipe -> output
      if (max_bytes == 0 || max_bytes > 4096)
        return copySpliceAny(input, output, max_bytes);
#endif // __linux__

      // user copy
      return copy(static_cast<Stream &> (input),
                  static_cast<Stream &> (output),
                  max_bytes);
    }
  }
}
<commit_msg>Fix splice copy<commit_after>#ifdef __linux__
# include <sys/sendfile.h>
#endif

#include <cerrno>
#include <algorithm>
#include <limits>

#include "direct-fd-stream.hh"
#include "copy.hh"

namespace mimosa
{
  namespace stream
  {
    DirectFdStream::DirectFdStream(int fd, bool own_fd)
      : fd_(fd),
        own_fd_(own_fd),
        mode_(0)
    {
    }

    DirectFdStream::~DirectFdStream()
    {
      if (own_fd_ && fd_ >= 0)
      {
        ::close(fd_);
        fd_ = -1;
      }
    }

    int64_t
    DirectFdStream::write(const char * data, uint64_t nbytes)
    {
      return ::write(fd_, data, nbytes);
    }

    int64_t
    DirectFdStream::writev(const struct iovec *iov, int iovcnt)
    {
      return ::writev(fd_, iov, iovcnt < IOV_MAX ? iovcnt : IOV_MAX);
    }

    int64_t
    DirectFdStream::read(char * data, uint64_t nbytes)
    {
      return ::read(fd_, data, nbytes);
    }

    int64_t
    DirectFdStream::readv(const struct iovec *iov, int iovcnt)
    {
      return ::readv(fd_, iov, iovcnt < IOV_MAX ? iovcnt : IOV_MAX);
    }

    void
    DirectFdStream::close()
    {
      assert(own_fd_);
      if (own_fd_ && fd_ >= 0)
      {
        int fd = fd_;
        fd_    = -1;
        ::close(fd);
      }
    }

    bool
    DirectFdStream::stat() const
    {
      struct ::stat st;
      if (::fstat(fd_, &st))
        return false;
      mode_ = st.st_mode;
      return true;
    }

#ifdef __linux__
    static int64_t copySendfile(DirectFdStream & input,
                                DirectFdStream & output,
                                int64_t          max_bytes)
    {
      int64_t total = 0;

      while (total < max_bytes || max_bytes == 0) {
        int64_t limit;

        if (max_bytes == 0)
          limit = std::numeric_limits<int64_t>::max();
        else
          limit = max_bytes - total;

        ssize_t bytes = ::sendfile(output.fd(), input.fd(), nullptr, limit);
        if (bytes <= 0) {
          if (errno == EAGAIN)
            continue;
          return total;
        }
        total += bytes;
      }
      return total;
    }

    static int64_t copySplice(DirectFdStream & input,
                              DirectFdStream & output,
                              int64_t          max_bytes)
    {
      int64_t total = 0;

      while (total < max_bytes || max_bytes == 0) {
        int64_t limit;

        if (max_bytes == 0)
          limit = std::numeric_limits<int64_t>::max();
        else
          limit = max_bytes - total;

        ssize_t bytes = ::splice(input.fd(), nullptr, output.fd(), nullptr, limit, 0);
        if (bytes <= 0) {
          if (errno == EAGAIN)
            continue;
          return total;
        }
        total += bytes;
      }
      return total;
    }

    static int64_t copySpliceAny(DirectFdStream & input,
                                 DirectFdStream & output,
                                 int64_t          max_bytes)
    {
      int     pfd[2];
      int64_t total = 0;

      if (::pipe2(pfd, O_CLOEXEC | O_NONBLOCK))
        return -1;

      while (total < max_bytes || max_bytes == 0) {
        int64_t limit;

        if (max_bytes == 0)
          limit = std::numeric_limits<int64_t>::max();
        else
          limit = max_bytes - total;

        ssize_t rbytes = ::splice(input.fd(), nullptr, pfd[1], nullptr, limit, 0);
        if (rbytes <= 0) {
          if (errno == EAGAIN)
            continue;
          goto end;
        }

        while (rbytes > 0) {
          ssize_t wbytes = ::splice(pfd[0], nullptr, output.fd(), nullptr, rbytes, 0);
          if (wbytes < 0) {
            if (errno == EAGAIN)
              continue;
            total = -1;
            goto end;
          }

          total  += wbytes;
          rbytes -= wbytes;
        }
      }

      end:
      ::close(pfd[0]);
      ::close(pfd[1]);
      return total;
    }
#endif // __linux__

    int64_t copy(DirectFdStream & input,
                 DirectFdStream & output,
                 int64_t          max_bytes)
    {

#ifdef __linux__
      // disk to fd
      if (S_ISREG(input.fdMode()))
        return copySendfile(input, output, max_bytes);

      // from a pipe or to a pipe
      if (S_ISFIFO(input.fdMode()) || S_ISFIFO(output.fdMode()))
        return copySplice(input, output, max_bytes);

      // splice: input -> pipe -> output
      if (max_bytes == 0 || max_bytes > 4096)
        return copySpliceAny(input, output, max_bytes);
#endif // __linux__

      // user copy
      return copy(static_cast<Stream &> (input),
                  static_cast<Stream &> (output),
                  max_bytes);
    }
  }
}
<|endoftext|>


<commit_before>// Copyright 2013 The Flutter 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 "flutter/shell/common/shell_io_manager.h"

#include "flutter/fml/message_loop.h"
#include "flutter/shell/common/context_options.h"
#include "third_party/skia/include/gpu/gl/GrGLInterface.h"

namespace flutter {

sk_sp<GrDirectContext> ShellIOManager::CreateCompatibleResourceLoadingContext(
    GrBackend backend,
    sk_sp<const GrGLInterface> gl_interface) {
#if !OS_FUCHSIA && SK_GL
  if (backend != GrBackend::kOpenGL_GrBackend) {
    return nullptr;
  }

  const auto options = MakeDefaultContextOptions(ContextType::kResource);

  if (auto context = GrDirectContext::MakeGL(gl_interface, options)) {
    // Do not cache textures created by the image decoder.  These textures
    // should be deleted when they are no longer referenced by an SkImage.
    context->setResourceCacheLimit(0);
    return context;
  }
#endif  // !OS_FUCHSIA && SK_GL

  return nullptr;
}

ShellIOManager::ShellIOManager(
    sk_sp<GrDirectContext> resource_context,
    std::shared_ptr<const fml::SyncSwitch> is_gpu_disabled_sync_switch,
    fml::RefPtr<fml::TaskRunner> unref_queue_task_runner,
    std::shared_ptr<impeller::Context> impeller_context,
    fml::TimeDelta unref_queue_drain_delay)
    : resource_context_(std::move(resource_context)),
      resource_context_weak_factory_(
          resource_context_
              ? std::make_unique<fml::WeakPtrFactory<GrDirectContext>>(
                    resource_context_.get())
              : nullptr),
      unref_queue_(fml::MakeRefCounted<flutter::SkiaUnrefQueue>(
          std::move(unref_queue_task_runner),
          unref_queue_drain_delay,
          resource_context_)),
      is_gpu_disabled_sync_switch_(is_gpu_disabled_sync_switch),
      impeller_context_(std::move(impeller_context)),
      weak_factory_(this) {
  if (!resource_context_) {
#ifndef OS_FUCHSIA
    FML_DLOG(WARNING) << "The IO manager was initialized without a resource "
                         "context. Async texture uploads will be disabled. "
                         "Expect performance degradation.";
#endif  // OS_FUCHSIA
  }
}

ShellIOManager::~ShellIOManager() {
  // Last chance to drain the IO queue as the platform side reference to the
  // underlying OpenGL context may be going away.
  is_gpu_disabled_sync_switch_->Execute(
      fml::SyncSwitch::Handlers().SetIfFalse([&] { unref_queue_->Drain(); }));
}

void ShellIOManager::NotifyResourceContextAvailable(
    sk_sp<GrDirectContext> resource_context) {
  // The resource context needs to survive as long as we have Dart objects
  // referencing. We shouldn't ever need to replace it if we have one - unless
  // we've somehow shut down the Dart VM and started a new one fresh.
  if (!resource_context_) {
    UpdateResourceContext(std::move(resource_context));
  }
}

void ShellIOManager::UpdateResourceContext(
    sk_sp<GrDirectContext> resource_context) {
  resource_context_ = std::move(resource_context);
  resource_context_weak_factory_ =
      resource_context_
          ? std::make_unique<fml::WeakPtrFactory<GrDirectContext>>(
                resource_context_.get())
          : nullptr;
  unref_queue_->UpdateResourceContext(resource_context_);
}

fml::WeakPtr<ShellIOManager> ShellIOManager::GetWeakPtr() {
  return weak_factory_.GetWeakPtr();
}

// |IOManager|
fml::WeakPtr<GrDirectContext> ShellIOManager::GetResourceContext() const {
  return resource_context_weak_factory_
             ? resource_context_weak_factory_->GetWeakPtr()
             : fml::WeakPtr<GrDirectContext>();
}

// |IOManager|
fml::RefPtr<flutter::SkiaUnrefQueue> ShellIOManager::GetSkiaUnrefQueue() const {
  return unref_queue_;
}

// |IOManager|
fml::WeakPtr<IOManager> ShellIOManager::GetWeakIOManager() const {
  return weak_factory_.GetWeakPtr();
}

// |IOManager|
std::shared_ptr<const fml::SyncSwitch>
ShellIOManager::GetIsGpuDisabledSyncSwitch() {
  return is_gpu_disabled_sync_switch_;
}

// |IOManager|
std::shared_ptr<impeller::Context> ShellIOManager::GetImpellerContext() const {
  return impeller_context_;
}

}  // namespace flutter
<commit_msg>Remove IO manager Fuchsia workaround. (#34959)<commit_after>// Copyright 2013 The Flutter 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 "flutter/shell/common/shell_io_manager.h"

#include "flutter/fml/message_loop.h"
#include "flutter/shell/common/context_options.h"
#include "third_party/skia/include/gpu/gl/GrGLInterface.h"

namespace flutter {

sk_sp<GrDirectContext> ShellIOManager::CreateCompatibleResourceLoadingContext(
    GrBackend backend,
    sk_sp<const GrGLInterface> gl_interface) {
#if SK_GL
  if (backend != GrBackend::kOpenGL_GrBackend) {
    return nullptr;
  }

  const auto options = MakeDefaultContextOptions(ContextType::kResource);

  if (auto context = GrDirectContext::MakeGL(gl_interface, options)) {
    // Do not cache textures created by the image decoder.  These textures
    // should be deleted when they are no longer referenced by an SkImage.
    context->setResourceCacheLimit(0);
    return context;
  }
#endif  // SK_GL

  return nullptr;
}

ShellIOManager::ShellIOManager(
    sk_sp<GrDirectContext> resource_context,
    std::shared_ptr<const fml::SyncSwitch> is_gpu_disabled_sync_switch,
    fml::RefPtr<fml::TaskRunner> unref_queue_task_runner,
    std::shared_ptr<impeller::Context> impeller_context,
    fml::TimeDelta unref_queue_drain_delay)
    : resource_context_(std::move(resource_context)),
      resource_context_weak_factory_(
          resource_context_
              ? std::make_unique<fml::WeakPtrFactory<GrDirectContext>>(
                    resource_context_.get())
              : nullptr),
      unref_queue_(fml::MakeRefCounted<flutter::SkiaUnrefQueue>(
          std::move(unref_queue_task_runner),
          unref_queue_drain_delay,
          resource_context_)),
      is_gpu_disabled_sync_switch_(is_gpu_disabled_sync_switch),
      impeller_context_(std::move(impeller_context)),
      weak_factory_(this) {
  if (!resource_context_) {
#ifndef OS_FUCHSIA
    FML_DLOG(WARNING) << "The IO manager was initialized without a resource "
                         "context. Async texture uploads will be disabled. "
                         "Expect performance degradation.";
#endif  // OS_FUCHSIA
  }
}

ShellIOManager::~ShellIOManager() {
  // Last chance to drain the IO queue as the platform side reference to the
  // underlying OpenGL context may be going away.
  is_gpu_disabled_sync_switch_->Execute(
      fml::SyncSwitch::Handlers().SetIfFalse([&] { unref_queue_->Drain(); }));
}

void ShellIOManager::NotifyResourceContextAvailable(
    sk_sp<GrDirectContext> resource_context) {
  // The resource context needs to survive as long as we have Dart objects
  // referencing. We shouldn't ever need to replace it if we have one - unless
  // we've somehow shut down the Dart VM and started a new one fresh.
  if (!resource_context_) {
    UpdateResourceContext(std::move(resource_context));
  }
}

void ShellIOManager::UpdateResourceContext(
    sk_sp<GrDirectContext> resource_context) {
  resource_context_ = std::move(resource_context);
  resource_context_weak_factory_ =
      resource_context_
          ? std::make_unique<fml::WeakPtrFactory<GrDirectContext>>(
                resource_context_.get())
          : nullptr;
  unref_queue_->UpdateResourceContext(resource_context_);
}

fml::WeakPtr<ShellIOManager> ShellIOManager::GetWeakPtr() {
  return weak_factory_.GetWeakPtr();
}

// |IOManager|
fml::WeakPtr<GrDirectContext> ShellIOManager::GetResourceContext() const {
  return resource_context_weak_factory_
             ? resource_context_weak_factory_->GetWeakPtr()
             : fml::WeakPtr<GrDirectContext>();
}

// |IOManager|
fml::RefPtr<flutter::SkiaUnrefQueue> ShellIOManager::GetSkiaUnrefQueue() const {
  return unref_queue_;
}

// |IOManager|
fml::WeakPtr<IOManager> ShellIOManager::GetWeakIOManager() const {
  return weak_factory_.GetWeakPtr();
}

// |IOManager|
std::shared_ptr<const fml::SyncSwitch>
ShellIOManager::GetIsGpuDisabledSyncSwitch() {
  return is_gpu_disabled_sync_switch_;
}

// |IOManager|
std::shared_ptr<impeller::Context> ShellIOManager::GetImpellerContext() const {
  return impeller_context_;
}

}  // namespace flutter
<|endoftext|>


<commit_before>// RUN: %check_clang_tidy %s misc-misplaced-const %t

typedef int plain_i;
typedef int *ip;
typedef const int *cip;

void func() {
  if (const int *i = 0)
    ;
  if (const plain_i *i = 0)
    ;
  if (const cip i = 0)
    ;

  // CHECK-MESSAGES: :[[@LINE+1]]:16: warning: 'i' declared with a const-qualified typedef type; results in the type being 'int *const' instead of 'const int *'
  if (const ip i = 0)
    ;
}

template <typename Ty>
struct S {
  const Ty *i;
  const Ty &i2;
};

template struct S<int>;
template struct S<ip>; // ok
template struct S<cip>;
template struct S<int *>; // ok

struct T {
  typedef void (T::*PMF)();

  void f() {
    const PMF val = &T::f; // ok
  }
};
<commit_msg>Fixing a build bot issue with duplicate explicit instantiations.<commit_after>// RUN: %check_clang_tidy %s misc-misplaced-const %t

typedef int plain_i;
typedef int *ip;
typedef const int *cip;

void func() {
  if (const int *i = 0)
    ;
  if (const plain_i *i = 0)
    ;
  if (const cip i = 0)
    ;

  // CHECK-MESSAGES: :[[@LINE+1]]:16: warning: 'i' declared with a const-qualified typedef type; results in the type being 'int *const' instead of 'const int *'
  if (const ip i = 0)
    ;
}

template <typename Ty>
struct S {
  const Ty *i;
  const Ty &i2;
};

template struct S<int>;
template struct S<ip>; // ok
template struct S<cip>;

template <typename Ty>
struct U {
  const Ty *i;
  const Ty &i2;
};

template struct U<int *>; // ok

struct T {
  typedef void (T::*PMF)();

  void f() {
    const PMF val = &T::f; // ok
  }
};
<|endoftext|>