<commit_before>#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Constants.h"
#include "llvm/Support/raw_ostream.h"

#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"

#include "llvm/IR/Instructions.h"
#include "llvm/IR/IRBuilder.h"

#ifndef NDEBUG
#include "llvm/IR/Verifier.h"
#include "llvm/Support/Debug.h"
#endif

#include <vector>
#include <random>

using namespace llvm;

namespace {
class ObfuscateZero : public BasicBlockPass {
  std::vector<Value *> IntegerVect;
  std::default_random_engine Generator;

public:
  static char ID;

  ObfuscateZero() : BasicBlockPass(ID) {}

  virtual bool runOnBasicBlock(BasicBlock &BB) override {
    IntegerVect.clear();
    bool modified = false;

    // Not iterating from the beginning to avoid obfuscation of Phi instructions
    // parameters
    for (typename BasicBlock::iterator I = BB.getFirstInsertionPt(),
                                       end = BB.end();
         I != end; ++I) {
      Instruction &Inst = *I;
      if (isValidCandidateInstruction(Inst)) {
        for (size_t i{0}; i < Inst.getNumOperands(); ++i) {
          if (Constant *C = isValidCandidateOperand(Inst.getOperand(i))) {
            if (Value *New_val = replaceZero(Inst, C)) {
              Inst.setOperand(i, New_val);
              modified = true;
            } else {
              //dbgs() << "ObfuscateZero: could not rand pick a variable for replacement\n";
            }
          }
        }
      }
      registerInteger(Inst);
    }

#ifndef NDEBUG
    verifyFunction(*BB.getParent());
#endif
    return modified;
  }

private:
  bool isValidCandidateInstruction(Instruction &Inst) {
    if (isa<GetElementPtrInst>(&Inst)) {
      // dbgs() << "Ignoring GEP\n";
      return false;
    } else if (isa<SwitchInst>(&Inst)) {
      // dbgs() << "Ignoring Switch\n";
      return false;
    } else if (isa<CallInst>(&Inst)) {
      // dbgs() << "Ignoring Calls\n";
      return false;
    } else {
      return true;
    }
  }

  Constant *isValidCandidateOperand(Value *V) {
    if (Constant *C = dyn_cast<Constant>(V)) {
      // Checking constant eligibility
      if (isa<PointerType>(C->getType())) {
        // dbgs() << "Ignoring NULL pointers\n";
        return nullptr;
      } else if (C->getType()->isFloatingPointTy()) {
        // dbgs() << "Ignoring Floats 0\n";
        return nullptr;
      } else if (C->isNullValue()) {
        return C;
      } else {
        return nullptr;
      }
    } else {
      return nullptr;
    }
  }

  void registerInteger(Value &V) {
    if (V.getType()->isIntegerTy())
      IntegerVect.emplace_back(&V);
  }

  Value *replaceZero(Instruction &Inst, Value *VReplace) {
    // Replacing 0 by:
    // prime1 * ((x | any1)**2) != prime2 * ((y | any2)**2)
    // with prime1 != prime2 and any1 != 0 and any2 != 0
    using prime_type = uint32_t;
    // FIXME : replace by dynamic generation
    const prime_type p1 = 431, p2 = 277;

    Type *ReplacedType = VReplace->getType(),
         *IntermediaryType = IntegerType::get(Inst.getParent()->getContext(),
                                              sizeof(prime_type) * 8);

    if (IntegerVect.size() < 1) {
      return nullptr;
    }

    std::uniform_int_distribution<size_t> Rand(0, IntegerVect.size() - 1);
    std::uniform_int_distribution<size_t> RandAny(1, 10);

    size_t Index1 = Rand(Generator), Index2 = Rand(Generator);

    // Masking Any1 and Any2 to avoid overflow in the obsfuscation
    Constant *any1 = ConstantInt::get(IntermediaryType, 1 + RandAny(Generator)),
             *any2 = ConstantInt::get(IntermediaryType, 1 + RandAny(Generator)),
             *prime1 = ConstantInt::get(IntermediaryType, p1),
             *prime2 = ConstantInt::get(IntermediaryType, p2),
             // Bitmasks to prevent overflow
        *OverflowMaskLHS = ConstantInt::get(IntermediaryType, 0x00000007),
             *OverflowMaskRHS = ConstantInt::get(IntermediaryType, 0x00000007);

    IRBuilder<> Builder(&Inst);

    // lhs
    // To avoid overflow
    Value *LhsCast =
        Builder.CreateZExtOrTrunc(IntegerVect.at(Index1), IntermediaryType);
    registerInteger(*LhsCast);
    Value *LhsAnd = Builder.CreateAnd(LhsCast, OverflowMaskLHS);
    registerInteger(*LhsAnd);
    Value *LhsOr = Builder.CreateOr(LhsAnd, any1);
    registerInteger(*LhsOr);
    Value *LhsSquare = Builder.CreateMul(LhsOr, LhsOr);
    registerInteger(*LhsSquare);
    Value *LhsTot = Builder.CreateMul(LhsSquare, prime1);
    registerInteger(*LhsTot);

    // rhs
    Value *RhsCast =
        Builder.CreateZExtOrTrunc(IntegerVect.at(Index2), IntermediaryType);
    registerInteger(*RhsCast);
    Value *RhsAnd = Builder.CreateAnd(RhsCast, OverflowMaskRHS);
    registerInteger(*RhsAnd);
    Value *RhsOr = Builder.CreateOr(RhsAnd, any2);
    registerInteger(*RhsOr);
    Value *RhsSquare = Builder.CreateMul(RhsOr, RhsOr);
    registerInteger(*RhsSquare);
    Value *RhsTot = Builder.CreateMul(RhsSquare, prime2);
    registerInteger(*RhsTot);

    // comp
    Value *comp =
        Builder.CreateICmp(CmpInst::Predicate::ICMP_EQ, LhsTot, RhsTot);
    registerInteger(*comp);
    Value *castComp = Builder.CreateZExt(comp, ReplacedType);
    registerInteger(*castComp);

    return castComp;
  }
};
}

char ObfuscateZero::ID = 0;
static RegisterPass<ObfuscateZero> X("ObfuscateZero", "Obfuscates zeroes",
                                     false, false);

// register pass for clang use
static void registerObfuscateZeroPass(const PassManagerBuilder &,
                                      PassManagerBase &PM) {
  PM.add(new ObfuscateZero());
}
static RegisterStandardPasses
    RegisterMBAPass(PassManagerBuilder::EP_EarlyAsPossible,
                    registerObfuscateZeroPass);
<commit_msg>Adding randomization of prime numbers<commit_after>#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Constants.h"
#include "llvm/Support/raw_ostream.h"

#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"

#include "llvm/IR/Instructions.h"
#include "llvm/IR/IRBuilder.h"

#ifndef NDEBUG
#include "llvm/IR/Verifier.h"
#include "llvm/Support/Debug.h"
#endif

#include <vector>
#include <random>

using namespace llvm;

namespace {
  using prime_type = uint32_t;

static const prime_type Prime_array[] = {
     2 ,    3 ,    5 ,    7,     11,     13,     17,     19,     23,     29,
     31,    37,    41,    43,    47,     53,     59,     61,     67,     71,
     73,    79,    83,    89,    97,    101,    103,    107,    109,    113,
    127,   131,   137,   139,   149,    151,    157,    163,    167,    173,
    179,   181,   191,   193,   197,    199,    211,    223,    227,    229,
    233,   239,   241,   251,   257,    263,    269,    271,    277,    281,
    283,   293,   307,   311,   313,    317,    331,    337,    347,    349,
    353,   359,   367,   373,   379,    383,    389,    397,    401,    409,
    419,   421,   431,   433,   439,    443,    449,    457,    461,    463,
    467,   479,   487,   491,   499,    503,    509,    521,    523,    541,
    547,   557,   563,   569,   571,    577,    587,    593,    599,    601,
    607,   613,   617,   619,   631,    641,    643,    647,    653,    659,
    661,   673,   677,   683,   691,    701,    709,    719,    727,    733,
    739,   743,   751,   757,   761,    769,    773,    787,    797,    809,
    811,   821,   823,   827,   829,    839,    853,    857,    859,    863,
    877,   881,   883,   887,   907,    911,    919,    929,    937,    941,
    947,   953,   967,   971,   977,    983,    991,    997};

class ObfuscateZero : public BasicBlockPass {
  std::vector<Value *> IntegerVect;
  std::default_random_engine Generator;

public:

  static char ID;

  ObfuscateZero() : BasicBlockPass(ID) {}

  virtual bool runOnBasicBlock(BasicBlock &BB) override {
    IntegerVect.clear();
    bool modified = false;

    // Not iterating from the beginning to avoid obfuscation of Phi instructions
    // parameters
    for (typename BasicBlock::iterator I = BB.getFirstInsertionPt(),
                                       end = BB.end();
         I != end; ++I) {
      Instruction &Inst = *I;
      if (isValidCandidateInstruction(Inst)) {
        for (size_t i{0}; i < Inst.getNumOperands(); ++i) {
          if (Constant *C = isValidCandidateOperand(Inst.getOperand(i))) {
            if (Value *New_val = replaceZero(Inst, C)) {
              Inst.setOperand(i, New_val);
              modified = true;
            } else {
              //dbgs() << "ObfuscateZero: could not rand pick a variable for replacement\n";
            }
          }
        }
      }
      registerInteger(Inst);
    }

#ifndef NDEBUG
    verifyFunction(*BB.getParent());
#endif
    return modified;
  }

private:
  bool isValidCandidateInstruction(Instruction &Inst) {
    if (isa<GetElementPtrInst>(&Inst)) {
      // dbgs() << "Ignoring GEP\n";
      return false;
    } else if (isa<SwitchInst>(&Inst)) {
      // dbgs() << "Ignoring Switch\n";
      return false;
    } else if (isa<CallInst>(&Inst)) {
      // dbgs() << "Ignoring Calls\n";
      return false;
    } else {
      return true;
    }
  }

  Constant *isValidCandidateOperand(Value *V) {
    if (Constant *C = dyn_cast<Constant>(V)) {
      // Checking constant eligibility
      if (isa<PointerType>(C->getType())) {
        // dbgs() << "Ignoring NULL pointers\n";
        return nullptr;
      } else if (C->getType()->isFloatingPointTy()) {
        // dbgs() << "Ignoring Floats 0\n";
        return nullptr;
      } else if (C->isNullValue()) {
        return C;
      } else {
        return nullptr;
      }
    } else {
      return nullptr;
    }
  }

  void registerInteger(Value &V) {
    if (V.getType()->isIntegerTy())
      IntegerVect.emplace_back(&V);
  }

  // Return a random prime number not equal to DifferentFrom
  // If an error occurs returns 0
  prime_type getPrime(prime_type DifferentFrom = 0) {
      static std::uniform_int_distribution<prime_type> Rand(0, sizeof(Prime_array) / sizeof(prime_type));
      size_t MaxLoop = 10;
      prime_type Prime;

      do {
            Prime = Prime_array[Rand(Generator)];
      } while(Prime == DifferentFrom && --MaxLoop);

      if(!MaxLoop) {
          return 0;
      }

      return Prime;
  }

  Value *replaceZero(Instruction &Inst, Value *VReplace) {
    // Replacing 0 by:
    // prime1 * ((x | any1)**2) != prime2 * ((y | any2)**2)
    // with prime1 != prime2 and any1 != 0 and any2 != 0
    prime_type p1 = getPrime(),
               p2 = getPrime(p1);

    if(p2 == 0 || p1 == 0)
        return nullptr;

    Type *ReplacedType = VReplace->getType(),
         *IntermediaryType = IntegerType::get(Inst.getParent()->getContext(),
                                              sizeof(prime_type) * 8);

    if (IntegerVect.size() < 1) {
      return nullptr;
    }

    std::uniform_int_distribution<size_t> Rand(0, IntegerVect.size() - 1);
    std::uniform_int_distribution<size_t> RandAny(1, 10);

    size_t Index1 = Rand(Generator), Index2 = Rand(Generator);

    // Masking Any1 and Any2 to avoid overflow in the obsfuscation
    Constant *any1 = ConstantInt::get(IntermediaryType, 1 + RandAny(Generator)),
             *any2 = ConstantInt::get(IntermediaryType, 1 + RandAny(Generator)),
             *prime1 = ConstantInt::get(IntermediaryType, p1),
             *prime2 = ConstantInt::get(IntermediaryType, p2),
             // Bitmasks to prevent overflow
        *OverflowMaskLHS = ConstantInt::get(IntermediaryType, 0x00000007),
             *OverflowMaskRHS = ConstantInt::get(IntermediaryType, 0x00000007);

    IRBuilder<> Builder(&Inst);

    // lhs
    // To avoid overflow
    Value *LhsCast =
        Builder.CreateZExtOrTrunc(IntegerVect.at(Index1), IntermediaryType);
    registerInteger(*LhsCast);
    Value *LhsAnd = Builder.CreateAnd(LhsCast, OverflowMaskLHS);
    registerInteger(*LhsAnd);
    Value *LhsOr = Builder.CreateOr(LhsAnd, any1);
    registerInteger(*LhsOr);
    Value *LhsSquare = Builder.CreateMul(LhsOr, LhsOr);
    registerInteger(*LhsSquare);
    Value *LhsTot = Builder.CreateMul(LhsSquare, prime1);
    registerInteger(*LhsTot);

    // rhs
    Value *RhsCast =
        Builder.CreateZExtOrTrunc(IntegerVect.at(Index2), IntermediaryType);
    registerInteger(*RhsCast);
    Value *RhsAnd = Builder.CreateAnd(RhsCast, OverflowMaskRHS);
    registerInteger(*RhsAnd);
    Value *RhsOr = Builder.CreateOr(RhsAnd, any2);
    registerInteger(*RhsOr);
    Value *RhsSquare = Builder.CreateMul(RhsOr, RhsOr);
    registerInteger(*RhsSquare);
    Value *RhsTot = Builder.CreateMul(RhsSquare, prime2);
    registerInteger(*RhsTot);

    // comp
    Value *comp =
        Builder.CreateICmp(CmpInst::Predicate::ICMP_EQ, LhsTot, RhsTot);
    registerInteger(*comp);
    Value *castComp = Builder.CreateZExt(comp, ReplacedType);
    registerInteger(*castComp);

    return castComp;
  }
};
}

char ObfuscateZero::ID = 0;
static RegisterPass<ObfuscateZero> X("ObfuscateZero", "Obfuscates zeroes",
                                     false, false);

// register pass for clang use
static void registerObfuscateZeroPass(const PassManagerBuilder &,
                                      PassManagerBase &PM) {
  PM.add(new ObfuscateZero());
}
static RegisterStandardPasses
    RegisterMBAPass(PassManagerBuilder::EP_EarlyAsPossible,
                    registerObfuscateZeroPass);
<|endoftext|>


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

#include <psprint/jobdata.hxx>
#include <psprint/printerinfomanager.hxx>
#include <tools/stream.hxx>

#ifdef SOLARIS
#include <alloca.h>
#else
#include <stdlib.h>
#endif

using namespace psp;
using namespace rtl;

bool JobData::getStreamBuffer( void*& pData, int& bytes )
{
    // consistency checks
    if( ! m_pParser )
        m_pParser = m_aContext.getParser();
    if( m_pParser != m_aContext.getParser() ||
        ! m_pParser )
        return false;

    SvMemoryStream aStream;
    ByteString aLine;

    // write header job data
    aStream.WriteLine( "JobData 1" );

    aLine = "printer=";
    aLine += ByteString( String( m_aPrinterName ), RTL_TEXTENCODING_UTF8 );
    aStream.WriteLine( aLine );

    aLine = "orientation=";
    aLine += m_eOrientation == orientation::Landscape ? "Landscape" : "Portrait";
    aStream.WriteLine( aLine );

    aLine = "copies=";
    aLine += ByteString::CreateFromInt32( m_nCopies );
    aStream.WriteLine( aLine );

    aLine = "scale=";
    aLine += ByteString::CreateFromInt32( m_nScale );
    aStream.WriteLine( aLine );

    aLine = "margindajustment=";
    aLine += ByteString::CreateFromInt32( m_nLeftMarginAdjust );
    aLine += ',';
    aLine += ByteString::CreateFromInt32( m_nRightMarginAdjust );
    aLine += ',';
    aLine += ByteString::CreateFromInt32( m_nTopMarginAdjust );
    aLine += ',';
    aLine += ByteString::CreateFromInt32( m_nBottomMarginAdjust );
    aStream.WriteLine( aLine );

    aLine = "colordepth=";
    aLine += ByteString::CreateFromInt32( m_nColorDepth );
    aStream.WriteLine( aLine );

    aLine = "pslevel=";
    aLine += ByteString::CreateFromInt32( m_nPSLevel );
    aStream.WriteLine( aLine );

    aLine = "colordevice=";
    aLine += ByteString::CreateFromInt32( m_nColorDevice );
    aStream.WriteLine( aLine );

    // now append the PPDContext stream buffer
    aStream.WriteLine( "PPDContexData" );
    ULONG nBytes;
    void* pContextBuffer = m_aContext.getStreamableBuffer( nBytes );
    if( nBytes )
        aStream.Write( pContextBuffer, nBytes );

    // success
    pData = rtl_allocateMemory( bytes = aStream.GetSize() );
    memcpy( pData, aStream.GetData(), bytes );
    return true;
}

bool JobData::constructFromStreamBuffer( void* pData, int bytes, JobData& rJobData )
{
    SvMemoryStream aStream( pData, bytes, STREAM_READ );
    ByteString aLine;
    bool bVersion       = false;
    bool bPrinter       = false;
    bool bOrientation   = false;
    bool bCopies        = false;
    bool bScale         = false;
    bool bContext       = false;
    bool bMargin        = false;
    bool bColorDepth    = false;
    bool bColorDevice   = false;
    bool bPSLevel       = false;
    while( ! aStream.IsEof() )
    {
        aStream.ReadLine( aLine );
        if( aLine.CompareTo( "JobData", 7 ) == COMPARE_EQUAL )
            bVersion = true;
        else if( aLine.CompareTo( "printer=", 8 ) == COMPARE_EQUAL )
        {
            bPrinter = true;
            rJobData.m_aPrinterName = String( aLine.Copy( 8 ), RTL_TEXTENCODING_UTF8 );
        }
        else if( aLine.CompareTo( "orientation=", 12 ) == COMPARE_EQUAL )
        {
            bOrientation = true;
            rJobData.m_eOrientation = aLine.Copy( 12 ).EqualsIgnoreCaseAscii( "landscape" ) ? orientation::Landscape : orientation::Portrait;
        }
        else if( aLine.CompareTo( "copies=", 7 ) == COMPARE_EQUAL )
        {
            bCopies = true;
            rJobData.m_nCopies = aLine.Copy( 7 ).ToInt32();
        }
        else if( aLine.CompareTo( "scale=", 6 ) == COMPARE_EQUAL )
        {
            bScale = true;
            rJobData.m_nScale = aLine.Copy( 6 ).ToInt32();
        }
        else if( aLine.CompareTo( "margindajustment=",17 ) == COMPARE_EQUAL )
        {
            bMargin = true;
            ByteString aValues( aLine.Copy( 17 ) );
            rJobData.m_nLeftMarginAdjust = aValues.GetToken( 0, ',' ).ToInt32();
            rJobData.m_nRightMarginAdjust = aValues.GetToken( 1, ',' ).ToInt32();
            rJobData.m_nTopMarginAdjust = aValues.GetToken( 2, ',' ).ToInt32();
            rJobData.m_nBottomMarginAdjust = aValues.GetToken( 3, ',' ).ToInt32();
        }
        else if( aLine.CompareTo( "colordepth=", 11 ) == COMPARE_EQUAL )
        {
            bColorDepth = true;
            rJobData.m_nColorDepth = aLine.Copy( 11 ).ToInt32();
        }
        else if( aLine.CompareTo( "colordevice=", 12 ) == COMPARE_EQUAL )
        {
            bColorDevice = true;
            rJobData.m_nColorDevice = aLine.Copy( 12 ).ToInt32();
        }
        else if( aLine.CompareTo( "pslevel=", 8 ) == COMPARE_EQUAL )
        {
            bPSLevel = true;
            rJobData.m_nPSLevel = aLine.Copy( 8 ).ToInt32();
        }
        else if( aLine.Equals( "PPDContexData" ) )
        {
            if( bPrinter )
            {
                PrinterInfoManager& rManager = PrinterInfoManager::get();
                const PrinterInfo& rInfo = rManager.getPrinterInfo( rJobData.m_aPrinterName );
                rJobData.m_pParser = PPDParser::getParser( rInfo.m_aDriverName );
                if( rJobData.m_pParser )
                {
                    rJobData.m_aContext.setParser( rJobData.m_pParser );
                    int nBytes = bytes - aStream.Tell();
                    void* pRemain = alloca( bytes - aStream.Tell() );
                    aStream.Read( pRemain, nBytes );
                    rJobData.m_aContext.rebuildFromStreamBuffer( pRemain, nBytes );
                    bContext = true;
                }
            }
        }
    }

    return bVersion && bPrinter && bOrientation && bCopies && bScale && bContext && bMargin && bPSLevel && bColorDevice && bColorDepth;
}
<commit_msg>INTEGRATION: CWS valgrind01 (1.2.88); FILE MERGED 2003/10/30 17:43:00 hr 1.2.88.1: #i20184#: JobData::getStreamBuffer() return buffer tailored to the actual size of the stream instead to the size of the stream buffer<commit_after>/*************************************************************************
 *
 *  $RCSfile: jobdata.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2003-11-25 10:30:17 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <psprint/jobdata.hxx>
#include <psprint/printerinfomanager.hxx>
#include <tools/stream.hxx>

#ifdef SOLARIS
#include <alloca.h>
#else
#include <stdlib.h>
#endif

using namespace psp;
using namespace rtl;

bool JobData::getStreamBuffer( void*& pData, int& bytes )
{
    // consistency checks
    if( ! m_pParser )
        m_pParser = m_aContext.getParser();
    if( m_pParser != m_aContext.getParser() ||
        ! m_pParser )
        return false;

    SvMemoryStream aStream;
    ByteString aLine;

    // write header job data
    aStream.WriteLine( "JobData 1" );

    aLine = "printer=";
    aLine += ByteString( String( m_aPrinterName ), RTL_TEXTENCODING_UTF8 );
    aStream.WriteLine( aLine );

    aLine = "orientation=";
    aLine += m_eOrientation == orientation::Landscape ? "Landscape" : "Portrait";
    aStream.WriteLine( aLine );

    aLine = "copies=";
    aLine += ByteString::CreateFromInt32( m_nCopies );
    aStream.WriteLine( aLine );

    aLine = "scale=";
    aLine += ByteString::CreateFromInt32( m_nScale );
    aStream.WriteLine( aLine );

    aLine = "margindajustment=";
    aLine += ByteString::CreateFromInt32( m_nLeftMarginAdjust );
    aLine += ',';
    aLine += ByteString::CreateFromInt32( m_nRightMarginAdjust );
    aLine += ',';
    aLine += ByteString::CreateFromInt32( m_nTopMarginAdjust );
    aLine += ',';
    aLine += ByteString::CreateFromInt32( m_nBottomMarginAdjust );
    aStream.WriteLine( aLine );

    aLine = "colordepth=";
    aLine += ByteString::CreateFromInt32( m_nColorDepth );
    aStream.WriteLine( aLine );

    aLine = "pslevel=";
    aLine += ByteString::CreateFromInt32( m_nPSLevel );
    aStream.WriteLine( aLine );

    aLine = "colordevice=";
    aLine += ByteString::CreateFromInt32( m_nColorDevice );
    aStream.WriteLine( aLine );

    // now append the PPDContext stream buffer
    aStream.WriteLine( "PPDContexData" );
    ULONG nBytes;
    void* pContextBuffer = m_aContext.getStreamableBuffer( nBytes );
    if( nBytes )
        aStream.Write( pContextBuffer, nBytes );

    // success
    pData = rtl_allocateMemory( bytes = aStream.Tell() );
    memcpy( pData, aStream.GetData(), bytes );
    return true;
}

bool JobData::constructFromStreamBuffer( void* pData, int bytes, JobData& rJobData )
{
    SvMemoryStream aStream( pData, bytes, STREAM_READ );
    ByteString aLine;
    bool bVersion       = false;
    bool bPrinter       = false;
    bool bOrientation   = false;
    bool bCopies        = false;
    bool bScale         = false;
    bool bContext       = false;
    bool bMargin        = false;
    bool bColorDepth    = false;
    bool bColorDevice   = false;
    bool bPSLevel       = false;
    while( ! aStream.IsEof() )
    {
        aStream.ReadLine( aLine );
        if( aLine.CompareTo( "JobData", 7 ) == COMPARE_EQUAL )
            bVersion = true;
        else if( aLine.CompareTo( "printer=", 8 ) == COMPARE_EQUAL )
        {
            bPrinter = true;
            rJobData.m_aPrinterName = String( aLine.Copy( 8 ), RTL_TEXTENCODING_UTF8 );
        }
        else if( aLine.CompareTo( "orientation=", 12 ) == COMPARE_EQUAL )
        {
            bOrientation = true;
            rJobData.m_eOrientation = aLine.Copy( 12 ).EqualsIgnoreCaseAscii( "landscape" ) ? orientation::Landscape : orientation::Portrait;
        }
        else if( aLine.CompareTo( "copies=", 7 ) == COMPARE_EQUAL )
        {
            bCopies = true;
            rJobData.m_nCopies = aLine.Copy( 7 ).ToInt32();
        }
        else if( aLine.CompareTo( "scale=", 6 ) == COMPARE_EQUAL )
        {
            bScale = true;
            rJobData.m_nScale = aLine.Copy( 6 ).ToInt32();
        }
        else if( aLine.CompareTo( "margindajustment=",17 ) == COMPARE_EQUAL )
        {
            bMargin = true;
            ByteString aValues( aLine.Copy( 17 ) );
            rJobData.m_nLeftMarginAdjust = aValues.GetToken( 0, ',' ).ToInt32();
            rJobData.m_nRightMarginAdjust = aValues.GetToken( 1, ',' ).ToInt32();
            rJobData.m_nTopMarginAdjust = aValues.GetToken( 2, ',' ).ToInt32();
            rJobData.m_nBottomMarginAdjust = aValues.GetToken( 3, ',' ).ToInt32();
        }
        else if( aLine.CompareTo( "colordepth=", 11 ) == COMPARE_EQUAL )
        {
            bColorDepth = true;
            rJobData.m_nColorDepth = aLine.Copy( 11 ).ToInt32();
        }
        else if( aLine.CompareTo( "colordevice=", 12 ) == COMPARE_EQUAL )
        {
            bColorDevice = true;
            rJobData.m_nColorDevice = aLine.Copy( 12 ).ToInt32();
        }
        else if( aLine.CompareTo( "pslevel=", 8 ) == COMPARE_EQUAL )
        {
            bPSLevel = true;
            rJobData.m_nPSLevel = aLine.Copy( 8 ).ToInt32();
        }
        else if( aLine.Equals( "PPDContexData" ) )
        {
            if( bPrinter )
            {
                PrinterInfoManager& rManager = PrinterInfoManager::get();
                const PrinterInfo& rInfo = rManager.getPrinterInfo( rJobData.m_aPrinterName );
                rJobData.m_pParser = PPDParser::getParser( rInfo.m_aDriverName );
                if( rJobData.m_pParser )
                {
                    rJobData.m_aContext.setParser( rJobData.m_pParser );
                    int nBytes = bytes - aStream.Tell();
                    void* pRemain = alloca( bytes - aStream.Tell() );
                    aStream.Read( pRemain, nBytes );
                    rJobData.m_aContext.rebuildFromStreamBuffer( pRemain, nBytes );
                    bContext = true;
                }
            }
        }
    }

    return bVersion && bPrinter && bOrientation && bCopies && bScale && bContext && bMargin && bPSLevel && bColorDevice && bColorDepth;
}
<|endoftext|>


<commit_before><commit_msg>Reduce base energy requirement for launching missiles by 80%, and multiply by lvl**1.5 instead of **2.<commit_after><|endoftext|>


<commit_before><commit_msg>Update a comment.<commit_after><|endoftext|>


<commit_before>/*
 * SessionProjects.cpp
 *
 * Copyright (C) 2009-11 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

// TODO: detecting copy/move/network:
/*
    - read INDEX
    - read id file

    - if INDEX contains id mapped to correct path then use

    - if INDEX doesn't not contain id or path then create new

    - if INDEX has id but path doesn't match then may have been
      a move or a copy so create a copy of the scratch dir and
      associate it with a new id

    - if has an id file but nothing in the index at all then
      create a brand new entry/dir using that id
*/

#include <session/projects/SessionProjects.hpp>

#include <core/FilePath.hpp>
#include <core/Settings.hpp>
#include <core/Exec.hpp>
#include <core/FileSerializer.hpp>
#include <core/system/System.hpp>
#include <core/FileSerializer.hpp>
#include <core/r_util/RProjectFile.hpp>

#include <session/SessionModuleContext.hpp>
#include <session/SessionUserSettings.hpp>
#include <session/SessionPersistentState.hpp>

using namespace core;

namespace session {
namespace projects {

namespace {

ProjectContext s_projectContext;

void onSuspend(Settings*)
{
   // on suspend write out current project path as the one to use
   // on resume. we read this back in initalize (rather than in
   // the onResume handler) becuase we need it very early in the
   // processes lifetime and onResume happens too late
   persistentState().setNextSessionProjectPath(s_projectContext.file());
}

void onResume(const Settings&) {}

Error createProject(const json::JsonRpcRequest& request,
                    json::JsonRpcResponse* pResponse)
{
   // determine project file path
   std::string projectFile;
   Error error = json::readParam(request.params, 0, &projectFile);
   if (error)
      return error;
   FilePath projectFilePath = module_context::resolveAliasedPath(projectFile);

   // new uuid for project
   std::string uuid = core::system::generateUuid();

   // create the project file
   return r_util::writeProjectFile(uuid, projectFilePath);
}

}  // anonymous namespace

void startup()
{
   // register suspend handler
   using namespace module_context;
   addSuspendHandler(SuspendHandler(onSuspend, onResume));

   // determine project file path
   FilePath projectFilePath;

   // see if there is a project path hard-wired for the next session
   // (this would be used for a switch to project or for the resuming of
   // a suspended session)
   FilePath nextSessionProjectPath = persistentState().nextSessionProjectPath();
   if (!nextSessionProjectPath.empty())
   {
      // reset next session project path so its a one shot deal
      persistentState().setNextSessionProjectPath(FilePath());

      // clear any initial context settings which may be leftover
      // by a re-instatiation of rsession by desktop
      session::options().clearInitialContextSettings();

      // set project path
      projectFilePath = nextSessionProjectPath;
   }

   // check for envrionment variable (file association)
   else if (!session::options().initialProjectPath().empty())
   {
      projectFilePath = session::options().initialProjectPath();
   }

   // check for other working dir override (implies a launch of a file
   // but not of a project). this code path is here to prevent
   // the next code path from executing
   else if (!session::options().initialWorkingDirOverride().empty())
   {
      projectFilePath = FilePath();
   }

   // check for restore based on settings
   else if (userSettings().alwaysRestoreLastProject() &&
            !userSettings().lastProjectPath().empty())
   {
      projectFilePath = userSettings().lastProjectPath();
   }

   // else no active project for this session
   else
   {
      projectFilePath = FilePath();
   }

   // if we have a project file path then try to initialize the
   // project context (show a warning to the user if we can't)
   if (!projectFilePath.empty())
   {
      std::string userErrMsg;
      Error error = s_projectContext.initialize(projectFilePath, &userErrMsg);
      if (error)
      {
         // log the error
         error.addProperty("project-file", projectFilePath.absolutePath());
         error.addProperty("user-msg", userErrMsg);
         LOG_ERROR(error);

         // show the error
         std::string msg =
           "Project '" + projectFilePath.absolutePath() + "' "
           "could not be opened: " + userErrMsg;
          module_context::showErrorMessage("Error Opening Project", msg);
      }
   }

   // save the active project path for the next session (may be empty)
   userSettings().setLastProjectPath(s_projectContext.file());
}

Error initialize()
{
   using boost::bind;
   using namespace module_context;
   ExecBlock initBlock ;
   initBlock.addFunctions()
      (bind(registerRpcMethod, "create_project", createProject))
   ;
   return initBlock.execute();
}

const ProjectContext& projectContext()
{
   return s_projectContext;
}

} // namespace projects
} // namesapce session

<commit_msg>only attempt to restore a project once (so we don't keep trying to load a project which doesn't exist)<commit_after>/*
 * SessionProjects.cpp
 *
 * Copyright (C) 2009-11 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

// TODO: detecting copy/move/network:
/*
    - read INDEX
    - read id file

    - if INDEX contains id mapped to correct path then use

    - if INDEX doesn't not contain id or path then create new

    - if INDEX has id but path doesn't match then may have been
      a move or a copy so create a copy of the scratch dir and
      associate it with a new id

    - if has an id file but nothing in the index at all then
      create a brand new entry/dir using that id
*/

#include <session/projects/SessionProjects.hpp>

#include <core/FilePath.hpp>
#include <core/Settings.hpp>
#include <core/Exec.hpp>
#include <core/FileSerializer.hpp>
#include <core/system/System.hpp>
#include <core/FileSerializer.hpp>
#include <core/r_util/RProjectFile.hpp>

#include <session/SessionModuleContext.hpp>
#include <session/SessionUserSettings.hpp>
#include <session/SessionPersistentState.hpp>

using namespace core;

namespace session {
namespace projects {

namespace {

ProjectContext s_projectContext;

void onSuspend(Settings*)
{
   // on suspend write out current project path as the one to use
   // on resume. we read this back in initalize (rather than in
   // the onResume handler) becuase we need it very early in the
   // processes lifetime and onResume happens too late
   persistentState().setNextSessionProjectPath(s_projectContext.file());
}

void onResume(const Settings&) {}

Error createProject(const json::JsonRpcRequest& request,
                    json::JsonRpcResponse* pResponse)
{
   // determine project file path
   std::string projectFile;
   Error error = json::readParam(request.params, 0, &projectFile);
   if (error)
      return error;
   FilePath projectFilePath = module_context::resolveAliasedPath(projectFile);

   // new uuid for project
   std::string uuid = core::system::generateUuid();

   // create the project file
   return r_util::writeProjectFile(uuid, projectFilePath);
}

}  // anonymous namespace

void startup()
{
   // register suspend handler
   using namespace module_context;
   addSuspendHandler(SuspendHandler(onSuspend, onResume));

   // determine project file path
   FilePath projectFilePath;

   // see if there is a project path hard-wired for the next session
   // (this would be used for a switch to project or for the resuming of
   // a suspended session)
   FilePath nextSessionProjectPath = persistentState().nextSessionProjectPath();
   if (!nextSessionProjectPath.empty())
   {
      // reset next session project path so its a one shot deal
      persistentState().setNextSessionProjectPath(FilePath());

      // clear any initial context settings which may be leftover
      // by a re-instatiation of rsession by desktop
      session::options().clearInitialContextSettings();

      // set project path
      projectFilePath = nextSessionProjectPath;
   }

   // check for envrionment variable (file association)
   else if (!session::options().initialProjectPath().empty())
   {
      projectFilePath = session::options().initialProjectPath();
   }

   // check for other working dir override (implies a launch of a file
   // but not of a project). this code path is here to prevent
   // the next code path from executing
   else if (!session::options().initialWorkingDirOverride().empty())
   {
      projectFilePath = FilePath();
   }

   // check for restore based on settings
   else if (userSettings().alwaysRestoreLastProject() &&
            !userSettings().lastProjectPath().empty())
   {
      // get last project path
      projectFilePath = userSettings().lastProjectPath();

      // reset it to empty so that we only attempt to load the "lastProject"
      // a single time (this will be reset to the path below after we
      // clear the s_projectContext.initialize)
      userSettings().setLastProjectPath(FilePath());
   }

   // else no active project for this session
   else
   {
      projectFilePath = FilePath();
   }

   // if we have a project file path then try to initialize the
   // project context (show a warning to the user if we can't)
   if (!projectFilePath.empty())
   {
      std::string userErrMsg;
      Error error = s_projectContext.initialize(projectFilePath, &userErrMsg);
      if (error)
      {
         // log the error
         error.addProperty("project-file", projectFilePath.absolutePath());
         error.addProperty("user-msg", userErrMsg);
         LOG_ERROR(error);

         // show the error
         std::string msg =
           "Project '" + projectFilePath.absolutePath() + "' "
           "could not be opened: " + userErrMsg;
          module_context::showErrorMessage("Error Opening Project", msg);
      }
   }

   // save the active project path for the next session (may be empty)
   userSettings().setLastProjectPath(s_projectContext.file());
}

Error initialize()
{
   using boost::bind;
   using namespace module_context;
   ExecBlock initBlock ;
   initBlock.addFunctions()
      (bind(registerRpcMethod, "create_project", createProject))
   ;
   return initBlock.execute();
}

const ProjectContext& projectContext()
{
   return s_projectContext;
}

} // namespace projects
} // namesapce session

<|endoftext|>


<commit_before><commit_msg>Removing sync from file_util::Delete for ChromeOS.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix the final few remaining warnings in base<commit_after><|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2012
  \file      interface_db.h
  \authors     (cerevra@gmail.com)
  \authors     (rdo@rk9.bmstu.ru)
  \date      15.11.2012
  \brief
  \indent    4T
*/

template <class T>
void pushContext           (T context)
{
	pushContxt(bany<T>(context));
}

template <class T>
T popContext            ()
{
	return any_cast<T>(popContxt());
}
<commit_msg> - починка<commit_after>/*!
  \copyright (c) RDO-Team, 2012
  \file      interface_db.h
  \authors     (cerevra@gmail.com)
  \authors     (rdo@rk9.bmstu.ru)
  \date      15.11.2012
  \brief
  \indent    4T
*/

template <class T>
void IDB::pushContext           (T context)
{
	pushContxt(boost::any(context));
}

template <class T>
T IDB::popContext            ()
{
	return boost::any_cast<T>(popContxt());
}
<|endoftext|>


<commit_before>//bank00.cpp -- Bank class implementation
//version 00

#include <iostream>
#include <cstdlib>
#include <ctime>
#include "bank00.h"

using namespace std;

void Bank::create_account()
{
	srand(time(NULL));
	cout<<"Please enter your name."<<endl;
	getline(cin, name);
	cout<<"Please enter the amount you would like to deposit."<<endl;
	cin>>balance;
	account_no = rand();
	cout<<"Please enter a four digit number for your PIN."<<endl;
	cin>>pin;
}

void Bank::change_pin()
{
	int new_pin = 0;
	cout<<"Please enter a four digit number as your PIN."<<endl;
	cin>>new_pin;
	if(new_pin == pin)
	{
		cout<<"New PIN cannot be same as old PIN."<<endl;
		cout<<"Please enter a different PIN."<<endl;
		cin>>new_pin;
		pin = new_pin;
	}
	else
		pin = new_pin;
}

void Bank::withdraw()
{
	double amount = 0.0;
	cout<<"Please enter the amount."<<endl;
	cin>>amount;
	if(amount > balance)
		cout<<"Withdrawal amount cannot be greater than the available balance."<<endl;
	else
		balance -= amount;
	cout<<"Available balance is $"<<balance<<endl;
	cout<<"Thank you."<<endl;
}

void Bank::display_balance()
{
	cout<<"Account Number: "<<account_no<<endl;
	cout<<"Balance $"<<balance<<endl;
	cout<<"Thank you."<<endl;
}

void Bank::authenticate()
{
	int input_pin = 0, choice = 0;
	cout<<"Please enter your PIN."<<endl;
	cin>>input_pin;
	if(input_pin == pin)
	{
		cout<<"Hello "<<name<<endl;
		cout<<"Enter 1 to change pin."<<endl;
		cout<<"Enter 2 to withdraw cash."<<endl;
		cout<<"Enter 3 to check balance."<<endl;
		cout<<"Enter 4 to quit."<<endl;
		cin>>choice;
		switch(choice)
		{
			case 1:
				change_pin();
				break;

			case 2:
				withdraw();
				break;

			case 3:
				display_balance();
				break;

			default:
				exit(EXIT_SUCCESS);
		}
	}

	else
	{
		cout<<"Incorrect pin."<<endl;
		exit(EXIT_SUCCESS);
	}

}<commit_msg>Formatting<commit_after>//bank00.cpp -- Bank class implementation
//version 00

#include <iostream>
#include <cstdlib>
#include <ctime>
#include "bank00.h"

using namespace std;

void Bank::create_account()
{
	srand(time(NULL));
	cout<<"Please enter your name."<<endl;
	getline(cin, name);
	cout<<"Please enter the amount you would like to deposit."<<endl;
	cin>>balance;
	account_no = rand();
	cout<<"Please enter a four digit number for your PIN."<<endl;
	cin>>pin;
}

void Bank::change_pin()
{
	int new_pin = 0;
	cout<<"Please enter a four digit number as your PIN."<<endl;
	cin>>new_pin;
	if(new_pin == pin)
	{
		cout<<"New PIN cannot be same as old PIN."<<endl;
		cout<<"Please enter a different PIN."<<endl;
		cin>>new_pin;
		pin = new_pin;
	}
	else
		pin = new_pin;
}

void Bank::withdraw()
{
	double amount = 0.0;
	cout<<"Please enter the amount."<<endl;
	cin>>amount;
	if(amount > balance)
		cout<<"Withdrawal amount cannot be greater than the available balance."<<endl;
	else
		balance -= amount;
	cout<<"Available balance is $"<<balance<<endl;
	cout<<"Thank you."<<endl;
}

void Bank::display_balance()
{
	cout<<"Account Number: "<<account_no<<endl;
	cout<<"Balance $"<<balance<<endl;
	cout<<"Thank you."<<endl;
}

void Bank::authenticate()
{
	int input_pin = 0, choice = 0;
	cout<<"Please enter your PIN."<<endl;
	cin>>input_pin;
	if(input_pin == pin)
	{
		cout<<"Hello "<<name<<endl;
		cout<<"Enter 1 to change pin."<<endl;
		cout<<"Enter 2 to withdraw cash."<<endl;
		cout<<"Enter 3 to check balance."<<endl;
		cout<<"Enter 4 to quit."<<endl;
		cin>>choice;
		switch(choice)
		{
			case 1:
				change_pin();
				break;

			case 2:
				withdraw();
				break;

			case 3:
				display_balance();
				break;

			default:
				exit(EXIT_SUCCESS);
		}
	}
	else
	{
		cout<<"Incorrect pin."<<endl;
		exit(EXIT_SUCCESS);
	}
}
<|endoftext|>


<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 "Benchmark.h"
#include "SkCanvas.h"
#include "SkImage.h"
#include "SkPaint.h"
#include "SkSurface.h"

#if SK_SUPPORT_GPU

class GrMipMapBench: public Benchmark {
    sk_sp<SkSurface> fSurface;
    SkString fName;
    const int fW, fH;

public:
    GrMipMapBench(int w, int h) : fW(w), fH(h) {
        fName.printf("gr_mipmap_build_%dx%d", w, h);
    }

protected:
    bool isSuitableFor(Backend backend) override {
        return kGPU_Backend == backend;
    }

    const char* onGetName() override { return fName.c_str(); }

    void onDraw(int loops, SkCanvas* canvas) override {
        if (!fSurface) {
            GrContext* context = canvas->getGrContext();
            if (nullptr == context) {
                return;
            }
            SkImageInfo info = SkImageInfo::Make(fW, fH, kN32_SkColorType, kPremul_SkAlphaType,
                                                 kSRGB_SkColorProfileType);
            fSurface = SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info);
        }

        // Clear surface once:
        fSurface->getCanvas()->clear(SK_ColorBLACK);

        SkPaint paint;
        paint.setFilterQuality(kMedium_SkFilterQuality);

        for (int i = 0; i < loops; i++) {
            // Touch surface so mips are dirtied
            fSurface->getCanvas()->drawPoint(0, 0, SK_ColorWHITE);

            // Draw reduced version of surface to original canvas, to trigger mip generation
            canvas->save();
            canvas->scale(0.1f, 0.1f);
            canvas->drawImage(fSurface->makeImageSnapshot(SkBudgeted::kNo), 0, 0, &paint);
            canvas->restore();
        }
    }

    void onPerCanvasPostDraw(SkCanvas*) override {
        fSurface.reset(nullptr);
    }

private:
    typedef Benchmark INHERITED;
};

// Build variants that exercise the width and heights being even or odd at each level, as the
// impl specializes on each of these.
//
DEF_BENCH( return new GrMipMapBench(511, 1023); )
DEF_BENCH( return new GrMipMapBench(512, 511); )
DEF_BENCH( return new GrMipMapBench(511, 512); )
DEF_BENCH( return new GrMipMapBench(512, 512); )

#endif
<commit_msg>Fix incorrect parameter in new benchmark.<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 "Benchmark.h"
#include "SkCanvas.h"
#include "SkImage.h"
#include "SkPaint.h"
#include "SkSurface.h"

#if SK_SUPPORT_GPU

class GrMipMapBench: public Benchmark {
    sk_sp<SkSurface> fSurface;
    SkString fName;
    const int fW, fH;

public:
    GrMipMapBench(int w, int h) : fW(w), fH(h) {
        fName.printf("gr_mipmap_build_%dx%d", w, h);
    }

protected:
    bool isSuitableFor(Backend backend) override {
        return kGPU_Backend == backend;
    }

    const char* onGetName() override { return fName.c_str(); }

    void onDraw(int loops, SkCanvas* canvas) override {
        if (!fSurface) {
            GrContext* context = canvas->getGrContext();
            if (nullptr == context) {
                return;
            }
            SkImageInfo info = SkImageInfo::Make(fW, fH, kN32_SkColorType, kPremul_SkAlphaType,
                                                 kSRGB_SkColorProfileType);
            fSurface = SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info);
        }

        // Clear surface once:
        fSurface->getCanvas()->clear(SK_ColorBLACK);

        SkPaint paint;
        paint.setFilterQuality(kMedium_SkFilterQuality);

        for (int i = 0; i < loops; i++) {
            // Touch surface so mips are dirtied
            fSurface->getCanvas()->drawPoint(0, 0, SK_ColorWHITE);

            // Draw reduced version of surface to original canvas, to trigger mip generation
            canvas->save();
            canvas->scale(0.1f, 0.1f);
            canvas->drawImage(fSurface->makeImageSnapshot(SkBudgeted::kNo), 0, 0, &paint);
            canvas->restore();
        }
    }

    void onPerCanvasPostDraw(SkCanvas*) override {
        fSurface.reset(nullptr);
    }

private:
    typedef Benchmark INHERITED;
};

// Build variants that exercise the width and heights being even or odd at each level, as the
// impl specializes on each of these.
//
DEF_BENCH( return new GrMipMapBench(511, 511); )
DEF_BENCH( return new GrMipMapBench(512, 511); )
DEF_BENCH( return new GrMipMapBench(511, 512); )
DEF_BENCH( return new GrMipMapBench(512, 512); )

#endif
<|endoftext|>


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

#include "Benchmark.h"
#include "SkMatrix44.h"
#include "SkRandom.h"
#include "SkString.h"

class Matrix44Bench : public Benchmark {
    SkString    fName;
public:
    Matrix44Bench(const char name[]) {
        fName.printf("matrix44_%s", name);
    }

    bool isSuitableFor(Backend backend) override {
        return backend == kNonRendering_Backend;
    }

    virtual void performTest() = 0;

protected:
    virtual int mulLoopCount() const { return 1; }

    virtual const char* onGetName() {
        return fName.c_str();
    }

    virtual void onDraw(const int loops, SkCanvas*) {
        for (int i = 0; i < loops; i++) {
            this->performTest();
        }
    }

private:
    typedef Benchmark INHERITED;
};

class EqualsMatrix44Bench : public Matrix44Bench {
public:
    EqualsMatrix44Bench()
        : INHERITED("equals")
        , fM0(SkMatrix44::kIdentity_Constructor)
        , fM1(SkMatrix44::kIdentity_Constructor)
        , fM2(SkMatrix44::kIdentity_Constructor)
    {
        fM1.set(0, 0, 0);
        fM2.set(3, 3, 0);
    }
protected:
    virtual void performTest() {
        for (int i = 0; i < 10; ++i) {
            (void) (fM0 == fM1);
            (void) (fM1 == fM2);
            (void) (fM2 == fM0);
        }
    }
private:
    SkMatrix44 fM0, fM1, fM2;
    typedef Matrix44Bench INHERITED;
};

class SetIdentityMatrix44Bench : public Matrix44Bench {
public:
    SetIdentityMatrix44Bench()
        : INHERITED("setidentity")
        , mat(SkMatrix44::kIdentity_Constructor)
    {
        double rowMajor[16] =
                { 1, 2, 3, 4,
                  5, 6, 7, 8,
                  9, 10, 11, 12,
                  13, 14, 15, 16};
        mat.setRowMajord(rowMajor);
    }
protected:
    virtual void performTest() {
        for (int i = 0; i < 10; ++i) {
            mat.setIdentity();
        }
    }
private:
    SkMatrix44 mat;
    typedef Matrix44Bench INHERITED;
};

class PreScaleMatrix44Bench : public Matrix44Bench {
public:
    PreScaleMatrix44Bench()
        : INHERITED("prescale")
        , fM0(SkMatrix44::kUninitialized_Constructor)
    {
        fX = fY = fZ = SkDoubleToMScalar(1.5);
    }
protected:
    virtual void performTest() {
        fM0.reset();
        for (int i = 0; i < 10; ++i) {
            fM0.preScale(fX, fY, fZ);
        }
    }
private:
    SkMatrix44 fM0;
    SkMScalar  fX, fY, fZ;
    typedef Matrix44Bench INHERITED;
};

class InvertMatrix44Bench : public Matrix44Bench {
public:
    InvertMatrix44Bench()
        : INHERITED("invert")
        , fM0(SkMatrix44::kUninitialized_Constructor)
        , fM1(SkMatrix44::kUninitialized_Constructor)
    {
        fM0.set(0, 0, -1.1);
        fM0.set(0, 1, 2.1);
        fM0.set(0, 2, -3.1);
        fM0.set(0, 3, 4.1);
        fM0.set(1, 0, 5.1);
        fM0.set(1, 1, -6.1);
        fM0.set(1, 2, 7.1);
        fM0.set(1, 3, 8.1);
        fM0.set(2, 0, -9.1);
        fM0.set(2, 1, 10.1);
        fM0.set(2, 2, 11.1);
        fM0.set(2, 3, -12.1);
        fM0.set(3, 0, -13.1);
        fM0.set(3, 1, 14.1);
        fM0.set(3, 2, -15.1);
        fM0.set(3, 3, 16.1);
    }
protected:
    virtual void performTest() {
        for (int i = 0; i < 10; ++i) {
            fM0.invert(&fM1);
        }
    }
private:
    SkMatrix44 fM0, fM1;
    typedef Matrix44Bench INHERITED;
};

class InvertAffineMatrix44Bench : public Matrix44Bench {
public:
    InvertAffineMatrix44Bench()
        : INHERITED("invertaffine")
        , fM0(SkMatrix44::kIdentity_Constructor)
        , fM1(SkMatrix44::kUninitialized_Constructor)
    {
        fM0.set(0, 0, -1.1);
        fM0.set(0, 1, 2.1);
        fM0.set(0, 2, -3.1);
        fM0.set(0, 3, 4.1);
        fM0.set(1, 0, 5.1);
        fM0.set(1, 1, -6.1);
        fM0.set(1, 2, 7.1);
        fM0.set(1, 3, 8.1);
        fM0.set(2, 0, -9.1);
        fM0.set(2, 1, 10.1);
        fM0.set(2, 2, 11.1);
        fM0.set(2, 3, -12.1);
        // bottom row (perspective component) remains (0, 0, 0, 1).
    }
protected:
    virtual void performTest() {
        for (int i = 0; i < 10; ++i) {
            fM0.invert(&fM1);
        }
    }
private:
    SkMatrix44 fM0, fM1;
    typedef Matrix44Bench INHERITED;
};

class InvertScaleTranslateMatrix44Bench : public Matrix44Bench {
public:
    InvertScaleTranslateMatrix44Bench()
        : INHERITED("invertscaletranslate")
        , fM0(SkMatrix44::kIdentity_Constructor)
        , fM1(SkMatrix44::kUninitialized_Constructor)
    {
        fM0.set(0, 0, -1.1);
        fM0.set(0, 3, 4.1);

        fM0.set(1, 1, -6.1);
        fM0.set(1, 3, 8.1);

        fM0.set(2, 2, 11.1);
        fM0.set(2, 3, -12.1);
    }
protected:
    virtual void performTest() {
        for (int i = 0; i < 10; ++i) {
            fM0.invert(&fM1);
        }
    }
private:
    SkMatrix44 fM0, fM1;
    typedef Matrix44Bench INHERITED;
};

class InvertTranslateMatrix44Bench : public Matrix44Bench {
public:
    InvertTranslateMatrix44Bench()
        : INHERITED("inverttranslate")
        , fM0(SkMatrix44::kIdentity_Constructor)
        , fM1(SkMatrix44::kUninitialized_Constructor)
    {
        fM0.set(0, 3, 4.1);
        fM0.set(1, 3, 8.1);
        fM0.set(2, 3, -12.1);
    }
protected:
    virtual void performTest() {
        for (int i = 0; i < 10; ++i) {
            fM0.invert(&fM1);
        }
    }
private:
    SkMatrix44 fM0, fM1;
    typedef Matrix44Bench INHERITED;
};

class PostScaleMatrix44Bench : public Matrix44Bench {
public:
    PostScaleMatrix44Bench()
        : INHERITED("postscale")
        , fM0(SkMatrix44::kUninitialized_Constructor)
    {
        fX = fY = fZ = SkDoubleToMScalar(1.5);
    }
protected:
    virtual void performTest() {
        fM0.reset();
        for (int i = 0; i < 10; ++i) {
            fM0.postScale(fX, fY, fZ);
        }
    }
private:
    SkMatrix44 fM0;
    SkMScalar  fX, fY, fZ;
    typedef Matrix44Bench INHERITED;
};

class SetConcatMatrix44Bench : public Matrix44Bench {
public:
    // SkMatrix44::setConcat() has a fast path for matrices that are at most scale+translate.
    SetConcatMatrix44Bench(bool fastPath)
        : INHERITED(fastPath ? "setconcat_fast" : "setconcat_general")
        , fM0(SkMatrix44::kUninitialized_Constructor)
        , fM1(SkMatrix44::kUninitialized_Constructor)
        , fM2(SkMatrix44::kUninitialized_Constructor)
{
        if (fastPath) {
            const SkMScalar v = SkDoubleToMScalar(1.5);
            fM1.setScale(v,v,v);
            fM2.setTranslate(v,v,v);
        } else {
            SkRandom rand;
            for (int x = 0; x < 4; x++) {
            for (int y = 0; y < 4; y++) {
                fM1.setFloat(x,y, rand.nextF());
                fM2.setFloat(x,y, rand.nextF());
            }}
        }
    }
protected:
    virtual void performTest() {
        fM0.reset();    // just to normalize this test with prescale/postscale
        for (int i = 0; i < 10; ++i) {
            fM0.setConcat(fM1, fM2);
        }
    }
private:
    SkMatrix44 fM0, fM1, fM2;
    typedef Matrix44Bench INHERITED;
};

class GetTypeMatrix44Bench : public Matrix44Bench {
public:
    GetTypeMatrix44Bench()
        : INHERITED("gettype")
        , fMatrix(SkMatrix44::kIdentity_Constructor)
    {}
protected:
    // Putting random generation of the matrix inside performTest()
    // would help us avoid anomalous runs, but takes up 25% or
    // more of the function time.
    virtual void performTest() {
        for (int i = 0; i < 20; ++i) {
            fMatrix.set(1, 2, 1);   // to invalidate the type-cache
            fMatrix.getType();
        }
    }
private:
    SkMatrix44 fMatrix;
    typedef Matrix44Bench INHERITED;
};

DEF_BENCH( return new SetIdentityMatrix44Bench(); )
DEF_BENCH( return new EqualsMatrix44Bench(); )
DEF_BENCH( return new PreScaleMatrix44Bench(); )
DEF_BENCH( return new PostScaleMatrix44Bench(); )
DEF_BENCH( return new InvertMatrix44Bench(); )
DEF_BENCH( return new InvertAffineMatrix44Bench(); )
DEF_BENCH( return new InvertScaleTranslateMatrix44Bench(); )
DEF_BENCH( return new InvertTranslateMatrix44Bench(); )
DEF_BENCH( return new SetConcatMatrix44Bench(true); )
DEF_BENCH( return new SetConcatMatrix44Bench(false); )
DEF_BENCH( return new GetTypeMatrix44Bench(); )
<commit_msg>Pump up matrix44_setconcat benches 1000x so they can be timed on Android.<commit_after>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "Benchmark.h"
#include "SkMatrix44.h"
#include "SkRandom.h"
#include "SkString.h"

class Matrix44Bench : public Benchmark {
    SkString    fName;
public:
    Matrix44Bench(const char name[]) {
        fName.printf("matrix44_%s", name);
    }

    bool isSuitableFor(Backend backend) override {
        return backend == kNonRendering_Backend;
    }

    virtual void performTest() = 0;

protected:
    virtual int mulLoopCount() const { return 1; }

    virtual const char* onGetName() {
        return fName.c_str();
    }

    virtual void onDraw(const int loops, SkCanvas*) {
        for (int i = 0; i < loops; i++) {
            this->performTest();
        }
    }

private:
    typedef Benchmark INHERITED;
};

class EqualsMatrix44Bench : public Matrix44Bench {
public:
    EqualsMatrix44Bench()
        : INHERITED("equals")
        , fM0(SkMatrix44::kIdentity_Constructor)
        , fM1(SkMatrix44::kIdentity_Constructor)
        , fM2(SkMatrix44::kIdentity_Constructor)
    {
        fM1.set(0, 0, 0);
        fM2.set(3, 3, 0);
    }
protected:
    virtual void performTest() {
        for (int i = 0; i < 10; ++i) {
            (void) (fM0 == fM1);
            (void) (fM1 == fM2);
            (void) (fM2 == fM0);
        }
    }
private:
    SkMatrix44 fM0, fM1, fM2;
    typedef Matrix44Bench INHERITED;
};

class SetIdentityMatrix44Bench : public Matrix44Bench {
public:
    SetIdentityMatrix44Bench()
        : INHERITED("setidentity")
        , mat(SkMatrix44::kIdentity_Constructor)
    {
        double rowMajor[16] =
                { 1, 2, 3, 4,
                  5, 6, 7, 8,
                  9, 10, 11, 12,
                  13, 14, 15, 16};
        mat.setRowMajord(rowMajor);
    }
protected:
    virtual void performTest() {
        for (int i = 0; i < 10; ++i) {
            mat.setIdentity();
        }
    }
private:
    SkMatrix44 mat;
    typedef Matrix44Bench INHERITED;
};

class PreScaleMatrix44Bench : public Matrix44Bench {
public:
    PreScaleMatrix44Bench()
        : INHERITED("prescale")
        , fM0(SkMatrix44::kUninitialized_Constructor)
    {
        fX = fY = fZ = SkDoubleToMScalar(1.5);
    }
protected:
    virtual void performTest() {
        fM0.reset();
        for (int i = 0; i < 10; ++i) {
            fM0.preScale(fX, fY, fZ);
        }
    }
private:
    SkMatrix44 fM0;
    SkMScalar  fX, fY, fZ;
    typedef Matrix44Bench INHERITED;
};

class InvertMatrix44Bench : public Matrix44Bench {
public:
    InvertMatrix44Bench()
        : INHERITED("invert")
        , fM0(SkMatrix44::kUninitialized_Constructor)
        , fM1(SkMatrix44::kUninitialized_Constructor)
    {
        fM0.set(0, 0, -1.1);
        fM0.set(0, 1, 2.1);
        fM0.set(0, 2, -3.1);
        fM0.set(0, 3, 4.1);
        fM0.set(1, 0, 5.1);
        fM0.set(1, 1, -6.1);
        fM0.set(1, 2, 7.1);
        fM0.set(1, 3, 8.1);
        fM0.set(2, 0, -9.1);
        fM0.set(2, 1, 10.1);
        fM0.set(2, 2, 11.1);
        fM0.set(2, 3, -12.1);
        fM0.set(3, 0, -13.1);
        fM0.set(3, 1, 14.1);
        fM0.set(3, 2, -15.1);
        fM0.set(3, 3, 16.1);
    }
protected:
    virtual void performTest() {
        for (int i = 0; i < 10; ++i) {
            fM0.invert(&fM1);
        }
    }
private:
    SkMatrix44 fM0, fM1;
    typedef Matrix44Bench INHERITED;
};

class InvertAffineMatrix44Bench : public Matrix44Bench {
public:
    InvertAffineMatrix44Bench()
        : INHERITED("invertaffine")
        , fM0(SkMatrix44::kIdentity_Constructor)
        , fM1(SkMatrix44::kUninitialized_Constructor)
    {
        fM0.set(0, 0, -1.1);
        fM0.set(0, 1, 2.1);
        fM0.set(0, 2, -3.1);
        fM0.set(0, 3, 4.1);
        fM0.set(1, 0, 5.1);
        fM0.set(1, 1, -6.1);
        fM0.set(1, 2, 7.1);
        fM0.set(1, 3, 8.1);
        fM0.set(2, 0, -9.1);
        fM0.set(2, 1, 10.1);
        fM0.set(2, 2, 11.1);
        fM0.set(2, 3, -12.1);
        // bottom row (perspective component) remains (0, 0, 0, 1).
    }
protected:
    virtual void performTest() {
        for (int i = 0; i < 10; ++i) {
            fM0.invert(&fM1);
        }
    }
private:
    SkMatrix44 fM0, fM1;
    typedef Matrix44Bench INHERITED;
};

class InvertScaleTranslateMatrix44Bench : public Matrix44Bench {
public:
    InvertScaleTranslateMatrix44Bench()
        : INHERITED("invertscaletranslate")
        , fM0(SkMatrix44::kIdentity_Constructor)
        , fM1(SkMatrix44::kUninitialized_Constructor)
    {
        fM0.set(0, 0, -1.1);
        fM0.set(0, 3, 4.1);

        fM0.set(1, 1, -6.1);
        fM0.set(1, 3, 8.1);

        fM0.set(2, 2, 11.1);
        fM0.set(2, 3, -12.1);
    }
protected:
    virtual void performTest() {
        for (int i = 0; i < 10; ++i) {
            fM0.invert(&fM1);
        }
    }
private:
    SkMatrix44 fM0, fM1;
    typedef Matrix44Bench INHERITED;
};

class InvertTranslateMatrix44Bench : public Matrix44Bench {
public:
    InvertTranslateMatrix44Bench()
        : INHERITED("inverttranslate")
        , fM0(SkMatrix44::kIdentity_Constructor)
        , fM1(SkMatrix44::kUninitialized_Constructor)
    {
        fM0.set(0, 3, 4.1);
        fM0.set(1, 3, 8.1);
        fM0.set(2, 3, -12.1);
    }
protected:
    virtual void performTest() {
        for (int i = 0; i < 10; ++i) {
            fM0.invert(&fM1);
        }
    }
private:
    SkMatrix44 fM0, fM1;
    typedef Matrix44Bench INHERITED;
};

class PostScaleMatrix44Bench : public Matrix44Bench {
public:
    PostScaleMatrix44Bench()
        : INHERITED("postscale")
        , fM0(SkMatrix44::kUninitialized_Constructor)
    {
        fX = fY = fZ = SkDoubleToMScalar(1.5);
    }
protected:
    virtual void performTest() {
        fM0.reset();
        for (int i = 0; i < 10; ++i) {
            fM0.postScale(fX, fY, fZ);
        }
    }
private:
    SkMatrix44 fM0;
    SkMScalar  fX, fY, fZ;
    typedef Matrix44Bench INHERITED;
};

class SetConcatMatrix44Bench : public Matrix44Bench {
public:
    // SkMatrix44::setConcat() has a fast path for matrices that are at most scale+translate.
    SetConcatMatrix44Bench(bool fastPath)
        : INHERITED(fastPath ? "setconcat_fast" : "setconcat_general")
        , fM0(SkMatrix44::kUninitialized_Constructor)
        , fM1(SkMatrix44::kUninitialized_Constructor)
        , fM2(SkMatrix44::kUninitialized_Constructor)
{
        if (fastPath) {
            const SkMScalar v = SkDoubleToMScalar(1.5);
            fM1.setScale(v,v,v);
            fM2.setTranslate(v,v,v);
        } else {
            SkRandom rand;
            for (int x = 0; x < 4; x++) {
            for (int y = 0; y < 4; y++) {
                fM1.setFloat(x,y, rand.nextF());
                fM2.setFloat(x,y, rand.nextF());
            }}
        }
    }
protected:
    virtual void performTest() {
        fM0.reset();    // just to normalize this test with prescale/postscale
        for (int i = 0; i < 10000; ++i) {
            fM0.setConcat(fM1, fM2);
        }
    }
private:
    SkMatrix44 fM0, fM1, fM2;
    typedef Matrix44Bench INHERITED;
};

class GetTypeMatrix44Bench : public Matrix44Bench {
public:
    GetTypeMatrix44Bench()
        : INHERITED("gettype")
        , fMatrix(SkMatrix44::kIdentity_Constructor)
    {}
protected:
    // Putting random generation of the matrix inside performTest()
    // would help us avoid anomalous runs, but takes up 25% or
    // more of the function time.
    virtual void performTest() {
        for (int i = 0; i < 20; ++i) {
            fMatrix.set(1, 2, 1);   // to invalidate the type-cache
            fMatrix.getType();
        }
    }
private:
    SkMatrix44 fMatrix;
    typedef Matrix44Bench INHERITED;
};

DEF_BENCH( return new SetIdentityMatrix44Bench(); )
DEF_BENCH( return new EqualsMatrix44Bench(); )
DEF_BENCH( return new PreScaleMatrix44Bench(); )
DEF_BENCH( return new PostScaleMatrix44Bench(); )
DEF_BENCH( return new InvertMatrix44Bench(); )
DEF_BENCH( return new InvertAffineMatrix44Bench(); )
DEF_BENCH( return new InvertScaleTranslateMatrix44Bench(); )
DEF_BENCH( return new InvertTranslateMatrix44Bench(); )
DEF_BENCH( return new SetConcatMatrix44Bench(true); )
DEF_BENCH( return new SetConcatMatrix44Bench(false); )
DEF_BENCH( return new GetTypeMatrix44Bench(); )
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2017 Darius Rückert
 * Licensed under the MIT License.
 * See LICENSE file for more information.
 */

#include "framework.h"

#include "saiga/core/image/image.h"
#include "saiga/core/model/ModelLoader.h"
#include "saiga/core/util/assert.h"
#include "saiga/core/util/directory.h"
#include "saiga/core/util/easylogging++.h"
#include "saiga/core/util/fileChecker.h"
#include "saiga/core/util/floatingPoint.h"
#include "saiga/core/util/ini/ini.h"
#include "saiga/core/util/threadName.h"
#include "saiga/core/util/tostring.h"

namespace Saiga
{
bool initialized = false;

bool isShaderDirectory(const std::string& dir)
{
    Directory dirbase(dir);
    Directory dirgeo(dir + "/geometry");
    return dirbase.existsFile("colored_points.glsl") && dirgeo.existsFile("deferred_mvp_texture.glsl");
}

void SaigaParameters::fromConfigFile(const std::string& file)
{
    Saiga::SimpleIni ini;
    ini.LoadFile(file.c_str());

    std::string comment =
        "# Multiple search pathes must be separated by '!'.\n"
        "# Example:\n"
        "# shaderDirectory = shader!/usr/local/share/saiga/shader!somepath/asdf/shader";

    char sep = '!';
    shaderDirectory =
        split(ini.GetAddString("saiga", "shaderDirectory", concat(shaderDirectory, sep).c_str(), comment.c_str()), sep);
    textureDirectory = split(ini.GetAddString("saiga", "textureDirectory", concat(textureDirectory, sep).c_str()), sep);
    modelDirectory   = split(ini.GetAddString("saiga", "modelDirectory", concat(modelDirectory, sep).c_str()), sep);
    fontDirectory    = split(ini.GetAddString("saiga", "fontDirectory", concat(fontDirectory, sep).c_str()), sep);
    dataDirectory    = split(ini.GetAddString("saiga", "dataDirectory", concat(dataDirectory, sep).c_str()), sep);
    mainThreadName   = ini.GetAddString("saiga", "mainThreadName", mainThreadName.c_str());
    logging_enabled  = ini.GetAddBool("saiga", "logging", logging_enabled);
    verbose_logging  = ini.GetAddBool("saiga", "verbose_logging", verbose_logging);
    if (ini.changed()) ini.SaveFile(file.c_str());
}

static void printSaigaInfo()
{
    cout << "Saiga Version " << SAIGA_VERSION_MAJOR << "." << SAIGA_VERSION_MINOR << endl;
    std::string libs;
#ifdef SAIGA_USE_SDL
    libs += "SDL,";
#endif
#ifdef SAIGA_USE_GLFW
    libs += "GLFW,";
#endif
#ifdef SAIGA_USE_OPENAL
    libs += "OPENAL,";
#endif
#ifdef SAIGA_USE_ALUT
    libs += "ALUT,";
#endif
#ifdef SAIGA_USE_OPUS
    libs += "OPUS,";
#endif
#ifdef SAIGA_USE_ASSIMP
    libs += "ASSIMP,";
#endif
#ifdef SAIGA_USE_PNG
    libs += "PNG,";
#endif
#ifdef SAIGA_USE_FREEIMAGE
    libs += "FREEIMAGE,";
#endif
#ifdef SAIGA_USE_FFMPEG
    libs += "FFMPEG,";
#endif
#ifdef SAIGA_USE_CUDA
    libs += "CUDA,";
#endif
#ifdef SAIGA_USE_EIGEN
    libs += "EIGEN,";
#endif
    cout << "Libs: " << libs << endl;

    std::string options;
#ifdef SAIGA_BUILD_SHARED
    options += "BUILD_SHARED,";
#endif
#ifdef SAIGA_DEBUG
    options += "DEBUG,";
#endif
#ifdef SAIGA_ASSERTS
    options += "ASSERTS,";
#endif
#ifdef SAIGA_BUILD_SAMPLES
    options += "BUILD_SAMPLES,";
#endif
#ifdef SAIGA_WITH_CUDA
    options += "WITH_CUDA,";
#endif
#ifdef SAIGA_STRICT_FP
    options += "STRICT_FP,";
#endif
#ifdef SAIGA_FULL_OPTIMIZE
    options += "FULL_OPTIMIZE,";
#endif
#ifdef SAIGA_CUDA_DEBUG
    options += "CUDA_DEBUG,";
#endif
    cout << "Build Options: " << options << endl;
}

void initSample(SaigaParameters& saigaParameters)
{
    saigaParameters.shaderDirectory  = {SAIGA_PROJECT_SOURCE_DIR "/shader"};
    saigaParameters.textureDirectory = {SAIGA_PROJECT_SOURCE_DIR "/data/textures"};
    saigaParameters.modelDirectory   = {SAIGA_PROJECT_SOURCE_DIR "/data/models"};
    saigaParameters.fontDirectory    = {SAIGA_PROJECT_SOURCE_DIR "/data/fonts"};
    saigaParameters.dataDirectory    = {SAIGA_PROJECT_SOURCE_DIR "/data"};
    saigaParameters.logging_enabled  = false;
    saigaParameters.verbose_logging  = false;
}

void initSaiga(const SaigaParameters& params)
{
    if (initialized)
    {
        return;
    }

    FP::resetSSECSR();

    std::vector<std::string> searchPathes = {
        // First check in the local working directory
        "shader",
    };

    searchPathes.insert(searchPathes.end(), params.shaderDirectory.begin(), params.shaderDirectory.end());
    // Then the given paramter from the config file
    //        params.shaderDirectory,
    // And last the install prefix from cmake
    searchPathes.push_back(SAIGA_INSTALL_PREFIX "/share/saiga/shader");
    searchPathes.push_back(SAIGA_SHADER_PREFIX);
    //    };

    std::string shaderDir;

    for (auto str : searchPathes)
    {
        if (isShaderDirectory(str))
        {
            shaderDir = str;
            cout << "Found the Saiga shaders at " << shaderDir << endl;
            break;
        }
    }

    if (shaderDir.empty())
    {
        cout << "Could not find the Saiga shaders." << endl;
        cout << "Set the 'shaderDirectory' variable of 'SaigaParameters' accordingly." << endl;
        for (auto s : searchPathes)
        {
            cout << "     " << s << endl;
        }
        exit(1);
    }

    SearchPathes::shader.addSearchPath(shaderDir);
    SearchPathes::shader.addSearchPath(shaderDir + "/include");
    SearchPathes::shader.addSearchPath(params.shaderDirectory);

    SearchPathes::image.addSearchPath(params.textureDirectory);
    SearchPathes::data.addSearchPath(params.dataDirectory);
    SearchPathes::font.addSearchPath(params.fontDirectory);
    SearchPathes::model.addSearchPath(params.modelDirectory);

    //#ifdef SAIGA_USE_OPENGL
    //    initSaigaGL(shaderDir, params.textureDirectory);
    //#endif

    //#ifdef SAIGA_USE_VULKAN
    //    Vulkan::GLSLANG::init();
    //#endif

    setThreadName(params.mainThreadName);

    el::Configurations defaultConf;
    defaultConf.setToDefault();
    // Values are always std::string
    defaultConf.set(el::Level::Global, el::ConfigurationType::ToFile, "false");
    // defaultConf.set(el::Level::Global, el::ConfigurationType::ToStandardOutput,
    // std::to_string(params.logging_enabled));
    defaultConf.set(el::Level::Global, el::ConfigurationType::Enabled, std::to_string(params.logging_enabled));
    defaultConf.set(el::Level::Verbose, el::ConfigurationType::Enabled, std::to_string(params.verbose_logging));
    el::Loggers::reconfigureLogger("default", defaultConf);

    if (params.logging_enabled)
    {
        cout << "Logging is enabled" << endl;
    }

    printSaigaInfo();
    cout << "========================== Saiga initialization done!  ==========================" << endl << endl;
    initialized = true;
}

void cleanupSaiga()
{
    //#ifdef SAIGA_USE_VULKAN
    //    Saiga::Vulkan::GLSLANG::quit();
    //#endif

    //#ifdef SAIGA_USE_OPENGL
    //    cleanupSaigaGL();
    //#endif

    cout << "========================== Saiga cleanup done! ==========================" << endl;
    initialized = false;
}

}  // namespace Saiga
<commit_msg>Fixes verbose logging<commit_after>/**
 * Copyright (c) 2017 Darius Rückert
 * Licensed under the MIT License.
 * See LICENSE file for more information.
 */

#include "framework.h"

#include "saiga/core/image/image.h"
#include "saiga/core/model/ModelLoader.h"
#include "saiga/core/util/assert.h"
#include "saiga/core/util/directory.h"
#include "saiga/core/util/easylogging++.h"
#include "saiga/core/util/fileChecker.h"
#include "saiga/core/util/floatingPoint.h"
#include "saiga/core/util/ini/ini.h"
#include "saiga/core/util/threadName.h"
#include "saiga/core/util/tostring.h"

namespace Saiga
{
bool initialized = false;

bool isShaderDirectory(const std::string& dir)
{
    Directory dirbase(dir);
    Directory dirgeo(dir + "/geometry");
    return dirbase.existsFile("colored_points.glsl") && dirgeo.existsFile("deferred_mvp_texture.glsl");
}

void SaigaParameters::fromConfigFile(const std::string& file)
{
    Saiga::SimpleIni ini;
    ini.LoadFile(file.c_str());

    std::string comment =
        "# Multiple search pathes must be separated by '!'.\n"
        "# Example:\n"
        "# shaderDirectory = shader!/usr/local/share/saiga/shader!somepath/asdf/shader";

    char sep = '!';
    shaderDirectory =
        split(ini.GetAddString("saiga", "shaderDirectory", concat(shaderDirectory, sep).c_str(), comment.c_str()), sep);
    textureDirectory = split(ini.GetAddString("saiga", "textureDirectory", concat(textureDirectory, sep).c_str()), sep);
    modelDirectory   = split(ini.GetAddString("saiga", "modelDirectory", concat(modelDirectory, sep).c_str()), sep);
    fontDirectory    = split(ini.GetAddString("saiga", "fontDirectory", concat(fontDirectory, sep).c_str()), sep);
    dataDirectory    = split(ini.GetAddString("saiga", "dataDirectory", concat(dataDirectory, sep).c_str()), sep);
    mainThreadName   = ini.GetAddString("saiga", "mainThreadName", mainThreadName.c_str());
    logging_enabled  = ini.GetAddBool("saiga", "logging", logging_enabled);
    verbose_logging  = ini.GetAddBool("saiga", "verbose_logging", verbose_logging);
    if (ini.changed()) ini.SaveFile(file.c_str());
}

static void printSaigaInfo()
{
    cout << "Saiga Version " << SAIGA_VERSION_MAJOR << "." << SAIGA_VERSION_MINOR << endl;
    std::string libs;
#ifdef SAIGA_USE_SDL
    libs += "SDL,";
#endif
#ifdef SAIGA_USE_GLFW
    libs += "GLFW,";
#endif
#ifdef SAIGA_USE_OPENAL
    libs += "OPENAL,";
#endif
#ifdef SAIGA_USE_ALUT
    libs += "ALUT,";
#endif
#ifdef SAIGA_USE_OPUS
    libs += "OPUS,";
#endif
#ifdef SAIGA_USE_ASSIMP
    libs += "ASSIMP,";
#endif
#ifdef SAIGA_USE_PNG
    libs += "PNG,";
#endif
#ifdef SAIGA_USE_FREEIMAGE
    libs += "FREEIMAGE,";
#endif
#ifdef SAIGA_USE_FFMPEG
    libs += "FFMPEG,";
#endif
#ifdef SAIGA_USE_CUDA
    libs += "CUDA,";
#endif
#ifdef SAIGA_USE_EIGEN
    libs += "EIGEN,";
#endif
    cout << "Libs: " << libs << endl;

    std::string options;
#ifdef SAIGA_BUILD_SHARED
    options += "BUILD_SHARED,";
#endif
#ifdef SAIGA_DEBUG
    options += "DEBUG,";
#endif
#ifdef SAIGA_ASSERTS
    options += "ASSERTS,";
#endif
#ifdef SAIGA_BUILD_SAMPLES
    options += "BUILD_SAMPLES,";
#endif
#ifdef SAIGA_WITH_CUDA
    options += "WITH_CUDA,";
#endif
#ifdef SAIGA_STRICT_FP
    options += "STRICT_FP,";
#endif
#ifdef SAIGA_FULL_OPTIMIZE
    options += "FULL_OPTIMIZE,";
#endif
#ifdef SAIGA_CUDA_DEBUG
    options += "CUDA_DEBUG,";
#endif
    cout << "Build Options: " << options << endl;
}

void initSample(SaigaParameters& saigaParameters)
{
    saigaParameters.shaderDirectory  = {SAIGA_PROJECT_SOURCE_DIR "/shader"};
    saigaParameters.textureDirectory = {SAIGA_PROJECT_SOURCE_DIR "/data/textures"};
    saigaParameters.modelDirectory   = {SAIGA_PROJECT_SOURCE_DIR "/data/models"};
    saigaParameters.fontDirectory    = {SAIGA_PROJECT_SOURCE_DIR "/data/fonts"};
    saigaParameters.dataDirectory    = {SAIGA_PROJECT_SOURCE_DIR "/data"};
    saigaParameters.logging_enabled  = false;
    saigaParameters.verbose_logging  = false;
}

void initSaiga(const SaigaParameters& params)
{
    if (initialized)
    {
        return;
    }

    FP::resetSSECSR();

    std::vector<std::string> searchPathes = {
        // First check in the local working directory
        "shader",
    };

    searchPathes.insert(searchPathes.end(), params.shaderDirectory.begin(), params.shaderDirectory.end());
    // Then the given paramter from the config file
    //        params.shaderDirectory,
    // And last the install prefix from cmake
    searchPathes.push_back(SAIGA_INSTALL_PREFIX "/share/saiga/shader");
    searchPathes.push_back(SAIGA_SHADER_PREFIX);
    //    };

    std::string shaderDir;

    for (auto str : searchPathes)
    {
        if (isShaderDirectory(str))
        {
            shaderDir = str;
            cout << "Found the Saiga shaders at " << shaderDir << endl;
            break;
        }
    }

    if (shaderDir.empty())
    {
        cout << "Could not find the Saiga shaders." << endl;
        cout << "Set the 'shaderDirectory' variable of 'SaigaParameters' accordingly." << endl;
        for (auto s : searchPathes)
        {
            cout << "     " << s << endl;
        }
        exit(1);
    }

    SearchPathes::shader.addSearchPath(shaderDir);
    SearchPathes::shader.addSearchPath(shaderDir + "/include");
    SearchPathes::shader.addSearchPath(params.shaderDirectory);

    SearchPathes::image.addSearchPath(params.textureDirectory);
    SearchPathes::data.addSearchPath(params.dataDirectory);
    SearchPathes::font.addSearchPath(params.fontDirectory);
    SearchPathes::model.addSearchPath(params.modelDirectory);

    //#ifdef SAIGA_USE_OPENGL
    //    initSaigaGL(shaderDir, params.textureDirectory);
    //#endif

    //#ifdef SAIGA_USE_VULKAN
    //    Vulkan::GLSLANG::init();
    //#endif

    setThreadName(params.mainThreadName);

    el::Configurations defaultConf;
    defaultConf.setToDefault();
    if (params.logging_enabled)
    {
        cout << "Enabling logging" << endl;

        // Values are always std::string
        defaultConf.set(el::Level::Global, el::ConfigurationType::ToFile, "false");
        // defaultConf.set(el::Level::Global, el::ConfigurationType::ToStandardOutput,
        // std::to_string(params.logging_enabled));
        defaultConf.set(el::Level::Global, el::ConfigurationType::Enabled, std::to_string(params.logging_enabled));
        defaultConf.set(el::Level::Verbose, el::ConfigurationType::Enabled, std::to_string(params.verbose_logging));

        if (params.verbose_logging)
        {
            el::Loggers::setVerboseLevel(1);
        }
    }
    el::Loggers::reconfigureLogger("default", defaultConf);

    printSaigaInfo();
    cout << "========================== Saiga initialization done!  ==========================" << endl << endl;
    initialized = true;
}

void cleanupSaiga()
{
    //#ifdef SAIGA_USE_VULKAN
    //    Saiga::Vulkan::GLSLANG::quit();
    //#endif

    //#ifdef SAIGA_USE_OPENGL
    //    cleanupSaigaGL();
    //#endif

    cout << "========================== Saiga cleanup done! ==========================" << endl;
    initialized = false;
}

}  // namespace Saiga
<|endoftext|>


<commit_before>/*
    aboutdata.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB

    Kleopatra is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Kleopatra is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "aboutdata.h"

#include <klocale.h>

static const char kleopatra_version[] = "0.30";
static const char description[] = I18N_NOOP("KDE Key Manager");

struct about_data {
  const char * name;
  const char * desc;
  const char * email;
  const char * web;
};

static const about_data authors[] = {
  { "Marc Mutz", I18N_NOOP("Current Maintainer"), "mutz@kde.org", 0 },
  { "Steffen Hansen", I18N_NOOP("Former Maintainer"), "hansen@kde.org", 0 },
  { "Kalle Dalheimer", I18N_NOOP("Original Author"), "kalle@kde.org", 0 },
  { "Jesper Petersen", I18N_NOOP("Original Author"), "blackie@kde.org", 0 },
};

static const about_data credits[] = {
  { "David Faure",
    I18N_NOOP("Backend configuration framework, KIO integration"),
    "faure@kde.org", 0 },
  { "Michel Boyer de la Giroday",
    I18N_NOOP("Key-state dependant colors and fonts in the key list"),
    "michel@klaralvdalens-datakonsult.se", 0 },
  { "Daniel Molkentin",
    I18N_NOOP("Certificate Wizard KIOSK integration, infrastructure"),
    "molkentin@kde.org", 0 },
  { "Ralf Nolden",
    I18N_NOOP("Support for obsolete EMAIL RDN in Certificate Wizard"),
    "nolden@kde.org", 0 },
  { "Karl-Heinz Zimmer",
    I18N_NOOP("DN display ordering support, infrastructure"),
    "khz@kde.org", 0 },
};

AboutData::AboutData()
  : KAboutData( "kleopatra", I18N_NOOP("Kleopatra"),
		kleopatra_version, description, License_GPL,
		"(c) 2002 Steffen Hansen, Jesper Pedersen,\n"
		"Kalle Dalheimer, Klar\xC3\xA4lvdalens Datakonsult AB\n\n"
		"(c) 2004 Marc Mutz, Klar\xC3\xA4lvdalens Datakonsult AB" )
{
  using ::authors;
  using ::credits;
  for ( unsigned int i = 0 ; i < sizeof authors / sizeof *authors ; ++i )
    addAuthor( authors[i].name, authors[i].desc,
	       authors[i].email, authors[i].web );
  for ( unsigned int i = 0 ; i < sizeof credits / sizeof *credits ; ++i )
    addCredit( credits[i].name, credits[i].desc,
	       credits[i].email, credits[i].web );
}
<commit_msg>up the version<commit_after>/*
    aboutdata.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB

    Kleopatra is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Kleopatra is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "aboutdata.h"

#include <klocale.h>

static const char kleopatra_version[] = "0.31";
static const char description[] = I18N_NOOP("KDE Key Manager");

struct about_data {
  const char * name;
  const char * desc;
  const char * email;
  const char * web;
};

static const about_data authors[] = {
  { "Marc Mutz", I18N_NOOP("Current Maintainer"), "mutz@kde.org", 0 },
  { "Steffen Hansen", I18N_NOOP("Former Maintainer"), "hansen@kde.org", 0 },
  { "Kalle Dalheimer", I18N_NOOP("Original Author"), "kalle@kde.org", 0 },
  { "Jesper Petersen", I18N_NOOP("Original Author"), "blackie@kde.org", 0 },
};

static const about_data credits[] = {
  { "David Faure",
    I18N_NOOP("Backend configuration framework, KIO integration"),
    "faure@kde.org", 0 },
  { "Michel Boyer de la Giroday",
    I18N_NOOP("Key-state dependant colors and fonts in the key list"),
    "michel@klaralvdalens-datakonsult.se", 0 },
  { "Daniel Molkentin",
    I18N_NOOP("Certificate Wizard KIOSK integration, infrastructure"),
    "molkentin@kde.org", 0 },
  { "Ralf Nolden",
    I18N_NOOP("Support for obsolete EMAIL RDN in Certificate Wizard"),
    "nolden@kde.org", 0 },
  { "Karl-Heinz Zimmer",
    I18N_NOOP("DN display ordering support, infrastructure"),
    "khz@kde.org", 0 },
};

AboutData::AboutData()
  : KAboutData( "kleopatra", I18N_NOOP("Kleopatra"),
		kleopatra_version, description, License_GPL,
		"(c) 2002 Steffen Hansen, Jesper Pedersen,\n"
		"Kalle Dalheimer, Klar\xC3\xA4lvdalens Datakonsult AB\n\n"
		"(c) 2004 Marc Mutz, Klar\xC3\xA4lvdalens Datakonsult AB" )
{
  using ::authors;
  using ::credits;
  for ( unsigned int i = 0 ; i < sizeof authors / sizeof *authors ; ++i )
    addAuthor( authors[i].name, authors[i].desc,
	       authors[i].email, authors[i].web );
  for ( unsigned int i = 0 ; i < sizeof credits / sizeof *credits ; ++i )
    addCredit( credits[i].name, credits[i].desc,
	       credits[i].email, credits[i].web );
}
<|endoftext|>