<commit_before>#include "options.hpp"

#include <riemannpp/riemannpp.hpp>

#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>

namespace bpo = boost::program_options;
namespace rpp = riemannpp;

using namespace client;
using namespace std;

bpo::options_description
send_options()
{
	bpo::options_description options("Send Command Options");
	options.add_options()
		( "state,s",         bpo::value<string>(),  "Set the state of the event." )
		( "service,S",       bpo::value<string>(),  "Set the service sending the event." )
		( "host,h",          bpo::value<string>(),  "Set the origin host of the event." )
		( "description,D",   bpo::value<string>(),  "Set the description of the event." )
		( "attribute,a",     bpo::value<string>(),  "Add a new attribute to the event." )
		( "tag,t",           bpo::value<string>(),  "Add a tag to the event." )
		( "metric-sint64,i", bpo::value<int64_t>(), "Set the 64-bit integer metric of the event." )
		( "metric-d,d",      bpo::value<double>(),  "Set the double metric of the event." )
		( "metric-f,f",      bpo::value<float>(),   "Set the float metric of the event." )
		( "ttl,L",           bpo::value<int>(),     "Set the TTL of the event." )
		( "tcp,T",           bpo::value<bool>()->default_value(true), "Send the message over TCP (default)." )
		( "udp,U",           bpo::value<bool>(),    "Send the message over UDP." )
		;
	return options;
}

bpo::options_description
query_options() {
	bpo::options_description options("Query Command Options");
	options.add_options()
		( "query,q", bpo::value<string>(), "Query to send to Riemann." )
		( "json,j",  "Output the results as a JSON array." )
		;
	return options;
}

bpo::options_description
miscellaneous_options() {
	bpo::options_description options("Miscellaneous Options");
	options.add_options()
		( "version,V", "Display version." )
		( "help,?",    "Show this help page." )
		;
	return options;
}

void
process_command_send(const bpo::variables_map& vm) {
	rpp::client_type type = rpp::client_type::tcp;
	if (vm.count("tcp")) {
		type = (vm["tcp"].as<bool>()) ? rpp::client_type::tcp : rpp::client_type::udp;
	} else if (vm.count("udp")) {
		type = (vm["udp"].as<bool>()) ? rpp::client_type::udp : rpp::client_type::tcp;
	}

	rpp::client client;
	client.connect(type, vm["rhost"].as<string>(), vm["rport"].as<int>());

	rpp::event event;
	if (vm.count("state")) {
		rpp::field f(rpp::event_field::state, vm["state"].as<string>());
		event << f;
	}
	if (vm.count("service")) {
		rpp::field f(rpp::event_field::service, vm["service"].as<string>());
		event << f;
	}
	if (vm.count("host")) {
		rpp::field f(rpp::event_field::host, vm["host"].as<string>());
		event << f;
	}
	if (vm.count("description")) {
		rpp::field f(rpp::event_field::description, vm["description"].as<string>());
		event << f;
	}
//	if (vm.count("attribute")) {
//		rpp::attribute attribute;
//		vm["attribute"].as<string>();
//	}
	if (vm.count("tag")) {
		string s(vm["tag"].as<string>());
		event << s;
	}
	if (vm.count("metric-sint64")) {
		rpp::field f(rpp::event_field::metrics64, vm["metric-sint64"].as<string>());
		event << f;
	}
	if (vm.count("metric-dbl")) {
		rpp::field f(rpp::event_field::metricd, vm["metric-dbl"].as<string>());
		event << f;
	}
	if (vm.count("metric-flt")) {
		rpp::field f(rpp::event_field::metricf, vm["metric-flt"].as<string>());
		event << f;
	}
	if (vm.count("ttl")) {
		rpp::field f(rpp::event_field::ttl, vm["ttl"].as<string>());
		event << f;
	}

	rpp::message message;
	message << event;

	client << message;
}

void
process_command_query(const bpo::variables_map& vm) {
	rpp::client client;
	client.connect(rpp::client_type::tcp, vm["rhost"].as<string>(), vm["rport"].as<int>());

	rpp::query query;
	if (vm.count("query")) {
		query.set_string(vm["query"].as<string>());
	}

	rpp::message message;
	message.set_query(query);

	client.send_message_oneshot(message);

	// ops.result_json = (vm.count("json") > 0);
	// client.recv();
}

options
process_command_line(int argc, char const* argv[]) {
	bpo::positional_options_description arguments;
	arguments.add("command", 1);
	arguments.add("rhost", 1);
	arguments.add("rport", 1);

	bpo::options_description all;
	all.add(miscellaneous_options());
	all.add_options()
		( "command", bpo::value<string>(), "Either query or send" )
		;
	all.add(send_options());
	all.add(query_options());
	all.add_options()
		( "rhost", bpo::value<string>()->default_value("localhost"), "The address of the Riemann server (default: localhost)" )
		( "rport", bpo::value<int>()->default_value(5555),           "The port of the Riemann server (default: 5555)" )
		;

	bpo::variables_map vm;
	options ops;

	try {
		bpo::store(bpo::command_line_parser(argc, argv).options(all).positional(arguments).run(), vm);
	} catch(bpo::too_many_positional_options_error& e) {
		cerr << "Too many arguments provided." << endl;
		ops.show_usage = true;
	} catch(bpo::unknown_option& e) {
		cerr << "Unknown option '" << e.get_option_name() << "'." << endl;
		ops.show_usage = true;
	} catch(bpo::error& e) {
		cerr << "command line parse error: " << e.what() << "'." << endl;
		ops.show_usage = true;
	}

	if ((0 == vm.count("command")) || vm.count("help")) {
		ops.show_usage = true;
	} if (vm.count("command") && (vm["command"].as<string>() == string("query")) && (0 == vm.count("query"))) {
		ops.show_usage = true;
	}

	ops.show_version = (vm.count("version") > 0);
	ops.show_help = (vm.count("help") > 0);

	try {
		if (vm.count("command")) {
			if (vm["command"].as<string>() == "send") {
				process_command_send(vm);
			} else if (vm["command"].as<string>() == "query") {
				process_command_query(vm);
			}
		}
	} catch (rpp::internal_exception &e) {
		cerr << "Error: " << e.error() << " - " << e.reason() << "." << endl;
		ops.show_usage = true;
	}
	return ops;
}

ostream&
show_usage(ostream& stream) {
	stream << "Usage: riemannpp COMMAND [options...] [HOST] [PORT]" << endl;
	stream << endl;
	stream << "The HOST and PORT arguments are optional, and they default to" << endl;
	stream << "\"localhost\" and 5555, respectively." << endl;
	stream << endl;
	stream << "Command can be either `send` or `query`." << endl;
	return stream;
}

ostream&
show_help(ostream& stream) {
	stream << "Available commands: send and query." << endl;
	stream << send_options() << endl;
	stream << endl;
	stream << query_options() << endl;
	stream << endl;
	stream << miscellaneous_options() << endl;
	return stream;
}
<commit_msg>Fixed attribute on client options<commit_after>#include "options.hpp"

#include <riemannpp/riemannpp.hpp>

#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>

namespace bpo = boost::program_options;
namespace rpp = riemannpp;

using namespace client;
using namespace std;

bpo::options_description
send_options()
{
	bpo::options_description options("Send Command Options");
	options.add_options()
		( "state,s",         bpo::value<string>(),  "Set the state of the event." )
		( "service,S",       bpo::value<string>(),  "Set the service sending the event." )
		( "host,h",          bpo::value<string>(),  "Set the origin host of the event." )
		( "description,D",   bpo::value<string>(),  "Set the description of the event." )
		( "attribute,a",     bpo::value<string>(),  "Add a new attribute to the event." )
		( "tag,t",           bpo::value<string>(),  "Add a tag to the event." )
		( "metric-sint64,i", bpo::value<int64_t>(), "Set the 64-bit integer metric of the event." )
		( "metric-d,d",      bpo::value<double>(),  "Set the double metric of the event." )
		( "metric-f,f",      bpo::value<float>(),   "Set the float metric of the event." )
		( "ttl,L",           bpo::value<int>(),     "Set the TTL of the event." )
		( "tcp,T",           bpo::value<bool>()->default_value(true), "Send the message over TCP (default)." )
		( "udp,U",           bpo::value<bool>(),    "Send the message over UDP." )
		;
	return options;
}

bpo::options_description
query_options() {
	bpo::options_description options("Query Command Options");
	options.add_options()
		( "query,q", bpo::value<string>(), "Query to send to Riemann." )
		( "json,j",  "Output the results as a JSON array." )
		;
	return options;
}

bpo::options_description
miscellaneous_options() {
	bpo::options_description options("Miscellaneous Options");
	options.add_options()
		( "version,V", "Display version." )
		( "help,?",    "Show this help page." )
		;
	return options;
}

void
process_command_send(const bpo::variables_map& vm) {
	rpp::client_type type = rpp::client_type::tcp;
	if (vm.count("tcp")) {
		type = (vm["tcp"].as<bool>()) ? rpp::client_type::tcp : rpp::client_type::udp;
	} else if (vm.count("udp")) {
		type = (vm["udp"].as<bool>()) ? rpp::client_type::udp : rpp::client_type::tcp;
	}

	rpp::client client;
	client.connect(type, vm["rhost"].as<string>(), vm["rport"].as<int>());

	rpp::event event;
	if (vm.count("state")) {
		rpp::field f(rpp::event_field::state, vm["state"].as<string>());
		event << f;
	}
	if (vm.count("service")) {
		rpp::field f(rpp::event_field::service, vm["service"].as<string>());
		event << f;
	}
	if (vm.count("host")) {
		rpp::field f(rpp::event_field::host, vm["host"].as<string>());
		event << f;
	}
	if (vm.count("description")) {
		rpp::field f(rpp::event_field::description, vm["description"].as<string>());
		event << f;
	}
	if (vm.count("attribute")) {
		rpp::attribute attribute;
		string tmp = vm["attribute"].as<string>();
		if (size_t it = tmp.find(':') != string::npos) {
			attribute.set(tmp.substr(0, (it+2)), tmp.substr(it+3));
		} else {
			attribute.set_key(tmp);
		}
	}
	if (vm.count("tag")) {
		string s(vm["tag"].as<string>());
		event << s;
	}
	if (vm.count("metric-sint64")) {
		rpp::field f(rpp::event_field::metrics64, vm["metric-sint64"].as<string>());
		event << f;
	}
	if (vm.count("metric-dbl")) {
		rpp::field f(rpp::event_field::metricd, vm["metric-dbl"].as<string>());
		event << f;
	}
	if (vm.count("metric-flt")) {
		rpp::field f(rpp::event_field::metricf, vm["metric-flt"].as<string>());
		event << f;
	}
	if (vm.count("ttl")) {
		rpp::field f(rpp::event_field::ttl, vm["ttl"].as<string>());
		event << f;
	}

	rpp::message message;
	message << event;

	client << message;
}

void
process_command_query(const bpo::variables_map& vm) {
	rpp::client client;
	client.connect(rpp::client_type::tcp, vm["rhost"].as<string>(), vm["rport"].as<int>());

	rpp::query query;
	if (vm.count("query")) {
		query.set_string(vm["query"].as<string>());
	}

	rpp::message message;
	message.set_query(query);

	client.send_message_oneshot(message);

	// ops.result_json = (vm.count("json") > 0);
	// client.recv();
}

options
process_command_line(int argc, char const* argv[]) {
	bpo::positional_options_description arguments;
	arguments.add("command", 1);
	arguments.add("rhost", 1);
	arguments.add("rport", 1);

	bpo::options_description all;
	all.add(miscellaneous_options());
	all.add_options()
		( "command", bpo::value<string>(), "Either query or send" )
		;
	all.add(send_options());
	all.add(query_options());
	all.add_options()
		( "rhost", bpo::value<string>()->default_value("localhost"), "The address of the Riemann server (default: localhost)" )
		( "rport", bpo::value<int>()->default_value(5555),           "The port of the Riemann server (default: 5555)" )
		;

	bpo::variables_map vm;
	options ops;

	try {
		bpo::store(bpo::command_line_parser(argc, argv).options(all).positional(arguments).run(), vm);
	} catch(bpo::too_many_positional_options_error& e) {
		cerr << "Too many arguments provided." << endl;
		ops.show_usage = true;
	} catch(bpo::unknown_option& e) {
		cerr << "Unknown option '" << e.get_option_name() << "'." << endl;
		ops.show_usage = true;
	} catch(bpo::error& e) {
		cerr << "command line parse error: " << e.what() << "'." << endl;
		ops.show_usage = true;
	}

	if ((0 == vm.count("command")) || vm.count("help")) {
		ops.show_usage = true;
	} if (vm.count("command") && (vm["command"].as<string>() == string("query")) && (0 == vm.count("query"))) {
		ops.show_usage = true;
	}

	ops.show_version = (vm.count("version") > 0);
	ops.show_help = (vm.count("help") > 0);

	try {
		if (vm.count("command")) {
			if (vm["command"].as<string>() == "send") {
				process_command_send(vm);
			} else if (vm["command"].as<string>() == "query") {
				process_command_query(vm);
			}
		}
	} catch (rpp::internal_exception &e) {
		cerr << "Error: " << e.error() << " - " << e.reason() << "." << endl;
		ops.show_usage = true;
	}
	return ops;
}

ostream&
show_usage(ostream& stream) {
	stream << "Usage: riemannpp COMMAND [options...] [HOST] [PORT]" << endl;
	stream << endl;
	stream << "The HOST and PORT arguments are optional, and they default to" << endl;
	stream << "\"localhost\" and 5555, respectively." << endl;
	stream << endl;
	stream << "Command can be either `send` or `query`." << endl;
	return stream;
}

ostream&
show_help(ostream& stream) {
	stream << "Available commands: send and query." << endl;
	stream << send_options() << endl;
	stream << endl;
	stream << query_options() << endl;
	stream << endl;
	stream << miscellaneous_options() << endl;
	return stream;
}
<|endoftext|>


<commit_before>//===--- InstructionDeleter.cpp - InstructionDeleter utility --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/SIL/SILFunction.h"
#include "swift/SILOptimizer/Utils/ConstExpr.h"
#include "swift/SILOptimizer/Utils/DebugOptUtils.h"
#include "swift/SILOptimizer/Utils/InstructionDeleter.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"

using namespace swift;

static bool hasOnlyIncidentalUses(SILInstruction *inst,
                                  bool preserveDebugInfo = false) {
  for (SILValue result : inst->getResults()) {
    for (Operand *use : result->getUses()) {
      SILInstruction *user = use->getUser();
      if (!isIncidentalUse(user))
        return false;
      if (preserveDebugInfo && user->isDebugInstruction())
        return false;
    }
  }
  return true;
}

/// A scope-affecting instruction is an instruction which may end the scope of
/// its operand or may produce scoped results that require cleaning up. E.g.
/// begin_borrow, begin_access, copy_value, a call that produces a owned value
/// are scoped instructions. The scope of the results of the first two
/// instructions end with an end_borrow/acess instruction, while those of the
/// latter two end with a consuming operation like destroy_value instruction.
/// These instruction may also end the scope of its operand e.g. a call could
/// consume owned arguments thereby ending its scope. Dead-code eliminating a
/// scope-affecting instruction requires fixing the lifetime of the non-trivial
/// operands of the instruction and requires cleaning up the end-of-scope uses
/// of non-trivial results.
///
/// \param inst instruction that checked for liveness.
///
/// TODO: Handle partial_apply [stack] which has a dealloc_stack user.
static bool isScopeAffectingInstructionDead(SILInstruction *inst,
                                            bool fixLifetime) {
  SILFunction *fun = inst->getFunction();
  assert(fun && "Instruction has no function.");
  // Only support ownership SIL for scoped instructions.
  if (!fun->hasOwnership()) {
    return false;
  }
  // If the instruction has any use other than end of scope use or destroy_value
  // use, bail out.
  if (!hasOnlyEndOfScopeOrEndOfLifetimeUses(inst)) {
    return false;
  }
  // If inst is a copy or beginning of scope, inst is dead, since we know that
  // it is used only in a destroy_value or end-of-scope instruction.
  if (getSingleValueCopyOrCast(inst))
    return true;

  switch (inst->getKind()) {
  case SILInstructionKind::LoadBorrowInst: {
    // A load_borrow only used in an end_borrow is dead.
    return true;
  }
  case SILInstructionKind::LoadInst: {
    LoadOwnershipQualifier loadOwnershipQual =
        cast<LoadInst>(inst)->getOwnershipQualifier();
    // If the load creates a copy, it is dead, since we know that if at all it
    // is used, it is only in a destroy_value instruction.
    return (loadOwnershipQual == LoadOwnershipQualifier::Copy ||
            loadOwnershipQual == LoadOwnershipQualifier::Trivial);
    // TODO: we can handle load [take] but we would have to know that the
    // operand has been consumed. Note that OperandOwnershipKind map does not
    // say this for load.
  }
  case SILInstructionKind::PartialApplyInst: {
    bool onlyTrivialArgs = true;
    for (auto &arg : cast<PartialApplyInst>(inst)->getArgumentOperands()) {
      auto argTy = arg.get()->getType();
      // Non-stack partial apply captures that are passed by address are always
      // captured at +1 by the closure contrext, regardless of the calling
      // convention.
      //
      // TODO: When on-stack partial applies are also handled, then their +0
      // address arguments can be ignored.
      //
      // FIXME: Even with fixLifetimes enabled, InstructionDeleter does not know
      // how to cleanup arguments captured by address. This should be as simple
      // as inserting a destroy_addr. But the analagous code in
      // tryDeleteDeadClosure() and keepArgsOfPartialApplyAlive() mysteriously
      // creates new alloc_stack's and invalidates stack nesting. So we
      // conservatively bail-out until we understand why that hack exists.
      if (argTy.isAddress())
        return false;

      onlyTrivialArgs &= argTy.isTrivial(*fun);
    }
    // Partial applies that are only used in destroys cannot have any effect on
    // the program state, provided the values they capture are explicitly
    // destroyed, which only happens when fixLifetime is true.
    return onlyTrivialArgs || fixLifetime;
  }
  case SILInstructionKind::StructInst:
  case SILInstructionKind::EnumInst:
  case SILInstructionKind::TupleInst:
  case SILInstructionKind::ConvertFunctionInst:
  case SILInstructionKind::DestructureStructInst:
  case SILInstructionKind::DestructureTupleInst: {
    // All these ownership forwarding instructions that are only used in
    // destroys are dead provided the values they consume are destroyed
    // explicitly.
    return true;
  }
  case SILInstructionKind::ApplyInst: {
    // The following property holds for constant-evaluable functions that do
    // not take arguments of generic type:
    // 1. they do not create objects having deinitializers with global
    // side effects, as they can only create objects consisting of trivial
    // values, (non-generic) arrays and strings.
    // 2. they do not use global variables or call arbitrary functions with
    // side effects.
    // The above two properties imply that a value returned by a constant
    // evaluable function does not have a deinitializer with global side
    // effects. Therefore, the deinitializer can be sinked.
    //
    // A generic, read-only constant evaluable call only reads and/or
    // destroys its (non-generic) parameters. It therefore cannot have any
    // side effects (note that parameters being non-generic have value
    // semantics). Therefore, the constant evaluable call can be removed
    // provided the parameter lifetimes are handled correctly, which is taken
    // care of by the function: \c deleteInstruction.
    FullApplySite applySite(cast<ApplyInst>(inst));
    return isReadOnlyConstantEvaluableCall(applySite);
  }
  default: {
    return false;
  }
  }
}

bool InstructionDeleter::trackIfDead(SILInstruction *inst) {
  bool fixLifetime = inst->getFunction()->hasOwnership();
  if (isInstructionTriviallyDead(inst)
      || isScopeAffectingInstructionDead(inst, fixLifetime)) {
    assert(!isIncidentalUse(inst) && !isa<DestroyValueInst>(inst) &&
           "Incidental uses cannot be removed in isolation. "
           "They would be removed iff the operand is dead");
    getCallbacks().notifyWillBeDeleted(inst);
    deadInstructions.insert(inst);
    return true;
  }
  return false;
}

void InstructionDeleter::forceTrackAsDead(SILInstruction *inst) {
  bool preserveDebugInfo = inst->getFunction()->getEffectiveOptimizationMode()
                           <= OptimizationMode::NoOptimization;
  assert(hasOnlyIncidentalUses(inst, preserveDebugInfo));
  getCallbacks().notifyWillBeDeleted(inst);
  deadInstructions.insert(inst);
}

/// Force-delete \p inst and all its uses.
///
/// \p fixLifetimes causes new destroys to be inserted after dropping
/// operands.
///
/// \p forceDeleteUsers allows deleting an instruction with non-incidental,
/// non-destoy uses, such as a store.
///
/// Does not call callbacks.notifyWillBeDeleted for \p inst. But does
/// for any other instructions that become dead as a result.
///
/// Carefully orchestrated steps for deleting an instruction with its uses:
///
/// Recursively gather the instruction's uses into the toDeleteInsts set and
/// dropping the operand for each use traversed.
///
/// For the remaining operands, insert destroys for consuming operands and track
/// newly dead operand definitions.
///
/// Finally, erase the instruction.
void InstructionDeleter::deleteWithUses(SILInstruction *inst, bool fixLifetimes,
                                        bool forceDeleteUsers) {
  // Cannot fix operand lifetimes in non-ownership SIL.
  assert(!fixLifetimes || inst->getFunction()->hasOwnership());

  // Recursively visit all uses while growing toDeleteInsts in def-use order and
  // dropping dead operands.
  SmallVector<SILInstruction *, 4> toDeleteInsts;

  toDeleteInsts.push_back(inst);
  swift::salvageDebugInfo(inst);
  for (unsigned idx = 0; idx < toDeleteInsts.size(); ++idx) {
    for (SILValue result : toDeleteInsts[idx]->getResults()) {
      // Temporary use vector to avoid iterator invalidation.
      auto uses = llvm::to_vector<4>(result->getUses());
      for (Operand *use : uses) {
        SILInstruction *user = use->getUser();
        assert(forceDeleteUsers || isIncidentalUse(user) ||
               isa<DestroyValueInst>(user));
        assert(!isa<BranchInst>(user) && "can't delete phis");

        toDeleteInsts.push_back(user);
        swift::salvageDebugInfo(user);
        use->drop();
      }
    }
  }
  // Process the remaining operands. Insert destroys for consuming
  // operands. Track newly dead operand values.
  for (auto *inst : toDeleteInsts) {
    for (Operand &operand : inst->getAllOperands()) {
      SILValue operandValue = operand.get();
      // Check for dead operands, which are dropped above.
      if (!operandValue)
        continue;

      if (fixLifetimes && operand.isConsuming()) {
        SILBuilderWithScope builder(inst);
        auto *dvi = builder.createDestroyValue(inst->getLoc(), operandValue);
        getCallbacks().createdNewInst(dvi);
      }
      auto *operDef = operandValue->getDefiningInstruction();
      operand.drop();
      if (operDef) {
        trackIfDead(operDef);
      }
    }
    inst->dropNonOperandReferences();
    deadInstructions.remove(inst);
    getCallbacks().deleteInst(inst, false /*notify when deleting*/);
  }
}

void InstructionDeleter::cleanupDeadInstructions() {
  while (!deadInstructions.empty()) {
    SmallVector<SILInstruction *, 8> currentDeadInsts(deadInstructions.begin(),
                                                      deadInstructions.end());
    // Though deadInstructions is cleared here, calls to deleteInstruction may
    // append to deadInstructions. So we need to iterate until this it is empty.
    deadInstructions.clear();
    for (SILInstruction *deadInst : currentDeadInsts) {
      // deadInst will not have been deleted in the previous iterations,
      // because, by definition, deleteInstruction will only delete an earlier
      // instruction and its incidental/destroy uses. The former cannot be
      // deadInst as deadInstructions is a set vector, and the latter cannot be
      // in deadInstructions as they are incidental uses which are never added
      // to deadInstructions.
      deleteWithUses(deadInst,
                     /*fixLifetimes*/ deadInst->getFunction()->hasOwnership());
    }
  }
}

bool InstructionDeleter::deleteIfDead(SILInstruction *inst) {
  bool fixLifetime = inst->getFunction()->hasOwnership();
  if (isInstructionTriviallyDead(inst)
      || isScopeAffectingInstructionDead(inst, fixLifetime)) {
    getCallbacks().notifyWillBeDeleted(inst);
    deleteWithUses(inst, fixLifetime);
    return true;
  }
  return false;
}

void InstructionDeleter::forceDeleteAndFixLifetimes(SILInstruction *inst) {
  SILFunction *fun = inst->getFunction();
  bool preserveDebugInfo =
      fun->getEffectiveOptimizationMode() <= OptimizationMode::NoOptimization;
  assert(hasOnlyIncidentalUses(inst, preserveDebugInfo));
  deleteWithUses(inst, /*fixLifetimes*/ fun->hasOwnership());
}

void InstructionDeleter::forceDelete(SILInstruction *inst) {
  bool preserveDebugInfo = inst->getFunction()->getEffectiveOptimizationMode()
                           <= OptimizationMode::NoOptimization;
  assert(hasOnlyIncidentalUses(inst, preserveDebugInfo));
  deleteWithUses(inst, /*fixLifetimes*/ false);
}

void InstructionDeleter::recursivelyDeleteUsersIfDead(SILInstruction *inst) {
  SmallVector<SILInstruction *, 8> users;
  for (SILValue result : inst->getResults())
    for (Operand *use : result->getUses())
      users.push_back(use->getUser());

  for (SILInstruction *user : users)
    recursivelyDeleteUsersIfDead(user);
  deleteIfDead(inst);
}

void InstructionDeleter::recursivelyForceDeleteUsersAndFixLifetimes(
    SILInstruction *inst) {
  for (SILValue result : inst->getResults()) {
    while (!result->use_empty()) {
      SILInstruction *user = result->use_begin()->getUser();
      recursivelyForceDeleteUsersAndFixLifetimes(user);
    }
  }
  if (isIncidentalUse(inst) || isa<DestroyValueInst>(inst)) {
    forceDelete(inst);
    return;
  }
  forceDeleteAndFixLifetimes(inst);
}

void swift::eliminateDeadInstruction(SILInstruction *inst,
                                     InstModCallbacks callbacks) {
  InstructionDeleter deleter(std::move(callbacks));
  deleter.trackIfDead(inst);
  deleter.cleanupDeadInstructions();
}

void swift::recursivelyDeleteTriviallyDeadInstructions(
    ArrayRef<SILInstruction *> ia, bool force, InstModCallbacks callbacks) {
  // Delete these instruction and others that become dead after it's deleted.
  llvm::SmallPtrSet<SILInstruction *, 8> deadInsts;
  for (auto *inst : ia) {
    // If the instruction is not dead and force is false, do nothing.
    if (force || isInstructionTriviallyDead(inst))
      deadInsts.insert(inst);
  }
  llvm::SmallPtrSet<SILInstruction *, 8> nextInsts;
  while (!deadInsts.empty()) {
    for (auto inst : deadInsts) {
      // Call the callback before we mutate the to be deleted instruction in any
      // way.
      callbacks.notifyWillBeDeleted(inst);

      // Check if any of the operands will become dead as well.
      MutableArrayRef<Operand> operands = inst->getAllOperands();
      for (Operand &operand : operands) {
        SILValue operandVal = operand.get();
        if (!operandVal)
          continue;

        // Remove the reference from the instruction being deleted to this
        // operand.
        operand.drop();

        // If the operand is an instruction that is only used by the instruction
        // being deleted, delete it.
        if (auto *operandValInst = operandVal->getDefiningInstruction())
          if (!deadInsts.count(operandValInst) &&
              isInstructionTriviallyDead(operandValInst))
            nextInsts.insert(operandValInst);
      }

      // If we have a function ref inst, we need to especially drop its function
      // argument so that it gets a proper ref decrement.
      if (auto *fri = dyn_cast<FunctionRefBaseInst>(inst))
        fri->dropReferencedFunction();
    }

    for (auto inst : deadInsts) {
      // This will remove this instruction and all its uses.
      eraseFromParentWithDebugInsts(inst, callbacks);
    }

    nextInsts.swap(deadInsts);
    nextInsts.clear();
  }
}

<commit_msg>InstructionDeleter - ignore already-deleted instructions<commit_after>//===--- InstructionDeleter.cpp - InstructionDeleter utility --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/SIL/SILFunction.h"
#include "swift/SILOptimizer/Utils/ConstExpr.h"
#include "swift/SILOptimizer/Utils/DebugOptUtils.h"
#include "swift/SILOptimizer/Utils/InstructionDeleter.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"

using namespace swift;

static bool hasOnlyIncidentalUses(SILInstruction *inst,
                                  bool preserveDebugInfo = false) {
  for (SILValue result : inst->getResults()) {
    for (Operand *use : result->getUses()) {
      SILInstruction *user = use->getUser();
      if (!isIncidentalUse(user))
        return false;
      if (preserveDebugInfo && user->isDebugInstruction())
        return false;
    }
  }
  return true;
}

/// A scope-affecting instruction is an instruction which may end the scope of
/// its operand or may produce scoped results that require cleaning up. E.g.
/// begin_borrow, begin_access, copy_value, a call that produces a owned value
/// are scoped instructions. The scope of the results of the first two
/// instructions end with an end_borrow/acess instruction, while those of the
/// latter two end with a consuming operation like destroy_value instruction.
/// These instruction may also end the scope of its operand e.g. a call could
/// consume owned arguments thereby ending its scope. Dead-code eliminating a
/// scope-affecting instruction requires fixing the lifetime of the non-trivial
/// operands of the instruction and requires cleaning up the end-of-scope uses
/// of non-trivial results.
///
/// \param inst instruction that checked for liveness.
///
/// TODO: Handle partial_apply [stack] which has a dealloc_stack user.
static bool isScopeAffectingInstructionDead(SILInstruction *inst,
                                            bool fixLifetime) {
  SILFunction *fun = inst->getFunction();
  assert(fun && "Instruction has no function.");
  // Only support ownership SIL for scoped instructions.
  if (!fun->hasOwnership()) {
    return false;
  }
  // If the instruction has any use other than end of scope use or destroy_value
  // use, bail out.
  if (!hasOnlyEndOfScopeOrEndOfLifetimeUses(inst)) {
    return false;
  }
  // If inst is a copy or beginning of scope, inst is dead, since we know that
  // it is used only in a destroy_value or end-of-scope instruction.
  if (getSingleValueCopyOrCast(inst))
    return true;

  switch (inst->getKind()) {
  case SILInstructionKind::LoadBorrowInst: {
    // A load_borrow only used in an end_borrow is dead.
    return true;
  }
  case SILInstructionKind::LoadInst: {
    LoadOwnershipQualifier loadOwnershipQual =
        cast<LoadInst>(inst)->getOwnershipQualifier();
    // If the load creates a copy, it is dead, since we know that if at all it
    // is used, it is only in a destroy_value instruction.
    return (loadOwnershipQual == LoadOwnershipQualifier::Copy ||
            loadOwnershipQual == LoadOwnershipQualifier::Trivial);
    // TODO: we can handle load [take] but we would have to know that the
    // operand has been consumed. Note that OperandOwnershipKind map does not
    // say this for load.
  }
  case SILInstructionKind::PartialApplyInst: {
    bool onlyTrivialArgs = true;
    for (auto &arg : cast<PartialApplyInst>(inst)->getArgumentOperands()) {
      auto argTy = arg.get()->getType();
      // Non-stack partial apply captures that are passed by address are always
      // captured at +1 by the closure contrext, regardless of the calling
      // convention.
      //
      // TODO: When on-stack partial applies are also handled, then their +0
      // address arguments can be ignored.
      //
      // FIXME: Even with fixLifetimes enabled, InstructionDeleter does not know
      // how to cleanup arguments captured by address. This should be as simple
      // as inserting a destroy_addr. But the analagous code in
      // tryDeleteDeadClosure() and keepArgsOfPartialApplyAlive() mysteriously
      // creates new alloc_stack's and invalidates stack nesting. So we
      // conservatively bail-out until we understand why that hack exists.
      if (argTy.isAddress())
        return false;

      onlyTrivialArgs &= argTy.isTrivial(*fun);
    }
    // Partial applies that are only used in destroys cannot have any effect on
    // the program state, provided the values they capture are explicitly
    // destroyed, which only happens when fixLifetime is true.
    return onlyTrivialArgs || fixLifetime;
  }
  case SILInstructionKind::StructInst:
  case SILInstructionKind::EnumInst:
  case SILInstructionKind::TupleInst:
  case SILInstructionKind::ConvertFunctionInst:
  case SILInstructionKind::DestructureStructInst:
  case SILInstructionKind::DestructureTupleInst: {
    // All these ownership forwarding instructions that are only used in
    // destroys are dead provided the values they consume are destroyed
    // explicitly.
    return true;
  }
  case SILInstructionKind::ApplyInst: {
    // The following property holds for constant-evaluable functions that do
    // not take arguments of generic type:
    // 1. they do not create objects having deinitializers with global
    // side effects, as they can only create objects consisting of trivial
    // values, (non-generic) arrays and strings.
    // 2. they do not use global variables or call arbitrary functions with
    // side effects.
    // The above two properties imply that a value returned by a constant
    // evaluable function does not have a deinitializer with global side
    // effects. Therefore, the deinitializer can be sinked.
    //
    // A generic, read-only constant evaluable call only reads and/or
    // destroys its (non-generic) parameters. It therefore cannot have any
    // side effects (note that parameters being non-generic have value
    // semantics). Therefore, the constant evaluable call can be removed
    // provided the parameter lifetimes are handled correctly, which is taken
    // care of by the function: \c deleteInstruction.
    FullApplySite applySite(cast<ApplyInst>(inst));
    return isReadOnlyConstantEvaluableCall(applySite);
  }
  default: {
    return false;
  }
  }
}

bool InstructionDeleter::trackIfDead(SILInstruction *inst) {
  bool fixLifetime = inst->getFunction()->hasOwnership();
  if (isInstructionTriviallyDead(inst)
      || isScopeAffectingInstructionDead(inst, fixLifetime)) {
    assert(!isIncidentalUse(inst) && !isa<DestroyValueInst>(inst) &&
           "Incidental uses cannot be removed in isolation. "
           "They would be removed iff the operand is dead");
    getCallbacks().notifyWillBeDeleted(inst);
    deadInstructions.insert(inst);
    return true;
  }
  return false;
}

void InstructionDeleter::forceTrackAsDead(SILInstruction *inst) {
  bool preserveDebugInfo = inst->getFunction()->getEffectiveOptimizationMode()
                           <= OptimizationMode::NoOptimization;
  assert(hasOnlyIncidentalUses(inst, preserveDebugInfo));
  getCallbacks().notifyWillBeDeleted(inst);
  deadInstructions.insert(inst);
}

/// Force-delete \p inst and all its uses.
///
/// \p fixLifetimes causes new destroys to be inserted after dropping
/// operands.
///
/// \p forceDeleteUsers allows deleting an instruction with non-incidental,
/// non-destoy uses, such as a store.
///
/// Does not call callbacks.notifyWillBeDeleted for \p inst. But does
/// for any other instructions that become dead as a result.
///
/// Carefully orchestrated steps for deleting an instruction with its uses:
///
/// Recursively gather the instruction's uses into the toDeleteInsts set and
/// dropping the operand for each use traversed.
///
/// For the remaining operands, insert destroys for consuming operands and track
/// newly dead operand definitions.
///
/// Finally, erase the instruction.
void InstructionDeleter::deleteWithUses(SILInstruction *inst, bool fixLifetimes,
                                        bool forceDeleteUsers) {
  // Cannot fix operand lifetimes in non-ownership SIL.
  assert(!fixLifetimes || inst->getFunction()->hasOwnership());

  // Recursively visit all uses while growing toDeleteInsts in def-use order and
  // dropping dead operands.
  SmallVector<SILInstruction *, 4> toDeleteInsts;

  toDeleteInsts.push_back(inst);
  swift::salvageDebugInfo(inst);
  for (unsigned idx = 0; idx < toDeleteInsts.size(); ++idx) {
    for (SILValue result : toDeleteInsts[idx]->getResults()) {
      // Temporary use vector to avoid iterator invalidation.
      auto uses = llvm::to_vector<4>(result->getUses());
      for (Operand *use : uses) {
        SILInstruction *user = use->getUser();
        assert(forceDeleteUsers || isIncidentalUse(user) ||
               isa<DestroyValueInst>(user));
        assert(!isa<BranchInst>(user) && "can't delete phis");

        toDeleteInsts.push_back(user);
        swift::salvageDebugInfo(user);
        use->drop();
      }
    }
  }
  // Process the remaining operands. Insert destroys for consuming
  // operands. Track newly dead operand values. Instructions with multiple dead
  // operands may occur in toDeleteInsts multiple times.
  for (auto *inst : toDeleteInsts) {
    if (inst->isDeleted())
      continue;

    for (Operand &operand : inst->getAllOperands()) {
      SILValue operandValue = operand.get();
      // Check for dead operands, which are dropped above.
      if (!operandValue)
        continue;

      if (fixLifetimes && operand.isConsuming()) {
        SILBuilderWithScope builder(inst);
        auto *dvi = builder.createDestroyValue(inst->getLoc(), operandValue);
        getCallbacks().createdNewInst(dvi);
      }
      auto *operDef = operandValue->getDefiningInstruction();
      operand.drop();
      if (operDef) {
        trackIfDead(operDef);
      }
    }
    inst->dropNonOperandReferences();
    deadInstructions.remove(inst);
    getCallbacks().deleteInst(inst, false /*notify when deleting*/);
  }
}

void InstructionDeleter::cleanupDeadInstructions() {
  while (!deadInstructions.empty()) {
    SmallVector<SILInstruction *, 8> currentDeadInsts(deadInstructions.begin(),
                                                      deadInstructions.end());
    // Though deadInstructions is cleared here, calls to deleteInstruction may
    // append to deadInstructions. So we need to iterate until this it is empty.
    deadInstructions.clear();
    for (SILInstruction *deadInst : currentDeadInsts) {
      if (deadInst->isDeleted())
        continue;

      // deadInst will not have been deleted in the previous iterations,
      // because, by definition, deleteInstruction will only delete an earlier
      // instruction and its incidental/destroy uses. The former cannot be
      // deadInst as deadInstructions is a set vector, and the latter cannot be
      // in deadInstructions as they are incidental uses which are never added
      // to deadInstructions.
      deleteWithUses(deadInst,
                     /*fixLifetimes*/ deadInst->getFunction()->hasOwnership());
    }
  }
}

bool InstructionDeleter::deleteIfDead(SILInstruction *inst) {
  bool fixLifetime = inst->getFunction()->hasOwnership();
  if (isInstructionTriviallyDead(inst)
      || isScopeAffectingInstructionDead(inst, fixLifetime)) {
    getCallbacks().notifyWillBeDeleted(inst);
    deleteWithUses(inst, fixLifetime);
    return true;
  }
  return false;
}

void InstructionDeleter::forceDeleteAndFixLifetimes(SILInstruction *inst) {
  SILFunction *fun = inst->getFunction();
  bool preserveDebugInfo =
      fun->getEffectiveOptimizationMode() <= OptimizationMode::NoOptimization;
  assert(hasOnlyIncidentalUses(inst, preserveDebugInfo));
  deleteWithUses(inst, /*fixLifetimes*/ fun->hasOwnership());
}

void InstructionDeleter::forceDelete(SILInstruction *inst) {
  bool preserveDebugInfo = inst->getFunction()->getEffectiveOptimizationMode()
                           <= OptimizationMode::NoOptimization;
  assert(hasOnlyIncidentalUses(inst, preserveDebugInfo));
  deleteWithUses(inst, /*fixLifetimes*/ false);
}

void InstructionDeleter::recursivelyDeleteUsersIfDead(SILInstruction *inst) {
  SmallVector<SILInstruction *, 8> users;
  for (SILValue result : inst->getResults())
    for (Operand *use : result->getUses())
      users.push_back(use->getUser());

  for (SILInstruction *user : users)
    recursivelyDeleteUsersIfDead(user);
  deleteIfDead(inst);
}

void InstructionDeleter::recursivelyForceDeleteUsersAndFixLifetimes(
    SILInstruction *inst) {
  for (SILValue result : inst->getResults()) {
    while (!result->use_empty()) {
      SILInstruction *user = result->use_begin()->getUser();
      recursivelyForceDeleteUsersAndFixLifetimes(user);
    }
  }
  if (isIncidentalUse(inst) || isa<DestroyValueInst>(inst)) {
    forceDelete(inst);
    return;
  }
  forceDeleteAndFixLifetimes(inst);
}

void swift::eliminateDeadInstruction(SILInstruction *inst,
                                     InstModCallbacks callbacks) {
  InstructionDeleter deleter(std::move(callbacks));
  deleter.trackIfDead(inst);
  deleter.cleanupDeadInstructions();
}

void swift::recursivelyDeleteTriviallyDeadInstructions(
    ArrayRef<SILInstruction *> ia, bool force, InstModCallbacks callbacks) {
  // Delete these instruction and others that become dead after it's deleted.
  llvm::SmallPtrSet<SILInstruction *, 8> deadInsts;
  for (auto *inst : ia) {
    // If the instruction is not dead and force is false, do nothing.
    if (force || isInstructionTriviallyDead(inst))
      deadInsts.insert(inst);
  }
  llvm::SmallPtrSet<SILInstruction *, 8> nextInsts;
  while (!deadInsts.empty()) {
    for (auto inst : deadInsts) {
      // Call the callback before we mutate the to be deleted instruction in any
      // way.
      callbacks.notifyWillBeDeleted(inst);

      // Check if any of the operands will become dead as well.
      MutableArrayRef<Operand> operands = inst->getAllOperands();
      for (Operand &operand : operands) {
        SILValue operandVal = operand.get();
        if (!operandVal)
          continue;

        // Remove the reference from the instruction being deleted to this
        // operand.
        operand.drop();

        // If the operand is an instruction that is only used by the instruction
        // being deleted, delete it.
        if (auto *operandValInst = operandVal->getDefiningInstruction())
          if (!deadInsts.count(operandValInst) &&
              isInstructionTriviallyDead(operandValInst))
            nextInsts.insert(operandValInst);
      }

      // If we have a function ref inst, we need to especially drop its function
      // argument so that it gets a proper ref decrement.
      if (auto *fri = dyn_cast<FunctionRefBaseInst>(inst))
        fri->dropReferencedFunction();
    }

    for (auto inst : deadInsts) {
      // This will remove this instruction and all its uses.
      eraseFromParentWithDebugInsts(inst, callbacks);
    }

    nextInsts.swap(deadInsts);
    nextInsts.clear();
  }
}

<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/random.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/VFS.h"
#include "fnord-rpc/ServerGroup.h"
#include "fnord-rpc/RPC.h"
#include "fnord-rpc/RPCClient.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-json/json.h"
#include "fnord-json/jsonrpc.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-feeds/FeedService.h"
#include "fnord-feeds/RemoteFeedFactory.h"
#include "fnord-feeds/RemoteFeedReader.h"
#include "fnord-base/stats/statsdagent.h"
#include "fnord-sstable/SSTableServlet.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"

using namespace fnord;

int main(int argc, const char** argv) {
  fnord::Application::init();
  fnord::Application::logToStderr();

  fnord::cli::FlagParser flags;

  flags.defineFlag(
      "http_port",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "8000",
      "Start the public http server on this port",
      "<port>");

  flags.defineFlag(
      "loglevel",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  /* start event loop */
  fnord::thread::EventLoop ev;

  WhitelistVFS vfs;
  vfs.registerFile("test.sstable", "/tmp/fu2");

  sstable::SSTableServlet sstable_servlet("/sstable", &vfs);

  /* start http server */
  fnord::http::HTTPRouter http_router;
  http_router.addRouteByPrefixMatch("/sstable", &sstable_servlet);
  fnord::http::HTTPServer http_server(&http_router, &ev);
  http_server.listen(flags.getInt("http_port"));

  ev.run();

  return 0;
}

<commit_msg>serve directory from reportserver<commit_after>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/filerepository.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/random.h"
#include "fnord-base/thread/eventloop.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/VFS.h"
#include "fnord-rpc/ServerGroup.h"
#include "fnord-rpc/RPC.h"
#include "fnord-rpc/RPCClient.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-json/json.h"
#include "fnord-json/jsonrpc.h"
#include "fnord-http/httprouter.h"
#include "fnord-http/httpserver.h"
#include "fnord-feeds/FeedService.h"
#include "fnord-feeds/RemoteFeedFactory.h"
#include "fnord-feeds/RemoteFeedReader.h"
#include "fnord-base/stats/statsdagent.h"
#include "fnord-sstable/SSTableServlet.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"

using namespace fnord;

int main(int argc, const char** argv) {
  fnord::Application::init();
  fnord::Application::logToStderr();

  fnord::cli::FlagParser flags;

  flags.defineFlag(
      "http_port",
      fnord::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "8000",
      "Start the public http server on this port",
      "<port>");

  flags.defineFlag(
      "report_path",
      cli::FlagParser::T_STRING,
      true,
      NULL,
      NULL,
      "report path",
      "<path>");

  flags.defineFlag(
      "loglevel",
      fnord::cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  WhitelistVFS vfs;

  /* start http server */
  fnord::thread::EventLoop ev;
  fnord::http::HTTPRouter http_router;
  fnord::http::HTTPServer http_server(&http_router, &ev);
  http_server.listen(flags.getInt("http_port"));

  /* sstable servlet */
  sstable::SSTableServlet sstable_servlet("/sstable", &vfs);
  http_router.addRouteByPrefixMatch("/sstable", &sstable_servlet);

  /* add all files to whitelist vfs */
  auto report_path = flags.getString("report_path");
  FileUtil::ls(report_path, [&vfs, &report_path] (const String& file) -> bool {
    vfs.registerFile(file, FileUtil::joinPaths(report_path, file));
    fnord::logInfo("cm.reportserver", "[VFS] Adding file: $0", file);
    return true;
  });

  ev.run();
  return 0;
}

<|endoftext|>


<commit_before>#include "wsdlmessage.h"

WSDLMessage::WSDLMessage(xmlNodePtr node)
{
	Load(node);
}

WSDLMessage::~WSDLMessage()
{
	for(map<string, WSDLMessagePart *>::iterator i = mParts.begin(); i != mParts.end(); i++) {
		delete i->second;
	}
}

string WSDLMessage::get_Name() const
{
	return mName;
}

vector<string> WSDLMessage::get_PartNames()
{
	vector<string> retval;

	for(map<string, WSDLMessagePart *>::iterator i = mParts.begin(); i != mParts.end(); i++) {
		retval.push_back(i->first);
	}

	return retval;
}

WSDLMessagePart &WSDLMessage::get_Part(string name) const
{
	return *(const_cast<WSDLMessage *>(this)->mParts[name]);
}

void WSDLMessage::Load(xmlNodePtr node)
{
	xmlChar *name = xmlGetProp(node, (const xmlChar *)"name");
	if(name != nullptr) {
		mName = (char *)name;
		xmlFree(name);
		LoadParts(node);
	}
}

void WSDLMessage::LoadParts(xmlNodePtr node)
{
	for(xmlNode *cur_node = node->children; cur_node != nullptr; cur_node = cur_node->next) {
		if(cur_node->type == XML_ELEMENT_NODE && !xmlStrcmp(cur_node->name, (const xmlChar *)"part")) {
			WSDLMessagePart *part = new WSDLMessagePart(cur_node);
			if(part != nullptr) {
				if(part->get_Name().length() > 0) {
					mParts[part->get_Name()] = part;
				}
				else {
					delete part;
				}
			}
		}
	}
}
<commit_msg>Fixed several lint errors<commit_after>#include "lib/wsdl/wsdlmessage.h"

#include <map>
#include <string>
#include <vector>

WSDLMessage::WSDLMessage(xmlNodePtr node) {
    Load(node);
}

WSDLMessage::~WSDLMessage() {
    for (::std::map<::std::string, WSDLMessagePart *>::iterator
         i = mParts.begin(); i != mParts.end(); i++) {
        delete i->second;
    }
}

::std::string WSDLMessage::get_Name() const {
    return mName;
}

::std::vector<::std::string> WSDLMessage::get_PartNames() {
    ::std::vector<::std::string> retval;

    for (::std::map<::std::string, WSDLMessagePart *>::iterator
         i = mParts.begin(); i != mParts.end(); i++) {
        retval.push_back(i->first);
    }

    return retval;
}

WSDLMessagePart &WSDLMessage::get_Part(::std::string name) const {
    return *(const_cast<WSDLMessage *>(this)->mParts[name]);
}

void WSDLMessage::Load(xmlNodePtr node) {
    xmlChar *name = xmlGetProp(node, (const xmlChar *)"name");
    if (name != nullptr) {
        mName = reinterpret_cast<char *>(name);
        xmlFree(name);
        LoadParts(node);
    }
}

void WSDLMessage::LoadParts(xmlNodePtr node) {
    for (xmlNode *cur_node = node->children; cur_node != nullptr;
         cur_node = cur_node->next) {
        if (cur_node->type == XML_ELEMENT_NODE &&
            !xmlStrcmp(cur_node->name, (const xmlChar *)"part")) {
            WSDLMessagePart *part = new WSDLMessagePart(cur_node);
            if (part != nullptr) {
                if (part->get_Name().length() > 0) {
                    mParts[part->get_Name()] = part;
                } else {
                    delete part;
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>MUONdisplay (Int_t nevent=0) {
// Dynamically link some shared libs
   if (gClassTable->GetID("AliRun") < 0) {
      gROOT->LoadMacro("loadlibs.C");
      loadlibs();
      /*
   } else {
      delete gAlice;
      gAlice = 0;
      */
   }

// Connect the Root Galice file containing Geometry, Kine and Hits
   TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject("galice.root");
   if (!file) file = new TFile("galice.root");

// Get AliRun object from file or create it if not on file
   if (!gAlice) {
      gAlice = (AliRun*)file->Get("gAlice");
      if (gAlice) printf("AliRun object found on file\n");
      if (!gAlice) gAlice = new AliRun("gAlice","Alice test program");
   }

// Create Event Display object
   AliMUONDisplay *muondisplay = new AliMUONDisplay(750);

// Display first event
   gAlice->GetEvent(nevent);
   muondisplay->ShowNextEvent(0);
}
<commit_msg>Add input file name as a parameter, default is galice.root<commit_after>MUONdisplay (Int_t nevent=0, TString fileName="galice.root") {
// Dynamically link some shared libs
   if (gClassTable->GetID("AliRun") < 0) {
      gROOT->LoadMacro("loadlibs.C");
      loadlibs();
      /*
   } else {
      delete gAlice;
      gAlice = 0;
      */
   }

// Connect the Root Galice file containing Geometry, Kine and Hits
   TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject(fileName);
   if (!file) file = new TFile(fileName);

// Get AliRun object from file or create it if not on file
   if (!gAlice) {
      gAlice = (AliRun*)file->Get("gAlice");
      if (gAlice) printf("AliRun object found on file\n");
      if (!gAlice) gAlice = new AliRun("gAlice","Alice test program");
   }

// Create Event Display object
   AliMUONDisplay *muondisplay = new AliMUONDisplay(750);

// Display first event
   gAlice->GetEvent(nevent);
   muondisplay->ShowNextEvent(0);
}
<|endoftext|>


<commit_before>// Copyright 2014 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 "media/mojo/services/mojo_renderer_impl.h"

#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/demuxer_stream_provider.h"
#include "media/mojo/services/mojo_demuxer_stream_impl.h"
#include "mojo/public/cpp/application/connect.h"
#include "mojo/public/cpp/bindings/interface_impl.h"
#include "mojo/public/interfaces/application/service_provider.mojom.h"

namespace media {

MojoRendererImpl::MojoRendererImpl(
    const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
    mojo::MediaRendererPtr remote_media_renderer)
    : task_runner_(task_runner),
      remote_media_renderer_(remote_media_renderer.Pass()),
      weak_factory_(this) {
  DVLOG(1) << __FUNCTION__;
  DCHECK(remote_media_renderer_);
  remote_media_renderer_.set_client(this);
}

MojoRendererImpl::~MojoRendererImpl() {
  DVLOG(1) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());
  // Connection to |remote_media_renderer_| will error-out here.
}

// TODO(xhwang): Support |paint_cb| if needed.
void MojoRendererImpl::Initialize(
    DemuxerStreamProvider* demuxer_stream_provider,
    const base::Closure& init_cb,
    const StatisticsCB& statistics_cb,
    const BufferingStateCB& buffering_state_cb,
    const PaintCB& /* paint_cb */,
    const base::Closure& ended_cb,
    const PipelineStatusCB& error_cb) {
  DVLOG(1) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());
  DCHECK(demuxer_stream_provider);

  demuxer_stream_provider_ = demuxer_stream_provider;
  // |init_cb| can be called on other thread.
  init_cb_ = init_cb;
  ended_cb_ = ended_cb;
  error_cb_ = error_cb;
  buffering_state_cb_ = buffering_state_cb;

  // Create audio and video mojo::DemuxerStream and bind its lifetime to the
  // pipe.
  DemuxerStream* const audio =
      demuxer_stream_provider_->GetStream(DemuxerStream::AUDIO);
  DemuxerStream* const video =
      demuxer_stream_provider_->GetStream(DemuxerStream::VIDEO);

  mojo::DemuxerStreamPtr audio_stream;
  if (audio) {
    mojo::BindToProxy(new MojoDemuxerStreamImpl(audio), &audio_stream)
        ->DidConnect();
  }

  mojo::DemuxerStreamPtr video_stream;
  if (video) {
    mojo::BindToProxy(new MojoDemuxerStreamImpl(video), &video_stream)
        ->DidConnect();
  }

  remote_media_renderer_->Initialize(
      audio_stream.Pass(),
      video_stream.Pass(),
      BindToCurrentLoop(base::Bind(&MojoRendererImpl::OnInitialized,
                                   weak_factory_.GetWeakPtr())));
}

void MojoRendererImpl::SetCdm(CdmContext* cdm_context,
                              const CdmAttachedCB& cdm_attached_cb) {
  DVLOG(1) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());
  NOTIMPLEMENTED();
  cdm_attached_cb.Run(false);
}

void MojoRendererImpl::Flush(const base::Closure& flush_cb) {
  DVLOG(2) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());
  remote_media_renderer_->Flush(flush_cb);
}

void MojoRendererImpl::StartPlayingFrom(base::TimeDelta time) {
  DVLOG(2) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());

  {
    base::AutoLock auto_lock(lock_);
    time_ = time;
  }

  remote_media_renderer_->StartPlayingFrom(time.InMicroseconds());
}

void MojoRendererImpl::SetPlaybackRate(float playback_rate) {
  DVLOG(2) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());
  remote_media_renderer_->SetPlaybackRate(playback_rate);
}

void MojoRendererImpl::SetVolume(float volume) {
  DVLOG(2) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());
  remote_media_renderer_->SetVolume(volume);
}

base::TimeDelta MojoRendererImpl::GetMediaTime() {
  base::AutoLock auto_lock(lock_);
  DVLOG(3) << __FUNCTION__ << ": " << time_.InMilliseconds() << " ms";
  return time_;
}

bool MojoRendererImpl::HasAudio() {
  DVLOG(1) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());
  DCHECK(remote_media_renderer_.get());  // We always bind the renderer.
  return !!demuxer_stream_provider_->GetStream(DemuxerStream::AUDIO);
}

bool MojoRendererImpl::HasVideo() {
  DVLOG(1) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());
  return !!demuxer_stream_provider_->GetStream(DemuxerStream::VIDEO);
}

void MojoRendererImpl::OnTimeUpdate(int64_t time_usec, int64_t max_time_usec) {
  DVLOG(3) << __FUNCTION__ << ": " << time_usec << ", " << max_time_usec;

  if (!task_runner_->BelongsToCurrentThread()) {
    task_runner_->PostTask(FROM_HERE,
                           base::Bind(&MojoRendererImpl::OnTimeUpdate,
                                      weak_factory_.GetWeakPtr(),
                                      time_usec,
                                      max_time_usec));
    return;
  }

  base::AutoLock auto_lock(lock_);
  time_ = base::TimeDelta::FromMicroseconds(time_usec);
  max_time_ = base::TimeDelta::FromMicroseconds(max_time_usec);
}

void MojoRendererImpl::OnBufferingStateChange(mojo::BufferingState state) {
  DVLOG(2) << __FUNCTION__;

  if (!task_runner_->BelongsToCurrentThread()) {
    task_runner_->PostTask(FROM_HERE,
                           base::Bind(&MojoRendererImpl::OnBufferingStateChange,
                                      weak_factory_.GetWeakPtr(),
                                      state));
    return;
  }

  buffering_state_cb_.Run(static_cast<media::BufferingState>(state));
}

void MojoRendererImpl::OnEnded() {
  DVLOG(1) << __FUNCTION__;

  if (!task_runner_->BelongsToCurrentThread()) {
    task_runner_->PostTask(
        FROM_HERE,
        base::Bind(&MojoRendererImpl::OnEnded, weak_factory_.GetWeakPtr()));
    return;
  }

  base::ResetAndReturn(&ended_cb_).Run();
}

void MojoRendererImpl::OnError() {
  DVLOG(1) << __FUNCTION__;

  if (!task_runner_->BelongsToCurrentThread()) {
    task_runner_->PostTask(
        FROM_HERE,
        base::Bind(&MojoRendererImpl::OnError, weak_factory_.GetWeakPtr()));
    return;
  }

  // TODO(tim): Should we plumb error code from remote renderer?
  // http://crbug.com/410451.
  if (init_cb_.is_null())  // We have initialized already.
    error_cb_.Run(PIPELINE_ERROR_DECODE);
  else
    error_cb_.Run(PIPELINE_ERROR_COULD_NOT_RENDER);
}

void MojoRendererImpl::OnInitialized() {
  DVLOG(1) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());
  DCHECK(!init_cb_.is_null());

  base::ResetAndReturn(&init_cb_).Run();
}

}  // namespace media
<commit_msg>Don't reset ended_cb_ after ending in the MojoRendererImpl.<commit_after>// Copyright 2014 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 "media/mojo/services/mojo_renderer_impl.h"

#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/demuxer_stream_provider.h"
#include "media/mojo/services/mojo_demuxer_stream_impl.h"
#include "mojo/public/cpp/application/connect.h"
#include "mojo/public/cpp/bindings/interface_impl.h"
#include "mojo/public/interfaces/application/service_provider.mojom.h"

namespace media {

MojoRendererImpl::MojoRendererImpl(
    const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
    mojo::MediaRendererPtr remote_media_renderer)
    : task_runner_(task_runner),
      remote_media_renderer_(remote_media_renderer.Pass()),
      weak_factory_(this) {
  DVLOG(1) << __FUNCTION__;
  DCHECK(remote_media_renderer_);
  remote_media_renderer_.set_client(this);
}

MojoRendererImpl::~MojoRendererImpl() {
  DVLOG(1) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());
  // Connection to |remote_media_renderer_| will error-out here.
}

// TODO(xhwang): Support |paint_cb| if needed.
void MojoRendererImpl::Initialize(
    DemuxerStreamProvider* demuxer_stream_provider,
    const base::Closure& init_cb,
    const StatisticsCB& statistics_cb,
    const BufferingStateCB& buffering_state_cb,
    const PaintCB& /* paint_cb */,
    const base::Closure& ended_cb,
    const PipelineStatusCB& error_cb) {
  DVLOG(1) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());
  DCHECK(demuxer_stream_provider);

  demuxer_stream_provider_ = demuxer_stream_provider;
  // |init_cb| can be called on other thread.
  init_cb_ = init_cb;
  ended_cb_ = ended_cb;
  error_cb_ = error_cb;
  buffering_state_cb_ = buffering_state_cb;

  // Create audio and video mojo::DemuxerStream and bind its lifetime to the
  // pipe.
  DemuxerStream* const audio =
      demuxer_stream_provider_->GetStream(DemuxerStream::AUDIO);
  DemuxerStream* const video =
      demuxer_stream_provider_->GetStream(DemuxerStream::VIDEO);

  mojo::DemuxerStreamPtr audio_stream;
  if (audio) {
    mojo::BindToProxy(new MojoDemuxerStreamImpl(audio), &audio_stream)
        ->DidConnect();
  }

  mojo::DemuxerStreamPtr video_stream;
  if (video) {
    mojo::BindToProxy(new MojoDemuxerStreamImpl(video), &video_stream)
        ->DidConnect();
  }

  remote_media_renderer_->Initialize(
      audio_stream.Pass(),
      video_stream.Pass(),
      BindToCurrentLoop(base::Bind(&MojoRendererImpl::OnInitialized,
                                   weak_factory_.GetWeakPtr())));
}

void MojoRendererImpl::SetCdm(CdmContext* cdm_context,
                              const CdmAttachedCB& cdm_attached_cb) {
  DVLOG(1) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());
  NOTIMPLEMENTED();
  cdm_attached_cb.Run(false);
}

void MojoRendererImpl::Flush(const base::Closure& flush_cb) {
  DVLOG(2) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());
  remote_media_renderer_->Flush(flush_cb);
}

void MojoRendererImpl::StartPlayingFrom(base::TimeDelta time) {
  DVLOG(2) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());

  {
    base::AutoLock auto_lock(lock_);
    time_ = time;
  }

  remote_media_renderer_->StartPlayingFrom(time.InMicroseconds());
}

void MojoRendererImpl::SetPlaybackRate(float playback_rate) {
  DVLOG(2) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());
  remote_media_renderer_->SetPlaybackRate(playback_rate);
}

void MojoRendererImpl::SetVolume(float volume) {
  DVLOG(2) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());
  remote_media_renderer_->SetVolume(volume);
}

base::TimeDelta MojoRendererImpl::GetMediaTime() {
  base::AutoLock auto_lock(lock_);
  DVLOG(3) << __FUNCTION__ << ": " << time_.InMilliseconds() << " ms";
  return time_;
}

bool MojoRendererImpl::HasAudio() {
  DVLOG(1) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());
  DCHECK(remote_media_renderer_.get());  // We always bind the renderer.
  return !!demuxer_stream_provider_->GetStream(DemuxerStream::AUDIO);
}

bool MojoRendererImpl::HasVideo() {
  DVLOG(1) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());
  return !!demuxer_stream_provider_->GetStream(DemuxerStream::VIDEO);
}

void MojoRendererImpl::OnTimeUpdate(int64_t time_usec, int64_t max_time_usec) {
  DVLOG(3) << __FUNCTION__ << ": " << time_usec << ", " << max_time_usec;

  if (!task_runner_->BelongsToCurrentThread()) {
    task_runner_->PostTask(FROM_HERE,
                           base::Bind(&MojoRendererImpl::OnTimeUpdate,
                                      weak_factory_.GetWeakPtr(),
                                      time_usec,
                                      max_time_usec));
    return;
  }

  base::AutoLock auto_lock(lock_);
  time_ = base::TimeDelta::FromMicroseconds(time_usec);
  max_time_ = base::TimeDelta::FromMicroseconds(max_time_usec);
}

void MojoRendererImpl::OnBufferingStateChange(mojo::BufferingState state) {
  DVLOG(2) << __FUNCTION__;

  if (!task_runner_->BelongsToCurrentThread()) {
    task_runner_->PostTask(FROM_HERE,
                           base::Bind(&MojoRendererImpl::OnBufferingStateChange,
                                      weak_factory_.GetWeakPtr(),
                                      state));
    return;
  }

  buffering_state_cb_.Run(static_cast<media::BufferingState>(state));
}

void MojoRendererImpl::OnEnded() {
  DVLOG(1) << __FUNCTION__;

  if (!task_runner_->BelongsToCurrentThread()) {
    task_runner_->PostTask(
        FROM_HERE,
        base::Bind(&MojoRendererImpl::OnEnded, weak_factory_.GetWeakPtr()));
    return;
  }

  ended_cb_.Run();
}

void MojoRendererImpl::OnError() {
  DVLOG(1) << __FUNCTION__;

  if (!task_runner_->BelongsToCurrentThread()) {
    task_runner_->PostTask(
        FROM_HERE,
        base::Bind(&MojoRendererImpl::OnError, weak_factory_.GetWeakPtr()));
    return;
  }

  // TODO(tim): Should we plumb error code from remote renderer?
  // http://crbug.com/410451.
  if (init_cb_.is_null())  // We have initialized already.
    error_cb_.Run(PIPELINE_ERROR_DECODE);
  else
    error_cb_.Run(PIPELINE_ERROR_COULD_NOT_RENDER);
}

void MojoRendererImpl::OnInitialized() {
  DVLOG(1) << __FUNCTION__;
  DCHECK(task_runner_->BelongsToCurrentThread());
  DCHECK(!init_cb_.is_null());

  base::ResetAndReturn(&init_cb_).Run();
}

}  // namespace media
<|endoftext|>


<commit_before>/*
    Copyright (c) 2007 Cyrus Daboo. All rights reserved.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

#include "CTimezonePopup.h"

#include "CPreferences.h"
#include "CTextListChoice.h"

#include "MyCFString.h"

#include "CICalendar.h"
#include "CICalendarManager.h"

// ---------------------------------------------------------------------------
//	CTimezonePopup														  [public]
/**
	Default constructor */

CTimezonePopup::CTimezonePopup(LStream* inStream) :
	LPopupButton(inStream)
{
	mNoFloating = false;
}

// ---------------------------------------------------------------------------
//	~CTimezonePopup														  [public]
/**
	Destructor */

CTimezonePopup::~CTimezonePopup()
{
}

#pragma mark -

void CTimezonePopup::FinishCreateSelf()
{
	// Init the popup menu

	// Always start with the current user default
	SetTimezone(iCal::CICalendarManager::sICalendarManager->GetDefaultTimezone());
}

void CTimezonePopup::Reset(const iCal::CICalendarTimezone& tz)
{
	// Get the set of favorite timezones and always include the default
	cdstrvect tzids;
	cdstrset menutzids(CPreferences::sPrefs->mFavouriteTimezones.GetValue());
	menutzids.insert(iCal::CICalendarManager::sICalendarManager->GetDefaultTimezoneID());
	menutzids.insert(tz.GetTimezoneID());
	for(cdstrset::const_iterator iter = menutzids.begin(); iter != menutzids.end(); iter++)
		tzids.push_back(*iter);

	// Sort list of favorite timezones
	iCal::CICalendar::getSICalendar().SortTimezones(tzids);

	// Clear existing menu
	SInt32 adjusted_separator = eSeparator - (mNoFloating ? 1 : 0);
	SInt32 adjusted_first = eFirstTimezone - (mNoFloating ? 1 : 0);
	MenuRef menu = GetMacMenuH();
	if (::CountMenuItems(menu) > adjusted_separator)
		::DeleteMenuItems(menu, adjusted_first, ::CountMenuItems(menu) - adjusted_separator);

	// Add to menu
	for(cdstrvect::const_iterator iter = tzids.begin(); iter != tzids.end(); iter++)
	{
		// Make a CFString from UTF8 data
		MyCFString menu_title((*iter).c_str(), kCFStringEncodingUTF8);
		::AppendMenuItemTextWithCFString(menu, menu_title, 0, 0, NULL);
	}

	// Readjust max
	SetMaxValue(::CountMenuItems(menu));
}

void CTimezonePopup::NoFloating()
{
	// Remove first menu item
	MenuRef menu = GetMacMenuH();
	::DeleteMenuItems(menu, eNoTimezone, 1);
	mNoFloating = true;

	// Always start with the current user default
	SetTimezone(iCal::CICalendarManager::sICalendarManager->GetDefaultTimezone());
}

void CTimezonePopup::SetTimezone(const iCal::CICalendarTimezone& tz)
{
	Reset(tz);

	// Extract zone from dt and apply to menu
	SInt32 new_value;
	if (tz.GetUTC())
	{
		new_value = eUTC - (mNoFloating ? 1 : 0);
	}
	else
	{
		// Always set no timezone (or UTC when floating) so that if named timezone is not found we have a default
		new_value = eNoTimezone;

		cdstring tzid(tz.GetTimezoneID());
		if (!tzid.empty())
		{
			// Start with no timezone in
			// Scan menu looking for match
			MenuRef menu = GetMacMenuH();
			MyCFString comp(tzid.c_str(), kCFStringEncodingUTF8);
			for(UInt32 i = eFirstTimezone - (mNoFloating ? 1 : 0); i <= ::CountMenuItems(menu); i++)
			{
				// Get name of menu title
				CFStringRef txt;
				::CopyMenuItemTextAsCFString(menu, i, &txt);
				MyCFString temp(txt, false);

				// Compare with tzid
				if (comp.CompareTo(temp, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
				{
					new_value = i;
					break;
				}
			}
		}
	}

	// Set value only if different
	if (new_value != GetValue())
	{
		SetValue(new_value);
		mOldValue = new_value;
	}
}

void CTimezonePopup::GetTimezone(iCal::CICalendarTimezone& tz) const
{
	SInt32 value = GetValue();
	SInt32 adjusted_value = value + (mNoFloating ? 1 : 0);
	tz.SetUTC(adjusted_value == eUTC);
	if ((adjusted_value == eNoTimezone) || (adjusted_value == eUTC))
	{
		cdstring empty;
		tz.SetTimezoneID(empty);
	}
	else if (adjusted_value == eOther)
	{
		cdstrvect tzids;
		iCal::CICalendar::sICalendar.GetTimezones(tzids);
		std::sort(tzids.begin(), tzids.end());

		ulvector selected;
		if (CTextListChoice::PoseDialog(
			"Alerts::Calendar::TimezoneChoice::Title",
			"Alerts::Calendar::TimezoneChoice::Description",
			NULL, false, true, false, true, tzids, cdstring::null_str, selected,
			"Alerts::Calendar::TimezoneChoice::Button"))
		{
			// Get selection from list
			cdstring tzid = tzids.at(selected.front());
			tz.SetTimezoneID(tzid);
			CPreferences::sPrefs->mFavouriteTimezones.Value().insert(tzid);
			const_cast<CTimezonePopup*>(this)->Reset(iCal::CICalendar::getSICalendar().GetTimezone(tzid));
			const_cast<CTimezonePopup*>(this)->SetTimezone(iCal::CICalendar::getSICalendar().GetTimezone(tzid));
		}
		else
		{
			const_cast<CTimezonePopup*>(this)->SetValue(mOldValue);
		}
	}
	else
	{
		// Get name of menu title
		CFStringRef txt;
		::CopyMenuItemTextAsCFString(GetMacMenuH(), value, &txt);
		MyCFString temp(txt, false);

		cdstring tzid = temp.GetString();

		tz.SetTimezoneID(tzid);
		mOldValue = value;
	}
}
<commit_msg>Replaced static CICalendar::sICalendar variable by a static method (part 2, forgotten file).<commit_after>/*
    Copyright (c) 2007 Cyrus Daboo. All rights reserved.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

#include "CTimezonePopup.h"

#include "CPreferences.h"
#include "CTextListChoice.h"

#include "MyCFString.h"

#include "CICalendar.h"
#include "CICalendarManager.h"

// ---------------------------------------------------------------------------
//	CTimezonePopup														  [public]
/**
	Default constructor */

CTimezonePopup::CTimezonePopup(LStream* inStream) :
	LPopupButton(inStream)
{
	mNoFloating = false;
}

// ---------------------------------------------------------------------------
//	~CTimezonePopup														  [public]
/**
	Destructor */

CTimezonePopup::~CTimezonePopup()
{
}

#pragma mark -

void CTimezonePopup::FinishCreateSelf()
{
	// Init the popup menu

	// Always start with the current user default
	SetTimezone(iCal::CICalendarManager::sICalendarManager->GetDefaultTimezone());
}

void CTimezonePopup::Reset(const iCal::CICalendarTimezone& tz)
{
	// Get the set of favorite timezones and always include the default
	cdstrvect tzids;
	cdstrset menutzids(CPreferences::sPrefs->mFavouriteTimezones.GetValue());
	menutzids.insert(iCal::CICalendarManager::sICalendarManager->GetDefaultTimezoneID());
	menutzids.insert(tz.GetTimezoneID());
	for(cdstrset::const_iterator iter = menutzids.begin(); iter != menutzids.end(); iter++)
		tzids.push_back(*iter);

	// Sort list of favorite timezones
	iCal::CICalendar::getSICalendar().SortTimezones(tzids);

	// Clear existing menu
	SInt32 adjusted_separator = eSeparator - (mNoFloating ? 1 : 0);
	SInt32 adjusted_first = eFirstTimezone - (mNoFloating ? 1 : 0);
	MenuRef menu = GetMacMenuH();
	if (::CountMenuItems(menu) > adjusted_separator)
		::DeleteMenuItems(menu, adjusted_first, ::CountMenuItems(menu) - adjusted_separator);

	// Add to menu
	for(cdstrvect::const_iterator iter = tzids.begin(); iter != tzids.end(); iter++)
	{
		// Make a CFString from UTF8 data
		MyCFString menu_title((*iter).c_str(), kCFStringEncodingUTF8);
		::AppendMenuItemTextWithCFString(menu, menu_title, 0, 0, NULL);
	}

	// Readjust max
	SetMaxValue(::CountMenuItems(menu));
}

void CTimezonePopup::NoFloating()
{
	// Remove first menu item
	MenuRef menu = GetMacMenuH();
	::DeleteMenuItems(menu, eNoTimezone, 1);
	mNoFloating = true;

	// Always start with the current user default
	SetTimezone(iCal::CICalendarManager::sICalendarManager->GetDefaultTimezone());
}

void CTimezonePopup::SetTimezone(const iCal::CICalendarTimezone& tz)
{
	Reset(tz);

	// Extract zone from dt and apply to menu
	SInt32 new_value;
	if (tz.GetUTC())
	{
		new_value = eUTC - (mNoFloating ? 1 : 0);
	}
	else
	{
		// Always set no timezone (or UTC when floating) so that if named timezone is not found we have a default
		new_value = eNoTimezone;

		cdstring tzid(tz.GetTimezoneID());
		if (!tzid.empty())
		{
			// Start with no timezone in
			// Scan menu looking for match
			MenuRef menu = GetMacMenuH();
			MyCFString comp(tzid.c_str(), kCFStringEncodingUTF8);
			for(UInt32 i = eFirstTimezone - (mNoFloating ? 1 : 0); i <= ::CountMenuItems(menu); i++)
			{
				// Get name of menu title
				CFStringRef txt;
				::CopyMenuItemTextAsCFString(menu, i, &txt);
				MyCFString temp(txt, false);

				// Compare with tzid
				if (comp.CompareTo(temp, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
				{
					new_value = i;
					break;
				}
			}
		}
	}

	// Set value only if different
	if (new_value != GetValue())
	{
		SetValue(new_value);
		mOldValue = new_value;
	}
}

void CTimezonePopup::GetTimezone(iCal::CICalendarTimezone& tz) const
{
	SInt32 value = GetValue();
	SInt32 adjusted_value = value + (mNoFloating ? 1 : 0);
	tz.SetUTC(adjusted_value == eUTC);
	if ((adjusted_value == eNoTimezone) || (adjusted_value == eUTC))
	{
		cdstring empty;
		tz.SetTimezoneID(empty);
	}
	else if (adjusted_value == eOther)
	{
		cdstrvect tzids;
		iCal::CICalendar::getSICalendar().GetTimezones(tzids);
		std::sort(tzids.begin(), tzids.end());

		ulvector selected;
		if (CTextListChoice::PoseDialog(
			"Alerts::Calendar::TimezoneChoice::Title",
			"Alerts::Calendar::TimezoneChoice::Description",
			NULL, false, true, false, true, tzids, cdstring::null_str, selected,
			"Alerts::Calendar::TimezoneChoice::Button"))
		{
			// Get selection from list
			cdstring tzid = tzids.at(selected.front());
			tz.SetTimezoneID(tzid);
			CPreferences::sPrefs->mFavouriteTimezones.Value().insert(tzid);
			const_cast<CTimezonePopup*>(this)->Reset(iCal::CICalendar::getSICalendar().GetTimezone(tzid));
			const_cast<CTimezonePopup*>(this)->SetTimezone(iCal::CICalendar::getSICalendar().GetTimezone(tzid));
		}
		else
		{
			const_cast<CTimezonePopup*>(this)->SetValue(mOldValue);
		}
	}
	else
	{
		// Get name of menu title
		CFStringRef txt;
		::CopyMenuItemTextAsCFString(GetMacMenuH(), value, &txt);
		MyCFString temp(txt, false);

		cdstring tzid = temp.GetString();

		tz.SetTimezoneID(tzid);
		mOldValue = value;
	}
}
<|endoftext|>


<commit_before>/**
 * Copyright 2014 Open Connectome Project (http://openconnecto.me)
 * Written by Da Zheng (zhengda1936@gmail.com)
 *
 * This file is part of libcommon.
 * This library is used by SAFS and FlashGraph, and potentially by other
 * systems.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <algorithm>
#include <iostream>
#include <sstream>

#include "config_map.h"

static bool read_config_file(const std::string &conf_file,
		std::map<std::string, std::string> &configs)
{
	FILE *f = fopen(conf_file.c_str(), "r");
	if (f == NULL) {
		perror("fopen");
		return false;
	}

	char *line = NULL;
	size_t len = 0;
	ssize_t read;
	while ((read = getline(&line, &len, f)) > 0) {
		std::string str = line;
		if (str.length() == 1)
			continue;
		if (line[0] == '#')
			continue;

		size_t found = str.find("=");
		/* if there isn't `=', I assume it's a file name*/
		if (found == std::string::npos) {
			fprintf(stderr, "wrong format: %s\n", line);
			assert(0);
		}

		std::string value = str.substr(found + 1);
		value.erase(std::remove_if(value.begin(), value.end(), isspace),
				value.end());
		std::string key = str.substr(0, found);
		key.erase(std::remove_if(key.begin(), key.end(), isspace),
				key.end());
		bool res = configs.insert(std::pair<std::string, std::string>(key,
					value)).second;
		if (!res)
			configs[key] = value;
	}
	fclose(f);
	return true;
}

config_map::ptr config_map::create(const std::string &conf_file)
{
	config_map::ptr map = config_map::create();
	// If we can't read the config file, return an empty pointer.
	if (!read_config_file(conf_file, map->configs))
		return config_map::ptr(NULL);
	else
		return map;
}

/**
 * All options should have the following format:
 *		key=value.
 * All options that don't have the format are ignored.
 */
void config_map::add_options(const char *argv[], int argc)
{
	for (int i = 0; i < argc; i++) {
		std::string str = argv[i];

		size_t found = str.find("=");
		if (found == std::string::npos) {
			continue;
		}

		std::string value = str.substr(found + 1);
		value.erase(std::remove_if(value.begin(), value.end(), isspace),
				value.end());
		std::string key = str.substr(0, found);
		key.erase(std::remove_if(key.begin(), key.end(), isspace),
				key.end());
		bool res = configs.insert(std::pair<std::string, std::string>(key,
					value)).second;
		if (!res)
			configs[key] = value;
	}
}

size_t split_string(const std::string &str, const std::string &delimiter,
		std::vector<std::string> &splits)
{
	std::stringstream ss(str);
	size_t num = 0;
	while (ss.good()) {
		std::string s;
		ss >> s;
		splits.push_back(s);
		num++;
	}
	return num;
}

void config_map::add_options(const std::string &opts)
{
	std::vector<std::string> parts;
	split_string(opts, " ", parts);
	std::vector<const char *> part_chars;
	for (size_t i = 0; i < parts.size(); i++) {
		part_chars.push_back(parts[i].c_str());
	}
	config_map::add_options(part_chars.data(), part_chars.size());
}
<commit_msg>[Common]: replace assert(0) with ABORT_MSG.<commit_after>/**
 * Copyright 2014 Open Connectome Project (http://openconnecto.me)
 * Written by Da Zheng (zhengda1936@gmail.com)
 *
 * This file is part of libcommon.
 * This library is used by SAFS and FlashGraph, and potentially by other
 * systems.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <algorithm>
#include <iostream>
#include <sstream>

#include "common.h"
#include "config_map.h"

static bool read_config_file(const std::string &conf_file,
		std::map<std::string, std::string> &configs)
{
	FILE *f = fopen(conf_file.c_str(), "r");
	if (f == NULL) {
		perror("fopen");
		return false;
	}

	char *line = NULL;
	size_t len = 0;
	ssize_t read;
	while ((read = getline(&line, &len, f)) > 0) {
		std::string str = line;
		if (str.length() == 1)
			continue;
		if (line[0] == '#')
			continue;

		size_t found = str.find("=");
		/* if there isn't `=', I assume it's a file name*/
		if (found == std::string::npos) {
			ABORT_MSG(std::string("wrong format: ") + line);
		}

		std::string value = str.substr(found + 1);
		value.erase(std::remove_if(value.begin(), value.end(), isspace),
				value.end());
		std::string key = str.substr(0, found);
		key.erase(std::remove_if(key.begin(), key.end(), isspace),
				key.end());
		bool res = configs.insert(std::pair<std::string, std::string>(key,
					value)).second;
		if (!res)
			configs[key] = value;
	}
	fclose(f);
	return true;
}

config_map::ptr config_map::create(const std::string &conf_file)
{
	config_map::ptr map = config_map::create();
	// If we can't read the config file, return an empty pointer.
	if (!read_config_file(conf_file, map->configs))
		return config_map::ptr(NULL);
	else
		return map;
}

/**
 * All options should have the following format:
 *		key=value.
 * All options that don't have the format are ignored.
 */
void config_map::add_options(const char *argv[], int argc)
{
	for (int i = 0; i < argc; i++) {
		std::string str = argv[i];

		size_t found = str.find("=");
		if (found == std::string::npos) {
			continue;
		}

		std::string value = str.substr(found + 1);
		value.erase(std::remove_if(value.begin(), value.end(), isspace),
				value.end());
		std::string key = str.substr(0, found);
		key.erase(std::remove_if(key.begin(), key.end(), isspace),
				key.end());
		bool res = configs.insert(std::pair<std::string, std::string>(key,
					value)).second;
		if (!res)
			configs[key] = value;
	}
}

size_t split_string(const std::string &str, const std::string &delimiter,
		std::vector<std::string> &splits)
{
	std::stringstream ss(str);
	size_t num = 0;
	while (ss.good()) {
		std::string s;
		ss >> s;
		splits.push_back(s);
		num++;
	}
	return num;
}

void config_map::add_options(const std::string &opts)
{
	std::vector<std::string> parts;
	split_string(opts, " ", parts);
	std::vector<const char *> part_chars;
	for (size_t i = 0; i < parts.size(); i++) {
		part_chars.push_back(parts[i].c_str());
	}
	config_map::add_options(part_chars.data(), part_chars.size());
}
<|endoftext|>