<commit_before>/*
 * Copyright 2016 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "Test.h"
#include "SkHalf.h"
#include "SkRasterPipeline.h"

DEF_TEST(SkRasterPipeline, r) {
    // Build and run a simple pipeline to exercise SkRasterPipeline,
    // drawing 50% transparent blue over opaque red in half-floats.
    uint64_t red  = 0x3c00000000003c00ull,
             blue = 0x3800380000000000ull,
             result;

    void* load_s_ctx = &blue;
    void* load_d_ctx = &red;
    void* store_ctx  = &result;

    SkRasterPipeline_<256> p;
    p.append(SkRasterPipeline::load_f16, &load_s_ctx);
    p.append(SkRasterPipeline::move_src_dst);
    p.append(SkRasterPipeline::load_f16, &load_d_ctx);
    p.append(SkRasterPipeline::swap);
    p.append(SkRasterPipeline::srcover);
    p.append(SkRasterPipeline::store_f16, &store_ctx);
    p.run(0,1);

    // We should see half-intensity magenta.
    REPORTER_ASSERT(r, ((result >>  0) & 0xffff) == 0x3800);
    REPORTER_ASSERT(r, ((result >> 16) & 0xffff) == 0x0000);
    REPORTER_ASSERT(r, ((result >> 32) & 0xffff) == 0x3800);
    REPORTER_ASSERT(r, ((result >> 48) & 0xffff) == 0x3c00);
}

DEF_TEST(SkRasterPipeline_empty, r) {
    // No asserts... just a test that this is safe to run.
    SkRasterPipeline_<256> p;
    p.run(0,20);
}

DEF_TEST(SkRasterPipeline_nonsense, r) {
    // No asserts... just a test that this is safe to run and terminates.
    // srcover() calls st->next(); this makes sure we've always got something there to call.
    SkRasterPipeline_<256> p;
    p.append(SkRasterPipeline::srcover);
    p.run(0,20);
}

DEF_TEST(SkRasterPipeline_JIT, r) {
    // This tests a couple odd corners that a JIT backend can stumble over.

    uint32_t buf[72] = {
         0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
         1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12,
        13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
         0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
         0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
         0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    };

    const uint32_t* src = buf +  0;
    uint32_t*       dst = buf + 36;

    // Copy buf[x] to buf[x+36] for x in [15,35).
    SkRasterPipeline_<256> p;
    p.append(SkRasterPipeline:: load_8888, &src);
    p.append(SkRasterPipeline::store_8888, &dst);
    p.run(15, 20);

    for (int i = 0; i < 36; i++) {
        if (i < 15 || i == 35) {
            REPORTER_ASSERT(r, dst[i] == 0);
        } else {
            REPORTER_ASSERT(r, dst[i] == (uint32_t)(i - 11));
        }
    }
}
<commit_msg>Add tests for tail handling in SkJumper.<commit_after>/*
 * Copyright 2016 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "Test.h"
#include "SkHalf.h"
#include "SkRasterPipeline.h"

DEF_TEST(SkRasterPipeline, r) {
    // Build and run a simple pipeline to exercise SkRasterPipeline,
    // drawing 50% transparent blue over opaque red in half-floats.
    uint64_t red  = 0x3c00000000003c00ull,
             blue = 0x3800380000000000ull,
             result;

    void* load_s_ctx = &blue;
    void* load_d_ctx = &red;
    void* store_ctx  = &result;

    SkRasterPipeline_<256> p;
    p.append(SkRasterPipeline::load_f16, &load_s_ctx);
    p.append(SkRasterPipeline::move_src_dst);
    p.append(SkRasterPipeline::load_f16, &load_d_ctx);
    p.append(SkRasterPipeline::swap);
    p.append(SkRasterPipeline::srcover);
    p.append(SkRasterPipeline::store_f16, &store_ctx);
    p.run(0,1);

    // We should see half-intensity magenta.
    REPORTER_ASSERT(r, ((result >>  0) & 0xffff) == 0x3800);
    REPORTER_ASSERT(r, ((result >> 16) & 0xffff) == 0x0000);
    REPORTER_ASSERT(r, ((result >> 32) & 0xffff) == 0x3800);
    REPORTER_ASSERT(r, ((result >> 48) & 0xffff) == 0x3c00);
}

DEF_TEST(SkRasterPipeline_empty, r) {
    // No asserts... just a test that this is safe to run.
    SkRasterPipeline_<256> p;
    p.run(0,20);
}

DEF_TEST(SkRasterPipeline_nonsense, r) {
    // No asserts... just a test that this is safe to run and terminates.
    // srcover() calls st->next(); this makes sure we've always got something there to call.
    SkRasterPipeline_<256> p;
    p.append(SkRasterPipeline::srcover);
    p.run(0,20);
}

DEF_TEST(SkRasterPipeline_JIT, r) {
    // This tests a couple odd corners that a JIT backend can stumble over.

    uint32_t buf[72] = {
         0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
         1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12,
        13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
         0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
         0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
         0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    };

    const uint32_t* src = buf +  0;
    uint32_t*       dst = buf + 36;

    // Copy buf[x] to buf[x+36] for x in [15,35).
    SkRasterPipeline_<256> p;
    p.append(SkRasterPipeline:: load_8888, &src);
    p.append(SkRasterPipeline::store_8888, &dst);
    p.run(15, 20);

    for (int i = 0; i < 36; i++) {
        if (i < 15 || i == 35) {
            REPORTER_ASSERT(r, dst[i] == 0);
        } else {
            REPORTER_ASSERT(r, dst[i] == (uint32_t)(i - 11));
        }
    }
}

static uint16_t h(float f) {
    // Remember, a float is 1-8-23 (sign-exponent-mantissa) with 127 exponent bias.
    uint32_t sem;
    memcpy(&sem, &f, sizeof(sem));
    uint32_t s  = sem & 0x80000000,
             em = sem ^ s;

    // Convert to 1-5-10 half with 15 bias, flushing denorm halfs (including zero) to zero.
    auto denorm = (int32_t)em < 0x38800000;  // I32 comparison is often quicker, and always safe
    // here.
    return denorm ? SkTo<uint16_t>(0)
                  : SkTo<uint16_t>((s>>16) + (em>>13) - ((127-15)<<10));
}

static uint16_t n(uint16_t x) {
    return (x<<8) | (x>>8);
}

static float a(uint16_t x) {
    return (1/65535.0f) * x;
}

DEF_TEST(SkRasterPipeline_tail, r) {
    {
        float data[][4] = {
            {00, 01, 02, 03},
            {10, 11, 12, 13},
            {20, 21, 22, 23},
            {30, 31, 32, 33},
        };

        float buffer[4][4];
        float* src = &data[0][0];
        float* dst = &buffer[0][0];

        for (unsigned i = 0; i < 4; i++) {
            memset(buffer, 0xff, sizeof(buffer));
            SkRasterPipeline_<256> p;
            p.append(SkRasterPipeline::load_f32, &src);
            p.append(SkRasterPipeline::store_f32, &dst);
            p.run(0, i % 4);
            for (unsigned j = 0; j < i; j++) {
                REPORTER_ASSERT(r,
                                !memcmp(&data[j][0], &buffer[j][0], sizeof(buffer[j])));
            }
            for (int j = i; j < 4; j++) {
                for (auto f : buffer[j]) {
                    REPORTER_ASSERT(r, SkScalarIsNaN(f));
                }
            }
        }
    }

    {
        uint16_t data[][4] = {
            {h(00), h(01), h(02), h(03)},
            {h(10), h(11), h(12), h(13)},
            {h(20), h(21), h(22), h(23)},
            {h(30), h(31), h(32), h(33)},
        };
        uint16_t buffer[4][4];
        uint16_t* src = &data[0][0];
        uint16_t* dst = &buffer[0][0];

        for (unsigned i = 0; i < 4; i++) {
            memset(buffer, 0xff, sizeof(buffer));
            SkRasterPipeline_<256> p;
            p.append(SkRasterPipeline::load_f16, &src);
            p.append(SkRasterPipeline::store_f16, &dst);
            p.run(0, i % 4);
            for (unsigned j = 0; j < i; j++) {
                REPORTER_ASSERT(r,
                                !memcmp(&data[j][0], &buffer[j][0], sizeof(buffer[j])));
            }
            for (int j = i; j < 4; j++) {
                for (auto f : buffer[j]) {
                    REPORTER_ASSERT(r, f == 0xffff);
                }
            }
        }
    }

    {
        uint16_t data[][3] = {
            {n(00), n(01), n(02)},
            {n(10), n(11), n(12)},
            {n(20), n(21), n(22)},
            {n(30), n(31), n(32)}
        };

        float answer[][4] = {
            {a(00), a(01), a(02), 1.0f},
            {a(10), a(11), a(12), 1.0f},
            {a(20), a(21), a(22), 1.0f},
            {a(30), a(31), a(32), 1.0f}
        };

        float buffer[4][4];
        uint16_t* src = &data[0][0];
        float* dst = &buffer[0][0];

        for (unsigned i = 0; i < 4; i++) {
            memset(buffer, 0xff, sizeof(buffer));
            SkRasterPipeline_<256> p;
            p.append(SkRasterPipeline::load_rgb_u16_be, &src);
            p.append(SkRasterPipeline::store_f32, &dst);
            p.run(0, i % 4);
            for (unsigned j = 0; j < i; j++) {
                for (unsigned k = 0; k < 4; k++) {
                    if (buffer[j][k] != answer[j][k]) {
                        ERRORF(r, "(%u, %u) - a: %g r: %g\n", j, k, answer[j][k], buffer[j][k]);
                    }
                }
            }
            for (int j = i; j < 4; j++) {
                for (auto f : buffer[j]) {
                    REPORTER_ASSERT(r, SkScalarIsNaN(f));
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>// $Id$

//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project        *
//* ALICE Experiment at CERN, All rights reserved.                         *
//*                                                                        *
//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
//*                  for The ALICE HLT Project.                            *
//*                                                                        *
//* Permission to use, copy, modify and distribute this software and its   *
//* documentation strictly for non-commercial purposes is hereby granted   *
//* without fee, provided that the above copyright notice appears in all   *
//* copies and that both the copyright notice and this permission notice   *
//* appear in the supporting documentation. The authors make no claims     *
//* about the suitability of this software for any purpose. It is          *
//* provided "as is" without express or implied warranty.                  *
//**************************************************************************

/** @file   AliHLTReadoutListDumpComponent.cxx
    @author Matthias Richter
    @date
    @brief  Base class for writer components to store data in a ROOT file

                                                                          */

#include "AliHLTReadoutListDumpComponent.h"
#include "AliHLTTriggerDecision.h"
#include "AliHLTCTPData.h"
#include "TH1I.h"
#include "TH2I.h"
#include "TString.h"
#include "TFile.h"
#include "TSystem.h"

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTReadoutListDumpComponent)

AliHLTReadoutListDumpComponent::AliHLTReadoutListDumpComponent()
  : AliHLTFileWriter()
  , fMode(AliHLTReadoutListDumpComponent::kModeBinaryList)
  , fBitsHisto(NULL)
  , fBitsVsCTP(NULL)
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}

AliHLTReadoutListDumpComponent::~AliHLTReadoutListDumpComponent()
{
  // see header file for class documentation
}

int AliHLTReadoutListDumpComponent::InitWriter()
{
  // see header file for class documentation
  int iResult=0;
  fBitsHisto=CreateReadoutListHistogram();
  fBitsVsCTP=CreateReadoutListVsCTPHistogram();
  if (!fBitsHisto || !fBitsVsCTP) return -ENOMEM;

  return iResult;
}

int AliHLTReadoutListDumpComponent::CloseWriter()
{
  // see header file for class documentation
  TString filename=GetDirectory();
  if (!filename.IsNull() && !filename.EndsWith("/")) filename+="/";
  filename+=fBitsHisto->GetName();
  filename+="_";
  filename+=GetRunNo();
  filename+=".root";

  TFile out(filename, "RECREATE");
  fBitsHisto->Write();
  fBitsVsCTP->Write();
  out.Close();

  delete fBitsHisto;
  fBitsHisto=NULL;
  delete fBitsVsCTP;
  fBitsVsCTP=NULL;
  return 0;
}

int AliHLTReadoutListDumpComponent::DumpEvent( const AliHLTComponentEventData& /*evtData*/,
					    const AliHLTComponentBlockData* /*blocks*/,
					    AliHLTComponentTriggerData& trigData )
{
  // see header file for class documentation
  int iResult=0;
  if (!IsDataEvent()) return 0;

  if (fMode==AliHLTReadoutListDumpComponent::kModeBinaryList) {
    const AliHLTComponentDataType hltrdlstdt=AliHLTComponentDataTypeInitializer("HLTRDLST", "HLT ");
    for (const AliHLTComponentBlockData* pBlock=GetFirstInputBlock();
	 pBlock && iResult>=0;
	 pBlock=GetNextInputBlock()) {
      if (pBlock->fDataType!=hltrdlstdt) continue;
      if (pBlock->fSize==sizeof(AliHLTEventDDL)) {
	HLTDebug("Filling histograms from binary buffer");
	FillReadoutListHistogram(fBitsHisto, reinterpret_cast<AliHLTEventDDL*>(pBlock->fPtr));
	FillReadoutListVsCTP(fBitsVsCTP, reinterpret_cast<AliHLTEventDDL*>(pBlock->fPtr), &trigData);
      } else {
	HLTError("HLTRDLST size missmatch: %d, expected %d", pBlock->fSize, sizeof(AliHLTEventDDL));
      }
    }
  } else if (fMode==AliHLTReadoutListDumpComponent::kModeHLTDecision) {
    for (const TObject* pObject=GetFirstInputObject();
	 pObject && iResult>=0;
	 pObject=GetNextInputObject()) {
      const AliHLTTriggerDecision* pDecision=dynamic_cast<const AliHLTTriggerDecision*>(pObject);
      if (!pDecision) continue;

      AliHLTReadoutList list=pDecision->ReadoutList();
      HLTDebug("Filling histograms from HLT decision object");
      FillReadoutListHistogram(fBitsHisto, &list);
      FillReadoutListVsCTP(fBitsVsCTP, &list, &trigData);
    }
  } else {
    HLTError("invalid mode %d", fMode);
    iResult=-EFAULT;
  }
  return iResult;
}

int AliHLTReadoutListDumpComponent::ScanArgument(int argc, const char** argv)
{
  // see header file for class documentation
  int iResult=-EINVAL;
  if (argc<=0) return 0;
  int i=0;
  TString argument=argv[i];

  // -binary
  if (argument.CompareTo("-binary")==0) {
    fMode=AliHLTReadoutListDumpComponent::kModeBinaryList;
    return 1;
  }

  // -decision
  if (argument.CompareTo("-decision")==0) {
    fMode=AliHLTReadoutListDumpComponent::kModeHLTDecision;
    return 1;
  }

  return iResult;
}

TH1I* AliHLTReadoutListDumpComponent::CreateReadoutListHistogram()
{
  // see header file for class documentation
  int bins=gkAliHLTDDLListSize*sizeof(AliHLTUInt32_t)*8;
  TH1I* histo=new TH1I("HLTRDLST","HLT readout list", bins, 0, bins);
  return histo;
}

TH2I* AliHLTReadoutListDumpComponent::CreateReadoutListVsCTPHistogram()
{
  // see header file for class documentation
  int bins=gkAliHLTDDLListSize*sizeof(AliHLTUInt32_t)*8;
  TH2I* histo=new TH2I("HLTRDLSTvsCTP","HLT readout list vs. CTP trigger", bins, 0, bins, gkNCTPTriggerClasses, 0, gkNCTPTriggerClasses);
  return histo;
}

int AliHLTReadoutListDumpComponent::FillReadoutListHistogram(TH1I* histo, const AliHLTReadoutList* list)
{
  // see header file for class documentation
  if (!histo || !list) return -EINVAL;
  if (list->BufferSize()!=sizeof(AliHLTEventDDL)) return -EBADR;

  return FillReadoutListHistogram(histo, list->Buffer());
}

int AliHLTReadoutListDumpComponent::FillReadoutListHistogram(TH1I* histo, const AliHLTEventDDL* field)
{
  // see header file for class documentation
  if (!histo || !field) return -EINVAL;

  if (field->fCount!=(unsigned)gkAliHLTDDLListSize) return -EBADF;

  for (int word=0; word<gkAliHLTDDLListSize; word++) {
    for (unsigned bit=0; bit<sizeof(AliHLTUInt32_t)*8; bit++) {
      if (field->fList[word]&0x1<<bit) histo->Fill(word*sizeof(AliHLTUInt32_t)*8+bit);
    }
  }

  return 0;
}

int AliHLTReadoutListDumpComponent::FillReadoutListVsCTP(TH2I* histo, const AliHLTReadoutList* list, const AliHLTComponentTriggerData* trigData)
{
  // see header file for class documentation
  if (!histo || !list || !trigData) return -EINVAL;
  if (list->BufferSize()!=sizeof(AliHLTEventDDL)) return -EBADR;

  return FillReadoutListVsCTP(histo, list->Buffer(), trigData);
}

int AliHLTReadoutListDumpComponent::FillReadoutListVsCTP(TH2I* histo, const AliHLTEventDDL* field, const AliHLTComponentTriggerData* trigData)
{
  // see header file for class documentation
  if (!histo || !field || !trigData) return -EINVAL;

  if (field->fCount!=(unsigned)gkAliHLTDDLListSize) return -EBADF;

  AliHLTUInt64_t triggerMask=AliHLTCTPData::ActiveTriggers(*trigData);
  AliHLTUInt64_t bit0=0x1;
  for (int word=0; word<gkAliHLTDDLListSize; word++) {
    for (unsigned bit=0; bit<sizeof(AliHLTUInt32_t)*8; bit++) {
      if (field->fList[word]&0x1<<bit) {
	for (int trigger=0; trigger<gkNCTPTriggerClasses; trigger++) {
	  if ((triggerMask&(bit0<<trigger))!=0) {
	    histo->Fill(word*sizeof(AliHLTUInt32_t)*8+bit, trigger);
	  }
	}
      }
    }
  }

  return 0;
}
<commit_msg>bugfix: mac does not define the EBADR error code, changing to EBADF<commit_after>// $Id$

//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project        *
//* ALICE Experiment at CERN, All rights reserved.                         *
//*                                                                        *
//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
//*                  for The ALICE HLT Project.                            *
//*                                                                        *
//* Permission to use, copy, modify and distribute this software and its   *
//* documentation strictly for non-commercial purposes is hereby granted   *
//* without fee, provided that the above copyright notice appears in all   *
//* copies and that both the copyright notice and this permission notice   *
//* appear in the supporting documentation. The authors make no claims     *
//* about the suitability of this software for any purpose. It is          *
//* provided "as is" without express or implied warranty.                  *
//**************************************************************************

/** @file   AliHLTReadoutListDumpComponent.cxx
    @author Matthias Richter
    @date
    @brief  Base class for writer components to store data in a ROOT file

                                                                          */

#include "AliHLTReadoutListDumpComponent.h"
#include "AliHLTTriggerDecision.h"
#include "AliHLTCTPData.h"
#include "TH1I.h"
#include "TH2I.h"
#include "TString.h"
#include "TFile.h"
#include "TSystem.h"

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTReadoutListDumpComponent)

AliHLTReadoutListDumpComponent::AliHLTReadoutListDumpComponent()
  : AliHLTFileWriter()
  , fMode(AliHLTReadoutListDumpComponent::kModeBinaryList)
  , fBitsHisto(NULL)
  , fBitsVsCTP(NULL)
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}

AliHLTReadoutListDumpComponent::~AliHLTReadoutListDumpComponent()
{
  // see header file for class documentation
}

int AliHLTReadoutListDumpComponent::InitWriter()
{
  // see header file for class documentation
  int iResult=0;
  fBitsHisto=CreateReadoutListHistogram();
  fBitsVsCTP=CreateReadoutListVsCTPHistogram();
  if (!fBitsHisto || !fBitsVsCTP) return -ENOMEM;

  return iResult;
}

int AliHLTReadoutListDumpComponent::CloseWriter()
{
  // see header file for class documentation
  TString filename=GetDirectory();
  if (!filename.IsNull() && !filename.EndsWith("/")) filename+="/";
  filename+=fBitsHisto->GetName();
  filename+="_";
  filename+=GetRunNo();
  filename+=".root";

  TFile out(filename, "RECREATE");
  fBitsHisto->Write();
  fBitsVsCTP->Write();
  out.Close();

  delete fBitsHisto;
  fBitsHisto=NULL;
  delete fBitsVsCTP;
  fBitsVsCTP=NULL;
  return 0;
}

int AliHLTReadoutListDumpComponent::DumpEvent( const AliHLTComponentEventData& /*evtData*/,
					    const AliHLTComponentBlockData* /*blocks*/,
					    AliHLTComponentTriggerData& trigData )
{
  // see header file for class documentation
  int iResult=0;
  if (!IsDataEvent()) return 0;

  if (fMode==AliHLTReadoutListDumpComponent::kModeBinaryList) {
    const AliHLTComponentDataType hltrdlstdt=AliHLTComponentDataTypeInitializer("HLTRDLST", "HLT ");
    for (const AliHLTComponentBlockData* pBlock=GetFirstInputBlock();
	 pBlock && iResult>=0;
	 pBlock=GetNextInputBlock()) {
      if (pBlock->fDataType!=hltrdlstdt) continue;
      if (pBlock->fSize==sizeof(AliHLTEventDDL)) {
	HLTDebug("Filling histograms from binary buffer");
	FillReadoutListHistogram(fBitsHisto, reinterpret_cast<AliHLTEventDDL*>(pBlock->fPtr));
	FillReadoutListVsCTP(fBitsVsCTP, reinterpret_cast<AliHLTEventDDL*>(pBlock->fPtr), &trigData);
      } else {
	HLTError("HLTRDLST size missmatch: %d, expected %d", pBlock->fSize, sizeof(AliHLTEventDDL));
      }
    }
  } else if (fMode==AliHLTReadoutListDumpComponent::kModeHLTDecision) {
    for (const TObject* pObject=GetFirstInputObject();
	 pObject && iResult>=0;
	 pObject=GetNextInputObject()) {
      const AliHLTTriggerDecision* pDecision=dynamic_cast<const AliHLTTriggerDecision*>(pObject);
      if (!pDecision) continue;

      AliHLTReadoutList list=pDecision->ReadoutList();
      HLTDebug("Filling histograms from HLT decision object");
      FillReadoutListHistogram(fBitsHisto, &list);
      FillReadoutListVsCTP(fBitsVsCTP, &list, &trigData);
    }
  } else {
    HLTError("invalid mode %d", fMode);
    iResult=-EFAULT;
  }
  return iResult;
}

int AliHLTReadoutListDumpComponent::ScanArgument(int argc, const char** argv)
{
  // see header file for class documentation
  int iResult=-EINVAL;
  if (argc<=0) return 0;
  int i=0;
  TString argument=argv[i];

  // -binary
  if (argument.CompareTo("-binary")==0) {
    fMode=AliHLTReadoutListDumpComponent::kModeBinaryList;
    return 1;
  }

  // -decision
  if (argument.CompareTo("-decision")==0) {
    fMode=AliHLTReadoutListDumpComponent::kModeHLTDecision;
    return 1;
  }

  return iResult;
}

TH1I* AliHLTReadoutListDumpComponent::CreateReadoutListHistogram()
{
  // see header file for class documentation
  int bins=gkAliHLTDDLListSize*sizeof(AliHLTUInt32_t)*8;
  TH1I* histo=new TH1I("HLTRDLST","HLT readout list", bins, 0, bins);
  return histo;
}

TH2I* AliHLTReadoutListDumpComponent::CreateReadoutListVsCTPHistogram()
{
  // see header file for class documentation
  int bins=gkAliHLTDDLListSize*sizeof(AliHLTUInt32_t)*8;
  TH2I* histo=new TH2I("HLTRDLSTvsCTP","HLT readout list vs. CTP trigger", bins, 0, bins, gkNCTPTriggerClasses, 0, gkNCTPTriggerClasses);
  return histo;
}

int AliHLTReadoutListDumpComponent::FillReadoutListHistogram(TH1I* histo, const AliHLTReadoutList* list)
{
  // see header file for class documentation
  if (!histo || !list) return -EINVAL;
  if (list->BufferSize()!=sizeof(AliHLTEventDDL)) return -EBADF;

  return FillReadoutListHistogram(histo, list->Buffer());
}

int AliHLTReadoutListDumpComponent::FillReadoutListHistogram(TH1I* histo, const AliHLTEventDDL* field)
{
  // see header file for class documentation
  if (!histo || !field) return -EINVAL;

  if (field->fCount!=(unsigned)gkAliHLTDDLListSize) return -EBADF;

  for (int word=0; word<gkAliHLTDDLListSize; word++) {
    for (unsigned bit=0; bit<sizeof(AliHLTUInt32_t)*8; bit++) {
      if (field->fList[word]&0x1<<bit) histo->Fill(word*sizeof(AliHLTUInt32_t)*8+bit);
    }
  }

  return 0;
}

int AliHLTReadoutListDumpComponent::FillReadoutListVsCTP(TH2I* histo, const AliHLTReadoutList* list, const AliHLTComponentTriggerData* trigData)
{
  // see header file for class documentation
  if (!histo || !list || !trigData) return -EINVAL;
  if (list->BufferSize()!=sizeof(AliHLTEventDDL)) return -EBADF;

  return FillReadoutListVsCTP(histo, list->Buffer(), trigData);
}

int AliHLTReadoutListDumpComponent::FillReadoutListVsCTP(TH2I* histo, const AliHLTEventDDL* field, const AliHLTComponentTriggerData* trigData)
{
  // see header file for class documentation
  if (!histo || !field || !trigData) return -EINVAL;

  if (field->fCount!=(unsigned)gkAliHLTDDLListSize) return -EBADF;

  AliHLTUInt64_t triggerMask=AliHLTCTPData::ActiveTriggers(*trigData);
  AliHLTUInt64_t bit0=0x1;
  for (int word=0; word<gkAliHLTDDLListSize; word++) {
    for (unsigned bit=0; bit<sizeof(AliHLTUInt32_t)*8; bit++) {
      if (field->fList[word]&0x1<<bit) {
	for (int trigger=0; trigger<gkNCTPTriggerClasses; trigger++) {
	  if ((triggerMask&(bit0<<trigger))!=0) {
	    histo->Fill(word*sizeof(AliHLTUInt32_t)*8+bit, trigger);
	  }
	}
      }
    }
  }

  return 0;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Copyright 2012 LibreOffice contributors.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "templatedlg.hxx"

#include <comphelper/processfactory.hxx>
#include <sfx2/filedlghelper.hxx>
#include <sfx2/sfxresid.hxx>
#include <sfx2/templatefolderview.hxx>
#include <sfx2/templatefolderviewitem.hxx>
#include <sfx2/templateviewitem.hxx>
#include <sfx2/thumbnailviewitem.hxx>
#include <tools/urlobj.hxx>
#include <unotools/moduleoptions.hxx>
#include <vcl/edit.hxx>
#include <vcl/toolbox.hxx>

#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/ui/dialogs/TemplateDescription.hpp>

#include "doc.hrc"
#include "templatedlg.hrc"

#define MAX_COLUMN_COUNT 4
#define MAX_LINE_COUNT 2

#define PADDING_TOOLBAR_VIEW    15
#define PADDING_DLG_BORDER      10

using namespace ::com::sun::star;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;

SfxTemplateManagerDlg::SfxTemplateManagerDlg (Window *parent)
    : ModalDialog(parent, SfxResId(DLG_TEMPLATE_MANAGER)),
      aButtonAll(this,SfxResId(BTN_SELECT_ALL)),
      aButtonDocs(this,SfxResId(BTN_SELECT_DOCS)),
      aButtonPresents(this,SfxResId(BTN_SELECT_PRESENTATIONS)),
      aButtonSheets(this,SfxResId(BTN_SELECT_SHEETS)),
      aButtonDraws(this,SfxResId(BTN_SELECT_DRAWS)),
      maButtonSelMode(this,SfxResId(BTN_SELECTION_MODE)),
      mpSearchEdit(new Edit(this,WB_HIDE | WB_BORDER)),
      mpViewBar( new ToolBox(this, SfxResId(TBX_ACTION_VIEW))),
      mpActionBar( new ToolBox(this, SfxResId(TBX_ACTION_ACTION))),
      mpTemplateBar( new ToolBox(this, SfxResId(TBX_ACTION_TEMPLATES))),
      maView(new TemplateFolderView(this,SfxResId(TEMPLATE_VIEW))),
      mnSelectionCount(0),
      mxDesktop(comphelper::getProcessServiceFactory()->createInstance( "com.sun.star.frame.Desktop" ),uno::UNO_QUERY )
{
    maButtonSelMode.SetStyle(maButtonSelMode.GetStyle() | WB_TOGGLE);

    // Calculate toolboxs size and positions
    Size aWinSize = GetOutputSize();
    Size aViewSize = mpViewBar->CalcMinimumWindowSizePixel();
    Size aActionSize = mpActionBar->CalcMinimumWindowSizePixel();
    Size aTemplateSize = mpTemplateBar->CalcMinimumWindowSizePixel();

    aActionSize.setWidth(2*aActionSize.getWidth());
    aViewSize.setWidth(aWinSize.getWidth()-aActionSize.getWidth()-mpViewBar->GetPosPixel().X());
    aTemplateSize.setWidth(aWinSize.getWidth());

    Point aActionPos = mpActionBar->GetPosPixel();
    aActionPos.setX(aWinSize.getWidth() - aActionSize.getWidth());

    mpViewBar->SetSizePixel(aViewSize);
    mpActionBar->SetPosSizePixel(aActionPos,aActionSize);
    mpTemplateBar->SetSizePixel(aTemplateSize);

    // Set toolbox styles
    mpViewBar->SetButtonType(BUTTON_SYMBOLTEXT);
    mpTemplateBar->SetButtonType(BUTTON_SYMBOLTEXT);

    // Set toolbox handlers
    mpViewBar->SetClickHdl(LINK(this,SfxTemplateManagerDlg,TBXViewHdl));
    mpActionBar->SetClickHdl(LINK(this,SfxTemplateManagerDlg,TBXActionHdl));
    mpTemplateBar->SetClickHdl(LINK(this,SfxTemplateManagerDlg,TBXTemplateHdl));

    // Set view position below toolbox
    Point aViewPos = maView->GetPosPixel();
    aViewPos.setY(aActionPos.Y() + aActionSize.getHeight() + PADDING_TOOLBAR_VIEW);
    maView->SetPosPixel(aViewPos);

    // Set search box position and size
    Size aSearchSize = mpSearchEdit->CalcMinimumSize();
    aSearchSize.setWidth(aWinSize.getWidth() - 2*PADDING_DLG_BORDER);

    mpSearchEdit->SetSizePixel(aSearchSize);
    mpSearchEdit->SetPosPixel(Point(PADDING_DLG_BORDER,aActionPos.Y()+aActionSize.getHeight()));

    maView->SetStyle(WB_TABSTOP | WB_VSCROLL);
    maView->SetColCount(MAX_COLUMN_COUNT);
    maView->SetLineCount(MAX_LINE_COUNT);

    maView->setItemStateHdl(LINK(this,SfxTemplateManagerDlg,TVFolderStateHdl));
    maView->setTemplateStateHdl(LINK(this,SfxTemplateManagerDlg,TVTemplateStateHdl));

    aButtonAll.SetClickHdl(LINK(this,SfxTemplateManagerDlg,ViewAllHdl));
    aButtonDocs.SetClickHdl(LINK(this,SfxTemplateManagerDlg,ViewDocsHdl));
    aButtonPresents.SetClickHdl(LINK(this,SfxTemplateManagerDlg,ViewPresentsHdl));
    aButtonSheets.SetClickHdl(LINK(this,SfxTemplateManagerDlg,ViewSheetsHdl));
    aButtonDraws.SetClickHdl(LINK(this,SfxTemplateManagerDlg,ViewDrawsHdl));
    maButtonSelMode.SetClickHdl(LINK(this,SfxTemplateManagerDlg,OnClickSelectionMode));

    mpViewBar->Show();
    mpActionBar->Show();

    maView->Populate();
    maView->Show();

    FreeResource();
}

SfxTemplateManagerDlg::~SfxTemplateManagerDlg ()
{
    delete maView;
}

IMPL_LINK_NOARG(SfxTemplateManagerDlg,ViewAllHdl)
{
    maView->filterTemplatesByApp(FILTER_APP_NONE);
    return 0;
}

IMPL_LINK_NOARG(SfxTemplateManagerDlg,ViewDocsHdl)
{
    maView->filterTemplatesByApp(FILTER_APP_WRITER);
    return 0;
}

IMPL_LINK_NOARG(SfxTemplateManagerDlg,ViewPresentsHdl)
{
    maView->filterTemplatesByApp(FILTER_APP_IMPRESS);
    return 0;
}

IMPL_LINK_NOARG(SfxTemplateManagerDlg,ViewSheetsHdl)
{
    maView->filterTemplatesByApp(FILTER_APP_CALC);
    return 0;
}

IMPL_LINK_NOARG(SfxTemplateManagerDlg,ViewDrawsHdl)
{
    maView->filterTemplatesByApp(FILTER_APP_DRAW);
    return 0;
}

void SfxTemplateManagerDlg::MouseButtonDown( const MouseEvent& rMEvt )
{
    if (!maView->GetActiveClipRegion().IsInside(rMEvt.GetPosPixel()) && maView->isOverlayVisible())
        maView->showOverlay(false);
}

IMPL_LINK (SfxTemplateManagerDlg, OnClickSelectionMode, ImageButton*, pButton)
{
    maView->setSelectionMode(pButton->GetState() == STATE_CHECK);
    return 0;
}

IMPL_LINK_NOARG(SfxTemplateManagerDlg,TBXViewHdl)
{
    switch(mpViewBar->GetCurItemId())
    {
    case TBI_TEMPLATE_CREATE:
        OnTemplateCreate();
        break;
    case TBI_TEMPLATE_IMPORT:
        OnTemplateImport();
        break;
    default:
        break;
    }

    return 0;
}

IMPL_LINK_NOARG(SfxTemplateManagerDlg,TBXActionHdl)
{
    switch(mpActionBar->GetCurItemId())
    {
    case TBI_TEMPLATE_SEARCH:
        OnTemplateSearch();
        break;
    case TBI_TEMPLATE_ACTION:
        OnTemplateAction();
        break;
    default:
        break;
    }

    return 0;
}

IMPL_LINK_NOARG(SfxTemplateManagerDlg,TBXTemplateHdl)
{
    switch(mpTemplateBar->GetCurItemId())
    {
    case TBI_TEMPLATE_EDIT:
        OnTemplateEdit();
        break;
    case TBI_TEMPLATE_PROPERTIES:
        OnTemplateProperties();
        break;
    case TBI_TEMPLATE_MOVE:
        OnTemplateMove();
        break;
    case TBI_TEMPLATE_DELETE:
        OnTemplateDelete();
        break;
    default:
        break;
    }

    return 0;
}

IMPL_LINK(SfxTemplateManagerDlg, TVFolderStateHdl, const ThumbnailViewItem*, pItem)
{
    if (pItem->isSelected())
    {
        maSelFolders.insert(pItem);
    }
    else
    {
        maSelFolders.erase(pItem);
    }

    return 0;
}

IMPL_LINK(SfxTemplateManagerDlg, TVTemplateStateHdl, const ThumbnailViewItem*, pItem)
{
    if (pItem->isSelected())
    {
        if (maSelTemplates.empty())
        {
            mpViewBar->Show(false);
            mpActionBar->Show(false);
            mpTemplateBar->Show();
        }

        maSelTemplates.insert(pItem);
    }
    else
    {
        if (maSelTemplates.find(pItem) != maSelTemplates.end())
        {
            maSelTemplates.erase(pItem);

            if (maSelTemplates.empty())
            {
                mpTemplateBar->Show(false);
                mpViewBar->Show();
                mpActionBar->Show();
            }
        }
    }

    return 0;
}

void SfxTemplateManagerDlg::OnTemplateCreate ()
{
}

void SfxTemplateManagerDlg::OnTemplateImport ()
{
    sal_Int16 nDialogType =
        com::sun::star::ui::dialogs::TemplateDescription::FILEOPEN_SIMPLE;

    sfx2::FileDialogHelper aFileDlg(nDialogType, SFXWB_MULTISELECTION);

    // add "All" filter
    aFileDlg.AddFilter( String(SfxResId( STR_SFX_FILTERNAME_ALL) ),
                        DEFINE_CONST_UNICODE(FILEDIALOG_FILTER_ALL) );

    // add template filter
    rtl::OUString sFilterExt;
    rtl::OUString sFilterName( SfxResId( STR_TEMPLATE_FILTER ).toString() );

    // add filters of modules which are installed
    SvtModuleOptions aModuleOpt;
    if ( aModuleOpt.IsModuleInstalled( SvtModuleOptions::E_SWRITER ) )
        sFilterExt += "*.ott;*.stw;*.oth";

    if ( aModuleOpt.IsModuleInstalled( SvtModuleOptions::E_SCALC ) )
    {
        if ( !sFilterExt.isEmpty() )
            sFilterExt += ";";

        sFilterExt += "*.ots;*.stc";
    }

    if ( aModuleOpt.IsModuleInstalled( SvtModuleOptions::E_SIMPRESS ) )
    {
        if ( !sFilterExt.isEmpty() )
            sFilterExt += ";";

        sFilterExt += "*.otp;*.sti";
    }

    if ( aModuleOpt.IsModuleInstalled( SvtModuleOptions::E_SDRAW ) )
    {
        if ( !sFilterExt.isEmpty() )
            sFilterExt += ";";

        sFilterExt += "*.otg;*.std";
    }

    if ( !sFilterExt.isEmpty() )
        sFilterExt += ";";

    sFilterExt += "*.vor";

    sFilterName += " (";
    sFilterName += sFilterExt;
    sFilterName += ")";

    aFileDlg.AddFilter( sFilterName, sFilterExt );
    aFileDlg.SetCurrentFilter( sFilterName );

    ErrCode nCode = aFileDlg.Execute();

    if ( nCode == ERRCODE_NONE )
    {
        com::sun::star::uno::Sequence< ::rtl::OUString > aFiles = aFileDlg.GetSelectedFiles();

        if (aFiles.hasElements())
        {
            std::set<const ThumbnailViewItem*>::const_iterator pIter;
            for (pIter = maSelFolders.begin(); pIter != maSelFolders.end(); ++pIter)
            {
                TemplateFolderViewItem *pFolder = (TemplateFolderViewItem*)(*pIter);

                for (size_t i = 0, n = aFiles.getLength(); i < n; ++i)
                    maView->copyFrom(pFolder,aFiles[i]);
            }
        }
    }
}

void SfxTemplateManagerDlg::OnTemplateSearch ()
{
    Point aPos = maView->GetPosPixel();
    bool bVisible = mpSearchEdit->IsVisible();
    Size aWinSize = GetSizePixel();
    long nEditHeight = mpSearchEdit->GetSizePixel().getHeight();

    if (bVisible)
    {
        aWinSize.setHeight(aWinSize.getHeight() - nEditHeight );
        aPos.setY(aPos.getY() - nEditHeight );
        mpActionBar->SetItemState(TBI_TEMPLATE_SEARCH,STATE_NOCHECK);
    }
    else
    {
        aWinSize.setHeight(aWinSize.getHeight() + nEditHeight );
        aPos.setY(aPos.getY() + nEditHeight );
        mpActionBar->SetItemState(TBI_TEMPLATE_SEARCH,STATE_CHECK);
    }

    SetSizePixel(aWinSize);
    maView->SetPosPixel(aPos);
    mpSearchEdit->Show(!bVisible);
}

void SfxTemplateManagerDlg::OnTemplateAction ()
{
}

void SfxTemplateManagerDlg::OnTemplateEdit ()
{
    uno::Sequence< PropertyValue > aArgs(1);
    aArgs[0].Name = "AsTemplate";
    aArgs[0].Value <<= sal_False;

    uno::Reference< XStorable > xStorable;
    std::set<const ThumbnailViewItem*>::const_iterator pIter;
    for (pIter = maSelTemplates.begin(); pIter != maSelTemplates.end(); ++pIter)
    {
        const TemplateViewItem *pItem = static_cast<const TemplateViewItem*>(*pIter);

        try
        {
            xStorable = uno::Reference< XStorable >(
                        mxDesktop->loadComponentFromURL(pItem->getPath(),rtl::OUString("_blank"), 0, aArgs ),
                        uno::UNO_QUERY );
        }
        catch( const uno::Exception& )
        {
        }
    }
}

void SfxTemplateManagerDlg::OnTemplateProperties ()
{
}

void SfxTemplateManagerDlg::OnTemplateMove ()
{
}

void SfxTemplateManagerDlg::OnTemplateDelete ()
{
    std::set<const ThumbnailViewItem*>::const_iterator pIter;
    for (pIter = maSelTemplates.begin(); pIter != maSelTemplates.end();)
    {
        if (maView->removeTemplate((*pIter)->mnId))
            maSelTemplates.erase(pIter++);
        else
            ++pIter;
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Add a function to create a new template depending on their type.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Copyright 2012 LibreOffice contributors.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "templatedlg.hxx"

#include <comphelper/processfactory.hxx>
#include <sfx2/filedlghelper.hxx>
#include <sfx2/sfxresid.hxx>
#include <sfx2/templatefolderview.hxx>
#include <sfx2/templatefolderviewitem.hxx>
#include <sfx2/templateviewitem.hxx>
#include <sfx2/thumbnailviewitem.hxx>
#include <tools/urlobj.hxx>
#include <unotools/moduleoptions.hxx>
#include <vcl/edit.hxx>
#include <vcl/toolbox.hxx>

#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/ui/dialogs/TemplateDescription.hpp>

#include "doc.hrc"
#include "templatedlg.hrc"

#define MAX_COLUMN_COUNT 4
#define MAX_LINE_COUNT 2

#define PADDING_TOOLBAR_VIEW    15
#define PADDING_DLG_BORDER      10

using namespace ::com::sun::star;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;

void lcl_createTemplate(const FILTER_APPLICATION eApp);

SfxTemplateManagerDlg::SfxTemplateManagerDlg (Window *parent)
    : ModalDialog(parent, SfxResId(DLG_TEMPLATE_MANAGER)),
      aButtonAll(this,SfxResId(BTN_SELECT_ALL)),
      aButtonDocs(this,SfxResId(BTN_SELECT_DOCS)),
      aButtonPresents(this,SfxResId(BTN_SELECT_PRESENTATIONS)),
      aButtonSheets(this,SfxResId(BTN_SELECT_SHEETS)),
      aButtonDraws(this,SfxResId(BTN_SELECT_DRAWS)),
      maButtonSelMode(this,SfxResId(BTN_SELECTION_MODE)),
      mpSearchEdit(new Edit(this,WB_HIDE | WB_BORDER)),
      mpViewBar( new ToolBox(this, SfxResId(TBX_ACTION_VIEW))),
      mpActionBar( new ToolBox(this, SfxResId(TBX_ACTION_ACTION))),
      mpTemplateBar( new ToolBox(this, SfxResId(TBX_ACTION_TEMPLATES))),
      maView(new TemplateFolderView(this,SfxResId(TEMPLATE_VIEW))),
      mnSelectionCount(0),
      mxDesktop(comphelper::getProcessServiceFactory()->createInstance( "com.sun.star.frame.Desktop" ),uno::UNO_QUERY )
{
    maButtonSelMode.SetStyle(maButtonSelMode.GetStyle() | WB_TOGGLE);

    // Calculate toolboxs size and positions
    Size aWinSize = GetOutputSize();
    Size aViewSize = mpViewBar->CalcMinimumWindowSizePixel();
    Size aActionSize = mpActionBar->CalcMinimumWindowSizePixel();
    Size aTemplateSize = mpTemplateBar->CalcMinimumWindowSizePixel();

    aActionSize.setWidth(2*aActionSize.getWidth());
    aViewSize.setWidth(aWinSize.getWidth()-aActionSize.getWidth()-mpViewBar->GetPosPixel().X());
    aTemplateSize.setWidth(aWinSize.getWidth());

    Point aActionPos = mpActionBar->GetPosPixel();
    aActionPos.setX(aWinSize.getWidth() - aActionSize.getWidth());

    mpViewBar->SetSizePixel(aViewSize);
    mpActionBar->SetPosSizePixel(aActionPos,aActionSize);
    mpTemplateBar->SetSizePixel(aTemplateSize);

    // Set toolbox styles
    mpViewBar->SetButtonType(BUTTON_SYMBOLTEXT);
    mpTemplateBar->SetButtonType(BUTTON_SYMBOLTEXT);

    // Set toolbox handlers
    mpViewBar->SetClickHdl(LINK(this,SfxTemplateManagerDlg,TBXViewHdl));
    mpActionBar->SetClickHdl(LINK(this,SfxTemplateManagerDlg,TBXActionHdl));
    mpTemplateBar->SetClickHdl(LINK(this,SfxTemplateManagerDlg,TBXTemplateHdl));

    // Set view position below toolbox
    Point aViewPos = maView->GetPosPixel();
    aViewPos.setY(aActionPos.Y() + aActionSize.getHeight() + PADDING_TOOLBAR_VIEW);
    maView->SetPosPixel(aViewPos);

    // Set search box position and size
    Size aSearchSize = mpSearchEdit->CalcMinimumSize();
    aSearchSize.setWidth(aWinSize.getWidth() - 2*PADDING_DLG_BORDER);

    mpSearchEdit->SetSizePixel(aSearchSize);
    mpSearchEdit->SetPosPixel(Point(PADDING_DLG_BORDER,aActionPos.Y()+aActionSize.getHeight()));

    maView->SetStyle(WB_TABSTOP | WB_VSCROLL);
    maView->SetColCount(MAX_COLUMN_COUNT);
    maView->SetLineCount(MAX_LINE_COUNT);

    maView->setItemStateHdl(LINK(this,SfxTemplateManagerDlg,TVFolderStateHdl));
    maView->setTemplateStateHdl(LINK(this,SfxTemplateManagerDlg,TVTemplateStateHdl));

    aButtonAll.SetClickHdl(LINK(this,SfxTemplateManagerDlg,ViewAllHdl));
    aButtonDocs.SetClickHdl(LINK(this,SfxTemplateManagerDlg,ViewDocsHdl));
    aButtonPresents.SetClickHdl(LINK(this,SfxTemplateManagerDlg,ViewPresentsHdl));
    aButtonSheets.SetClickHdl(LINK(this,SfxTemplateManagerDlg,ViewSheetsHdl));
    aButtonDraws.SetClickHdl(LINK(this,SfxTemplateManagerDlg,ViewDrawsHdl));
    maButtonSelMode.SetClickHdl(LINK(this,SfxTemplateManagerDlg,OnClickSelectionMode));

    mpViewBar->Show();
    mpActionBar->Show();

    maView->Populate();
    maView->Show();

    FreeResource();
}

SfxTemplateManagerDlg::~SfxTemplateManagerDlg ()
{
    delete maView;
}

IMPL_LINK_NOARG(SfxTemplateManagerDlg,ViewAllHdl)
{
    maView->filterTemplatesByApp(FILTER_APP_NONE);
    return 0;
}

IMPL_LINK_NOARG(SfxTemplateManagerDlg,ViewDocsHdl)
{
    maView->filterTemplatesByApp(FILTER_APP_WRITER);
    return 0;
}

IMPL_LINK_NOARG(SfxTemplateManagerDlg,ViewPresentsHdl)
{
    maView->filterTemplatesByApp(FILTER_APP_IMPRESS);
    return 0;
}

IMPL_LINK_NOARG(SfxTemplateManagerDlg,ViewSheetsHdl)
{
    maView->filterTemplatesByApp(FILTER_APP_CALC);
    return 0;
}

IMPL_LINK_NOARG(SfxTemplateManagerDlg,ViewDrawsHdl)
{
    maView->filterTemplatesByApp(FILTER_APP_DRAW);
    return 0;
}

void SfxTemplateManagerDlg::MouseButtonDown( const MouseEvent& rMEvt )
{
    if (!maView->GetActiveClipRegion().IsInside(rMEvt.GetPosPixel()) && maView->isOverlayVisible())
        maView->showOverlay(false);
}

IMPL_LINK (SfxTemplateManagerDlg, OnClickSelectionMode, ImageButton*, pButton)
{
    maView->setSelectionMode(pButton->GetState() == STATE_CHECK);
    return 0;
}

IMPL_LINK_NOARG(SfxTemplateManagerDlg,TBXViewHdl)
{
    switch(mpViewBar->GetCurItemId())
    {
    case TBI_TEMPLATE_CREATE:
        OnTemplateCreate();
        break;
    case TBI_TEMPLATE_IMPORT:
        OnTemplateImport();
        break;
    default:
        break;
    }

    return 0;
}

IMPL_LINK_NOARG(SfxTemplateManagerDlg,TBXActionHdl)
{
    switch(mpActionBar->GetCurItemId())
    {
    case TBI_TEMPLATE_SEARCH:
        OnTemplateSearch();
        break;
    case TBI_TEMPLATE_ACTION:
        OnTemplateAction();
        break;
    default:
        break;
    }

    return 0;
}

IMPL_LINK_NOARG(SfxTemplateManagerDlg,TBXTemplateHdl)
{
    switch(mpTemplateBar->GetCurItemId())
    {
    case TBI_TEMPLATE_EDIT:
        OnTemplateEdit();
        break;
    case TBI_TEMPLATE_PROPERTIES:
        OnTemplateProperties();
        break;
    case TBI_TEMPLATE_MOVE:
        OnTemplateMove();
        break;
    case TBI_TEMPLATE_DELETE:
        OnTemplateDelete();
        break;
    default:
        break;
    }

    return 0;
}

IMPL_LINK(SfxTemplateManagerDlg, TVFolderStateHdl, const ThumbnailViewItem*, pItem)
{
    if (pItem->isSelected())
    {
        maSelFolders.insert(pItem);
    }
    else
    {
        maSelFolders.erase(pItem);
    }

    return 0;
}

IMPL_LINK(SfxTemplateManagerDlg, TVTemplateStateHdl, const ThumbnailViewItem*, pItem)
{
    if (pItem->isSelected())
    {
        if (maSelTemplates.empty())
        {
            mpViewBar->Show(false);
            mpActionBar->Show(false);
            mpTemplateBar->Show();
        }

        maSelTemplates.insert(pItem);
    }
    else
    {
        if (maSelTemplates.find(pItem) != maSelTemplates.end())
        {
            maSelTemplates.erase(pItem);

            if (maSelTemplates.empty())
            {
                mpTemplateBar->Show(false);
                mpViewBar->Show();
                mpActionBar->Show();
            }
        }
    }

    return 0;
}

void SfxTemplateManagerDlg::OnTemplateCreate ()
{
}

void SfxTemplateManagerDlg::OnTemplateImport ()
{
    sal_Int16 nDialogType =
        com::sun::star::ui::dialogs::TemplateDescription::FILEOPEN_SIMPLE;

    sfx2::FileDialogHelper aFileDlg(nDialogType, SFXWB_MULTISELECTION);

    // add "All" filter
    aFileDlg.AddFilter( String(SfxResId( STR_SFX_FILTERNAME_ALL) ),
                        DEFINE_CONST_UNICODE(FILEDIALOG_FILTER_ALL) );

    // add template filter
    rtl::OUString sFilterExt;
    rtl::OUString sFilterName( SfxResId( STR_TEMPLATE_FILTER ).toString() );

    // add filters of modules which are installed
    SvtModuleOptions aModuleOpt;
    if ( aModuleOpt.IsModuleInstalled( SvtModuleOptions::E_SWRITER ) )
        sFilterExt += "*.ott;*.stw;*.oth";

    if ( aModuleOpt.IsModuleInstalled( SvtModuleOptions::E_SCALC ) )
    {
        if ( !sFilterExt.isEmpty() )
            sFilterExt += ";";

        sFilterExt += "*.ots;*.stc";
    }

    if ( aModuleOpt.IsModuleInstalled( SvtModuleOptions::E_SIMPRESS ) )
    {
        if ( !sFilterExt.isEmpty() )
            sFilterExt += ";";

        sFilterExt += "*.otp;*.sti";
    }

    if ( aModuleOpt.IsModuleInstalled( SvtModuleOptions::E_SDRAW ) )
    {
        if ( !sFilterExt.isEmpty() )
            sFilterExt += ";";

        sFilterExt += "*.otg;*.std";
    }

    if ( !sFilterExt.isEmpty() )
        sFilterExt += ";";

    sFilterExt += "*.vor";

    sFilterName += " (";
    sFilterName += sFilterExt;
    sFilterName += ")";

    aFileDlg.AddFilter( sFilterName, sFilterExt );
    aFileDlg.SetCurrentFilter( sFilterName );

    ErrCode nCode = aFileDlg.Execute();

    if ( nCode == ERRCODE_NONE )
    {
        com::sun::star::uno::Sequence< ::rtl::OUString > aFiles = aFileDlg.GetSelectedFiles();

        if (aFiles.hasElements())
        {
            std::set<const ThumbnailViewItem*>::const_iterator pIter;
            for (pIter = maSelFolders.begin(); pIter != maSelFolders.end(); ++pIter)
            {
                TemplateFolderViewItem *pFolder = (TemplateFolderViewItem*)(*pIter);

                for (size_t i = 0, n = aFiles.getLength(); i < n; ++i)
                    maView->copyFrom(pFolder,aFiles[i]);
            }
        }
    }
}

void SfxTemplateManagerDlg::OnTemplateSearch ()
{
    Point aPos = maView->GetPosPixel();
    bool bVisible = mpSearchEdit->IsVisible();
    Size aWinSize = GetSizePixel();
    long nEditHeight = mpSearchEdit->GetSizePixel().getHeight();

    if (bVisible)
    {
        aWinSize.setHeight(aWinSize.getHeight() - nEditHeight );
        aPos.setY(aPos.getY() - nEditHeight );
        mpActionBar->SetItemState(TBI_TEMPLATE_SEARCH,STATE_NOCHECK);
    }
    else
    {
        aWinSize.setHeight(aWinSize.getHeight() + nEditHeight );
        aPos.setY(aPos.getY() + nEditHeight );
        mpActionBar->SetItemState(TBI_TEMPLATE_SEARCH,STATE_CHECK);
    }

    SetSizePixel(aWinSize);
    maView->SetPosPixel(aPos);
    mpSearchEdit->Show(!bVisible);
}

void SfxTemplateManagerDlg::OnTemplateAction ()
{
}

void SfxTemplateManagerDlg::OnTemplateEdit ()
{
    uno::Sequence< PropertyValue > aArgs(1);
    aArgs[0].Name = "AsTemplate";
    aArgs[0].Value <<= sal_False;

    uno::Reference< XStorable > xStorable;
    std::set<const ThumbnailViewItem*>::const_iterator pIter;
    for (pIter = maSelTemplates.begin(); pIter != maSelTemplates.end(); ++pIter)
    {
        const TemplateViewItem *pItem = static_cast<const TemplateViewItem*>(*pIter);

        try
        {
            xStorable = uno::Reference< XStorable >(
                        mxDesktop->loadComponentFromURL(pItem->getPath(),rtl::OUString("_blank"), 0, aArgs ),
                        uno::UNO_QUERY );
        }
        catch( const uno::Exception& )
        {
        }
    }
}

void SfxTemplateManagerDlg::OnTemplateProperties ()
{
}

void SfxTemplateManagerDlg::OnTemplateMove ()
{
}

void SfxTemplateManagerDlg::OnTemplateDelete ()
{
    std::set<const ThumbnailViewItem*>::const_iterator pIter;
    for (pIter = maSelTemplates.begin(); pIter != maSelTemplates.end();)
    {
        if (maView->removeTemplate((*pIter)->mnId))
            maSelTemplates.erase(pIter++);
        else
            ++pIter;
    }
}

void lcl_createTemplate(const FILTER_APPLICATION eApp)
{
    rtl::OUString aURL;

    switch(eApp)
    {
    case FILTER_APP_WRITER:
        aURL = "private:factory/swriter";
        break;
    case FILTER_APP_CALC:
        aURL = "private:factory/scalc";
        break;
    case FILTER_APP_IMPRESS:
        aURL = "private:factory/simpress";
        break;
    case FILTER_APP_DRAW:
        aURL = "private:factory/sdraw";
        break;
    default:
        break;
    }

    if (!aURL.isEmpty())
    {
        uno::Sequence<PropertyValue> aArgs;
        mxDesktop->loadComponentFromURL(aURL,rtl::OUString("_blank"), 0, aArgs );
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


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

#include "stdafx.h"

#include "wbem.h"

#include "StrUtil.h"
#include "MiscUtil.h"

static void SafeArrayDestroyAll(SAFEARRAY **arr)
{
	SafeArrayDestroyData(*arr);
	SafeArrayDestroyDescriptor(*arr);
	*arr = NULL;
}

static SAFEARRAY *CreateDnsArray(OLECHAR *dns1, OLECHAR *dns2)
{
	int				srvCount = 0;
	SAFEARRAYBOUND	arrayBound;
	SAFEARRAY *		dnsArray = NULL;
	BSTR *			dnsServerAddress;

	if (dns1) ++srvCount;
	if (dns2) ++srvCount;

	if (0 == srvCount)
		return NULL;

	arrayBound.cElements = srvCount;
	arrayBound.lLbound = 0;
	dnsArray = ::SafeArrayCreateEx(VT_BSTR, 1, &arrayBound, NULL);
	if (!dnsArray)
		return NULL;

	::SafeArrayAccessData(dnsArray, reinterpret_cast<LPVOID*>(&dnsServerAddress));

	int index = 0;
	if (dns1)
		dnsServerAddress[index++] = ::SysAllocString(dns1);

	if (dns2)
		dnsServerAddress[index] = ::SysAllocString(dns2);

	::SafeArrayUnaccessData(dnsArray);
	return dnsArray;
}

static void SetDnsServers(IWbemServices *wmiSvc, int adapterIdx, OLECHAR *dns1, OLECHAR *dns2)
{
	IWbemClassObject *	pObject = NULL;
	IWbemClassObject *	pInstance = NULL;
	IWbemClassObject *	pMethod = NULL;
	IWbemClassObject *	pResult = NULL;
	HRESULT				hr;
	VARIANT				serverList;
	VARIANT				vtReturnValue;
	CString				adapterPath;
	BSTR				adapterPathBstr = NULL;
	SAFEARRAY *			dnsServers = NULL;
	int					retVal;

    hr = wmiSvc->GetObject(bstr_t("Win32_NetworkAdapterConfiguration"), 0, NULL, &pObject, NULL);
	if (FAILED(hr))
		goto done;

	hr = pObject->GetMethod(bstr_t("SetDNSServerSearchOrder"), 0, &pMethod, NULL);
	if (FAILED(hr))
		goto done;

#if 0 // TODO: not sure if I need this, seems to work without
    hr = pMethod->SpawnInstance(0, &pInstance);
	if (FAILED(hr))
		goto done;
#endif

	dnsServers = CreateDnsArray(dns1, dns2);
	if (!dnsServers)
		goto done;

	serverList.vt = VT_ARRAY | VT_BSTR;
	serverList.parray = dnsServers;
	hr = pObject->Put(L"DNSServerSearchOrder", 0, &serverList, 0);
	if (FAILED(hr))
		goto done;

	adapterPath.Format("Win32_NetworkAdapterConfiguration.Index='%d'", adapterIdx);
	adapterPath.SetSysString(&adapterPathBstr);
	hr = wmiSvc->ExecMethod(adapterPathBstr, bstr_t("SetDNSServerSearchOrder"), 0, NULL, pObject, &pResult, NULL);
	if (FAILED(hr))
		goto done;

    hr = pResult->Get(L"ReturnValue", 0, &vtReturnValue, NULL, 0);
	if (FAILED(hr))
		goto done;

	retVal = vtReturnValue.intVal;

done:
	if (pObject) pObject->Release();
	if (pInstance) pInstance->Release();
	if (pMethod) pMethod->Release();
	if (pResult) pResult->Release();
	if (dnsServers) SafeArrayDestroyAll(&dnsServers);
	::SysFreeString(adapterPathBstr);
}

static void ClearDnsServers(IWbemServices *pSvc, int adapterIdx)
{
	SetDnsServers(pSvc, adapterIdx, NULL, NULL);
}

// We don't want to change the DNS settings of VirtualBox/VMWare etc. virtual ethernet adapters
// I wish I knew a better heurstic to filter non-physical adapters
static BOOL ShouldSkipNetworkAdapter(WCHAR *caption)
{
	// virtual adapter from VirtualBox
	if (-1 != WStrFind(caption, L"VirtualBox"))
		return TRUE;
	// virtual adapter from coLinux (http://colinux.wikia.com/wiki/TAP-Win32_Adapter_V8_%28coLinux%29)
	if (-1 != WStrFind(caption, L"TAP-Win32"))
		return TRUE;
	// virtual adapter from VMWare
	if (-1 != WStrFind(caption, L"VMware"))
		return TRUE;
	return FALSE;
}

void SetOpenDnsServersOnAllAdapters()
{
	IWbemLocator *pLoc = NULL;
	IWbemServices *pSvc = NULL;
	IEnumWbemClassObject* pEnumerator = NULL;

	HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
	if (FAILED(hr))
		return;

	hr =  CoInitializeSecurity(
		NULL,
		-1,                          // COM authentication
		NULL,                        // Authentication services
		NULL,                        // Reserved
		RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication
		RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
		NULL,                        // Authentication info
		EOAC_NONE,                   // Additional capabilities
		NULL                         // Reserved
	);

	if (FAILED(hr))
		goto Exit;

	hr = CoCreateInstance(
		CLSID_WbemLocator,
		0,
		CLSCTX_INPROC_SERVER,
		IID_IWbemLocator, (LPVOID *) &pLoc);

	if (FAILED(hr))
		goto Exit;

	hr = pLoc->ConnectServer(
		 bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace
		 NULL,					  // User name. NULL = current user
		 NULL,					  // User password. NULL = current
		 0, 					  // Locale. NULL indicates current
		 NULL,					  // Security flags.
		 0, 					  // Authority (e.g. Kerberos)
		 0, 					  // Context object
		 &pSvc					  // pointer to IWbemServices proxy
		 );

	if (FAILED(hr))
		goto Exit;

	// Set security levels on the proxy
	hr = CoSetProxyBlanket(
		pSvc,						// Indicates the proxy to set
		RPC_C_AUTHN_WINNT,			// RPC_C_AUTHN_xxx
		RPC_C_AUTHZ_NONE,			// RPC_C_AUTHZ_xxx
		NULL,						// Server principal name
		RPC_C_AUTHN_LEVEL_CALL,		// RPC_C_AUTHN_LEVEL_xxx
		RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
		NULL,						// client identity
		EOAC_NONE					// proxy capabilities
	);

	if (FAILED(hr))
		goto Exit;

	hr = pSvc->ExecQuery(
		bstr_t("WQL"),
		bstr_t("SELECT * FROM Win32_NetworkAdapterConfiguration"),
		WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
		NULL,
		&pEnumerator);

	if (FAILED(hr))
		goto Exit;

	if (!pEnumerator)
		goto Exit;

	IWbemClassObject *pObj;
	ULONG result = 0;

	for (;;)
	{
		VARIANT vtProp;
		VARIANT vtCaption;
		WCHAR *caption = NULL;

		VariantInit(&vtProp);
		VariantInit(&vtCaption);

		hr = pEnumerator->Next(WBEM_INFINITE, 1, &pObj, &result);
		if (0 == result)
			break;

		hr = pObj->Get(L"IPEnabled", 0, &vtProp, 0, 0);
		if (FAILED(hr) || !vtProp.boolVal)
			goto Next;

#if 0
		VariantClear(&vtProp);
		hr = pObj->Get(L"SettingID", 0, &vtProp, 0, 0);
		if (FAILED(hr))
			goto Next;
		s = vtProp.bstrVal;
#endif

		hr = pObj->Get(L"Caption", 0, &vtCaption, 0, 0);
		if (FAILED(hr))
			goto Next;
		caption = vtCaption.bstrVal;

		if (ShouldSkipNetworkAdapter(caption))
			goto Next;

		// TODO: skip disabled adapters (probably needs to use
		// Win32_NetworkAdapter.Availability correlated via
		// MACAddress with Win32_NetworkAdapterConfiguration)

#if 0
		VariantClear(&vtProp);
		hr = pObj->Get(L"DNSServerSearchOrder", 0, &vtProp, 0, 0);
		if (FAILED(hr))
			goto Next;
#endif

		VariantClear(&vtProp);
		hr = pObj->Get(L"Index", 0, &vtProp, 0, 0);
		if (FAILED(hr))
			goto Exit;
		assert(vtProp.vt == VT_I4);
		if (vtProp.vt != VT_I4)
			goto Exit;
		int idx = vtProp.lVal;

		SetDnsServers(pSvc, idx, OLESTR("208.67.222.222"), OLESTR("208.67.220.220"));
Next:
		VariantClear(&vtProp);
		VariantClear(&vtCaption);
		pObj->Release();
	}

Exit:
	if (pEnumerator) pEnumerator->Release();
	if (pSvc) pSvc->Release();
	if (pLoc) pLoc->Release();

	CoUninitialize();
	return;
}

<commit_msg>naming changes and cleanups<commit_after>// Copyright (c) 2009 OpenDNS Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "stdafx.h"

#include "wbem.h"

#include "MiscUtil.h"
#include "SimpleLog.h"
#include "StrUtil.h"

static void SafeArrayDestroyAll(SAFEARRAY **arr)
{
	SafeArrayDestroyData(*arr);
	SafeArrayDestroyDescriptor(*arr);
	*arr = NULL;
}

static SAFEARRAY *CreateDnsArray(OLECHAR *dns1, OLECHAR *dns2)
{
	int				srvCount = 0;
	SAFEARRAYBOUND	arrayBound;
	SAFEARRAY *		dnsArray = NULL;
	BSTR *			dnsServerAddress;

	if (dns1) ++srvCount;
	if (dns2) ++srvCount;

	if (0 == srvCount)
		return NULL;

	arrayBound.cElements = srvCount;
	arrayBound.lLbound = 0;
	dnsArray = ::SafeArrayCreateEx(VT_BSTR, 1, &arrayBound, NULL);
	if (!dnsArray)
		return NULL;

	::SafeArrayAccessData(dnsArray, reinterpret_cast<LPVOID*>(&dnsServerAddress));

	int index = 0;
	if (dns1)
		dnsServerAddress[index++] = ::SysAllocString(dns1);

	if (dns2)
		dnsServerAddress[index] = ::SysAllocString(dns2);

	::SafeArrayUnaccessData(dnsArray);
	return dnsArray;
}

static void SetDnsServers(IWbemServices *wmiSvc, int adapterIdx, OLECHAR *dns1, OLECHAR *dns2)
{
	IWbemClassObject *	pObject = NULL;
	IWbemClassObject *	pInstance = NULL;
	IWbemClassObject *	pMethodParam = NULL;
	IWbemClassObject *	pResult = NULL;
	HRESULT				hr;
	VARIANT				vtDnsServers;
	VARIANT				vtRetVal;
	CString				adapterPath;
	BSTR				adapterPathBstr = NULL;
	SAFEARRAY *			dnsServers = NULL;
	int					retVal;

	VariantInit(&vtDnsServers);
	VariantInit(&vtRetVal);

	hr = wmiSvc->GetObject(bstr_t("Win32_NetworkAdapterConfiguration"), 0, NULL, &pObject, NULL);
	if (FAILED(hr))
		goto Exit;

#if 0 // TODO: not sure if I need this, seems to work without it
	hr = pObject->GetMethod(bstr_t("SetDNSServerSearchOrder"), 0, &pMethodParam, NULL);
	if (FAILED(hr))
		goto Exit;

    hr = pMethodParam->SpawnInstance(0, &pInstance);
	if (FAILED(hr))
		goto Exit;
#endif

	dnsServers = CreateDnsArray(dns1, dns2);
	if (!dnsServers)
		goto Exit;

	vtDnsServers.vt = VT_ARRAY | VT_BSTR;
	vtDnsServers.parray = dnsServers;
	hr = pObject->Put(L"DNSServerSearchOrder", 0, &vtDnsServers, 0);
	if (FAILED(hr))
		goto Exit;

	adapterPath.Format("Win32_NetworkAdapterConfiguration.Index='%d'", adapterIdx);
	adapterPath.SetSysString(&adapterPathBstr);
	hr = wmiSvc->ExecMethod(adapterPathBstr, bstr_t("SetDNSServerSearchOrder"), 0, NULL, pObject, &pResult, NULL);
	if (FAILED(hr))
		goto Exit;

	hr = pResult->Get(L"ReturnValue", 0, &vtRetVal, NULL, 0);
	if (FAILED(hr))
		goto Exit;

	retVal = vtRetVal.intVal;
	slogfmt("Set dns servers on adapter %d, retVal=%d", adapterIdx, retVal);

Exit:
	VariantClear(&vtDnsServers);
	VariantClear(&vtRetVal);
	if (pObject) pObject->Release();
	if (pInstance) pInstance->Release();
	if (pMethodParam) pMethodParam->Release();
	if (pResult) pResult->Release();
	if (dnsServers) SafeArrayDestroyAll(&dnsServers);
	::SysFreeString(adapterPathBstr);
}

static void ClearDnsServers(IWbemServices *pSvc, int adapterIdx)
{
	SetDnsServers(pSvc, adapterIdx, NULL, NULL);
}

// We don't want to change the DNS settings of VirtualBox/VMWare etc. virtual ethernet adapters
// I wish I knew a better heurstic to filter non-physical adapters
static BOOL ShouldSkipNetworkAdapter(WCHAR *caption)
{
	// virtual adapter from VirtualBox
	if (-1 != WStrFind(caption, L"VirtualBox"))
		return TRUE;
	// virtual adapter from coLinux (http://colinux.wikia.com/wiki/TAP-Win32_Adapter_V8_%28coLinux%29)
	if (-1 != WStrFind(caption, L"TAP-Win32"))
		return TRUE;
	// virtual adapter from VMWare
	if (-1 != WStrFind(caption, L"VMware"))
		return TRUE;
	return FALSE;
}

void SetOpenDnsServersOnAllAdapters()
{
	IWbemLocator *pLoc = NULL;
	IWbemServices *pSvc = NULL;
	IEnumWbemClassObject* pEnumerator = NULL;

	HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
	if (FAILED(hr))
		return;

	hr =  CoInitializeSecurity(
		NULL,
		-1,                          // COM authentication
		NULL,                        // Authentication services
		NULL,                        // Reserved
		RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication
		RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
		NULL,                        // Authentication info
		EOAC_NONE,                   // Additional capabilities
		NULL                         // Reserved
	);

	if (FAILED(hr))
		goto Exit;

	hr = CoCreateInstance(
		CLSID_WbemLocator,
		0,
		CLSCTX_INPROC_SERVER,
		IID_IWbemLocator, (LPVOID *) &pLoc);

	if (FAILED(hr))
		goto Exit;

	hr = pLoc->ConnectServer(
		 bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace
		 NULL,					  // User name. NULL = current user
		 NULL,					  // User password. NULL = current
		 0, 					  // Locale. NULL indicates current
		 NULL,					  // Security flags.
		 0, 					  // Authority (e.g. Kerberos)
		 0, 					  // Context object
		 &pSvc					  // pointer to IWbemServices proxy
		 );

	if (FAILED(hr))
		goto Exit;

	// Set security levels on the proxy
	hr = CoSetProxyBlanket(
		pSvc,						// Indicates the proxy to set
		RPC_C_AUTHN_WINNT,			// RPC_C_AUTHN_xxx
		RPC_C_AUTHZ_NONE,			// RPC_C_AUTHZ_xxx
		NULL,						// Server principal name
		RPC_C_AUTHN_LEVEL_CALL,		// RPC_C_AUTHN_LEVEL_xxx
		RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
		NULL,						// client identity
		EOAC_NONE					// proxy capabilities
	);

	if (FAILED(hr))
		goto Exit;

	hr = pSvc->ExecQuery(
		bstr_t("WQL"),
		bstr_t("SELECT * FROM Win32_NetworkAdapterConfiguration"),
		WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
		NULL,
		&pEnumerator);

	if (FAILED(hr))
		goto Exit;

	if (!pEnumerator)
		goto Exit;

	IWbemClassObject *pObj;
	ULONG result = 0;

	for (;;)
	{
		VARIANT vtProp;
		VARIANT vtCaption;
		WCHAR *caption = NULL;

		VariantInit(&vtProp);
		VariantInit(&vtCaption);

		hr = pEnumerator->Next(WBEM_INFINITE, 1, &pObj, &result);
		if (0 == result)
			break;

		hr = pObj->Get(L"IPEnabled", 0, &vtProp, 0, 0);
		if (FAILED(hr) || !vtProp.boolVal)
			goto Next;

#if 0
		VariantClear(&vtProp);
		hr = pObj->Get(L"SettingID", 0, &vtProp, 0, 0);
		if (FAILED(hr))
			goto Next;
		s = vtProp.bstrVal;
#endif

		hr = pObj->Get(L"Caption", 0, &vtCaption, 0, 0);
		if (FAILED(hr))
			goto Next;
		caption = vtCaption.bstrVal;

		if (ShouldSkipNetworkAdapter(caption))
			goto Next;

		// TODO: skip disabled adapters (probably needs to use
		// Win32_NetworkAdapter.Availability correlated via
		// MACAddress with Win32_NetworkAdapterConfiguration)

#if 0
		VariantClear(&vtProp);
		hr = pObj->Get(L"DNSServerSearchOrder", 0, &vtProp, 0, 0);
		if (FAILED(hr))
			goto Next;
#endif

		VariantClear(&vtProp);
		hr = pObj->Get(L"Index", 0, &vtProp, 0, 0);
		if (FAILED(hr))
			goto Exit;
		assert(vtProp.vt == VT_I4);
		if (vtProp.vt != VT_I4)
			goto Exit;
		int idx = vtProp.lVal;

		SetDnsServers(pSvc, idx, OLESTR("208.67.222.222"), OLESTR("208.67.220.220"));
Next:
		VariantClear(&vtProp);
		VariantClear(&vtCaption);
		pObj->Release();
	}

Exit:
	if (pEnumerator) pEnumerator->Release();
	if (pSvc) pSvc->Release();
	if (pLoc) pLoc->Release();

	CoUninitialize();
	return;
}

<|endoftext|>


<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

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 "tensorflow/compiler/xla/service/cpu/compiler_functor.h"

#include <algorithm>
#include <iterator>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "absl/memory/memory.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Verifier.h"
#include "llvm/MC/MCContext.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/SmallVectorMemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/AlwaysInliner.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "tensorflow/compiler/xla/service/cpu/cpu_runtime.h"
#include "tensorflow/compiler/xla/service/cpu/llvm_ir_runtime.h"
#include "tensorflow/compiler/xla/service/llvm_ir/llvm_util.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/platform/logging.h"

namespace xla {
namespace cpu {

/* Create filtered versions of the LLVM Pass Managers to filter out some
of the expensive passes.
Profiling:
   learning/brain/google/xla/benchmarks:inception_cpu_benchmark
   learning/brain/google/xla/benchmarks:cifarnet
pointed to LICM and IndVarSimplify as the hottest passes.
LICM is known to exhibit O(n^2) time in the number of instructions.
IndVarSimplify is slow due to SCEV. If loops are emitted in canonical form,
this pass is not necessary.
Disabling these as a starting point.
*/
// TODO(b/64227304) Creating a custom pass pipeline will replace this.

namespace {
class FilteredPassManager : public llvm::legacy::PassManager {
 public:
  explicit FilteredPassManager(bool disable_expensive_passes)
      : disable_expensive_passes_(disable_expensive_passes) {}
  void add(llvm::Pass* p) override {
    if (disable_expensive_passes_) {
      llvm::StringRef PassName = p->getPassName();
      if (PassName.contains("Unroll loops")) {
        return;
      }
    }
    llvm::legacy::PassManager::add(p);
  }

 private:
  bool disable_expensive_passes_;
};
}  // anonymous namespace

std::unique_ptr<llvm::MemoryBuffer> CompilerFunctor::operator()(
    llvm::Module& module) const {
  FilteredPassManager module_passes(disable_expensive_passes_);
  llvm::legacy::FunctionPassManager function_passes(&module);

  VLOG(2) << "IR before optimizations";
  XLA_VLOG_LINES(2, llvm_ir::DumpModuleToString(module));

  if (pre_optimization_hook_) {
    pre_optimization_hook_(module);
  }

  // Add the appropriate TargetLibraryInfo and TargetTransformInfo.
  AddTargetInfoPasses(&module_passes);

  // Build up optimization pipeline.
  if (optimize_for_size_) {
    // Optimizing for size turns on -O2 level optimizations.
    //
    // TODO(b/64153864): Although the code generator supports size_level = 2 to
    // turn on more aggressive code size optimizations than size_level = 1, we
    // pass size_level = 1 because in many cases a size_level of 2 does
    // worse. Investigate why.
    AddOptimizationPasses(&module_passes, &function_passes, /*opt_level=*/2,
                          /*size_level=*/1);
  } else {
    AddOptimizationPasses(&module_passes, &function_passes,
                          /*opt_level=*/opt_level_, /*size_level=*/0);
  }

  // Run optimization passes on module.
  function_passes.doInitialization();

  CHECK(!llvm::verifyModule(module, &llvm::dbgs()));

  for (auto func = module.begin(); func != module.end(); ++func) {
    function_passes.run(*func);
  }
  function_passes.doFinalization();
  module_passes.run(module);

  CHECK(!llvm::verifyModule(module, &llvm::dbgs()));

  runtime::RewriteIRRuntimeFunctions(&module, fast_math_flags_);

  // Buffer for holding machine code prior to constructing the ObjectFile.
  llvm::SmallVector<char, 0> stream_buffer;
  llvm::raw_svector_ostream ostream(stream_buffer);

  VLOG(2) << "IR after optimizations";
  XLA_VLOG_LINES(2, llvm_ir::DumpModuleToString(module));

  if (post_optimization_hook_) {
    post_optimization_hook_(module);
  }

  // Generate code.
  llvm::MCContext* mc_context;
  llvm::legacy::PassManager codegen_passes;
  target_machine_->addPassesToEmitMC(codegen_passes, mc_context, ostream);
  codegen_passes.run(module);

  std::unique_ptr<llvm::MemoryBuffer> memory_buffer(
      new llvm::SmallVectorMemoryBuffer(std::move(stream_buffer)));

  if (post_codegen_hook_) {
    llvm::Expected<std::unique_ptr<llvm::object::ObjectFile>> obj_file =
        llvm::object::ObjectFile::createObjectFile(*memory_buffer);
    if (obj_file) {
      post_codegen_hook_(*obj_file.get());
    } else {
      LOG(WARNING) << "Could convert memory buffer to object file!";
    }
  }

  return memory_buffer;
}

static std::vector<llvm::VecDesc> VectorFunctionsForTargetLibraryInfoImpl() {
  std::vector<llvm::VecDesc> result = {
      {"tanhf", runtime::kTanhV4F32SymbolName, 4},
      {"llvm.tanh.f32", runtime::kTanhV4F32SymbolName, 4},

      {"tanhf", runtime::kTanhV8F32SymbolName, 8},
      {"llvm.tanh.f32", runtime::kTanhV8F32SymbolName, 8},

      {"tanhf", runtime::kTanhV16F32SymbolName, 16},
      {"llvm.tanh.f32", runtime::kTanhV16F32SymbolName, 16},

      {"expf", runtime::kExpV4F32SymbolName, 4},
      {"llvm.exp.f32", runtime::kExpV4F32SymbolName, 4},

      {"expf", runtime::kExpV8F32SymbolName, 8},
      {"llvm.exp.f32", runtime::kExpV8F32SymbolName, 8},

      {"expf", runtime::kExpV16F32SymbolName, 16},
      {"llvm.exp.f32", runtime::kExpV16F32SymbolName, 16},

      {"logf", runtime::kLogV4F32SymbolName, 4},
      {"llvm.log.f32", runtime::kLogV4F32SymbolName, 4},

      {"logf", runtime::kLogV8F32SymbolName, 8},
      {"llvm.log.f32", runtime::kLogV8F32SymbolName, 8},

      {"logf", runtime::kLogV16F32SymbolName, 16},
      {"llvm.log.f32", runtime::kLogV16F32SymbolName, 16},
  };
  return result;
}

void CompilerFunctor::AddTargetInfoPasses(
    llvm::legacy::PassManagerBase* passes) const {
  llvm::Triple target_triple(target_machine_->getTargetTriple());
  auto target_library_info_impl =
      absl::make_unique<llvm::TargetLibraryInfoImpl>(target_triple);
  target_library_info_impl->addVectorizableFunctions(
      VectorFunctionsForTargetLibraryInfoImpl());

  // TODO(b/136651482): Disable pow(f) so LLVM doesn't transform it into powi.
  // It would be better to provide our own powi.
  target_library_info_impl->setUnavailable(llvm::LibFunc_pow);
  target_library_info_impl->setUnavailable(llvm::LibFunc_powf);

  passes->add(
      new llvm::TargetLibraryInfoWrapperPass(*target_library_info_impl));
  passes->add(createTargetTransformInfoWrapperPass(
      target_machine_->getTargetIRAnalysis()));
}

void CompilerFunctor::AddOptimizationPasses(
    llvm::legacy::PassManagerBase* module_passes,
    llvm::legacy::FunctionPassManager* function_passes, unsigned opt_level,
    unsigned size_level) const {
  llvm::PassManagerBuilder builder;
  builder.OptLevel = opt_level;
  builder.SizeLevel = size_level;

  if (opt_level > 1) {
    builder.Inliner = llvm::createFunctionInliningPass();
  } else {
    // Only inline functions marked with "alwaysinline".
    builder.Inliner = llvm::createAlwaysInlinerLegacyPass();
  }

  builder.DisableUnrollLoops = opt_level == 0;
  builder.LoopVectorize = opt_level > 0 && size_level == 0;
  builder.SLPVectorize = opt_level > 1 && size_level == 0;

  builder.populateFunctionPassManager(*function_passes);
  builder.populateModulePassManager(*module_passes);
}

}  // namespace cpu
}  // namespace xla
<commit_msg>[XLA] Fix a leak on codepath where --xla_llvm_disable_expensive_passes is set<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

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 "tensorflow/compiler/xla/service/cpu/compiler_functor.h"

#include <algorithm>
#include <iterator>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "absl/memory/memory.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Verifier.h"
#include "llvm/MC/MCContext.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/SmallVectorMemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/AlwaysInliner.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "tensorflow/compiler/xla/service/cpu/cpu_runtime.h"
#include "tensorflow/compiler/xla/service/cpu/llvm_ir_runtime.h"
#include "tensorflow/compiler/xla/service/llvm_ir/llvm_util.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/platform/logging.h"

namespace xla {
namespace cpu {

/* Create filtered versions of the LLVM Pass Managers to filter out some
of the expensive passes.
Profiling:
   learning/brain/google/xla/benchmarks:inception_cpu_benchmark
   learning/brain/google/xla/benchmarks:cifarnet
pointed to LICM and IndVarSimplify as the hottest passes.
LICM is known to exhibit O(n^2) time in the number of instructions.
IndVarSimplify is slow due to SCEV. If loops are emitted in canonical form,
this pass is not necessary.
Disabling these as a starting point.
*/
// TODO(b/64227304) Creating a custom pass pipeline will replace this.

namespace {
class FilteredPassManager : public llvm::legacy::PassManager {
 public:
  explicit FilteredPassManager(bool disable_expensive_passes)
      : disable_expensive_passes_(disable_expensive_passes) {}
  void add(llvm::Pass* p) override {
    bool pass_disabled =
        disable_expensive_passes_ && p->getPassName().contains("Unroll loops");
    if (!pass_disabled) {
      llvm::legacy::PassManager::add(p);
    } else {
      delete p;
    }
  }

 private:
  bool disable_expensive_passes_;
};
}  // anonymous namespace

std::unique_ptr<llvm::MemoryBuffer> CompilerFunctor::operator()(
    llvm::Module& module) const {
  FilteredPassManager module_passes(disable_expensive_passes_);
  llvm::legacy::FunctionPassManager function_passes(&module);

  VLOG(2) << "IR before optimizations";
  XLA_VLOG_LINES(2, llvm_ir::DumpModuleToString(module));

  if (pre_optimization_hook_) {
    pre_optimization_hook_(module);
  }

  // Add the appropriate TargetLibraryInfo and TargetTransformInfo.
  AddTargetInfoPasses(&module_passes);

  // Build up optimization pipeline.
  if (optimize_for_size_) {
    // Optimizing for size turns on -O2 level optimizations.
    //
    // TODO(b/64153864): Although the code generator supports size_level = 2 to
    // turn on more aggressive code size optimizations than size_level = 1, we
    // pass size_level = 1 because in many cases a size_level of 2 does
    // worse. Investigate why.
    AddOptimizationPasses(&module_passes, &function_passes, /*opt_level=*/2,
                          /*size_level=*/1);
  } else {
    AddOptimizationPasses(&module_passes, &function_passes,
                          /*opt_level=*/opt_level_, /*size_level=*/0);
  }

  // Run optimization passes on module.
  function_passes.doInitialization();

  CHECK(!llvm::verifyModule(module, &llvm::dbgs()));

  for (auto func = module.begin(); func != module.end(); ++func) {
    function_passes.run(*func);
  }
  function_passes.doFinalization();
  module_passes.run(module);

  CHECK(!llvm::verifyModule(module, &llvm::dbgs()));

  runtime::RewriteIRRuntimeFunctions(&module, fast_math_flags_);

  // Buffer for holding machine code prior to constructing the ObjectFile.
  llvm::SmallVector<char, 0> stream_buffer;
  llvm::raw_svector_ostream ostream(stream_buffer);

  VLOG(2) << "IR after optimizations";
  XLA_VLOG_LINES(2, llvm_ir::DumpModuleToString(module));

  if (post_optimization_hook_) {
    post_optimization_hook_(module);
  }

  // Generate code.
  llvm::MCContext* mc_context;
  llvm::legacy::PassManager codegen_passes;
  target_machine_->addPassesToEmitMC(codegen_passes, mc_context, ostream);
  codegen_passes.run(module);

  std::unique_ptr<llvm::MemoryBuffer> memory_buffer(
      new llvm::SmallVectorMemoryBuffer(std::move(stream_buffer)));

  if (post_codegen_hook_) {
    llvm::Expected<std::unique_ptr<llvm::object::ObjectFile>> obj_file =
        llvm::object::ObjectFile::createObjectFile(*memory_buffer);
    if (obj_file) {
      post_codegen_hook_(*obj_file.get());
    } else {
      LOG(WARNING) << "Could convert memory buffer to object file!";
    }
  }

  return memory_buffer;
}

static std::vector<llvm::VecDesc> VectorFunctionsForTargetLibraryInfoImpl() {
  std::vector<llvm::VecDesc> result = {
      {"tanhf", runtime::kTanhV4F32SymbolName, 4},
      {"llvm.tanh.f32", runtime::kTanhV4F32SymbolName, 4},

      {"tanhf", runtime::kTanhV8F32SymbolName, 8},
      {"llvm.tanh.f32", runtime::kTanhV8F32SymbolName, 8},

      {"tanhf", runtime::kTanhV16F32SymbolName, 16},
      {"llvm.tanh.f32", runtime::kTanhV16F32SymbolName, 16},

      {"expf", runtime::kExpV4F32SymbolName, 4},
      {"llvm.exp.f32", runtime::kExpV4F32SymbolName, 4},

      {"expf", runtime::kExpV8F32SymbolName, 8},
      {"llvm.exp.f32", runtime::kExpV8F32SymbolName, 8},

      {"expf", runtime::kExpV16F32SymbolName, 16},
      {"llvm.exp.f32", runtime::kExpV16F32SymbolName, 16},

      {"logf", runtime::kLogV4F32SymbolName, 4},
      {"llvm.log.f32", runtime::kLogV4F32SymbolName, 4},

      {"logf", runtime::kLogV8F32SymbolName, 8},
      {"llvm.log.f32", runtime::kLogV8F32SymbolName, 8},

      {"logf", runtime::kLogV16F32SymbolName, 16},
      {"llvm.log.f32", runtime::kLogV16F32SymbolName, 16},
  };
  return result;
}

void CompilerFunctor::AddTargetInfoPasses(
    llvm::legacy::PassManagerBase* passes) const {
  llvm::Triple target_triple(target_machine_->getTargetTriple());
  auto target_library_info_impl =
      absl::make_unique<llvm::TargetLibraryInfoImpl>(target_triple);
  target_library_info_impl->addVectorizableFunctions(
      VectorFunctionsForTargetLibraryInfoImpl());

  // TODO(b/136651482): Disable pow(f) so LLVM doesn't transform it into powi.
  // It would be better to provide our own powi.
  target_library_info_impl->setUnavailable(llvm::LibFunc_pow);
  target_library_info_impl->setUnavailable(llvm::LibFunc_powf);

  passes->add(
      new llvm::TargetLibraryInfoWrapperPass(*target_library_info_impl));
  passes->add(createTargetTransformInfoWrapperPass(
      target_machine_->getTargetIRAnalysis()));
}

void CompilerFunctor::AddOptimizationPasses(
    llvm::legacy::PassManagerBase* module_passes,
    llvm::legacy::FunctionPassManager* function_passes, unsigned opt_level,
    unsigned size_level) const {
  llvm::PassManagerBuilder builder;
  builder.OptLevel = opt_level;
  builder.SizeLevel = size_level;

  if (opt_level > 1) {
    builder.Inliner = llvm::createFunctionInliningPass();
  } else {
    // Only inline functions marked with "alwaysinline".
    builder.Inliner = llvm::createAlwaysInlinerLegacyPass();
  }

  builder.DisableUnrollLoops = opt_level == 0;
  builder.LoopVectorize = opt_level > 0 && size_level == 0;
  builder.SLPVectorize = opt_level > 1 && size_level == 0;

  builder.populateFunctionPassManager(*function_passes);
  builder.populateModulePassManager(*module_passes);
}

}  // namespace cpu
}  // namespace xla
<|endoftext|>


<commit_before>#include "S25FL208K.h"
#include <SPI.h>

S25FL208K::S25FL208K(uint8_t csPin){
  SPI.begin();
  mCsPin = csPin;
  pinMode(mCsPin, OUTPUT);
  digitalWrite(mCsPin, 1); // active low, start disabled
}

// returns dynamic memory
// therefore needs a delete[] call on the pointer when done
uint8_t* S25FL208K::sendCommand(uint8_t command, uint8_t bytesToRead){
  uint8_t* result = NULL;
  digitalWrite(mCsPin, 0);
  SPI.transfer(command);
  if (bytesToRead > 0){
    result = new uint8_t[bytesToRead];
    for (int i = 0; i<bytesToRead; i++){
      result[i] = SPI.transfer(DUMMY_VALUE);
    }
  }
  digitalWrite(mCsPin, 1);
  return result;
}

uint8_t S25FL208K::readStatus(){
  uint8_t* result = NULL;
  uint8_t output = 0;
  result = sendCommand(READ_STATUS_REG, 1);
  output = result[0];
  delete[] result;
  return output;
}

void S25FL208K::writeEnable(void){
  sendCommand(WRITE_ENABLE);
}

void S25FL208K::writeDisable(void){
  sendCommand(WRITE_DISABLE);
}

bool S25FL208K::getWIP(void){
  return (this->readStatus() & WIP_MASK);
}

bool S25FL208K::readData(uint32_t address, uint32_t numBytes, uint8_t* &result){
  // check WIP bit
  if (this->getWIP()){
    return false;
  }

  digitalWrite(mCsPin, 0);
  // transfer the address as 3 bytes
  SPI.transfer(READ_DATA);
  SPI.transfer(uint8_t(0xFF & (address>>16)));
  SPI.transfer(uint8_t(0xFF & (address>>8)));
  SPI.transfer(uint8_t(0xFF & address));

  // read the data into result
  for(int i = 0; i<numBytes; i++){
    result[i] = SPI.transfer(DUMMY_VALUE);
  }
  // end transfer
  digitalWrite(mCsPin, 1);
  return true;
}

bool S25FL208K::storeData(uint32_t address, uint8_t numBytes, uint8_t* &data){
  // check WIP bit
  if (this->getWIP()){
    return false;
  }

  // check page erased
  bool allOnes = true;
  uint8_t* tempResult = new uint8_t[numBytes];
  this->readData(address, numBytes, tempResult);
  for (int i = 0; i<numBytes; i++){
    if (tempResult[i]!=0xFF){
      allOnes = false;
    }
  }
  delete[] tempResult;

  if (!allOnes){
    return false;
  }

  // set WRITE_ENABLE
  this->writeEnable();

  digitalWrite(mCsPin, 0);
  // send address
  SPI.transfer(PAGE_PROGRAM);
  SPI.transfer(uint8_t(0xFF & (address>>16)));
  SPI.transfer(uint8_t(0xFF & (address>>8)));
  SPI.transfer(uint8_t(0xFF & address));
  //send data
  for(int i = 0; i<numBytes; i++){
    SPI.transfer(data[i]);
  }

  digitalWrite(mCsPin, 1);

  return true;
}

bool S25FL208K::chipErase(void){
  // check WIP bit
  if (this->getWIP()){
    return false;
  }
  this->sendCommand(CHIP_ERASE);
  return true;
}

bool S25FL208K::sectorErase(uint32_t address){
  // check WIP bit
  if (this->getWIP()){
    return false;
  }

  digitalWrite(mCsPin, 0);
  // transfer the address as 3 bytes
  SPI.transfer(SECTOR_ERASE);
  SPI.transfer(uint8_t(0xFF & (address>>16)));
  SPI.transfer(uint8_t(0xFF & (address>>8)));
  SPI.transfer(uint8_t(0xFF & address));
  digitalWrite(mCsPin, 1);

  return true;
}

bool S25FL208K::blockErase(uint32_t address){
  // check WIP bit
  if (this->getWIP()){
    return false;
  }

  digitalWrite(mCsPin, 0);
  // transfer the address as 3 bytes
  SPI.transfer(BLOCK_ERASE);
  SPI.transfer(uint8_t(0xFF & (address>>16)));
  SPI.transfer(uint8_t(0xFF & (address>>8)));
  SPI.transfer(uint8_t(0xFF & address));
  digitalWrite(mCsPin, 1);

  return true;
}
<commit_msg>added write enable to erase functions Erase functions were not working due to no write enable being called before<commit_after>#include "S25FL208K.h"
#include <SPI.h>

S25FL208K::S25FL208K(uint8_t csPin){
  SPI.begin();
  mCsPin = csPin;
  pinMode(mCsPin, OUTPUT);
  digitalWrite(mCsPin, 1); // active low, start disabled
}

// returns dynamic memory
// therefore needs a delete[] call on the pointer when done
uint8_t* S25FL208K::sendCommand(uint8_t command, uint8_t bytesToRead){
  uint8_t* result = NULL;
  digitalWrite(mCsPin, 0);
  SPI.transfer(command);
  if (bytesToRead > 0){
    result = new uint8_t[bytesToRead];
    for (int i = 0; i<bytesToRead; i++){
      result[i] = SPI.transfer(DUMMY_VALUE);
    }
  }
  digitalWrite(mCsPin, 1);
  return result;
}

uint8_t S25FL208K::readStatus(){
  uint8_t* result = NULL;
  uint8_t output = 0;
  result = sendCommand(READ_STATUS_REG, 1);
  output = result[0];
  delete[] result;
  return output;
}

void S25FL208K::writeEnable(void){
  sendCommand(WRITE_ENABLE);
}

void S25FL208K::writeDisable(void){
  sendCommand(WRITE_DISABLE);
}

bool S25FL208K::getWIP(void){
  return (this->readStatus() & WIP_MASK);
}

bool S25FL208K::readData(uint32_t address, uint32_t numBytes, uint8_t* &result){
  // check WIP bit
  if (this->getWIP()){
    return false;
  }

  digitalWrite(mCsPin, 0);
  // transfer the address as 3 bytes
  SPI.transfer(READ_DATA);
  SPI.transfer(uint8_t(0xFF & (address>>16)));
  SPI.transfer(uint8_t(0xFF & (address>>8)));
  SPI.transfer(uint8_t(0xFF & address));

  // read the data into result
  for(int i = 0; i<numBytes; i++){
    result[i] = SPI.transfer(DUMMY_VALUE);
  }
  // end transfer
  digitalWrite(mCsPin, 1);
  return true;
}

bool S25FL208K::storeData(uint32_t address, uint8_t numBytes, uint8_t* &data){
  // check WIP bit
  if (this->getWIP()){
    return false;
  }

  // check page erased
  bool allOnes = true;
  uint8_t* tempResult = new uint8_t[numBytes];
  this->readData(address, numBytes, tempResult);
  for (int i = 0; i<numBytes; i++){
    if (tempResult[i]!=0xFF){
      allOnes = false;
    }
  }
  delete[] tempResult;

  if (!allOnes){
    return false;
  }

  // set WRITE_ENABLE
  this->writeEnable();

  digitalWrite(mCsPin, 0);
  // send address
  SPI.transfer(PAGE_PROGRAM);
  SPI.transfer(uint8_t(0xFF & (address>>16)));
  SPI.transfer(uint8_t(0xFF & (address>>8)));
  SPI.transfer(uint8_t(0xFF & address));
  //send data
  for(int i = 0; i<numBytes; i++){
    SPI.transfer(data[i]);
  }

  digitalWrite(mCsPin, 1);

  return true;
}

bool S25FL208K::chipErase(void){
  // check WIP bit
  if (this->getWIP()){
    return false;
  }

  // set WRITE_ENABLE
  this->writeEnable();

  this->sendCommand(CHIP_ERASE);
  return true;
}

bool S25FL208K::sectorErase(uint32_t address){
  // check WIP bit
  if (this->getWIP()){
    return false;
  }

  // set WRITE_ENABLE
  this->writeEnable();

  digitalWrite(mCsPin, 0);
  // transfer the address as 3 bytes
  SPI.transfer(SECTOR_ERASE);
  SPI.transfer(uint8_t(0xFF & (address>>16)));
  SPI.transfer(uint8_t(0xFF & (address>>8)));
  SPI.transfer(uint8_t(0xFF & address));
  digitalWrite(mCsPin, 1);

  return true;
}

bool S25FL208K::blockErase(uint32_t address){
  // check WIP bit
  if (this->getWIP()){
    return false;
  }

  // set WRITE_ENABLE
  this->writeEnable();

  digitalWrite(mCsPin, 0);
  // transfer the address as 3 bytes
  SPI.transfer(BLOCK_ERASE);
  SPI.transfer(uint8_t(0xFF & (address>>16)));
  SPI.transfer(uint8_t(0xFF & (address>>8)));
  SPI.transfer(uint8_t(0xFF & address));
  digitalWrite(mCsPin, 1);

  return true;
}
<|endoftext|>


<commit_before>#include "NotificationLoader.h"

CNotificationLoader::CNotificationLoader()
{
	m_hNotificationDLL			= NULL;
	lpfn_Notify_FindClose		= NULL;
	lpfn_Notify_FindFirst		= NULL;
	lpfn_Notify_FindNext		= NULL;
	lpfn_Notify_SetCycleInfo	= NULL;
	lpfn_Notify_GetCycleInfo	= NULL;
	lpfn_Notify_SetState		= NULL;
	lpfn_Notify_GetState		= NULL;
	int m_iBeeperIndex			= -1;
	int m_iVibrateIndex			= -1;
}

CNotificationLoader::~CNotificationLoader()
{
	UnloadNotificationDLL();
}

//  Loading Notification DLL dynamically
BOOL CNotificationLoader::LoadNotificationDLL()
{
	m_hNotificationDLL = LoadLibrary(NOTIFY_DLL);
	if (!m_hNotificationDLL)
	{
		return FALSE;
	}
	//  Map the function pointers to functions exported from the DLL
	lpfn_Notify_FindClose = (LPFN_NOTIFY_FINDCLOSE_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_FindClose");
	lpfn_Notify_FindNext = (LPFN_NOTIFY_FINDNEXT_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_FindNext");
	lpfn_Notify_FindFirst = (LPFN_NOTIFY_FINDFIRST_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_FindFirst");
	lpfn_Notify_SetCycleInfo = (LPFN_NOTIFY_SETCYCLEINFO_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_SetCycleInfo");
	lpfn_Notify_GetCycleInfo = (LPFN_NOTIFY_GETCYCLEINFO_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_GetCycleInfo");
	lpfn_Notify_SetState = (LPFN_NOTIFY_SETSTATE_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_SetState");
	lpfn_Notify_GetState = (LPFN_NOTIFY_GETSTATE_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_GetState");

	if (lpfn_Notify_FindClose	== NULL ||
		lpfn_Notify_FindNext	== NULL ||
		lpfn_Notify_FindFirst	== NULL ||
		lpfn_Notify_SetCycleInfo== NULL ||
		lpfn_Notify_GetCycleInfo== NULL ||
		lpfn_Notify_SetState	== NULL ||
		lpfn_Notify_GetState	== NULL)
	{
		m_hNotificationDLL = NULL;
		return FALSE;
	}
	else
	{
		//  Set the indices of the beeper and vibrate index
		NOTIFY_FINDINFO notifyObject;
		HANDLE	hFindHandle = NULL;
		SI_ALLOC_ALL(&notifyObject);
		notifyObject.StructInfo.dwUsed = 0;
		if(lpfn_Notify_FindFirst(&notifyObject, &hFindHandle) == E_NTFY_SUCCESS)
		{
			int iObCount = 0;
			do
			{
				if(notifyObject.dwObjectType == NOTIFY_TYPE_BEEPER)
				{
					//  Found the Beeper
					m_iBeeperIndex = iObCount;
				}
				else if (notifyObject.dwObjectType == NOTIFY_TYPE_VIBRATOR)
				{
					m_iVibrateIndex = iObCount;
				}
				iObCount++;
				SI_ALLOC_ALL(&notifyObject);
				notifyObject.StructInfo.dwUsed = 0;
			} while(lpfn_Notify_FindNext(&notifyObject, hFindHandle) == E_NTFY_SUCCESS);
		}
		lpfn_Notify_FindClose(hFindHandle);
		return TRUE;
	}
}

BOOL CNotificationLoader::UnloadNotificationDLL()
{
	if (m_hNotificationDLL)
	{
		FreeLibrary(m_hNotificationDLL);
		m_hNotificationDLL		= NULL;
		lpfn_Notify_FindClose	= NULL;
		lpfn_Notify_FindNext	= NULL;
		lpfn_Notify_FindFirst	= NULL;
		lpfn_Notify_SetCycleInfo= NULL;
		lpfn_Notify_GetCycleInfo= NULL;
		lpfn_Notify_SetState	= NULL;
		lpfn_Notify_GetState	= NULL;
	}
	return TRUE;
}

BOOL CNotificationLoader::Beep(int iFrequency, int iVolume, int iDuration)
{
	if (m_iBeeperIndex < 0)
		return FALSE;

	CYCLE_INFO cycleInfo;
	SI_INIT(&cycleInfo);
	DWORD dwResult = lpfn_Notify_GetCycleInfo(m_iBeeperIndex, &cycleInfo);
	if(dwResult != E_NTFY_SUCCESS)
		return FALSE;
	cycleInfo.ObjectTypeSpecific.BeeperSpecific.dwFrequency = iFrequency;
	cycleInfo.ObjectTypeSpecific.BeeperSpecific.dwVolume = iVolume;
	cycleInfo.ObjectTypeSpecific.BeeperSpecific.dwDuration = iDuration;
	dwResult = lpfn_Notify_SetCycleInfo(m_iBeeperIndex, &cycleInfo);
	dwResult = lpfn_Notify_SetState(m_iBeeperIndex, NOTIFY_STATE_CYCLE);

	return TRUE;
}

BOOL CNotificationLoader::Vibrate(int iDuration)
{
	if (m_iVibrateIndex < 0)
		return FALSE;

	CYCLE_INFO cycleInfo;
	SI_INIT(&cycleInfo);
	DWORD dwResult = lpfn_Notify_GetCycleInfo(m_iVibrateIndex, &cycleInfo);
	if(dwResult != E_NTFY_SUCCESS)
		return FALSE;
	cycleInfo.ObjectTypeSpecific.VibratorSpecific.dwDuration = iDuration;
	dwResult = lpfn_Notify_SetCycleInfo(m_iVibrateIndex, &cycleInfo);
	dwResult = lpfn_Notify_SetState(m_iVibrateIndex, NOTIFY_STATE_CYCLE);
	return dwResult == E_NTFY_SUCCESS;
}
<commit_msg>Resolving EMBPD00156561 for 5.0 SP2<commit_after>#include "NotificationLoader.h"

CNotificationLoader::CNotificationLoader()
{
	m_hNotificationDLL			= NULL;
	lpfn_Notify_FindClose		= NULL;
	lpfn_Notify_FindFirst		= NULL;
	lpfn_Notify_FindNext		= NULL;
	lpfn_Notify_SetCycleInfo	= NULL;
	lpfn_Notify_GetCycleInfo	= NULL;
	lpfn_Notify_SetState		= NULL;
	lpfn_Notify_GetState		= NULL;
	m_iBeeperIndex			= -1;
	m_iVibrateIndex			= -1;
}

CNotificationLoader::~CNotificationLoader()
{
	UnloadNotificationDLL();
}

//  Loading Notification DLL dynamically
BOOL CNotificationLoader::LoadNotificationDLL()
{
	m_hNotificationDLL = LoadLibrary(NOTIFY_DLL);
	if (!m_hNotificationDLL)
	{
		return FALSE;
	}
	//  Map the function pointers to functions exported from the DLL
	lpfn_Notify_FindClose = (LPFN_NOTIFY_FINDCLOSE_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_FindClose");
	lpfn_Notify_FindNext = (LPFN_NOTIFY_FINDNEXT_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_FindNext");
	lpfn_Notify_FindFirst = (LPFN_NOTIFY_FINDFIRST_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_FindFirst");
	lpfn_Notify_SetCycleInfo = (LPFN_NOTIFY_SETCYCLEINFO_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_SetCycleInfo");
	lpfn_Notify_GetCycleInfo = (LPFN_NOTIFY_GETCYCLEINFO_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_GetCycleInfo");
	lpfn_Notify_SetState = (LPFN_NOTIFY_SETSTATE_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_SetState");
	lpfn_Notify_GetState = (LPFN_NOTIFY_GETSTATE_T)GetProcAddress
		(m_hNotificationDLL, L"NOTIFY_GetState");

	if (lpfn_Notify_FindClose	== NULL ||
		lpfn_Notify_FindNext	== NULL ||
		lpfn_Notify_FindFirst	== NULL ||
		lpfn_Notify_SetCycleInfo== NULL ||
		lpfn_Notify_GetCycleInfo== NULL ||
		lpfn_Notify_SetState	== NULL ||
		lpfn_Notify_GetState	== NULL)
	{
		m_hNotificationDLL = NULL;
		return FALSE;
	}
	else
	{
		//  Set the indices of the beeper and vibrate index
		NOTIFY_FINDINFO notifyObject;
		HANDLE	hFindHandle = NULL;
		SI_ALLOC_ALL(&notifyObject);
		notifyObject.StructInfo.dwUsed = 0;
		if(lpfn_Notify_FindFirst(&notifyObject, &hFindHandle) == E_NTFY_SUCCESS)
		{
			int iObCount = 0;
			do
			{
				if(notifyObject.dwObjectType == NOTIFY_TYPE_BEEPER)
				{
					//  Found the Beeper
					m_iBeeperIndex = iObCount;
				}
				else if (notifyObject.dwObjectType == NOTIFY_TYPE_VIBRATOR)
				{
					m_iVibrateIndex = iObCount;
				}
				iObCount++;
				SI_ALLOC_ALL(&notifyObject);
				notifyObject.StructInfo.dwUsed = 0;
			} while(lpfn_Notify_FindNext(&notifyObject, hFindHandle) == E_NTFY_SUCCESS);
		}
		lpfn_Notify_FindClose(hFindHandle);
		return TRUE;
	}
}

BOOL CNotificationLoader::UnloadNotificationDLL()
{
	if (m_hNotificationDLL)
	{
		FreeLibrary(m_hNotificationDLL);
		m_hNotificationDLL		= NULL;
		lpfn_Notify_FindClose	= NULL;
		lpfn_Notify_FindNext	= NULL;
		lpfn_Notify_FindFirst	= NULL;
		lpfn_Notify_SetCycleInfo= NULL;
		lpfn_Notify_GetCycleInfo= NULL;
		lpfn_Notify_SetState	= NULL;
		lpfn_Notify_GetState	= NULL;
	}
	return TRUE;
}

BOOL CNotificationLoader::Beep(int iFrequency, int iVolume, int iDuration)
{
	if (m_iBeeperIndex < 0)
		return FALSE;

	CYCLE_INFO cycleInfo;
	SI_INIT(&cycleInfo);
	DWORD dwResult = lpfn_Notify_GetCycleInfo(m_iBeeperIndex, &cycleInfo);
	if(dwResult != E_NTFY_SUCCESS)
		return FALSE;
	cycleInfo.ObjectTypeSpecific.BeeperSpecific.dwFrequency = iFrequency;
	cycleInfo.ObjectTypeSpecific.BeeperSpecific.dwVolume = iVolume;
	cycleInfo.ObjectTypeSpecific.BeeperSpecific.dwDuration = iDuration;
	dwResult = lpfn_Notify_SetCycleInfo(m_iBeeperIndex, &cycleInfo);
	dwResult = lpfn_Notify_SetState(m_iBeeperIndex, NOTIFY_STATE_CYCLE);

	return TRUE;
}

BOOL CNotificationLoader::Vibrate(int iDuration)
{
	if (m_iVibrateIndex < 0)
		return FALSE;

	CYCLE_INFO cycleInfo;
	SI_INIT(&cycleInfo);
	DWORD dwResult = lpfn_Notify_GetCycleInfo(m_iVibrateIndex, &cycleInfo);
	if(dwResult != E_NTFY_SUCCESS)
		return FALSE;
	cycleInfo.ObjectTypeSpecific.VibratorSpecific.dwDuration = iDuration;
	dwResult = lpfn_Notify_SetCycleInfo(m_iVibrateIndex, &cycleInfo);
	dwResult = lpfn_Notify_SetState(m_iVibrateIndex, NOTIFY_STATE_CYCLE);
	return dwResult == E_NTFY_SUCCESS;
}
<|endoftext|>