<commit_before>//===-- TargetMachine.cpp - General Target Information ---------------------==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file describes the general parts of a Target machine.
//
//===----------------------------------------------------------------------===//

#include "llvm/Target/TargetAsmInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/CommandLine.h"
using namespace llvm;

//---------------------------------------------------------------------------
// Command-line options that tend to be useful on more than one back-end.
//

namespace llvm {
  bool PrintMachineCode;
  bool NoFramePointerElim;
  bool NoExcessFPPrecision;
  bool UnsafeFPMath;
  bool FiniteOnlyFPMathOption;
  bool HonorSignDependentRoundingFPMathOption;
  bool UseSoftFloat;
  bool NoZerosInBSS;
  bool ExceptionHandling;
  bool UnwindTablesMandatory;
  Reloc::Model RelocationModel;
  CodeModel::Model CMModel;
  bool PerformTailCallOpt;
  unsigned StackAlignment;
  bool RealignStack;
  bool VerboseAsm;
  bool DisableJumpTables;
  bool StrongPHIElim;
  bool DisableRedZone;
}

static cl::opt<bool, true> PrintCode("print-machineinstrs",
  cl::desc("Print generated machine code"),
  cl::location(PrintMachineCode), cl::init(false));

static cl::opt<bool, true>
DisableFPElim("disable-fp-elim",
              cl::desc("Disable frame pointer elimination optimization"),
              cl::location(NoFramePointerElim),
              cl::init(false));
static cl::opt<bool, true>
DisableExcessPrecision("disable-excess-fp-precision",
             cl::desc("Disable optimizations that may increase FP precision"),
             cl::location(NoExcessFPPrecision),
             cl::init(false));
static cl::opt<bool, true>
EnableUnsafeFPMath("enable-unsafe-fp-math",
             cl::desc("Enable optimizations that may decrease FP precision"),
             cl::location(UnsafeFPMath),
             cl::init(false));
static cl::opt<bool, true>
EnableFiniteOnlyFPMath("enable-finite-only-fp-math",
             cl::desc("Enable optimizations that assumes non- NaNs / +-Infs"),
             cl::location(FiniteOnlyFPMathOption),
             cl::init(false));
static cl::opt<bool, true>
EnableHonorSignDependentRoundingFPMath(cl::Hidden,
             "enable-sign-dependent-rounding-fp-math",
     cl::desc("Force codegen to assume rounding mode can change dynamically"),
             cl::location(HonorSignDependentRoundingFPMathOption),
             cl::init(false));

static cl::opt<bool, true>
GenerateSoftFloatCalls("soft-float",
             cl::desc("Generate software floating point library calls"),
             cl::location(UseSoftFloat),
             cl::init(false));
static cl::opt<bool, true>
DontPlaceZerosInBSS("nozero-initialized-in-bss",
            cl::desc("Don't place zero-initialized symbols into bss section"),
            cl::location(NoZerosInBSS),
            cl::init(false));
static cl::opt<bool, true>
EnableExceptionHandling("enable-eh",
             cl::desc("Emit DWARF exception handling (default if target supports)"),
             cl::location(ExceptionHandling),
             cl::init(false));
static cl::opt<bool, true>
EnableUnwindTables("unwind-tables",
             cl::desc("Generate unwinding tables for all functions"),
             cl::location(UnwindTablesMandatory),
             cl::init(false));

static cl::opt<llvm::Reloc::Model, true>
DefRelocationModel(
  "relocation-model",
  cl::desc("Choose relocation model"),
  cl::location(RelocationModel),
  cl::init(Reloc::Default),
  cl::values(
    clEnumValN(Reloc::Default, "default",
               "Target default relocation model"),
    clEnumValN(Reloc::Static, "static",
               "Non-relocatable code"),
    clEnumValN(Reloc::PIC_, "pic",
               "Fully relocatable, position independent code"),
    clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
               "Relocatable external references, non-relocatable code"),
    clEnumValEnd));
static cl::opt<llvm::CodeModel::Model, true>
DefCodeModel(
  "code-model",
  cl::desc("Choose code model"),
  cl::location(CMModel),
  cl::init(CodeModel::Default),
  cl::values(
    clEnumValN(CodeModel::Default, "default",
               "Target default code model"),
    clEnumValN(CodeModel::Small, "small",
               "Small code model"),
    clEnumValN(CodeModel::Kernel, "kernel",
               "Kernel code model"),
    clEnumValN(CodeModel::Medium, "medium",
               "Medium code model"),
    clEnumValN(CodeModel::Large, "large",
               "Large code model"),
    clEnumValEnd));

static cl::opt<bool, true>
EnablePerformTailCallOpt("tailcallopt",
                         cl::desc("Turn on tail call optimization."),
                         cl::location(PerformTailCallOpt),
                         cl::init(false));

static cl::opt<unsigned, true>
OverrideStackAlignment("stack-alignment",
                       cl::desc("Override default stack alignment"),
                       cl::location(StackAlignment),
                       cl::init(0));

static cl::opt<bool, true>
EnableRealignStack("realign-stack",
                   cl::desc("Realign stack if needed"),
                   cl::location(RealignStack),
                   cl::init(true));

static cl::opt<bool, true>
AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
           cl::location(VerboseAsm),
           cl::init(false));

static cl::opt<bool, true>
DisableSwitchTables(cl::Hidden, "disable-jump-tables",
           cl::desc("Do not generate jump tables."),
           cl::location(DisableJumpTables),
           cl::init(false));

static cl::opt<bool, true>
EnableStrongPHIElim(cl::Hidden, "strong-phi-elim",
           cl::desc("Use strong PHI elimination."),
           cl::location(StrongPHIElim),
           cl::init(false));

static cl::opt<bool, true>
DisableRedZoneOption("disable-red-zone",
           cl::desc("Do not emit code that uses the red zone."),
           cl::location(DisableRedZone),
           cl::init(true));

//---------------------------------------------------------------------------
// TargetMachine Class
//

TargetMachine::~TargetMachine() {
  delete AsmInfo;
}

/// getRelocationModel - Returns the code generation relocation model. The
/// choices are static, PIC, and dynamic-no-pic, and target default.
Reloc::Model TargetMachine::getRelocationModel() {
  return RelocationModel;
}

/// setRelocationModel - Sets the code generation relocation model.
void TargetMachine::setRelocationModel(Reloc::Model Model) {
  RelocationModel = Model;
}

/// getCodeModel - Returns the code model. The choices are small, kernel,
/// medium, large, and target default.
CodeModel::Model TargetMachine::getCodeModel() {
  return CMModel;
}

/// setCodeModel - Sets the code model.
void TargetMachine::setCodeModel(CodeModel::Model Model) {
  CMModel = Model;
}

namespace llvm {
  /// FiniteOnlyFPMath - This returns true when the -enable-finite-only-fp-math
  /// option is specified on the command line. If this returns false (default),
  /// the code generator is not allowed to assume that FP arithmetic arguments
  /// and results are never NaNs or +-Infs.
  bool FiniteOnlyFPMath() { return UnsafeFPMath || FiniteOnlyFPMathOption; }

  /// HonorSignDependentRoundingFPMath - Return true if the codegen must assume
  /// that the rounding mode of the FPU can change from its default.
  bool HonorSignDependentRoundingFPMath() {
    return !UnsafeFPMath && HonorSignDependentRoundingFPMathOption;
  }
}

<commit_msg>Enable the red zone on x86-64 by default.<commit_after>//===-- TargetMachine.cpp - General Target Information ---------------------==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file describes the general parts of a Target machine.
//
//===----------------------------------------------------------------------===//

#include "llvm/Target/TargetAsmInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/CommandLine.h"
using namespace llvm;

//---------------------------------------------------------------------------
// Command-line options that tend to be useful on more than one back-end.
//

namespace llvm {
  bool PrintMachineCode;
  bool NoFramePointerElim;
  bool NoExcessFPPrecision;
  bool UnsafeFPMath;
  bool FiniteOnlyFPMathOption;
  bool HonorSignDependentRoundingFPMathOption;
  bool UseSoftFloat;
  bool NoZerosInBSS;
  bool ExceptionHandling;
  bool UnwindTablesMandatory;
  Reloc::Model RelocationModel;
  CodeModel::Model CMModel;
  bool PerformTailCallOpt;
  unsigned StackAlignment;
  bool RealignStack;
  bool VerboseAsm;
  bool DisableJumpTables;
  bool StrongPHIElim;
  bool DisableRedZone;
}

static cl::opt<bool, true> PrintCode("print-machineinstrs",
  cl::desc("Print generated machine code"),
  cl::location(PrintMachineCode), cl::init(false));

static cl::opt<bool, true>
DisableFPElim("disable-fp-elim",
              cl::desc("Disable frame pointer elimination optimization"),
              cl::location(NoFramePointerElim),
              cl::init(false));
static cl::opt<bool, true>
DisableExcessPrecision("disable-excess-fp-precision",
             cl::desc("Disable optimizations that may increase FP precision"),
             cl::location(NoExcessFPPrecision),
             cl::init(false));
static cl::opt<bool, true>
EnableUnsafeFPMath("enable-unsafe-fp-math",
             cl::desc("Enable optimizations that may decrease FP precision"),
             cl::location(UnsafeFPMath),
             cl::init(false));
static cl::opt<bool, true>
EnableFiniteOnlyFPMath("enable-finite-only-fp-math",
             cl::desc("Enable optimizations that assumes non- NaNs / +-Infs"),
             cl::location(FiniteOnlyFPMathOption),
             cl::init(false));
static cl::opt<bool, true>
EnableHonorSignDependentRoundingFPMath(cl::Hidden,
             "enable-sign-dependent-rounding-fp-math",
     cl::desc("Force codegen to assume rounding mode can change dynamically"),
             cl::location(HonorSignDependentRoundingFPMathOption),
             cl::init(false));

static cl::opt<bool, true>
GenerateSoftFloatCalls("soft-float",
             cl::desc("Generate software floating point library calls"),
             cl::location(UseSoftFloat),
             cl::init(false));
static cl::opt<bool, true>
DontPlaceZerosInBSS("nozero-initialized-in-bss",
            cl::desc("Don't place zero-initialized symbols into bss section"),
            cl::location(NoZerosInBSS),
            cl::init(false));
static cl::opt<bool, true>
EnableExceptionHandling("enable-eh",
             cl::desc("Emit DWARF exception handling (default if target supports)"),
             cl::location(ExceptionHandling),
             cl::init(false));
static cl::opt<bool, true>
EnableUnwindTables("unwind-tables",
             cl::desc("Generate unwinding tables for all functions"),
             cl::location(UnwindTablesMandatory),
             cl::init(false));

static cl::opt<llvm::Reloc::Model, true>
DefRelocationModel(
  "relocation-model",
  cl::desc("Choose relocation model"),
  cl::location(RelocationModel),
  cl::init(Reloc::Default),
  cl::values(
    clEnumValN(Reloc::Default, "default",
               "Target default relocation model"),
    clEnumValN(Reloc::Static, "static",
               "Non-relocatable code"),
    clEnumValN(Reloc::PIC_, "pic",
               "Fully relocatable, position independent code"),
    clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
               "Relocatable external references, non-relocatable code"),
    clEnumValEnd));
static cl::opt<llvm::CodeModel::Model, true>
DefCodeModel(
  "code-model",
  cl::desc("Choose code model"),
  cl::location(CMModel),
  cl::init(CodeModel::Default),
  cl::values(
    clEnumValN(CodeModel::Default, "default",
               "Target default code model"),
    clEnumValN(CodeModel::Small, "small",
               "Small code model"),
    clEnumValN(CodeModel::Kernel, "kernel",
               "Kernel code model"),
    clEnumValN(CodeModel::Medium, "medium",
               "Medium code model"),
    clEnumValN(CodeModel::Large, "large",
               "Large code model"),
    clEnumValEnd));

static cl::opt<bool, true>
EnablePerformTailCallOpt("tailcallopt",
                         cl::desc("Turn on tail call optimization."),
                         cl::location(PerformTailCallOpt),
                         cl::init(false));

static cl::opt<unsigned, true>
OverrideStackAlignment("stack-alignment",
                       cl::desc("Override default stack alignment"),
                       cl::location(StackAlignment),
                       cl::init(0));

static cl::opt<bool, true>
EnableRealignStack("realign-stack",
                   cl::desc("Realign stack if needed"),
                   cl::location(RealignStack),
                   cl::init(true));

static cl::opt<bool, true>
AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
           cl::location(VerboseAsm),
           cl::init(false));

static cl::opt<bool, true>
DisableSwitchTables(cl::Hidden, "disable-jump-tables",
           cl::desc("Do not generate jump tables."),
           cl::location(DisableJumpTables),
           cl::init(false));

static cl::opt<bool, true>
EnableStrongPHIElim(cl::Hidden, "strong-phi-elim",
           cl::desc("Use strong PHI elimination."),
           cl::location(StrongPHIElim),
           cl::init(false));

static cl::opt<bool, true>
DisableRedZoneOption("disable-red-zone",
           cl::desc("Do not emit code that uses the red zone."),
           cl::location(DisableRedZone),
           cl::init(false));

//---------------------------------------------------------------------------
// TargetMachine Class
//

TargetMachine::~TargetMachine() {
  delete AsmInfo;
}

/// getRelocationModel - Returns the code generation relocation model. The
/// choices are static, PIC, and dynamic-no-pic, and target default.
Reloc::Model TargetMachine::getRelocationModel() {
  return RelocationModel;
}

/// setRelocationModel - Sets the code generation relocation model.
void TargetMachine::setRelocationModel(Reloc::Model Model) {
  RelocationModel = Model;
}

/// getCodeModel - Returns the code model. The choices are small, kernel,
/// medium, large, and target default.
CodeModel::Model TargetMachine::getCodeModel() {
  return CMModel;
}

/// setCodeModel - Sets the code model.
void TargetMachine::setCodeModel(CodeModel::Model Model) {
  CMModel = Model;
}

namespace llvm {
  /// FiniteOnlyFPMath - This returns true when the -enable-finite-only-fp-math
  /// option is specified on the command line. If this returns false (default),
  /// the code generator is not allowed to assume that FP arithmetic arguments
  /// and results are never NaNs or +-Infs.
  bool FiniteOnlyFPMath() { return UnsafeFPMath || FiniteOnlyFPMathOption; }

  /// HonorSignDependentRoundingFPMath - Return true if the codegen must assume
  /// that the rounding mode of the FPU can change from its default.
  bool HonorSignDependentRoundingFPMath() {
    return !UnsafeFPMath && HonorSignDependentRoundingFPMathOption;
  }
}

<|endoftext|>


<commit_before>/* -*- C++ -*- */

/****************************************************************************
** Copyright (c) quickfixengine.org  All rights reserved.
**
** This file is part of the QuickFIX FIX Engine
**
** This file may be distributed under the terms of the quickfixengine.org
** license as defined by quickfixengine.org and appearing in the file
** LICENSE included in the packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.quickfixengine.org/LICENSE for licensing information.
**
** Contact ask@quickfixengine.org if any conditions of this licensing are
** not clear to you.
**
****************************************************************************/

#include "stdafx.h"

#ifdef _MSC_VER
#pragma warning( disable : 4503 4355 4786 )
#else
#include "config.h"
#endif

#include "MyApplication.h"

void MyApplication::onLogon( const FIX::SessionID& sessionID )
{
    std::cout << std::endl << "Logon - " << sessionID << std::endl;
}

void MyApplication::onLogout( const FIX::SessionID& sessionID )
{
    std::cout << std::endl << "Logout - " << sessionID << std::endl;
}

void MyApplication::onMessage(const FIX44::TwoFactorLogon &msg, const FIX::SessionID &sessionId)
{
  FIX::TwoFactorReason reason;
  msg.get(reason);
  char r = reason.getValue();

    FIX::Text text;
    msg.get(text);

    std::cout << std::endl << "TwoFactorLogon received - " << text.getValue() << std::endl;

    if (r == FIX::TwoFactorReason_SERVER_REQUEST)
    {
        std::cout << std::endl << "Enter One-time password: " << std::endl;

        std::string otp;
        std::getline(std::cin, otp);

        FIX44::TwoFactorLogon response(FIX::TwoFactorReason_CLIENT_RESPONSE);
        response.setField(FIX::OneTimePassword(otp));
        FIX::Session::sendToTarget(response, sessionId);
    }
    else if (r == FIX::TwoFactorReason_SERVER_SUCCESS)
        std::cout << std::endl << "One-time password was successfully validated!" << std::endl;
    else if (r == FIX::TwoFactorReason_SERVER_ERROR)
        std::cout << std::endl << "Failed to validate One-time password!" << std::endl;
    else
        std::cout << std::endl << "Invalid two factor reason!" << std::endl;
}

void MyApplication::onMessage( const FIX44::TradingSessionStatus& message, const FIX::SessionID& sessionId)
{
    std::cout << std::endl << "TradingSessionStatus received!" << std::endl;
	FIX44::TwoFactorLogon response(FIX::TwoFactorReason_CLIENT_RESUME);
	FIX::Session::sendToTarget(response, sessionId);
}

void MyApplication::fromAdmin( const FIX::Message& message, const FIX::SessionID& )
    throw( FIX::FieldNotFound, FIX::IncorrectDataFormat, FIX::IncorrectTagValue, FIX::RejectLogon )
{
    std::cout << std::endl << "IN: " << message << std::endl;
}

void MyApplication::fromApp( const FIX::Message& message, const FIX::SessionID& sessionID )
    throw( FIX::FieldNotFound, FIX::IncorrectDataFormat, FIX::IncorrectTagValue, FIX::UnsupportedMessageType )
{
    std::cout << std::endl << "IN: " << message << std::endl;
    crack( message, sessionID );
}

void MyApplication::toAdmin( FIX::Message& message, const FIX::SessionID& )
{
    if (FIX::MsgType_Logon == message.getHeader().getField(FIX::FIELD::MsgType))
    {
        message.setField(FIX::Username(m_username));
        message.setField(FIX::Password(m_password));
        message.setField(FIX::DeviceID(m_deviceId));
		message.setField(FIX::AppSessionID(m_appSessionId));
        message.setField(FIX::ProtocolSpec("ext.1.40"));
    }
    std::cout << std::endl << "OUT: " << message << std::endl;
}

void MyApplication::toApp( FIX::Message& message, const FIX::SessionID& sessionID )
    throw( FIX::DoNotSend )
{
    std::cout << std::endl << "OUT: " << message << std::endl;
}

void MyApplication::run()
{
    while ( true )
    {
        try
        {
            Sleep(3000);
        }
        catch ( std::exception & e )
        {
            std::cout << "Message Not Sent: " << e.what();
        }
    }
}
<commit_msg>Temporary remove AppSessionID filed<commit_after>/* -*- C++ -*- */

/****************************************************************************
** Copyright (c) quickfixengine.org  All rights reserved.
**
** This file is part of the QuickFIX FIX Engine
**
** This file may be distributed under the terms of the quickfixengine.org
** license as defined by quickfixengine.org and appearing in the file
** LICENSE included in the packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.quickfixengine.org/LICENSE for licensing information.
**
** Contact ask@quickfixengine.org if any conditions of this licensing are
** not clear to you.
**
****************************************************************************/

#include "stdafx.h"

#ifdef _MSC_VER
#pragma warning( disable : 4503 4355 4786 )
#else
#include "config.h"
#endif

#include "MyApplication.h"

void MyApplication::onLogon( const FIX::SessionID& sessionID )
{
    std::cout << std::endl << "Logon - " << sessionID << std::endl;
}

void MyApplication::onLogout( const FIX::SessionID& sessionID )
{
    std::cout << std::endl << "Logout - " << sessionID << std::endl;
}

void MyApplication::onMessage(const FIX44::TwoFactorLogon &msg, const FIX::SessionID &sessionId)
{
  FIX::TwoFactorReason reason;
  msg.get(reason);
  char r = reason.getValue();

    FIX::Text text;
    msg.get(text);

    std::cout << std::endl << "TwoFactorLogon received - " << text.getValue() << std::endl;

    if (r == FIX::TwoFactorReason_SERVER_REQUEST)
    {
        std::cout << std::endl << "Enter One-time password: " << std::endl;

        std::string otp;
        std::getline(std::cin, otp);

        FIX44::TwoFactorLogon response(FIX::TwoFactorReason_CLIENT_RESPONSE);
        response.setField(FIX::OneTimePassword(otp));
        FIX::Session::sendToTarget(response, sessionId);
    }
    else if (r == FIX::TwoFactorReason_SERVER_SUCCESS)
        std::cout << std::endl << "One-time password was successfully validated!" << std::endl;
    else if (r == FIX::TwoFactorReason_SERVER_ERROR)
        std::cout << std::endl << "Failed to validate One-time password!" << std::endl;
    else
        std::cout << std::endl << "Invalid two factor reason!" << std::endl;
}

void MyApplication::onMessage( const FIX44::TradingSessionStatus& message, const FIX::SessionID& sessionId)
{
    std::cout << std::endl << "TradingSessionStatus received!" << std::endl;
	FIX44::TwoFactorLogon response(FIX::TwoFactorReason_CLIENT_RESUME);
	FIX::Session::sendToTarget(response, sessionId);
}

void MyApplication::fromAdmin( const FIX::Message& message, const FIX::SessionID& )
    throw( FIX::FieldNotFound, FIX::IncorrectDataFormat, FIX::IncorrectTagValue, FIX::RejectLogon )
{
    std::cout << std::endl << "IN: " << message << std::endl;
}

void MyApplication::fromApp( const FIX::Message& message, const FIX::SessionID& sessionID )
    throw( FIX::FieldNotFound, FIX::IncorrectDataFormat, FIX::IncorrectTagValue, FIX::UnsupportedMessageType )
{
    std::cout << std::endl << "IN: " << message << std::endl;
    crack( message, sessionID );
}

void MyApplication::toAdmin( FIX::Message& message, const FIX::SessionID& )
{
    if (FIX::MsgType_Logon == message.getHeader().getField(FIX::FIELD::MsgType))
    {
        message.setField(FIX::Username(m_username));
        message.setField(FIX::Password(m_password));
        message.setField(FIX::DeviceID(m_deviceId));
		//message.setField(FIX::AppSessionID(m_appSessionId));
        message.setField(FIX::ProtocolSpec("ext.1.40"));
    }
    std::cout << std::endl << "OUT: " << message << std::endl;
}

void MyApplication::toApp( FIX::Message& message, const FIX::SessionID& sessionID )
    throw( FIX::DoNotSend )
{
    std::cout << std::endl << "OUT: " << message << std::endl;
}

void MyApplication::run()
{
    while ( true )
    {
        try
        {
            Sleep(3000);
        }
        catch ( std::exception & e )
        {
            std::cout << "Message Not Sent: " << e.what();
        }
    }
}
<|endoftext|>


<commit_before>//===-- InstrinsicInst.cpp - Intrinsic Instruction Wrappers -----*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by James M. Laskey and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements methods that make it really easy to deal with intrinsic
// functions with the isa/dyncast family of functions.  In particular, this
// allows you to do things like:
//
//     if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(Inst))
//        ... SPI->getFileName() ... SPI->getDirectory() ...
//
// All intrinsic function calls are instances of the call instruction, so these
// are all subclasses of the CallInst class.  Note that none of these classes
// has state or virtual methods, which is an important part of this gross/neat
// hack working.
//
// In some cases, arguments to intrinsics need to be generic and are defined as
// type pointer to empty struct { }*.  To access the real item of interest the
// cast instruction needs to be stripped away.
//
//===----------------------------------------------------------------------===//

#include "llvm/IntrinsicInst.h"

#include "llvm/Constants.h"
#include "llvm/GlobalVariable.h"
#include "llvm/CodeGen/MachineDebugInfo.h"

using namespace llvm;

//===----------------------------------------------------------------------===//
/// DbgInfoIntrinsic - This is the common base class for debug info intrinsics
///

static Value *CastOperand(Value *C) {
  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
    if (CE->getOpcode() == Instruction::Cast)
      return CE->getOperand(0);
  return NULL;
}

Value *DbgInfoIntrinsic::StripCast(Value *C) {
  if (Value *CO = CastOperand(C)) {
    C = StripCast(CO);
  } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
    if (GV->hasInitializer())
      if (Value *CO = CastOperand(GV->getInitializer()))
        C = StripCast(CO);
  }
  return dyn_cast<GlobalVariable>(C);
}

//===----------------------------------------------------------------------===//
/// DbgStopPointInst - This represents the llvm.dbg.stoppoint instruction.
///

std::string DbgStopPointInst::getFileName() const {
  // Once the operand indices are verified, update this assert
  assert(LLVMDebugVersion == (5 << 16) && "Verify operand indices");
  GlobalVariable *GV = cast<GlobalVariable>(getContext());
  ConstantStruct *CS = cast<ConstantStruct>(GV->getInitializer());
  return CS->getOperand(3)->getStringValue();
}

std::string DbgStopPointInst::getDirectory() const {
  // Once the operand indices are verified, update this assert
  assert(LLVMDebugVersion == (5 << 16) && "Verify operand indices");
  GlobalVariable *GV = cast<GlobalVariable>(getContext());
  ConstantStruct *CS = cast<ConstantStruct>(GV->getInitializer());
  return CS->getOperand(4)->getStringValue();
}

//===----------------------------------------------------------------------===//
/// Ensure that users of IntrinsicInst.h will link with this module.
DEFINING_FILE_FOR(IntrinsicInst)
<commit_msg>getFilename/getDirectory shouldn't abort if the global has no init.  This can happen on bugpoint reduced testcases f.e..<commit_after>//===-- InstrinsicInst.cpp - Intrinsic Instruction Wrappers -----*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by James M. Laskey and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements methods that make it really easy to deal with intrinsic
// functions with the isa/dyncast family of functions.  In particular, this
// allows you to do things like:
//
//     if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(Inst))
//        ... SPI->getFileName() ... SPI->getDirectory() ...
//
// All intrinsic function calls are instances of the call instruction, so these
// are all subclasses of the CallInst class.  Note that none of these classes
// has state or virtual methods, which is an important part of this gross/neat
// hack working.
//
// In some cases, arguments to intrinsics need to be generic and are defined as
// type pointer to empty struct { }*.  To access the real item of interest the
// cast instruction needs to be stripped away.
//
//===----------------------------------------------------------------------===//

#include "llvm/IntrinsicInst.h"
#include "llvm/Constants.h"
#include "llvm/GlobalVariable.h"
#include "llvm/CodeGen/MachineDebugInfo.h"
using namespace llvm;

//===----------------------------------------------------------------------===//
/// DbgInfoIntrinsic - This is the common base class for debug info intrinsics
///

static Value *CastOperand(Value *C) {
  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
    if (CE->getOpcode() == Instruction::Cast)
      return CE->getOperand(0);
  return NULL;
}

Value *DbgInfoIntrinsic::StripCast(Value *C) {
  if (Value *CO = CastOperand(C)) {
    C = StripCast(CO);
  } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
    if (GV->hasInitializer())
      if (Value *CO = CastOperand(GV->getInitializer()))
        C = StripCast(CO);
  }
  return dyn_cast<GlobalVariable>(C);
}

//===----------------------------------------------------------------------===//
/// DbgStopPointInst - This represents the llvm.dbg.stoppoint instruction.
///

std::string DbgStopPointInst::getFileName() const {
  // Once the operand indices are verified, update this assert
  assert(LLVMDebugVersion == (5 << 16) && "Verify operand indices");
  GlobalVariable *GV = cast<GlobalVariable>(getContext());
  if (!GV->hasInitializer()) return "";
  ConstantStruct *CS = cast<ConstantStruct>(GV->getInitializer());
  return CS->getOperand(3)->getStringValue();
}

std::string DbgStopPointInst::getDirectory() const {
  // Once the operand indices are verified, update this assert
  assert(LLVMDebugVersion == (5 << 16) && "Verify operand indices");
  GlobalVariable *GV = cast<GlobalVariable>(getContext());
  if (!GV->hasInitializer()) return "";
  ConstantStruct *CS = cast<ConstantStruct>(GV->getInitializer());
  return CS->getOperand(4)->getStringValue();
}

//===----------------------------------------------------------------------===//
/// Ensure that users of IntrinsicInst.h will link with this module.
DEFINING_FILE_FOR(IntrinsicInst)
<|endoftext|>


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

#include "chrome/browser/login_prompt.h"

#include <gtk/gtk.h>

#include "app/l10n_util.h"
#include "base/message_loop.h"
#include "chrome/browser/gtk/constrained_window_gtk.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/notification_service.h"
#include "grit/generated_resources.h"
#include "net/url_request/url_request.h"

using webkit_glue::PasswordForm;

// ----------------------------------------------------------------------------
// LoginHandlerGtk

// This class simply forwards the authentication from the LoginView (on
// the UI thread) to the URLRequest (on the I/O thread).
// This class uses ref counting to ensure that it lives until all InvokeLaters
// have been called.
class LoginHandlerGtk : public LoginHandler,
                        public base::RefCountedThreadSafe<LoginHandlerGtk>,
                        public ConstrainedWindowGtkDelegate {
 public:
  LoginHandlerGtk(URLRequest* request, MessageLoop* ui_loop)
      : handled_auth_(false),
        dialog_(NULL),
        ui_loop_(ui_loop),
        request_(request),
        request_loop_(MessageLoop::current()),
        password_manager_(NULL) {
    DCHECK(request_) << "LoginHandlerGtk constructed with NULL request";

    AddRef();  // matched by ReleaseLater.
    if (!ResourceDispatcherHost::RenderViewForRequest(request_,
                                                      &render_process_host_id_,
                                                      &tab_contents_id_)) {
      NOTREACHED();
    }
  }

  virtual ~LoginHandlerGtk() {
    root_.Destroy();
  }

  // LoginHandler:
  virtual void BuildViewForPasswordManager(PasswordManager* manager,
                                           std::wstring explanation) {
    DCHECK(MessageLoop::current() == ui_loop_);

    root_.Own(gtk_vbox_new(NULL, gtk_util::kContentAreaBorder));
    GtkWidget* label = gtk_label_new(WideToUTF8(explanation).c_str());
    gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
    gtk_box_pack_start(GTK_BOX(root_.get()), label, FALSE, FALSE, 0);

    username_entry_ = gtk_entry_new();
    gtk_entry_set_activates_default(GTK_ENTRY(username_entry_), TRUE);

    password_entry_ = gtk_entry_new();
    gtk_entry_set_activates_default(GTK_ENTRY(password_entry_), TRUE);
    gtk_entry_set_visibility(GTK_ENTRY(password_entry_), FALSE);

    GtkWidget* table = gtk_util::CreateLabeledControlsGroup(NULL,
        l10n_util::GetStringUTF8(IDS_LOGIN_DIALOG_USERNAME_FIELD).c_str(),
        username_entry_,
        l10n_util::GetStringUTF8(IDS_LOGIN_DIALOG_PASSWORD_FIELD).c_str(),
        password_entry_,
        NULL);
    gtk_box_pack_start(GTK_BOX(root_.get()), table, FALSE, FALSE, 0);

    GtkWidget* hbox = gtk_hbox_new(FALSE, 12);
    gtk_box_pack_start(GTK_BOX(root_.get()), hbox, FALSE, FALSE, 0);

    GtkWidget* ok = gtk_button_new_from_stock(GTK_STOCK_OK);
    gtk_button_set_label(
        GTK_BUTTON(ok),
        l10n_util::GetStringUTF8(IDS_LOGIN_DIALOG_OK_BUTTON_LABEL).c_str());
    g_signal_connect(ok, "clicked", G_CALLBACK(OnOKClicked), this);
    gtk_box_pack_end(GTK_BOX(hbox), ok, FALSE, FALSE, 0);

    GtkWidget* cancel = gtk_button_new_from_stock(GTK_STOCK_CANCEL);
    g_signal_connect(cancel, "clicked", G_CALLBACK(OnCancelClicked), this);
    gtk_box_pack_end(GTK_BOX(hbox), cancel, FALSE, FALSE, 0);

    // Scary thread safety note: This can potentially be called *after* SetAuth
    // or CancelAuth (say, if the request was cancelled before the UI thread got
    // control).  However, that's OK since any UI interaction in those functions
    // will occur via an InvokeLater on the UI thread, which is guaranteed
    // to happen after this is called (since this was InvokeLater'd first).
    dialog_ = GetTabContentsForLogin()->CreateConstrainedDialog(this);

    // Now that we have attached ourself to the window, we can make our OK
    // button the default action and mess with the focus.
    GTK_WIDGET_SET_FLAGS(ok, GTK_CAN_DEFAULT);
    gtk_widget_grab_default(ok);
    gtk_widget_grab_focus(username_entry_);

    SendNotifications();
  }

  virtual void SetPasswordForm(const webkit_glue::PasswordForm& form) {
    password_form_ = form;
  }

  virtual void SetPasswordManager(PasswordManager* password_manager) {
    password_manager_ = password_manager;
  }

  virtual TabContents* GetTabContentsForLogin() {
    DCHECK(MessageLoop::current() == ui_loop_);

    return tab_util::GetTabContentsByID(render_process_host_id_,
                                        tab_contents_id_);
  }

  virtual void SetAuth(const std::wstring& username,
                       const std::wstring& password) {
    if (WasAuthHandled(true))
      return;

    // Tell the password manager the credentials were submitted / accepted.
    if (password_manager_) {
      password_form_.username_value = username;
      password_form_.password_value = password;
      password_manager_->ProvisionallySavePassword(password_form_);
    }

    ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::CloseContentsDeferred));
    ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::SendNotifications));
    request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::SetAuthDeferred, username, password));
  }

  virtual void CancelAuth() {
    if (WasAuthHandled(true))
      return;

    ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::CloseContentsDeferred));
    ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::SendNotifications));
    request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::CancelAuthDeferred));
  }

  virtual void OnRequestCancelled() {
    DCHECK(MessageLoop::current() == request_loop_) <<
        "Why is OnRequestCancelled called from the UI thread?";

    // Reference is no longer valid.
    request_ = NULL;

    // Give up on auth if the request was cancelled.
    CancelAuth();
  }

  // Overridden from ConstrainedWindowGtkDelegate:
  virtual GtkWidget* GetWidgetRoot() {
    return root_.get();
  }

  virtual void DeleteDelegate() {
    if (!WasAuthHandled(true)) {
      request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
          this, &LoginHandlerGtk::CancelAuthDeferred));
      SendNotifications();
    }

    // Delete this object once all InvokeLaters have been called.
    request_loop_->ReleaseSoon(FROM_HERE, this);
  }

 private:
  friend class LoginPrompt;

  // Calls SetAuth from the request_loop.
  void SetAuthDeferred(const std::wstring& username,
                       const std::wstring& password) {
    DCHECK(MessageLoop::current() == request_loop_);

    if (request_) {
      request_->SetAuth(username, password);
      ResetLoginHandlerForRequest(request_);
    }
  }

  // Calls CancelAuth from the request_loop.
  void CancelAuthDeferred() {
    DCHECK(MessageLoop::current() == request_loop_);

    if (request_) {
      request_->CancelAuth();
      // Verify that CancelAuth does destroy the request via our delegate.
      DCHECK(request_ != NULL);
      ResetLoginHandlerForRequest(request_);
    }
  }

  // Closes the view_contents from the UI loop.
  void CloseContentsDeferred() {
    DCHECK(MessageLoop::current() == ui_loop_);

    // The hosting ConstrainedWindow may have been freed.
    if (dialog_)
      dialog_->CloseConstrainedWindow();
  }

  // Returns whether authentication had been handled (SetAuth or CancelAuth).
  // If |set_handled| is true, it will mark authentication as handled.
  bool WasAuthHandled(bool set_handled) {
    AutoLock lock(handled_auth_lock_);
    bool was_handled = handled_auth_;
    if (set_handled)
      handled_auth_ = true;
    return was_handled;
  }

  // Notify observers that authentication is needed or received.  The automation
  // proxy uses this for testing.
  void SendNotifications() {
    DCHECK(MessageLoop::current() == ui_loop_);

    NotificationService* service = NotificationService::current();
    TabContents* requesting_contents = GetTabContentsForLogin();
    if (!requesting_contents)
      return;

    NavigationController* controller = &requesting_contents->controller();

    if (!WasAuthHandled(false)) {
      LoginNotificationDetails details(this);
      service->Notify(NotificationType::AUTH_NEEDED,
                      Source<NavigationController>(controller),
                      Details<LoginNotificationDetails>(&details));
    } else {
      service->Notify(NotificationType::AUTH_SUPPLIED,
                      Source<NavigationController>(controller),
                      NotificationService::NoDetails());
    }
  }

  static void OnOKClicked(GtkButton *button, LoginHandlerGtk* handler) {
    DCHECK(MessageLoop::current() == handler->ui_loop_);

    handler->SetAuth(
        UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(handler->username_entry_))),
        UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(handler->password_entry_))));
  }

  static void OnCancelClicked(GtkButton *button, LoginHandlerGtk* handler) {
    DCHECK(MessageLoop::current() == handler->ui_loop_);
    handler->CancelAuth();
  }

  // True if we've handled auth (SetAuth or CancelAuth has been called).
  bool handled_auth_;
  Lock handled_auth_lock_;

  // The ConstrainedWindow that is hosting our LoginView.
  // This should only be accessed on the ui_loop_.
  ConstrainedWindow* dialog_;

  // The MessageLoop of the thread that the ChromeViewContents lives in.
  MessageLoop* ui_loop_;

  // The request that wants login data.
  // This should only be accessed on the request_loop_.
  URLRequest* request_;

  // The MessageLoop of the thread that the URLRequest lives in.
  MessageLoop* request_loop_;

  // The PasswordForm sent to the PasswordManager. This is so we can refer to it
  // when later notifying the password manager if the credentials were accepted
  // or rejected.
  // This should only be accessed on the ui_loop_.
  PasswordForm password_form_;

  // Points to the password manager owned by the TabContents requesting auth.
  // Can be null if the TabContents is not a TabContents.
  // This should only be accessed on the ui_loop_.
  PasswordManager* password_manager_;

  // Cached from the URLRequest, in case it goes NULL on us.
  int render_process_host_id_;
  int tab_contents_id_;

  // The GtkWidgets that form our visual hierarchy:
  // The root container we pass to our parent.
  OwnedWidgetGtk root_;

  // GtkEntry widgets that the user types into.
  GtkWidget* username_entry_;
  GtkWidget* password_entry_;

  DISALLOW_COPY_AND_ASSIGN(LoginHandlerGtk);
};

// static
LoginHandler* LoginHandler::Create(URLRequest* request, MessageLoop* ui_loop) {
  return new LoginHandlerGtk(request, ui_loop);
}
<commit_msg>gtk: Post the SendNotification in a task on the UI thread.  In rare instances, SendNotifications was being run before CancelAuthDeferred, so the proper cleanup was not happening before this object was deleted which leads to a crash.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/login_prompt.h"

#include <gtk/gtk.h>

#include "app/l10n_util.h"
#include "base/message_loop.h"
#include "chrome/browser/gtk/constrained_window_gtk.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/notification_service.h"
#include "grit/generated_resources.h"
#include "net/url_request/url_request.h"

using webkit_glue::PasswordForm;

// ----------------------------------------------------------------------------
// LoginHandlerGtk

// This class simply forwards the authentication from the LoginView (on
// the UI thread) to the URLRequest (on the I/O thread).
// This class uses ref counting to ensure that it lives until all InvokeLaters
// have been called.
class LoginHandlerGtk : public LoginHandler,
                        public base::RefCountedThreadSafe<LoginHandlerGtk>,
                        public ConstrainedWindowGtkDelegate {
 public:
  LoginHandlerGtk(URLRequest* request, MessageLoop* ui_loop)
      : handled_auth_(false),
        dialog_(NULL),
        ui_loop_(ui_loop),
        request_(request),
        request_loop_(MessageLoop::current()),
        password_manager_(NULL) {
    DCHECK(request_) << "LoginHandlerGtk constructed with NULL request";

    AddRef();  // matched by ReleaseLater.
    if (!ResourceDispatcherHost::RenderViewForRequest(request_,
                                                      &render_process_host_id_,
                                                      &tab_contents_id_)) {
      NOTREACHED();
    }
  }

  virtual ~LoginHandlerGtk() {
    root_.Destroy();
  }

  // LoginHandler:
  virtual void BuildViewForPasswordManager(PasswordManager* manager,
                                           std::wstring explanation) {
    DCHECK(MessageLoop::current() == ui_loop_);

    root_.Own(gtk_vbox_new(NULL, gtk_util::kContentAreaBorder));
    GtkWidget* label = gtk_label_new(WideToUTF8(explanation).c_str());
    gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
    gtk_box_pack_start(GTK_BOX(root_.get()), label, FALSE, FALSE, 0);

    username_entry_ = gtk_entry_new();
    gtk_entry_set_activates_default(GTK_ENTRY(username_entry_), TRUE);

    password_entry_ = gtk_entry_new();
    gtk_entry_set_activates_default(GTK_ENTRY(password_entry_), TRUE);
    gtk_entry_set_visibility(GTK_ENTRY(password_entry_), FALSE);

    GtkWidget* table = gtk_util::CreateLabeledControlsGroup(NULL,
        l10n_util::GetStringUTF8(IDS_LOGIN_DIALOG_USERNAME_FIELD).c_str(),
        username_entry_,
        l10n_util::GetStringUTF8(IDS_LOGIN_DIALOG_PASSWORD_FIELD).c_str(),
        password_entry_,
        NULL);
    gtk_box_pack_start(GTK_BOX(root_.get()), table, FALSE, FALSE, 0);

    GtkWidget* hbox = gtk_hbox_new(FALSE, 12);
    gtk_box_pack_start(GTK_BOX(root_.get()), hbox, FALSE, FALSE, 0);

    GtkWidget* ok = gtk_button_new_from_stock(GTK_STOCK_OK);
    gtk_button_set_label(
        GTK_BUTTON(ok),
        l10n_util::GetStringUTF8(IDS_LOGIN_DIALOG_OK_BUTTON_LABEL).c_str());
    g_signal_connect(ok, "clicked", G_CALLBACK(OnOKClicked), this);
    gtk_box_pack_end(GTK_BOX(hbox), ok, FALSE, FALSE, 0);

    GtkWidget* cancel = gtk_button_new_from_stock(GTK_STOCK_CANCEL);
    g_signal_connect(cancel, "clicked", G_CALLBACK(OnCancelClicked), this);
    gtk_box_pack_end(GTK_BOX(hbox), cancel, FALSE, FALSE, 0);

    // Scary thread safety note: This can potentially be called *after* SetAuth
    // or CancelAuth (say, if the request was cancelled before the UI thread got
    // control).  However, that's OK since any UI interaction in those functions
    // will occur via an InvokeLater on the UI thread, which is guaranteed
    // to happen after this is called (since this was InvokeLater'd first).
    dialog_ = GetTabContentsForLogin()->CreateConstrainedDialog(this);

    // Now that we have attached ourself to the window, we can make our OK
    // button the default action and mess with the focus.
    GTK_WIDGET_SET_FLAGS(ok, GTK_CAN_DEFAULT);
    gtk_widget_grab_default(ok);
    gtk_widget_grab_focus(username_entry_);

    SendNotifications();
  }

  virtual void SetPasswordForm(const webkit_glue::PasswordForm& form) {
    password_form_ = form;
  }

  virtual void SetPasswordManager(PasswordManager* password_manager) {
    password_manager_ = password_manager;
  }

  virtual TabContents* GetTabContentsForLogin() {
    DCHECK(MessageLoop::current() == ui_loop_);

    return tab_util::GetTabContentsByID(render_process_host_id_,
                                        tab_contents_id_);
  }

  virtual void SetAuth(const std::wstring& username,
                       const std::wstring& password) {
    if (WasAuthHandled(true))
      return;

    // Tell the password manager the credentials were submitted / accepted.
    if (password_manager_) {
      password_form_.username_value = username;
      password_form_.password_value = password;
      password_manager_->ProvisionallySavePassword(password_form_);
    }

    ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::CloseContentsDeferred));
    ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::SendNotifications));
    request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::SetAuthDeferred, username, password));
  }

  virtual void CancelAuth() {
    if (WasAuthHandled(true))
      return;

    ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::CloseContentsDeferred));
    ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::SendNotifications));
    request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
        this, &LoginHandlerGtk::CancelAuthDeferred));
  }

  virtual void OnRequestCancelled() {
    DCHECK(MessageLoop::current() == request_loop_) <<
        "Why is OnRequestCancelled called from the UI thread?";

    // Reference is no longer valid.
    request_ = NULL;

    // Give up on auth if the request was cancelled.
    CancelAuth();
  }

  // Overridden from ConstrainedWindowGtkDelegate:
  virtual GtkWidget* GetWidgetRoot() {
    return root_.get();
  }

  virtual void DeleteDelegate() {
    if (!WasAuthHandled(true)) {
      request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
          this, &LoginHandlerGtk::CancelAuthDeferred));
      ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
          this, &LoginHandlerGtk::SendNotifications));
    }

    // Delete this object once all InvokeLaters have been called.
    request_loop_->ReleaseSoon(FROM_HERE, this);
  }

 private:
  friend class LoginPrompt;

  // Calls SetAuth from the request_loop.
  void SetAuthDeferred(const std::wstring& username,
                       const std::wstring& password) {
    DCHECK(MessageLoop::current() == request_loop_);

    if (request_) {
      request_->SetAuth(username, password);
      ResetLoginHandlerForRequest(request_);
    }
  }

  // Calls CancelAuth from the request_loop.
  void CancelAuthDeferred() {
    DCHECK(MessageLoop::current() == request_loop_);

    if (request_) {
      request_->CancelAuth();
      // Verify that CancelAuth does destroy the request via our delegate.
      DCHECK(request_ != NULL);
      ResetLoginHandlerForRequest(request_);
    }
  }

  // Closes the view_contents from the UI loop.
  void CloseContentsDeferred() {
    DCHECK(MessageLoop::current() == ui_loop_);

    // The hosting ConstrainedWindow may have been freed.
    if (dialog_)
      dialog_->CloseConstrainedWindow();
  }

  // Returns whether authentication had been handled (SetAuth or CancelAuth).
  // If |set_handled| is true, it will mark authentication as handled.
  bool WasAuthHandled(bool set_handled) {
    AutoLock lock(handled_auth_lock_);
    bool was_handled = handled_auth_;
    if (set_handled)
      handled_auth_ = true;
    return was_handled;
  }

  // Notify observers that authentication is needed or received.  The automation
  // proxy uses this for testing.
  void SendNotifications() {
    DCHECK(MessageLoop::current() == ui_loop_);

    NotificationService* service = NotificationService::current();
    TabContents* requesting_contents = GetTabContentsForLogin();
    if (!requesting_contents)
      return;

    NavigationController* controller = &requesting_contents->controller();

    if (!WasAuthHandled(false)) {
      LoginNotificationDetails details(this);
      service->Notify(NotificationType::AUTH_NEEDED,
                      Source<NavigationController>(controller),
                      Details<LoginNotificationDetails>(&details));
    } else {
      service->Notify(NotificationType::AUTH_SUPPLIED,
                      Source<NavigationController>(controller),
                      NotificationService::NoDetails());
    }
  }

  static void OnOKClicked(GtkButton *button, LoginHandlerGtk* handler) {
    DCHECK(MessageLoop::current() == handler->ui_loop_);

    handler->SetAuth(
        UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(handler->username_entry_))),
        UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(handler->password_entry_))));
  }

  static void OnCancelClicked(GtkButton *button, LoginHandlerGtk* handler) {
    DCHECK(MessageLoop::current() == handler->ui_loop_);
    handler->CancelAuth();
  }

  // True if we've handled auth (SetAuth or CancelAuth has been called).
  bool handled_auth_;
  Lock handled_auth_lock_;

  // The ConstrainedWindow that is hosting our LoginView.
  // This should only be accessed on the ui_loop_.
  ConstrainedWindow* dialog_;

  // The MessageLoop of the thread that the ChromeViewContents lives in.
  MessageLoop* ui_loop_;

  // The request that wants login data.
  // This should only be accessed on the request_loop_.
  URLRequest* request_;

  // The MessageLoop of the thread that the URLRequest lives in.
  MessageLoop* request_loop_;

  // The PasswordForm sent to the PasswordManager. This is so we can refer to it
  // when later notifying the password manager if the credentials were accepted
  // or rejected.
  // This should only be accessed on the ui_loop_.
  PasswordForm password_form_;

  // Points to the password manager owned by the TabContents requesting auth.
  // Can be null if the TabContents is not a TabContents.
  // This should only be accessed on the ui_loop_.
  PasswordManager* password_manager_;

  // Cached from the URLRequest, in case it goes NULL on us.
  int render_process_host_id_;
  int tab_contents_id_;

  // The GtkWidgets that form our visual hierarchy:
  // The root container we pass to our parent.
  OwnedWidgetGtk root_;

  // GtkEntry widgets that the user types into.
  GtkWidget* username_entry_;
  GtkWidget* password_entry_;

  DISALLOW_COPY_AND_ASSIGN(LoginHandlerGtk);
};

// static
LoginHandler* LoginHandler::Create(URLRequest* request, MessageLoop* ui_loop) {
  return new LoginHandlerGtk(request, ui_loop);
}
<|endoftext|>


<commit_before>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//    * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//    * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/automation/url_request_mock_http_job.h"
#include "chrome/browser/save_package.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/url_request/url_request_unittest.h"

const std::wstring kTestDir = L"save_page";

class SavePageTest : public UITest {
 protected:
  SavePageTest() : UITest() {}

  void CheckFile(const std::wstring& client_file,
                 const std::wstring& server_file,
                 bool check_equal) {
    bool exist = false;
    for (int i = 0; i < 20; ++i) {
      if (file_util::PathExists(client_file)) {
        exist = true;
        break;
      }
      Sleep(kWaitForActionMaxMsec / 20);
    }
    EXPECT_TRUE(exist);

    if (check_equal) {
      std::wstring server_file_name;
      ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA,
                                   &server_file_name));
      server_file_name += L"\\" + kTestDir + L"\\" + server_file;
      ASSERT_TRUE(file_util::PathExists(server_file_name));

      EXPECT_PRED2(file_util::ContentsEqual, client_file, server_file_name);
    }

    EXPECT_TRUE(DieFileDie(client_file, false));
  }

  virtual void SetUp() {
    UITest::SetUp();
    EXPECT_TRUE(file_util::CreateNewTempDirectory(L"", &save_dir_));
    save_dir_ += file_util::kPathSeparator;
  }

  std::wstring save_dir_;
};

// bug 1306067
TEST_F(SavePageTest, DISABLED_SaveHTMLOnly) {
  std::wstring file_name = L"a.htm";
  std::wstring full_file_name = save_dir_ + file_name;
  std::wstring dir = save_dir_ + L"a_files";

  GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name);
  scoped_ptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab->NavigateToURL(url));
  WaitUntilTabCount(1);

  EXPECT_TRUE(tab->SavePage(full_file_name, dir,
      SavePackage::SAVE_AS_ONLY_HTML));
  EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get()));

  CheckFile(full_file_name, file_name, true);
  EXPECT_FALSE(file_util::PathExists(dir));
}

TEST_F(SavePageTest, SaveCompleteHTML) {
  std::wstring file_name = L"b.htm";
  std::wstring full_file_name = save_dir_ + file_name;
  std::wstring dir = save_dir_ + L"b_files";

  GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name);
  scoped_ptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab->NavigateToURL(url));
  WaitUntilTabCount(1);

  EXPECT_TRUE(tab->SavePage(full_file_name, dir,
      SavePackage::SAVE_AS_COMPLETE_HTML));
  EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get()));

  CheckFile(dir + L"\\1.png", L"1.png", true);
  CheckFile(dir + L"\\1.css", L"1.css", true);
  CheckFile(full_file_name, file_name, false);
  EXPECT_TRUE(DieFileDie(dir, true));
}

TEST_F(SavePageTest, NoSave) {
  std::wstring file_name = L"c.htm";
  std::wstring full_file_name = save_dir_ + file_name;
  std::wstring dir = save_dir_ + L"c_files";

  scoped_ptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab->NavigateToURL(GURL(L"about:blank")));
  WaitUntilTabCount(1);

  EXPECT_FALSE(tab->SavePage(full_file_name, dir,
      SavePackage::SAVE_AS_ONLY_HTML));
  EXPECT_FALSE(WaitForDownloadShelfVisible(tab.get()));
}
<commit_msg>Enable back SavePageTest.SaveHTMLOnly since it was mostly failing on Windows 2000 and add debugging information to know how SavePageTest.SaveCompleteHTML is failing.<commit_after>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//    * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//    * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/automation/url_request_mock_http_job.h"
#include "chrome/browser/save_package.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/url_request/url_request_unittest.h"

const std::wstring kTestDir = L"save_page";

class SavePageTest : public UITest {
 protected:
  SavePageTest() : UITest() {}

  void CheckFile(const std::wstring& client_file,
                 const std::wstring& server_file,
                 bool check_equal) {
    bool exist = false;
    for (int i = 0; i < 20; ++i) {
      if (file_util::PathExists(client_file)) {
        exist = true;
        break;
      }
      Sleep(kWaitForActionMaxMsec / 20);
    }
    EXPECT_TRUE(exist);

    if (check_equal) {
      std::wstring server_file_name;
      ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA,
                                   &server_file_name));
      server_file_name += L"\\" + kTestDir + L"\\" + server_file;
      ASSERT_TRUE(file_util::PathExists(server_file_name));

      int64 client_file_size = 0;
      int64 server_file_size = 0;
      EXPECT_TRUE(file_util::GetFileSize(client_file, &client_file_size));
      EXPECT_TRUE(file_util::GetFileSize(server_file_name, &server_file_size));
      EXPECT_EQ(client_file_size, server_file_size);
      EXPECT_PRED2(file_util::ContentsEqual, client_file, server_file_name);
    }

    EXPECT_TRUE(DieFileDie(client_file, false));
  }

  virtual void SetUp() {
    UITest::SetUp();
    EXPECT_TRUE(file_util::CreateNewTempDirectory(L"", &save_dir_));
    save_dir_ += file_util::kPathSeparator;
  }

  std::wstring save_dir_;
};

TEST_F(SavePageTest, SaveHTMLOnly) {
  std::wstring file_name = L"a.htm";
  std::wstring full_file_name = save_dir_ + file_name;
  std::wstring dir = save_dir_ + L"a_files";

  GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name);
  scoped_ptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab->NavigateToURL(url));
  WaitUntilTabCount(1);

  EXPECT_TRUE(tab->SavePage(full_file_name, dir,
      SavePackage::SAVE_AS_ONLY_HTML));
  EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get()));

  CheckFile(full_file_name, file_name, true);
  EXPECT_FALSE(file_util::PathExists(dir));
}

TEST_F(SavePageTest, SaveCompleteHTML) {
  std::wstring file_name = L"b.htm";
  std::wstring full_file_name = save_dir_ + file_name;
  std::wstring dir = save_dir_ + L"b_files";

  GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name);
  scoped_ptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab->NavigateToURL(url));
  WaitUntilTabCount(1);

  EXPECT_TRUE(tab->SavePage(full_file_name, dir,
      SavePackage::SAVE_AS_COMPLETE_HTML));
  EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get()));

  CheckFile(dir + L"\\1.png", L"1.png", true);
  CheckFile(dir + L"\\1.css", L"1.css", true);
  CheckFile(full_file_name, file_name, false);
  EXPECT_TRUE(DieFileDie(dir, true));
}

TEST_F(SavePageTest, NoSave) {
  std::wstring file_name = L"c.htm";
  std::wstring full_file_name = save_dir_ + file_name;
  std::wstring dir = save_dir_ + L"c_files";

  scoped_ptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab->NavigateToURL(GURL(L"about:blank")));
  WaitUntilTabCount(1);

  EXPECT_FALSE(tab->SavePage(full_file_name, dir,
      SavePackage::SAVE_AS_ONLY_HTML));
  EXPECT_FALSE(WaitForDownloadShelfVisible(tab.get()));
}
<|endoftext|>


<commit_before>/*
 * Copyright 2002-2010 Guillaume Cottenceau.
 *
 * This software may be freely redistributed under the terms
 * of the X11 license.
 *
 */

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>

#define PNG_DEBUG 3
#include "png.h"

void abort_(const char * s, ...)
{
  va_list args;
  va_start(args, s);
  vfprintf(stderr, s, args);
  fprintf(stderr, "\n");
  va_end(args);
  abort();
}

int x, y;

int width, height;
png_byte color_type;
png_byte bit_depth;

png_structp png_ptr;
png_infop info_ptr;
int number_of_passes;
png_bytep * row_pointers = NULL;

// BGR or BGRA data will be read into this buffer of pixels

uint32_t *pixels = NULL;

void allocate_row_pointers()
{
  if (row_pointers != NULL) {
    abort_("[allocate_row_pointers] row_pointers already allocated");
  }

  row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * height);

  if (!row_pointers) {
    abort_("[allocate_row_pointers] could not allocate %d bytes to store row data", (sizeof(png_bytep) * height));
  }

  for (y=0; y<height; y++) {
    row_pointers[y] = (png_byte*) malloc(png_get_rowbytes(png_ptr,info_ptr));

    if (!row_pointers[y]) {
      abort_("[allocate_row_pointers] could not allocate %d bytes to store row data", png_get_rowbytes(png_ptr,info_ptr));
    }
  }
}

void free_row_pointers()
{
  if (row_pointers == NULL) {
    return;
  }

  for (y=0; y<height; y++)
    free(row_pointers[y]);
  free(row_pointers);
  row_pointers = NULL;
}

void read_png_file(char* file_name)
{
  char header[8];    // 8 is the maximum size that can be checked

  /* open file and test for it being a png */
  FILE *fp = fopen(file_name, "rb");
  if (!fp)
    abort_("[read_png_file] File %s could not be opened for reading", file_name);
  fread(header, 1, 8, fp);
  if (png_sig_cmp((png_const_bytep)header, 0, 8))
    abort_("[read_png_file] File %s is not recognized as a PNG file", file_name);

  /* initialize stuff */
  png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

  if (!png_ptr)
    abort_("[read_png_file] png_create_read_struct failed");

  info_ptr = png_create_info_struct(png_ptr);
  if (!info_ptr)
    abort_("[read_png_file] png_create_info_struct failed");

  if (setjmp(png_jmpbuf(png_ptr)))
    abort_("[read_png_file] Error during init_io");

  png_init_io(png_ptr, fp);
  png_set_sig_bytes(png_ptr, 8);

  png_read_info(png_ptr, info_ptr);

  width = png_get_image_width(png_ptr, info_ptr);
  height = png_get_image_height(png_ptr, info_ptr);
  color_type = png_get_color_type(png_ptr, info_ptr);
  bit_depth = png_get_bit_depth(png_ptr, info_ptr);

  number_of_passes = png_set_interlace_handling(png_ptr);
  png_read_update_info(png_ptr, info_ptr);

  /* read file */
  if (setjmp(png_jmpbuf(png_ptr)))
    abort_("[read_png_file] Error during read_image");

  allocate_row_pointers();

  png_read_image(png_ptr, row_pointers);

  /* allocate pixels data and read into array of pixels */

  pixels = (uint32_t*) malloc(width * height * sizeof(uint32_t));

  if (!pixels) {
    abort_("[read_png_file] could not allocate %d bytes to store pixel data", (width * height * sizeof(uint32_t)));
  }

  int pixeli = 0;

  int isBGRA = 0;

  if (png_get_color_type(png_ptr, info_ptr) == PNG_COLOR_TYPE_RGBA) {
    isBGRA = 1;
  } else if (png_get_color_type(png_ptr, info_ptr) == PNG_COLOR_TYPE_RGB) {
    isBGRA = 0;
  } else {
    abort_("[read_png_file] unsupported input format type");
  }

  for (y=0; y<height; y++) {
    png_byte* row = row_pointers[y];

    if (isBGRA) {
      for (x=0; x<width; x++) {
        png_byte* ptr = &(row[x*4]);

        uint32_t B = ptr[2];
        uint32_t G = ptr[1];
        uint32_t R = ptr[0];
        uint32_t A = ptr[3];

        uint32_t pixel = (A << 24) | (R << 16) | (G << 8) | B;

        fprintf(stdout, "Read pixel 0x%08X at (x,y) (%d, %d)\n", pixel, x, y);

        pixels[pixeli] = pixel;

        pixeli++;
      }
    } else {
      // BGR with no alpha channel
      for (x=0; x<width; x++) {
        png_byte* ptr = &(row[x*3]);

        uint32_t B = ptr[2];
        uint32_t G = ptr[1];
        uint32_t R = ptr[0];

        uint32_t pixel = (0xFF << 24) | (R << 16) | (G << 8) | B;

        fprintf(stdout, "Read pixel 0x%08X at (x,y) (%d, %d)\n", pixel, x, y);

        pixels[pixeli] = pixel;

        pixeli++;
      }
    }
  }

  fclose(fp);

  free_row_pointers();
}

void write_png_file(char* file_name)
{
  /* create file */
  FILE *fp = fopen(file_name, "wb");
  if (!fp)
    abort_("[write_png_file] File %s could not be opened for writing", file_name);

  /* initialize stuff */
  png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

  if (!png_ptr)
    abort_("[write_png_file] png_create_write_struct failed");

  info_ptr = png_create_info_struct(png_ptr);
  if (!info_ptr)
    abort_("[write_png_file] png_create_info_struct failed");

  if (setjmp(png_jmpbuf(png_ptr)))
    abort_("[write_png_file] Error during init_io");

  png_init_io(png_ptr, fp);

  /* write header */
  if (setjmp(png_jmpbuf(png_ptr)))
    abort_("[write_png_file] Error during writing header");

  png_set_IHDR(png_ptr, info_ptr, width, height,
               bit_depth, color_type, PNG_INTERLACE_NONE,
               PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

  png_write_info(png_ptr, info_ptr);

  /* write pixels back to row_pointers */

  allocate_row_pointers();

  int isBGRA = 0;

  if (png_get_color_type(png_ptr, info_ptr) == PNG_COLOR_TYPE_RGBA) {
    isBGRA = 1;
  } else if (png_get_color_type(png_ptr, info_ptr) == PNG_COLOR_TYPE_RGB) {
    isBGRA = 0;
  } else {
    abort_("[write_png_file] unsupported input format type");
  }

  int pixeli = 0;

  for (y=0; y<height; y++) {
    png_byte* row = row_pointers[y];

    if (isBGRA) {
      for (x=0; x<width; x++) {
        png_byte* ptr = &(row[x*4]);

        uint32_t pixel = pixels[pixeli];

        uint32_t B = pixel & 0xFF;
        uint32_t G = (pixel >> 8) & 0xFF;
        uint32_t R = (pixel >> 16) & 0xFF;
        uint32_t A = (pixel >> 24) & 0xFF;

        ptr[0] = R;
        ptr[1] = G;
        ptr[2] = B;
        ptr[3] = A;

        fprintf(stdout, "Wrote pixel 0x%08X at (x,y) (%d, %d)\n", pixel, x, y);

        pixeli++;
      }
    } else {
      for (x=0; x<width; x++) {
        png_byte* ptr = &(row[x*3]);

        uint32_t pixel = pixels[pixeli];

        uint32_t B = pixel & 0xFF;
        uint32_t G = (pixel >> 8) & 0xFF;
        uint32_t R = (pixel >> 16) & 0xFF;

        ptr[0] = R;
        ptr[1] = G;
        ptr[2] = B;

        fprintf(stdout, "Wrote pixel 0x%08X at (x,y) (%d, %d)\n", pixel, x, y);

        pixeli++;
      }
    }
  }

  if (setjmp(png_jmpbuf(png_ptr)))
    abort_("[write_png_file] Error during writing bytes");

  png_write_image(png_ptr, row_pointers);

  /* end write */
  if (setjmp(png_jmpbuf(png_ptr)))
    abort_("[write_png_file] Error during end of write");

  png_write_end(png_ptr, NULL);

  fclose(fp);
}

void process_file(void)
{

//  for (y=0; y<height; y++) {
//    png_byte* row = row_pointers[y];
//    for (x=0; x<width; x++) {
//      png_byte* ptr = &(row[x*4]);
//      printf("Pixel at position [ %d - %d ] has RGBA values: %d - %d - %d - %d\n",
//             x, y, ptr[0], ptr[1], ptr[2], ptr[3]);
//
//      /* set red value to 0 and green value to the blue one */
//      ptr[0] = 0;
//      ptr[1] = ptr[2];
//    }
//  }
}

/* deallocate memory */

void cleanup()
{
  free_row_pointers();

  free(pixels);
}

int main(int argc, char **argv)
{
  if (argc != 3) {
    abort_("Usage: %s <file_in> <file_out>", argv[0]);
  }

  read_png_file(argv[1]);
  process_file();
  write_png_file(argv[2]);

  cleanup();

  printf("success\n");

  return 0;
}
<commit_msg>implement example logic to do a channel swap after reading pixels in<commit_after>/*
 * Copyright 2002-2010 Guillaume Cottenceau.
 *
 * This software may be freely redistributed under the terms
 * of the X11 license.
 *
 */

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>

#define PNG_DEBUG 3
#include "png.h"

void abort_(const char * s, ...)
{
  va_list args;
  va_start(args, s);
  vfprintf(stderr, s, args);
  fprintf(stderr, "\n");
  va_end(args);
  abort();
}

int x, y;

int width, height;
png_byte color_type;
png_byte bit_depth;

png_structp png_ptr;
png_infop info_ptr;
int number_of_passes;
png_bytep * row_pointers = NULL;

// BGR or BGRA data will be read into this buffer of pixels

uint32_t *pixels = NULL;

const int debugPrintPixelsReadAndWritten = 0;

void allocate_row_pointers()
{
  if (row_pointers != NULL) {
    abort_("[allocate_row_pointers] row_pointers already allocated");
  }

  row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * height);

  if (!row_pointers) {
    abort_("[allocate_row_pointers] could not allocate %d bytes to store row data", (sizeof(png_bytep) * height));
  }

  for (y=0; y<height; y++) {
    row_pointers[y] = (png_byte*) malloc(png_get_rowbytes(png_ptr,info_ptr));

    if (!row_pointers[y]) {
      abort_("[allocate_row_pointers] could not allocate %d bytes to store row data", png_get_rowbytes(png_ptr,info_ptr));
    }
  }
}

void free_row_pointers()
{
  if (row_pointers == NULL) {
    return;
  }

  for (y=0; y<height; y++)
    free(row_pointers[y]);
  free(row_pointers);
  row_pointers = NULL;
}

void read_png_file(char* file_name)
{
  char header[8];    // 8 is the maximum size that can be checked

  /* open file and test for it being a png */
  FILE *fp = fopen(file_name, "rb");
  if (!fp)
    abort_("[read_png_file] File %s could not be opened for reading", file_name);
  fread(header, 1, 8, fp);
  if (png_sig_cmp((png_const_bytep)header, 0, 8))
    abort_("[read_png_file] File %s is not recognized as a PNG file", file_name);

  /* initialize stuff */
  png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

  if (!png_ptr)
    abort_("[read_png_file] png_create_read_struct failed");

  info_ptr = png_create_info_struct(png_ptr);
  if (!info_ptr)
    abort_("[read_png_file] png_create_info_struct failed");

  if (setjmp(png_jmpbuf(png_ptr)))
    abort_("[read_png_file] Error during init_io");

  png_init_io(png_ptr, fp);
  png_set_sig_bytes(png_ptr, 8);

  png_read_info(png_ptr, info_ptr);

  width = png_get_image_width(png_ptr, info_ptr);
  height = png_get_image_height(png_ptr, info_ptr);
  color_type = png_get_color_type(png_ptr, info_ptr);
  bit_depth = png_get_bit_depth(png_ptr, info_ptr);

  number_of_passes = png_set_interlace_handling(png_ptr);
  png_read_update_info(png_ptr, info_ptr);

  /* read file */
  if (setjmp(png_jmpbuf(png_ptr)))
    abort_("[read_png_file] Error during read_image");

  allocate_row_pointers();

  png_read_image(png_ptr, row_pointers);

  /* allocate pixels data and read into array of pixels */

  pixels = (uint32_t*) malloc(width * height * sizeof(uint32_t));

  if (!pixels) {
    abort_("[read_png_file] could not allocate %d bytes to store pixel data", (width * height * sizeof(uint32_t)));
  }

  int pixeli = 0;

  int isBGRA = 0;

  if (png_get_color_type(png_ptr, info_ptr) == PNG_COLOR_TYPE_RGBA) {
    isBGRA = 1;
  } else if (png_get_color_type(png_ptr, info_ptr) == PNG_COLOR_TYPE_RGB) {
    isBGRA = 0;
  } else {
    abort_("[read_png_file] unsupported input format type");
  }

  for (y=0; y<height; y++) {
    png_byte* row = row_pointers[y];

    if (isBGRA) {
      for (x=0; x<width; x++) {
        png_byte* ptr = &(row[x*4]);

        uint32_t B = ptr[2];
        uint32_t G = ptr[1];
        uint32_t R = ptr[0];
        uint32_t A = ptr[3];

        uint32_t pixel = (A << 24) | (R << 16) | (G << 8) | B;

        if (debugPrintPixelsReadAndWritten) {
        fprintf(stdout, "Read pixel 0x%08X at (x,y) (%d, %d)\n", pixel, x, y);
        }

        pixels[pixeli] = pixel;

        pixeli++;
      }
    } else {
      // BGR with no alpha channel
      for (x=0; x<width; x++) {
        png_byte* ptr = &(row[x*3]);

        uint32_t B = ptr[2];
        uint32_t G = ptr[1];
        uint32_t R = ptr[0];

        uint32_t pixel = (0xFF << 24) | (R << 16) | (G << 8) | B;

        if (debugPrintPixelsReadAndWritten) {
        fprintf(stdout, "Read pixel 0x%08X at (x,y) (%d, %d)\n", pixel, x, y);
        }

        pixels[pixeli] = pixel;

        pixeli++;
      }
    }
  }

  fclose(fp);

  free_row_pointers();
}

void write_png_file(char* file_name)
{
  /* create file */
  FILE *fp = fopen(file_name, "wb");
  if (!fp)
    abort_("[write_png_file] File %s could not be opened for writing", file_name);

  /* initialize stuff */
  png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

  if (!png_ptr)
    abort_("[write_png_file] png_create_write_struct failed");

  info_ptr = png_create_info_struct(png_ptr);
  if (!info_ptr)
    abort_("[write_png_file] png_create_info_struct failed");

  if (setjmp(png_jmpbuf(png_ptr)))
    abort_("[write_png_file] Error during init_io");

  png_init_io(png_ptr, fp);

  /* write header */
  if (setjmp(png_jmpbuf(png_ptr)))
    abort_("[write_png_file] Error during writing header");

  png_set_IHDR(png_ptr, info_ptr, width, height,
               bit_depth, color_type, PNG_INTERLACE_NONE,
               PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

  png_write_info(png_ptr, info_ptr);

  /* write pixels back to row_pointers */

  allocate_row_pointers();

  int isBGRA = 0;

  if (png_get_color_type(png_ptr, info_ptr) == PNG_COLOR_TYPE_RGBA) {
    isBGRA = 1;
  } else if (png_get_color_type(png_ptr, info_ptr) == PNG_COLOR_TYPE_RGB) {
    isBGRA = 0;
  } else {
    abort_("[write_png_file] unsupported input format type");
  }

  int pixeli = 0;

  for (y=0; y<height; y++) {
    png_byte* row = row_pointers[y];

    if (isBGRA) {
      for (x=0; x<width; x++) {
        png_byte* ptr = &(row[x*4]);

        uint32_t pixel = pixels[pixeli];

        uint32_t B = pixel & 0xFF;
        uint32_t G = (pixel >> 8) & 0xFF;
        uint32_t R = (pixel >> 16) & 0xFF;
        uint32_t A = (pixel >> 24) & 0xFF;

        ptr[0] = R;
        ptr[1] = G;
        ptr[2] = B;
        ptr[3] = A;

        if (debugPrintPixelsReadAndWritten) {
        fprintf(stdout, "Wrote pixel 0x%08X at (x,y) (%d, %d)\n", pixel, x, y);
        }

        pixeli++;
      }
    } else {
      for (x=0; x<width; x++) {
        png_byte* ptr = &(row[x*3]);

        uint32_t pixel = pixels[pixeli];

        uint32_t B = pixel & 0xFF;
        uint32_t G = (pixel >> 8) & 0xFF;
        uint32_t R = (pixel >> 16) & 0xFF;

        ptr[0] = R;
        ptr[1] = G;
        ptr[2] = B;

        if (debugPrintPixelsReadAndWritten) {
        fprintf(stdout, "Wrote pixel 0x%08X at (x,y) (%d, %d)\n", pixel, x, y);
        }

        pixeli++;
      }
    }
  }

  if (setjmp(png_jmpbuf(png_ptr)))
    abort_("[write_png_file] Error during writing bytes");

  png_write_image(png_ptr, row_pointers);

  /* end write */
  if (setjmp(png_jmpbuf(png_ptr)))
    abort_("[write_png_file] Error during end of write");

  png_write_end(png_ptr, NULL);

  fclose(fp);
}

void process_file(void)
{
  // Swap the B and R channels in the BGRA format pixels

  int numPixels = width * height;

  for ( int i = 0; i < numPixels; i++) {
    uint32_t pixel = pixels[i];
    uint32_t B = pixel & 0xFF;
    uint32_t G = (pixel >> 8) & 0xFF;
    uint32_t R = (pixel >> 16) & 0xFF;
    uint32_t A = (pixel >> 24) & 0xFF;

    // Swap B and R channels

    if ((1)) {
      uint32_t tmp = B;
      B = R;
      R = tmp;
    }

    uint32_t outPixel = (A << 24) | (R << 16) | (G << 8) | B;

    pixels[i] = outPixel;
  }
}

/* deallocate memory */

void cleanup()
{
  free_row_pointers();

  free(pixels);
}

int main(int argc, char **argv)
{
  if (argc != 3) {
    abort_("Usage: %s <file_in> <file_out>", argv[0]);
  }

  read_png_file(argv[1]);
  process_file();
  write_png_file(argv[2]);

  cleanup();

  printf("success processing %d pixels from image of dimensions %d x %d\n", width*height, width, height);

  return 0;
}
<|endoftext|>


<commit_before><commit_msg>do not use new presets for connector shapes<commit_after><|endoftext|>


<commit_before>#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <random>
#include <vector>

#define PI 3.141592653589793

class Note {
 public:
  Note(unsigned seed) :
      random_(seed),
      duration_dist_(0.0, 1.0),
      frequency_dist_(0.0, 1.0),
      volume_dist_(0.0f, 1.0f),
      pan_dist_(0.0f, 1.0f) {}

  void GetSample(double t, float out[2]) {
    if (t > stop_) {
      if (!respawn_) {
        out[0] = 0.0f;
        out[1] = 0.0f;
        return;
      }

      start_ = t;
      stop_ = start_ + duration_dist_(random_);
      if (frequency_ > 0.0) {
        frequency_ = -1.0;
      } else {
        frequency_ = 20.0 + 256.0 * frequency_dist_(random_);
      }
      volume_ = volume_dist_(random_);
      pan_ = pan_dist_(random_);
    }

    if (frequency_ <= 0.0) {
      out[0] = 0.0f;
      out[1] = 0.0f;
      return;
    }

    float sample = 0.0f;
    float harmonic_factor = 1.0f;
    for (int harmonic = 1; harmonic_factor >= HARMONIC_THRESHOLD; ++harmonic) {
      sample +=
          harmonic_factor *
          sin(harmonic * (t - start_) * frequency_ * 2.0 * PI);
      harmonic_factor *= HARMONIC_FACTOR;
    }

    sample *= volume_;

    if (t - start_ < 0.02) {
      sample *= (t - start_) / 0.02;
    }
    if (stop_ - t < 0.02) {
      sample *= (stop_ - t) / 0.02;
    }

    out[0] = sample * pan_;
    out[1] = sample * (1.0f - pan_);
    return;
  }

  void StopGracefully() {
    respawn_ = false;
  }

  bool IsInUse(double t) {
    return respawn_ || t <= stop_;
  }

 private:
  bool respawn_ = true;
  double start_ = -1.0;
  double stop_ = -1.0;
  double frequency_ = -1.0;
  float volume_ = 0.0f;
  float pan_ = 0.5f;

  ::std::mt19937 random_;
  ::std::lognormal_distribution<double> duration_dist_;
  ::std::lognormal_distribution<double> frequency_dist_;
  ::std::uniform_real_distribution<float> volume_dist_;
  ::std::uniform_real_distribution<float> pan_dist_;
};

int main() {
  ::std::mt19937 random(SEED);

  ::std::vector<Note> notes;
  double adjust_notes_at = -1.0;
  ::std::uniform_real_distribution<double> adjust_notes_dist(
      MIN_NOTE_ADJUST_INTERVAL, MAX_NOTE_ADJUST_INTERVAL);
  ::std::poisson_distribution<int> note_count_dist(MEAN_NOTE_COUNT);

  ::std::vector<float> audio;
  for (int64_t n = 0; n >= 0; ++n) {
    double time = (double)n / SAMPLE_RATE;
    if (time > DURATION) {
      break;
    }

    if (time >= adjust_notes_at) {
      int note_count = 0;
      for (Note& note : notes) {
        if (note.IsInUse(time)) {
          ++note_count;
        }
      }

      int note_count_next = note_count_dist(random);
      for (Note& note : notes) {
        if (note_count == note_count_next) {
          break;
        } else if (note_count > note_count_next) {
          if (note.IsInUse(time)) {
            note.StopGracefully();
            --note_count;
          }
        } else {
          if (!note.IsInUse(time)) {
            note = Note(random());
            ++note_count;
          }
        }
      }
      while (note_count < note_count_next) {
        notes.emplace_back(random());
        ++note_count;
      }

      adjust_notes_at = time + adjust_notes_dist(random);
    }

    float sample[2] = {0.0f, 0.0f};

    for (Note& note : notes) {
      float note_sample[2];
      note.GetSample(time, note_sample);
      sample[0] += note_sample[0];
      sample[1] += note_sample[1];
    }

    audio.push_back(sample[0]);
    audio.push_back(sample[1]);
  }

  float peak = 0.0f;
  for (float sample : audio) {
    peak = ::std::max(peak, ::std::abs(sample));
  }

  for (float sample : audio) {
    sample /= peak;
    size_t written = fwrite(&sample, sizeof(sample), 1, stdout);
    assert(written == 1);
  }
}
<commit_msg>End all notes at the end of the track.<commit_after>#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <random>
#include <vector>

#define PI 3.141592653589793

class Note {
 public:
  Note(unsigned seed) :
      random_(seed),
      duration_dist_(0.0, 1.0),
      frequency_dist_(0.0, 1.0),
      volume_dist_(0.0f, 1.0f),
      pan_dist_(0.0f, 1.0f) {}

  void GetSample(double t, float out[2]) {
    if (t > stop_) {
      if (!respawn_) {
        out[0] = 0.0f;
        out[1] = 0.0f;
        return;
      }

      start_ = t;
      stop_ = start_ + duration_dist_(random_);
      if (stop_ > DURATION) {
        stop_ = DURATION;
      }

      if (frequency_ > 0.0) {
        frequency_ = -1.0;
      } else {
        frequency_ = 20.0 + 256.0 * frequency_dist_(random_);
      }

      volume_ = volume_dist_(random_);
      pan_ = pan_dist_(random_);
    }

    if (frequency_ <= 0.0) {
      out[0] = 0.0f;
      out[1] = 0.0f;
      return;
    }

    float sample = 0.0f;
    float harmonic_factor = 1.0f;
    for (int harmonic = 1; harmonic_factor >= HARMONIC_THRESHOLD; ++harmonic) {
      sample +=
          harmonic_factor *
          sin(harmonic * (t - start_) * frequency_ * 2.0 * PI);
      harmonic_factor *= HARMONIC_FACTOR;
    }

    sample *= volume_;

    if (t - start_ < 0.02) {
      sample *= (t - start_) / 0.02;
    }
    if (stop_ - t < 0.02) {
      sample *= (stop_ - t) / 0.02;
    }

    out[0] = sample * pan_;
    out[1] = sample * (1.0f - pan_);
    return;
  }

  void StopGracefully() {
    respawn_ = false;
  }

  bool IsInUse(double t) {
    return respawn_ || t <= stop_;
  }

 private:
  bool respawn_ = true;
  double start_ = -1.0;
  double stop_ = -1.0;
  double frequency_ = -1.0;
  float volume_ = 0.0f;
  float pan_ = 0.5f;

  ::std::mt19937 random_;
  ::std::lognormal_distribution<double> duration_dist_;
  ::std::lognormal_distribution<double> frequency_dist_;
  ::std::uniform_real_distribution<float> volume_dist_;
  ::std::uniform_real_distribution<float> pan_dist_;
};

int main() {
  ::std::mt19937 random(SEED);

  ::std::vector<Note> notes;
  double adjust_notes_at = -1.0;
  ::std::uniform_real_distribution<double> adjust_notes_dist(
      MIN_NOTE_ADJUST_INTERVAL, MAX_NOTE_ADJUST_INTERVAL);
  ::std::poisson_distribution<int> note_count_dist(MEAN_NOTE_COUNT);

  ::std::vector<float> audio;
  for (int64_t n = 0; n >= 0; ++n) {
    double time = (double)n / SAMPLE_RATE;
    if (time > DURATION) {
      break;
    }

    if (time >= adjust_notes_at) {
      int note_count = 0;
      for (Note& note : notes) {
        if (note.IsInUse(time)) {
          ++note_count;
        }
      }

      int note_count_next = note_count_dist(random);
      for (Note& note : notes) {
        if (note_count == note_count_next) {
          break;
        } else if (note_count > note_count_next) {
          if (note.IsInUse(time)) {
            note.StopGracefully();
            --note_count;
          }
        } else {
          if (!note.IsInUse(time)) {
            note = Note(random());
            ++note_count;
          }
        }
      }
      while (note_count < note_count_next) {
        notes.emplace_back(random());
        ++note_count;
      }

      adjust_notes_at = time + adjust_notes_dist(random);
    }

    float sample[2] = {0.0f, 0.0f};

    for (Note& note : notes) {
      float note_sample[2];
      note.GetSample(time, note_sample);
      sample[0] += note_sample[0];
      sample[1] += note_sample[1];
    }

    audio.push_back(sample[0]);
    audio.push_back(sample[1]);
  }

  float peak = 0.0f;
  for (float sample : audio) {
    peak = ::std::max(peak, ::std::abs(sample));
  }

  for (float sample : audio) {
    sample /= peak;
    size_t written = fwrite(&sample, sizeof(sample), 1, stdout);
    assert(written == 1);
  }
}
<|endoftext|>