<commit_before>#include "llvm/passes.hpp"

#include <llvm/Attributes.h>
#include <llvm/BasicBlock.h>
#include <llvm/Function.h>
#include <llvm/Instructions.h>
#include <llvm/Transforms/Utils/Cloning.h>
#include <llvm/Support/CallSite.h>
#include <llvm/ADT/APInt.h>
#include <llvm/Constants.h>
#include <llvm/Module.h>

#include <iostream>

namespace {

  using namespace llvm;

  namespace Attribute = llvm::Attribute;
  using llvm::BasicBlock;
  using llvm::CallInst;
  using llvm::Function;
  using llvm::FunctionPass;
  using llvm::InvokeInst;
  using llvm::dyn_cast;
  using llvm::isa;

  class OverflowConstantFolder : public FunctionPass {
    Function* sadd_;

  public:
    static char ID;
    OverflowConstantFolder()
      : FunctionPass(&ID)
      , sadd_(0)
    {}

    bool try_to_fold_addition(CallInst* call) {
      CallSite cs(call);

      Value* lhs = cs.getArgument(0);
      Value* rhs = cs.getArgument(1);

      bool changed = false;

      if(ConstantInt* lc = dyn_cast<ConstantInt>(lhs)) {
        if(ConstantInt* rc = dyn_cast<ConstantInt>(rhs)) {
          APInt zero(31, 0, true);
          const APInt& lval = lc->getValue();
          const APInt& rval = rc->getValue();
          APInt res = lval + rval;

          ConstantInt* overflow = ConstantInt::getFalse();
          if(lval.sgt(zero) && res.slt(rval)) {
            overflow = ConstantInt::getTrue();
          } else if(rval.sgt(zero) && res.slt(lval)) {
            overflow = ConstantInt::getTrue();
          }

          // Now, update the extracts
          for(Value::use_iterator i = call->use_begin();
              i != call->use_end();
              i++) {
            if(ExtractValueInst* extract = dyn_cast<ExtractValueInst>(*i)) {
              Value* result = 0;

              ExtractValueInst::idx_iterator idx = extract->idx_begin();
              if(*idx == 0) {
                result = ConstantInt::get(res);
              } else if(*idx == 1) {
                result = overflow;
              } else {
                std::cout << "unknown index on sadd.overflow extract\n";
              }

              if(result) {
                extract->replaceAllUsesWith(result);
                result->takeName(extract);
                extract->eraseFromParent();
              }
            }
          }

          changed = true;
        }
      }

      return changed;
    }

    virtual bool doInitialization(Module& m) {
      std::vector<const Type*> types;
      types.push_back(IntegerType::get(31));
      types.push_back(IntegerType::get(31));

      std::vector<const Type*> struct_types;
      struct_types.push_back(IntegerType::get(31));
      struct_types.push_back(Type::Int1Ty);

      StructType* st = StructType::get(struct_types);

      FunctionType* ft = FunctionType::get(st, types, false);
      sadd_ = cast<Function>(
          m.getOrInsertFunction("llvm.sadd.with.overflow.i31", ft));

      return true;
    }

    virtual bool runOnFunction(Function& f) {
      bool changed = false;

      std::vector<CallInst*> to_remove;

      for(Function::iterator bb = f.begin(), e = f.end();
          bb != e;
          bb++) {
        for(BasicBlock::iterator inst = bb->begin();
            inst != bb->end();
            inst++) {
          CallInst *call = dyn_cast<CallInst>(inst);
          if(call == NULL) continue;

          // This may miss inlining indirect calls that become
          // direct after inlining something else.
          Function *called_function = call->getCalledFunction();
          if(called_function == sadd_) {
            if(try_to_fold_addition(call)) {
              if(call->use_empty()) {
                to_remove.push_back(call);
                changed = true;
              }
            }
          }
        }
      }

      for(std::vector<CallInst*>::iterator i = to_remove.begin();
          i != to_remove.end();
          i++) {
        (*i)->eraseFromParent();
      }

      return changed;
    }
  };

  // The address of this variable identifies the pass.  See
  // http://llvm.org/docs/WritingAnLLVMPass.html#basiccode.
  char OverflowConstantFolder::ID = 0;

}  // anonymous namespace

namespace rubinius {
  llvm::FunctionPass* create_overflow_folding_pass() {
    return new OverflowConstantFolder();
  }
}
<commit_msg>Guard llvm/passes.cpp<commit_after>#ifdef ENABLE_LLVM

#include "llvm/passes.hpp"

#include <llvm/Attributes.h>
#include <llvm/BasicBlock.h>
#include <llvm/Function.h>
#include <llvm/Instructions.h>
#include <llvm/Transforms/Utils/Cloning.h>
#include <llvm/Support/CallSite.h>
#include <llvm/ADT/APInt.h>
#include <llvm/Constants.h>
#include <llvm/Module.h>

#include <iostream>

namespace {

  using namespace llvm;

  namespace Attribute = llvm::Attribute;
  using llvm::BasicBlock;
  using llvm::CallInst;
  using llvm::Function;
  using llvm::FunctionPass;
  using llvm::InvokeInst;
  using llvm::dyn_cast;
  using llvm::isa;

  class OverflowConstantFolder : public FunctionPass {
    Function* sadd_;

  public:
    static char ID;
    OverflowConstantFolder()
      : FunctionPass(&ID)
      , sadd_(0)
    {}

    bool try_to_fold_addition(CallInst* call) {
      CallSite cs(call);

      Value* lhs = cs.getArgument(0);
      Value* rhs = cs.getArgument(1);

      bool changed = false;

      if(ConstantInt* lc = dyn_cast<ConstantInt>(lhs)) {
        if(ConstantInt* rc = dyn_cast<ConstantInt>(rhs)) {
          APInt zero(31, 0, true);
          const APInt& lval = lc->getValue();
          const APInt& rval = rc->getValue();
          APInt res = lval + rval;

          ConstantInt* overflow = ConstantInt::getFalse();
          if(lval.sgt(zero) && res.slt(rval)) {
            overflow = ConstantInt::getTrue();
          } else if(rval.sgt(zero) && res.slt(lval)) {
            overflow = ConstantInt::getTrue();
          }

          // Now, update the extracts
          for(Value::use_iterator i = call->use_begin();
              i != call->use_end();
              i++) {
            if(ExtractValueInst* extract = dyn_cast<ExtractValueInst>(*i)) {
              Value* result = 0;

              ExtractValueInst::idx_iterator idx = extract->idx_begin();
              if(*idx == 0) {
                result = ConstantInt::get(res);
              } else if(*idx == 1) {
                result = overflow;
              } else {
                std::cout << "unknown index on sadd.overflow extract\n";
              }

              if(result) {
                extract->replaceAllUsesWith(result);
                result->takeName(extract);
                extract->eraseFromParent();
              }
            }
          }

          changed = true;
        }
      }

      return changed;
    }

    virtual bool doInitialization(Module& m) {
      std::vector<const Type*> types;
      types.push_back(IntegerType::get(31));
      types.push_back(IntegerType::get(31));

      std::vector<const Type*> struct_types;
      struct_types.push_back(IntegerType::get(31));
      struct_types.push_back(Type::Int1Ty);

      StructType* st = StructType::get(struct_types);

      FunctionType* ft = FunctionType::get(st, types, false);
      sadd_ = cast<Function>(
          m.getOrInsertFunction("llvm.sadd.with.overflow.i31", ft));

      return true;
    }

    virtual bool runOnFunction(Function& f) {
      bool changed = false;

      std::vector<CallInst*> to_remove;

      for(Function::iterator bb = f.begin(), e = f.end();
          bb != e;
          bb++) {
        for(BasicBlock::iterator inst = bb->begin();
            inst != bb->end();
            inst++) {
          CallInst *call = dyn_cast<CallInst>(inst);
          if(call == NULL) continue;

          // This may miss inlining indirect calls that become
          // direct after inlining something else.
          Function *called_function = call->getCalledFunction();
          if(called_function == sadd_) {
            if(try_to_fold_addition(call)) {
              if(call->use_empty()) {
                to_remove.push_back(call);
                changed = true;
              }
            }
          }
        }
      }

      for(std::vector<CallInst*>::iterator i = to_remove.begin();
          i != to_remove.end();
          i++) {
        (*i)->eraseFromParent();
      }

      return changed;
    }
  };

  // The address of this variable identifies the pass.  See
  // http://llvm.org/docs/WritingAnLLVMPass.html#basiccode.
  char OverflowConstantFolder::ID = 0;

}  // anonymous namespace

namespace rubinius {
  llvm::FunctionPass* create_overflow_folding_pass() {
    return new OverflowConstantFolder();
  }
}

#endif
<|endoftext|>


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

#include <cmake.h>
#include <iostream>
#include <sstream>
#include <Context.h>
#include <Filter.h>
#include <text.h>
#include <util.h>
#include <i18n.h>
#include <main.h>
#include <CmdImport.h>
#include <CmdModify.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
CmdImport::CmdImport ()
{
  _keyword               = "import";
  _usage                 = "task          import [<file> ...]";
  _description           = STRING_CMD_IMPORT_USAGE;
  _read_only             = false;
  _displays_id           = false;
  _needs_gc              = false;
  _uses_context          = false;
  _accepts_filter        = false;
  _accepts_modifications = false;
  _accepts_miscellaneous = true;
  _category              = Command::Category::migration;
}

////////////////////////////////////////////////////////////////////////////////
int CmdImport::execute (std::string& output)
{
  int rc = 0;
  int count = 0;

  Filter filter;
  if (filter.hasFilter ())
    throw std::string (STRING_ERROR_NO_FILTER);

  // Get filenames from command line arguments.
  std::vector <std::string> words = context.cli2.getWords ();
  if (! words.size () || (words.size () == 1 && words[0] == "-"))
  {
    std::cout << format (STRING_CMD_IMPORT_FILE, "STDIN") << "\n";

    std::string json;
    std::string line;
    while (std::getline (std::cin, line))
      json += line + "\n";

    if (nontrivial (json))
      count = import (json);
  }
  else
  {
    // Import tasks from all specified files.
    for (auto& word : words)
    {
      File incoming (word);
      if (! incoming.exists ())
        throw format (STRING_CMD_IMPORT_MISSING, word);

      std::cout << format (STRING_CMD_IMPORT_FILE, word) << "\n";

      // Load the file.
      std::string json;
      incoming.read (json);
      if (nontrivial (json))
        count += import (json);
    }
  }

  context.footnote (format (STRING_CMD_IMPORT_SUMMARY, count));
  return rc;
}

////////////////////////////////////////////////////////////////////////////////
int CmdImport::import (const std::string& input)
{
  int count = 0;
  try
  {
    json::value* root = json::parse (input);
    if (root)
    {
      // Single object parse. Input looks like:
      //   { ... }
      if (root->type () == json::j_object)
      {
        // For each object element...
        json::object* root_obj = (json::object*)root;
        importSingleTask (root_obj);
        ++count;
      }

      // Multiple object array. Input looks like:
      //   [ { ... } , { ... } ]
      else if (root->type () == json::j_array)
      {
        json::array* root_arr = (json::array*)root;

        // For each object element...
        for (auto& element : root_arr->_data)
        {
          // For each object element...
          json::object* root_obj = (json::object*)element;
          importSingleTask (root_obj);
          ++count;
        }
      }

      delete root;
    }
  }

  // If an exception is caught, then it is because the free-form JSON
  // objects/array above failed to parse. This is an indication that the input
  // is an old-style line-by-line set of JSON objects, because both an array of
  // objects, and a single object have failed to parse..
  //
  // Input looks like:
  //   { ... }
  //   { ... }
  catch (std::string& e)
  {
    std::vector <std::string> lines;
    split (lines, input, '\n');

    for (auto& line : lines)
    {
      if (line.length ())
      {
        json::value* root = json::parse (line);
        if (root)
        {
          importSingleTask ((json::object*) root);
          ++count;
          delete root;
        }
      }
    }
  }

  return count;
}

////////////////////////////////////////////////////////////////////////////////
void CmdImport::importSingleTask (json::object* obj)
{
  // Parse the whole thing, validate the data.
  Task task (obj);
  task.validate ();

  // Check whether the imported task is new or a modified existing task.
  Task before;
  if (context.tdb2.get (task.get ("uuid"), before))
  {
    // "modified:" is automatically set to the current time when a task is
    // changed.  If the imported task has a modification timestamp we need
    // to ignore it in task comparison in order to check for meaningful
    // differences.  Setting it to the previous value achieves just that.
    task.set ("modified", before.get ("modified"));
    if (before != task)
    {
      CmdModify modHelper;
      modHelper.checkConsistency (before, task);
      modHelper.modifyAndUpdate (before, task);
      std::cout << " mod  ";
    }
    else
    {
      std::cout << " skip ";
    }
  }
  else
  {
    context.tdb2.add (task);
    std::cout << " add  ";
  }

  std::cout << task.get ("uuid")
            << " "
            << task.get ("description")
            << "\n";
}

////////////////////////////////////////////////////////////////////////////////
<commit_msg>CmdImport: Neglect attributes with dynamic default values<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <iostream>
#include <sstream>
#include <Context.h>
#include <Filter.h>
#include <text.h>
#include <util.h>
#include <i18n.h>
#include <main.h>
#include <CmdImport.h>
#include <CmdModify.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
CmdImport::CmdImport ()
{
  _keyword               = "import";
  _usage                 = "task          import [<file> ...]";
  _description           = STRING_CMD_IMPORT_USAGE;
  _read_only             = false;
  _displays_id           = false;
  _needs_gc              = false;
  _uses_context          = false;
  _accepts_filter        = false;
  _accepts_modifications = false;
  _accepts_miscellaneous = true;
  _category              = Command::Category::migration;
}

////////////////////////////////////////////////////////////////////////////////
int CmdImport::execute (std::string& output)
{
  int rc = 0;
  int count = 0;

  Filter filter;
  if (filter.hasFilter ())
    throw std::string (STRING_ERROR_NO_FILTER);

  // Get filenames from command line arguments.
  std::vector <std::string> words = context.cli2.getWords ();
  if (! words.size () || (words.size () == 1 && words[0] == "-"))
  {
    std::cout << format (STRING_CMD_IMPORT_FILE, "STDIN") << "\n";

    std::string json;
    std::string line;
    while (std::getline (std::cin, line))
      json += line + "\n";

    if (nontrivial (json))
      count = import (json);
  }
  else
  {
    // Import tasks from all specified files.
    for (auto& word : words)
    {
      File incoming (word);
      if (! incoming.exists ())
        throw format (STRING_CMD_IMPORT_MISSING, word);

      std::cout << format (STRING_CMD_IMPORT_FILE, word) << "\n";

      // Load the file.
      std::string json;
      incoming.read (json);
      if (nontrivial (json))
        count += import (json);
    }
  }

  context.footnote (format (STRING_CMD_IMPORT_SUMMARY, count));
  return rc;
}

////////////////////////////////////////////////////////////////////////////////
int CmdImport::import (const std::string& input)
{
  int count = 0;
  try
  {
    json::value* root = json::parse (input);
    if (root)
    {
      // Single object parse. Input looks like:
      //   { ... }
      if (root->type () == json::j_object)
      {
        // For each object element...
        json::object* root_obj = (json::object*)root;
        importSingleTask (root_obj);
        ++count;
      }

      // Multiple object array. Input looks like:
      //   [ { ... } , { ... } ]
      else if (root->type () == json::j_array)
      {
        json::array* root_arr = (json::array*)root;

        // For each object element...
        for (auto& element : root_arr->_data)
        {
          // For each object element...
          json::object* root_obj = (json::object*)element;
          importSingleTask (root_obj);
          ++count;
        }
      }

      delete root;
    }
  }

  // If an exception is caught, then it is because the free-form JSON
  // objects/array above failed to parse. This is an indication that the input
  // is an old-style line-by-line set of JSON objects, because both an array of
  // objects, and a single object have failed to parse..
  //
  // Input looks like:
  //   { ... }
  //   { ... }
  catch (std::string& e)
  {
    std::vector <std::string> lines;
    split (lines, input, '\n');

    for (auto& line : lines)
    {
      if (line.length ())
      {
        json::value* root = json::parse (line);
        if (root)
        {
          importSingleTask ((json::object*) root);
          ++count;
          delete root;
        }
      }
    }
  }

  return count;
}

////////////////////////////////////////////////////////////////////////////////
void CmdImport::importSingleTask (json::object* obj)
{
  // Parse the whole thing, validate the data.
  Task task (obj);

  bool hasGeneratedEntry = not task.has ("entry");
  bool hasExplicitEnd = task.has ("end");

  task.validate ();

  bool hasGeneratedEnd = not hasExplicitEnd and task.has ("end");

  // Check whether the imported task is new or a modified existing task.
  Task before;
  if (context.tdb2.get (task.get ("uuid"), before))
  {
    // We need to neglect updates from attributes with dynamic defaults
    // unless they have been explicitly specified on import.
    //
    // There are three attributes with dynamic defaults, besites uuid:
    //   - modified: Ignored in any case.
    //   - entry: Ignored if generated.
    //   - end: Ignored if generated.

    // The 'modified' attribute is ignored in any case, since if it
    // were the only difference between the tasks, it would have been
    // neglected anyway, since it is bumped on each modification.
    task.set ("modified", before.get ("modified"));

    // Other generated values are replaced by values from existing task,
    // so that they are ignored on comparison.
    if (hasGeneratedEntry)
      task.set ("entry", before.get ("entry"));

    if (hasGeneratedEnd)
      task.set ("end", before.get ("end"));

    if (before != task)
    {
      CmdModify modHelper;
      modHelper.checkConsistency (before, task);
      modHelper.modifyAndUpdate (before, task);
      std::cout << " mod  ";
    }
    else
    {
      std::cout << " skip ";
    }
  }
  else
  {
    context.tdb2.add (task);
    std::cout << " add  ";
  }

  std::cout << task.get ("uuid")
            << " "
            << task.get ("description")
            << "\n";
}

////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#ifdef _MSC_VER
#pragma warning( 4:4786)
#endif

#include "VotingBooth.h"

const short int VotingBooth::RETRACTED_VOTE=-2;

/* private */

/* protected */

/* public: */

VotingBooth::VotingBooth(std::string question)
  : _question(question)
{
  return;
}

VotingBooth::VotingBooth(const VotingBooth& booth)
  : _question(booth._question),
    _choice(booth._choice),
    _vote(booth._vote)
{
  return;
}

VotingBooth::~VotingBooth(void)
{
  return;
}

/* convenience func that sets up and returns a default poll */
VotingBooth *YesNoVotingBooth(std::string question)
{
  VotingBooth *poll = new VotingBooth(question);

  poll->addResponse("no");
  poll->addResponse("yes");

  return poll;
}

bool VotingBooth::addResponse(const std::string response)
{
  if (response.size() == 0) {
    return false;
  }

  _choice.push_back(response);

  return true;
}

bool VotingBooth::hasVoted(const std::string voterName) const
{
  if (voterName.size() <= 0) {
    return false;
  }
  if (_vote.find(voterName) != _vote.end()) {
    return true;
  }
  return false;
}

bool VotingBooth::vote(std::string voterName, std::string response)
{
  if (this->hasVoted(voterName)) {
    /* voters are not allowed to vote multiple times */
    return false;
  }

  /* make sure the response is valid */
  std::vector<std::string>::iterator i = std::find(_choice.begin(), _choice.end(), response);
  if (i == _choice.end()) {
    return false;
  }

  /* record the dang vote */
  _vote[voterName] = i - _choice.begin();

  return true;
}

bool VotingBooth::retractVote(const std::string voterName)
{
  printf ("VotingBooth::retractVote() %s\n", voterName.c_str());
  VoterResponseMap::iterator i = _vote.find(voterName);

  /* if not found, then nothing to retract */
  if (i == _vote.end()) {
    return false;
  }

  _vote[voterName] = RETRACTED_VOTE;

  return false;
}

unsigned long int VotingBooth::getVoteCount(const std::string response) const
{
  unsigned long int total=0;

  for (VoterResponseMap::const_iterator i = _vote.begin();
       i != _vote.end(); ++i) {
    /* negative indices indicate an uncounted vote (perhaps retracted) */
    if ( (i->second >= 0) && (_choice[i->second] == response) ) {
      total++;
    }
  }
  return total;
}

unsigned long int VotingBooth::getTotalVotes(void) const
{
  unsigned long int total=0;

  for (std::vector<std::string>::const_iterator i = _choice.begin();
       i != _choice.end(); ++i) {
    total += this->getVoteCount(*i);
  }
  return total;
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8

<commit_msg>oops, removed printf<commit_after>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#ifdef _MSC_VER
#pragma warning( 4:4786)
#endif

#include "VotingBooth.h"

const short int VotingBooth::RETRACTED_VOTE=-2;

/* private */

/* protected */

/* public: */

VotingBooth::VotingBooth(std::string question)
  : _question(question)
{
  return;
}

VotingBooth::VotingBooth(const VotingBooth& booth)
  : _question(booth._question),
    _choice(booth._choice),
    _vote(booth._vote)
{
  return;
}

VotingBooth::~VotingBooth(void)
{
  return;
}

/* convenience func that sets up and returns a default poll */
VotingBooth *YesNoVotingBooth(std::string question)
{
  VotingBooth *poll = new VotingBooth(question);

  poll->addResponse("no");
  poll->addResponse("yes");

  return poll;
}

bool VotingBooth::addResponse(const std::string response)
{
  if (response.size() == 0) {
    return false;
  }

  _choice.push_back(response);

  return true;
}

bool VotingBooth::hasVoted(const std::string voterName) const
{
  if (voterName.size() <= 0) {
    return false;
  }
  if (_vote.find(voterName) != _vote.end()) {
    return true;
  }
  return false;
}

bool VotingBooth::vote(std::string voterName, std::string response)
{
  if (this->hasVoted(voterName)) {
    /* voters are not allowed to vote multiple times */
    return false;
  }

  /* make sure the response is valid */
  std::vector<std::string>::iterator i = std::find(_choice.begin(), _choice.end(), response);
  if (i == _choice.end()) {
    return false;
  }

  /* record the dang vote */
  _vote[voterName] = i - _choice.begin();

  return true;
}

bool VotingBooth::retractVote(const std::string voterName)
{
  VoterResponseMap::iterator i = _vote.find(voterName);

  /* if not found, then nothing to retract */
  if (i == _vote.end()) {
    return false;
  }

  _vote[voterName] = RETRACTED_VOTE;

  return false;
}

unsigned long int VotingBooth::getVoteCount(const std::string response) const
{
  unsigned long int total=0;

  for (VoterResponseMap::const_iterator i = _vote.begin();
       i != _vote.end(); ++i) {
    /* negative indices indicate an uncounted vote (perhaps retracted) */
    if ( (i->second >= 0) && (_choice[i->second] == response) ) {
      total++;
    }
  }
  return total;
}

unsigned long int VotingBooth::getTotalVotes(void) const
{
  unsigned long int total=0;

  for (std::vector<std::string>::const_iterator i = _choice.begin();
       i != _choice.end(); ++i) {
    total += this->getVoteCount(*i);
  }
  return total;
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8

<|endoftext|>


<commit_before>//===- subzero/src/IceBrowserCompileServer.cpp - Browser compile server ---===//
//
//                        The Subzero Code Generator
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the browser-based compile server.
//
//===----------------------------------------------------------------------===//

// Can only compile this with the NaCl compiler (needs irt.h, and the
// unsandboxed LLVM build using the trusted compiler does not have irt.h).
#if PNACL_BROWSER_TRANSLATOR

#include <cstring>
#include <irt.h>
#include <irt_dev.h>
#include <thread>

#include "llvm/Support/QueueStreamer.h"

#include "IceBrowserCompileServer.h"

namespace Ice {

// Create C wrappers around callback handlers for the IRT interface.
namespace {

BrowserCompileServer *gCompileServer;
struct nacl_irt_private_pnacl_translator_compile gIRTFuncs;

void getIRTInterfaces() {
  size_t QueryResult =
      nacl_interface_query(NACL_IRT_PRIVATE_PNACL_TRANSLATOR_COMPILE_v0_1,
                           &gIRTFuncs, sizeof(gIRTFuncs));
  if (QueryResult != sizeof(gIRTFuncs))
    llvm::report_fatal_error("Failed to get translator compile IRT interface");
}

char *onInitCallback(uint32_t NumThreads, int *ObjFileFDs,
                     size_t ObjFileFDCount, char **argv, size_t argc) {
  if (ObjFileFDCount < 1) {
    std::string Buffer;
    llvm::raw_string_ostream StrBuf(Buffer);
    StrBuf << "Invalid number of FDs for onInitCallback " << ObjFileFDCount
           << "\n";
    return strdup(StrBuf.str().c_str());
  }
  int ObjFileFD = ObjFileFDs[0];
  if (ObjFileFD < 0) {
    std::string Buffer;
    llvm::raw_string_ostream StrBuf(Buffer);
    StrBuf << "Invalid FD given for onInitCallback " << ObjFileFD << "\n";
    return strdup(StrBuf.str().c_str());
  }
  // NOTE: argv is owned by the caller, but we parse here before returning.
  gCompileServer->getParsedFlags(NumThreads, argc, argv);
  gCompileServer->startCompileThread(ObjFileFD);
  return nullptr;
}

int onDataCallback(const void *Data, size_t NumBytes) {
  return gCompileServer->pushInputBytes(Data, NumBytes) ? 1 : 0;
}

char *onEndCallback() {
  gCompileServer->endInputStream();
  gCompileServer->waitForCompileThread();
  // TODO(jvoung): Also return an error string, and UMA data.
  // Set up a report_fatal_error handler to grab that string.
  if (gCompileServer->getErrorCode().value()) {
    return strdup("Some error occurred");
  }
  return nullptr;
}

struct nacl_irt_pnacl_compile_funcs SubzeroCallbacks {
  &onInitCallback, &onDataCallback, &onEndCallback
};

std::unique_ptr<llvm::raw_fd_ostream> getOutputStream(int FD) {
  if (FD <= 0)
    llvm::report_fatal_error("Invalid output FD");
  const bool CloseOnDtor = true;
  const bool Unbuffered = false;
  return std::unique_ptr<llvm::raw_fd_ostream>(
      new llvm::raw_fd_ostream(FD, CloseOnDtor, Unbuffered));
}

} // end of anonymous namespace

BrowserCompileServer::~BrowserCompileServer() {}

void BrowserCompileServer::run() {
  gCompileServer = this;
  // TODO(jvoung): make a useful fatal error handler that can
  // exit all *worker* threads, keep the server thread alive,
  // and be able to handle a server request for the last error string.
  getIRTInterfaces();
  gIRTFuncs.serve_translate_request(&SubzeroCallbacks);
}

void BrowserCompileServer::getParsedFlags(uint32_t NumThreads, int argc,
                                          char **argv) {
  ClFlags::parseFlags(argc, argv);
  ClFlags::getParsedClFlags(Flags);
  ClFlags::getParsedClFlagsExtra(ExtraFlags);
  // Set some defaults which aren't specified via the argv string.
  Flags.setNumTranslationThreads(NumThreads);
  Flags.setUseSandboxing(true);
  Flags.setOutFileType(FT_Elf);
  // TODO(jvoung): allow setting different target arches.
  Flags.setTargetArch(Target_X8632);
  ExtraFlags.setBuildOnRead(true);
  ExtraFlags.setInputFileFormat(llvm::PNaClFormat);
}

bool BrowserCompileServer::pushInputBytes(const void *Data, size_t NumBytes) {
  return InputStream->PutBytes(
             const_cast<unsigned char *>(
                 reinterpret_cast<const unsigned char *>(Data)),
             NumBytes) != NumBytes;
}

void BrowserCompileServer::endInputStream() { InputStream->SetDone(); }

void BrowserCompileServer::startCompileThread(int ObjFD) {
  InputStream = new llvm::QueueStreamer();
  LogStream = getOutputStream(STDOUT_FILENO);
  LogStream->SetUnbuffered();
  EmitStream = getOutputStream(ObjFD);
  EmitStream->SetBufferSize(1 << 14);
  ELFStream.reset(new ELFStreamer(*EmitStream.get()));
  Ctx.reset(new GlobalContext(LogStream.get(), EmitStream.get(),
                              ELFStream.get(), Flags));
  CompileThread = std::thread([this]() {
    Ctx->initParserThread();
    this->getCompiler().run(ExtraFlags, *Ctx.get(),
                            // Retain original reference, but the compiler
                            // (LLVM's MemoryObject) wants to handle deletion.
                            std::unique_ptr<llvm::DataStreamer>(InputStream));
  });
}

} // end of namespace Ice

#endif // PNACL_BROWSER_TRANSLATOR
<commit_msg>Add argv[0] before parsing commandline flags.<commit_after>//===- subzero/src/IceBrowserCompileServer.cpp - Browser compile server ---===//
//
//                        The Subzero Code Generator
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the browser-based compile server.
//
//===----------------------------------------------------------------------===//

// Can only compile this with the NaCl compiler (needs irt.h, and the
// unsandboxed LLVM build using the trusted compiler does not have irt.h).
#if PNACL_BROWSER_TRANSLATOR

#include <cstring>
#include <irt.h>
#include <irt_dev.h>
#include <thread>

#include "llvm/Support/QueueStreamer.h"

#include "IceBrowserCompileServer.h"

namespace Ice {

// Create C wrappers around callback handlers for the IRT interface.
namespace {

BrowserCompileServer *gCompileServer;
struct nacl_irt_private_pnacl_translator_compile gIRTFuncs;

void getIRTInterfaces() {
  size_t QueryResult =
      nacl_interface_query(NACL_IRT_PRIVATE_PNACL_TRANSLATOR_COMPILE_v0_1,
                           &gIRTFuncs, sizeof(gIRTFuncs));
  if (QueryResult != sizeof(gIRTFuncs))
    llvm::report_fatal_error("Failed to get translator compile IRT interface");
}

char *onInitCallback(uint32_t NumThreads, int *ObjFileFDs,
                     size_t ObjFileFDCount, char **CLArgs, size_t CLArgsLen) {
  if (ObjFileFDCount < 1) {
    std::string Buffer;
    llvm::raw_string_ostream StrBuf(Buffer);
    StrBuf << "Invalid number of FDs for onInitCallback " << ObjFileFDCount
           << "\n";
    return strdup(StrBuf.str().c_str());
  }
  int ObjFileFD = ObjFileFDs[0];
  if (ObjFileFD < 0) {
    std::string Buffer;
    llvm::raw_string_ostream StrBuf(Buffer);
    StrBuf << "Invalid FD given for onInitCallback " << ObjFileFD << "\n";
    return strdup(StrBuf.str().c_str());
  }
  // CLArgs is almost an "argv", but is missing the argv[0] program name.
  std::vector<char *> Argv;
  char ProgramName[] = "pnacl-sz.nexe";
  Argv.reserve(CLArgsLen + 1);
  Argv.push_back(ProgramName);
  for (size_t i = 0; i < CLArgsLen; ++i) {
    Argv.push_back(CLArgs[i]);
  }
  // NOTE: strings pointed to by argv are owned by the caller, but we parse
  // here before returning and don't store them.
  gCompileServer->getParsedFlags(NumThreads, Argv.size(), Argv.data());
  gCompileServer->startCompileThread(ObjFileFD);
  return nullptr;
}

int onDataCallback(const void *Data, size_t NumBytes) {
  return gCompileServer->pushInputBytes(Data, NumBytes) ? 1 : 0;
}

char *onEndCallback() {
  gCompileServer->endInputStream();
  gCompileServer->waitForCompileThread();
  // TODO(jvoung): Also return an error string, and UMA data.
  // Set up a report_fatal_error handler to grab that string.
  if (gCompileServer->getErrorCode().value()) {
    return strdup("Some error occurred");
  }
  return nullptr;
}

struct nacl_irt_pnacl_compile_funcs SubzeroCallbacks {
  &onInitCallback, &onDataCallback, &onEndCallback
};

std::unique_ptr<llvm::raw_fd_ostream> getOutputStream(int FD) {
  if (FD <= 0)
    llvm::report_fatal_error("Invalid output FD");
  const bool CloseOnDtor = true;
  const bool Unbuffered = false;
  return std::unique_ptr<llvm::raw_fd_ostream>(
      new llvm::raw_fd_ostream(FD, CloseOnDtor, Unbuffered));
}

} // end of anonymous namespace

BrowserCompileServer::~BrowserCompileServer() {}

void BrowserCompileServer::run() {
  gCompileServer = this;
  // TODO(jvoung): make a useful fatal error handler that can
  // exit all *worker* threads, keep the server thread alive,
  // and be able to handle a server request for the last error string.
  getIRTInterfaces();
  gIRTFuncs.serve_translate_request(&SubzeroCallbacks);
}

void BrowserCompileServer::getParsedFlags(uint32_t NumThreads, int argc,
                                          char **argv) {
  ClFlags::parseFlags(argc, argv);
  ClFlags::getParsedClFlags(Flags);
  ClFlags::getParsedClFlagsExtra(ExtraFlags);
  // Set some defaults which aren't specified via the argv string.
  Flags.setNumTranslationThreads(NumThreads);
  Flags.setUseSandboxing(true);
  Flags.setOutFileType(FT_Elf);
  // TODO(jvoung): allow setting different target arches.
  Flags.setTargetArch(Target_X8632);
  ExtraFlags.setBuildOnRead(true);
  ExtraFlags.setInputFileFormat(llvm::PNaClFormat);
}

bool BrowserCompileServer::pushInputBytes(const void *Data, size_t NumBytes) {
  return InputStream->PutBytes(
             const_cast<unsigned char *>(
                 reinterpret_cast<const unsigned char *>(Data)),
             NumBytes) != NumBytes;
}

void BrowserCompileServer::endInputStream() { InputStream->SetDone(); }

void BrowserCompileServer::startCompileThread(int ObjFD) {
  InputStream = new llvm::QueueStreamer();
  LogStream = getOutputStream(STDOUT_FILENO);
  LogStream->SetUnbuffered();
  EmitStream = getOutputStream(ObjFD);
  EmitStream->SetBufferSize(1 << 14);
  ELFStream.reset(new ELFStreamer(*EmitStream.get()));
  Ctx.reset(new GlobalContext(LogStream.get(), EmitStream.get(),
                              ELFStream.get(), Flags));
  CompileThread = std::thread([this]() {
    Ctx->initParserThread();
    this->getCompiler().run(ExtraFlags, *Ctx.get(),
                            // Retain original reference, but the compiler
                            // (LLVM's MemoryObject) wants to handle deletion.
                            std::unique_ptr<llvm::DataStreamer>(InputStream));
  });
}

} // end of namespace Ice

#endif // PNACL_BROWSER_TRANSLATOR
<|endoftext|>


<commit_before>/*
    This file is part of KOrganizer.
    Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>

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

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

// $Id$

#include <time.h>
#include <unistd.h>

#include <qdir.h>
#include <qstring.h>
#include <qfont.h>
#include <qcolor.h>
#include <qstringlist.h>

#include <kglobal.h>
#include <kconfig.h>
#include <klocale.h>
#include <kdebug.h>
#include <kemailsettings.h>
#include <kstaticdeleter.h>

#include "koprefs.h"

KOPrefs *KOPrefs::mInstance = 0;
static KStaticDeleter<KOPrefs> insd;

KOPrefs::KOPrefs() :
  KPrefs("korganizerrc")
{
  mCategoryColors.setAutoDelete(true);

  mDefaultCategoryColor           = QColor(196,196,196);
  QColor defaultHolidayColor      = QColor("red");
  QColor defaultHighlightColor    = QColor("blue");
  QColor defaultAgendaBgColor     = QColor(128,128,128);
  QColor defaultWorkingHoursColor = QColor(160,160,160);

  mDefaultTimeBarFont = QFont("helvetica",12,QFont::Bold);
  mDefaultViewFont = QFont("helvetica",12);

  KPrefs::setCurrentGroup("General");

  addItemBool("Enable Group Scheduling",&mEnableGroupScheduling,false);
  addItemBool("Enable Project View",&mEnableProjectView,false);
  addItemBool("Auto Save",&mAutoSave,false);
  addItemInt("Auto Save Interval",&mAutoSaveInterval,10);
  addItemBool("Confirm Deletes",&mConfirm,true);
  addItemString("Archive File",&mArchiveFile);
  addItemString("Html Export File",&mHtmlExportFile,
      QDir::homeDirPath() + "/" + i18n("Default export file", "calendar.html"));

  KPrefs::setCurrentGroup("Personal Settings");

  addItemInt("Mail Client",&mMailClient,MailClientKMail);
  addItemBool("Use Control Center Email",&mEmailControlCenter,false);
  addItemBool("Bcc",&mBcc,false);

  KPrefs::setCurrentGroup("Time & Date");

  addItemString("Time Zone",&mTimeZone,"+0000");
  addItemString("TimeZoneId",&mTimeZoneId);
  addItemInt("Default Start Time",&mStartTime,10);
  addItemInt("Default Duration",&mDefaultDuration,2);
  addItemInt("Default Alarm Time",&mAlarmTime,0);
  addItemInt("Daylight Savings",&mDaylightSavings,0);

  KPrefs::setCurrentGroup("Calendar");

  addItemInt("Default Calendar Format",&mDefaultFormat,FormatICalendar);

  KPrefs::setCurrentGroup("Fonts");

  addItemFont("TimeBar Font",&mTimeBarFont);
  addItemFont("MonthView Font",&mMonthViewFont);
  addItemFont("AgendaView Font",&mAgendaViewFont);
  addItemFont("MarcusBains Font",&mAgendaViewFont);

  KPrefs::setCurrentGroup("Colors");

  addItemColor("Holiday Color",&mHolidayColor,defaultHolidayColor);
  addItemColor("Highlight Color",&mHighlightColor,defaultHighlightColor);
  addItemColor("Event Color",&mEventColor,mDefaultCategoryColor);
  addItemColor("Agenda Background Color",&mAgendaBgColor,defaultAgendaBgColor);
  addItemColor("WorkingHours Color",&mWorkingHoursColor,defaultWorkingHoursColor);

  KPrefs::setCurrentGroup("Views");

  addItemInt("Hour Size",&mHourSize,10);
  addItemBool("Show Daily Recurrences",&mDailyRecur,true);
  addItemBool("Show Weekly Recurrences",&mWeeklyRecur,true);
  addItemBool("Enable ToolTips",&mEnableToolTips,false);
  addItemBool("Enable MonthView ScrollBars",&mEnableMonthScroll,false);
  addItemBool("Marcus Bains shows seconds",&mMarcusBainsShowSeconds,false);
  addItemBool("Show Marcus Bains",&mMarcusBainsEnabled,true);

  addItemInt("Day Begins",&mDayBegins,7);
  addItemInt("Working Hours Start",&mWorkingHoursStart,8);
  addItemInt("Working Hours End",&mWorkingHoursEnd,17);
  addItemBool("Exclude Holidays",&mExcludeHolidays,true);
  addItemBool("Exclude Saturdays",&mExcludeSaturdays,true);

  addItemBool("Full View Month",&mFullViewMonth,false);
  addItemBool("Full View Todo",&mFullViewTodo,true);

  KPrefs::setCurrentGroup("Printer");

  KPrefs::setCurrentGroup("Layout");

  addItemBool("CompactDialogs",&mCompactDialogs,false);
  addItemBool("VerticalScreen",&mVerticalScreen,false);

  addItemString("Preview",&mPrintPreview,"kghostview");

  KPrefs::setCurrentGroup("KOrganizer Plugins");

  addItemStringList("SelectedPlugins",&mSelectedPlugins,"holidays");

  KPrefs::setCurrentGroup("Group Scheduling");

  addItemInt("IMIPScheduler",&mIMIPScheduler,IMIPKMail);
  addItemInt("IMIPSend",&mIMIPSend,IMIPOutbox);
  addItemStringList("AdditionalMails",&mAdditionalMails,"");
}

KOPrefs::~KOPrefs()
{
  kdDebug() << "KOPrefs::~KOPrefs()" << endl;
  if (mInstance == this)
      mInstance = insd.setObject(0);
}

KOPrefs *KOPrefs::instance()
{
  if (!mInstance) {
      mInstance = insd.setObject(new KOPrefs());
      mInstance->readConfig();
  }

  return mInstance;
}

void KOPrefs::usrSetDefaults()
{
  // Default should be set a bit smarter, respecting username and locale
  // settings for example.

  KEMailSettings settings;
  mName = settings.getSetting(KEMailSettings::RealName);
  mEmail = settings.getSetting(KEMailSettings::RealName);
  fillMailDefaults();

  mHoliday = KGlobal::locale()->country();

  mTimeZone = "+0000";

  mTimeBarFont = mDefaultTimeBarFont;
  mMonthViewFont = mDefaultViewFont;
  mAgendaViewFont = mDefaultViewFont;
  mMarcusBainsFont = mDefaultViewFont;

  setCategoryDefaults();

  setTimeZoneIdDefault();
}

void KOPrefs::fillMailDefaults()
{
  if (mName.isEmpty()) mName = i18n("Anonymous");
  if (mEmail.isEmpty()) mEmail = i18n("nobody@nowhere");
}

void KOPrefs::setTimeZoneIdDefault()
{
  QString zone;

  char zonefilebuf[100];
  int len = readlink("/etc/localtime",zonefilebuf,100);
  if (len > 0 && len < 100) {
    zonefilebuf[len] = '\0';
    zone = zonefilebuf;
    zone = zone.mid(zone.find("zoneinfo/") + 9);
  } else {
    tzset();
    zone = tzname[0];
  }

  kdDebug () << "----- time zone: " << zone << endl;

  mTimeZoneId = zone;
}

void KOPrefs::setCategoryDefaults()
{
  mCustomCategories.clear();

  mCustomCategories << i18n("Appointment") << i18n("Business")
      << i18n("Meeting") << i18n("Phone Call") << i18n("Education")
      << i18n("Holiday") << i18n("Vacation") << i18n("Special Occasion")
      << i18n("Personal") << i18n("Travel") << i18n("Miscellaneous")
      << i18n("Birthday");

  QStringList::Iterator it;
  for (it = mCustomCategories.begin();it != mCustomCategories.end();++it ) {
    setCategoryColor(*it,mDefaultCategoryColor);
  }
}

void KOPrefs::usrReadConfig()
{
  config()->setGroup("General");
  mCustomCategories = config()->readListEntry("Custom Categories");
  if (mCustomCategories.isEmpty()) setCategoryDefaults();

  config()->setGroup("Personal Settings");
  mName = config()->readEntry("user_name","");
  mEmail = config()->readEntry("user_email","");
  fillMailDefaults();
  mHoliday = config()->readEntry("Holidays", KGlobal::locale()->country());

  config()->setGroup("Category Colors");
  QStringList::Iterator it;
  for (it = mCustomCategories.begin();it != mCustomCategories.end();++it ) {
    setCategoryColor(*it,config()->readColorEntry(*it,&mDefaultCategoryColor));
  }

  if (mTimeZoneId.isEmpty()) {
    setTimeZoneIdDefault();
  }
}

void KOPrefs::usrWriteConfig()
{
  config()->setGroup("General");
  config()->writeEntry("Custom Categories",mCustomCategories);

  config()->setGroup("Personal Settings");
  config()->writeEntry("user_name",mName);
  config()->writeEntry("user_email",mEmail);
  config()->writeEntry("Holidays",mHoliday);

  config()->setGroup("Category Colors");
  QDictIterator<QColor> it(mCategoryColors);
  while (it.current()) {
    config()->writeEntry(it.currentKey(),*(it.current()));
    ++it;
  }
}

void KOPrefs::setCategoryColor(QString cat,const QColor & color)
{
  mCategoryColors.replace(cat,new QColor(color));
}

QColor *KOPrefs::categoryColor(QString cat)
{
  QColor *color = 0;

  if (!cat.isEmpty()) color = mCategoryColors[cat];

  if (color) return color;
  else return &mDefaultCategoryColor;
}

void KOPrefs::setFullName(const QString &name)
{
  mName = name;
}

void KOPrefs::setEmail(const QString &email)
{
  mEmail = email;
}

QString KOPrefs::fullName()
{
  if (mEmailControlCenter) {
    KEMailSettings settings;
    return settings.getSetting(KEMailSettings::RealName);
  } else {
    return mName;
  }
}

QString KOPrefs::email()
{
  if (mEmailControlCenter) {
    KEMailSettings settings;
    return settings.getSetting(KEMailSettings::EmailAddress);
  } else {
    return mEmail;
  }
}
<commit_msg>Fix saving of preferences.<commit_after>/*
    This file is part of KOrganizer.
    Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>

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

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

// $Id$

#include <time.h>
#include <unistd.h>

#include <qdir.h>
#include <qstring.h>
#include <qfont.h>
#include <qcolor.h>
#include <qstringlist.h>

#include <kglobal.h>
#include <kconfig.h>
#include <klocale.h>
#include <kdebug.h>
#include <kemailsettings.h>
#include <kstaticdeleter.h>

#include "koprefs.h"

KOPrefs *KOPrefs::mInstance = 0;
static KStaticDeleter<KOPrefs> insd;

KOPrefs::KOPrefs() :
  KPrefs("")
{
  mCategoryColors.setAutoDelete(true);

  mDefaultCategoryColor           = QColor(196,196,196);
  QColor defaultHolidayColor      = QColor("red");
  QColor defaultHighlightColor    = QColor("blue");
  QColor defaultAgendaBgColor     = QColor(128,128,128);
  QColor defaultWorkingHoursColor = QColor(160,160,160);

  mDefaultTimeBarFont = QFont("helvetica",12,QFont::Bold);
  mDefaultViewFont = QFont("helvetica",12);

  KPrefs::setCurrentGroup("General");

  addItemBool("Enable Group Scheduling",&mEnableGroupScheduling,false);
  addItemBool("Enable Project View",&mEnableProjectView,false);
  addItemBool("Auto Save",&mAutoSave,false);
  addItemInt("Auto Save Interval",&mAutoSaveInterval,10);
  addItemBool("Confirm Deletes",&mConfirm,true);
  addItemString("Archive File",&mArchiveFile);
  addItemString("Html Export File",&mHtmlExportFile,
      QDir::homeDirPath() + "/" + i18n("Default export file", "calendar.html"));

  KPrefs::setCurrentGroup("Personal Settings");

  addItemInt("Mail Client",&mMailClient,MailClientKMail);
  addItemBool("Use Control Center Email",&mEmailControlCenter,false);
  addItemBool("Bcc",&mBcc,false);

  KPrefs::setCurrentGroup("Time & Date");

  addItemString("Time Zone",&mTimeZone,"+0000");
  addItemString("TimeZoneId",&mTimeZoneId);
  addItemInt("Default Start Time",&mStartTime,10);
  addItemInt("Default Duration",&mDefaultDuration,2);
  addItemInt("Default Alarm Time",&mAlarmTime,0);
  addItemInt("Daylight Savings",&mDaylightSavings,0);

  KPrefs::setCurrentGroup("Calendar");

  addItemInt("Default Calendar Format",&mDefaultFormat,FormatICalendar);

  KPrefs::setCurrentGroup("Fonts");

  addItemFont("TimeBar Font",&mTimeBarFont);
  addItemFont("MonthView Font",&mMonthViewFont);
  addItemFont("AgendaView Font",&mAgendaViewFont);
  addItemFont("MarcusBains Font",&mAgendaViewFont);

  KPrefs::setCurrentGroup("Colors");

  addItemColor("Holiday Color",&mHolidayColor,defaultHolidayColor);
  addItemColor("Highlight Color",&mHighlightColor,defaultHighlightColor);
  addItemColor("Event Color",&mEventColor,mDefaultCategoryColor);
  addItemColor("Agenda Background Color",&mAgendaBgColor,defaultAgendaBgColor);
  addItemColor("WorkingHours Color",&mWorkingHoursColor,defaultWorkingHoursColor);

  KPrefs::setCurrentGroup("Views");

  addItemInt("Hour Size",&mHourSize,10);
  addItemBool("Show Daily Recurrences",&mDailyRecur,true);
  addItemBool("Show Weekly Recurrences",&mWeeklyRecur,true);
  addItemBool("Enable ToolTips",&mEnableToolTips,false);
  addItemBool("Enable MonthView ScrollBars",&mEnableMonthScroll,false);
  addItemBool("Marcus Bains shows seconds",&mMarcusBainsShowSeconds,false);
  addItemBool("Show Marcus Bains",&mMarcusBainsEnabled,true);

  addItemInt("Day Begins",&mDayBegins,7);
  addItemInt("Working Hours Start",&mWorkingHoursStart,8);
  addItemInt("Working Hours End",&mWorkingHoursEnd,17);
  addItemBool("Exclude Holidays",&mExcludeHolidays,true);
  addItemBool("Exclude Saturdays",&mExcludeSaturdays,true);

  addItemBool("Full View Month",&mFullViewMonth,false);
  addItemBool("Full View Todo",&mFullViewTodo,true);

  KPrefs::setCurrentGroup("Printer");

  KPrefs::setCurrentGroup("Layout");

  addItemBool("CompactDialogs",&mCompactDialogs,false);
  addItemBool("VerticalScreen",&mVerticalScreen,false);

  addItemString("Preview",&mPrintPreview,"kghostview");

  KPrefs::setCurrentGroup("KOrganizer Plugins");

  addItemStringList("SelectedPlugins",&mSelectedPlugins,"holidays");

  KPrefs::setCurrentGroup("Group Scheduling");

  addItemInt("IMIPScheduler",&mIMIPScheduler,IMIPKMail);
  addItemInt("IMIPSend",&mIMIPSend,IMIPOutbox);
  addItemStringList("AdditionalMails",&mAdditionalMails,"");
}

KOPrefs::~KOPrefs()
{
  kdDebug() << "KOPrefs::~KOPrefs()" << endl;
  if (mInstance == this)
      mInstance = insd.setObject(0);
}

KOPrefs *KOPrefs::instance()
{
  if (!mInstance) {
      mInstance = insd.setObject(new KOPrefs());
      mInstance->readConfig();
  }

  return mInstance;
}

void KOPrefs::usrSetDefaults()
{
  // Default should be set a bit smarter, respecting username and locale
  // settings for example.

  KEMailSettings settings;
  mName = settings.getSetting(KEMailSettings::RealName);
  mEmail = settings.getSetting(KEMailSettings::RealName);
  fillMailDefaults();

  mHoliday = KGlobal::locale()->country();

  mTimeZone = "+0000";

  mTimeBarFont = mDefaultTimeBarFont;
  mMonthViewFont = mDefaultViewFont;
  mAgendaViewFont = mDefaultViewFont;
  mMarcusBainsFont = mDefaultViewFont;

  setCategoryDefaults();

  setTimeZoneIdDefault();
}

void KOPrefs::fillMailDefaults()
{
  if (mName.isEmpty()) mName = i18n("Anonymous");
  if (mEmail.isEmpty()) mEmail = i18n("nobody@nowhere");
}

void KOPrefs::setTimeZoneIdDefault()
{
  QString zone;

  char zonefilebuf[100];
  int len = readlink("/etc/localtime",zonefilebuf,100);
  if (len > 0 && len < 100) {
    zonefilebuf[len] = '\0';
    zone = zonefilebuf;
    zone = zone.mid(zone.find("zoneinfo/") + 9);
  } else {
    tzset();
    zone = tzname[0];
  }

  kdDebug () << "----- time zone: " << zone << endl;

  mTimeZoneId = zone;
}

void KOPrefs::setCategoryDefaults()
{
  mCustomCategories.clear();

  mCustomCategories << i18n("Appointment") << i18n("Business")
      << i18n("Meeting") << i18n("Phone Call") << i18n("Education")
      << i18n("Holiday") << i18n("Vacation") << i18n("Special Occasion")
      << i18n("Personal") << i18n("Travel") << i18n("Miscellaneous")
      << i18n("Birthday");

  QStringList::Iterator it;
  for (it = mCustomCategories.begin();it != mCustomCategories.end();++it ) {
    setCategoryColor(*it,mDefaultCategoryColor);
  }
}

void KOPrefs::usrReadConfig()
{
  config()->setGroup("General");
  mCustomCategories = config()->readListEntry("Custom Categories");
  if (mCustomCategories.isEmpty()) setCategoryDefaults();

  config()->setGroup("Personal Settings");
  mName = config()->readEntry("user_name","");
  mEmail = config()->readEntry("user_email","");
  fillMailDefaults();
  mHoliday = config()->readEntry("Holidays", KGlobal::locale()->country());

  config()->setGroup("Category Colors");
  QStringList::Iterator it;
  for (it = mCustomCategories.begin();it != mCustomCategories.end();++it ) {
    setCategoryColor(*it,config()->readColorEntry(*it,&mDefaultCategoryColor));
  }

  if (mTimeZoneId.isEmpty()) {
    setTimeZoneIdDefault();
  }
}

void KOPrefs::usrWriteConfig()
{
  config()->setGroup("General");
  config()->writeEntry("Custom Categories",mCustomCategories);

  config()->setGroup("Personal Settings");
  config()->writeEntry("user_name",mName);
  config()->writeEntry("user_email",mEmail);
  config()->writeEntry("Holidays",mHoliday);

  config()->setGroup("Category Colors");
  QDictIterator<QColor> it(mCategoryColors);
  while (it.current()) {
    config()->writeEntry(it.currentKey(),*(it.current()));
    ++it;
  }
}

void KOPrefs::setCategoryColor(QString cat,const QColor & color)
{
  mCategoryColors.replace(cat,new QColor(color));
}

QColor *KOPrefs::categoryColor(QString cat)
{
  QColor *color = 0;

  if (!cat.isEmpty()) color = mCategoryColors[cat];

  if (color) return color;
  else return &mDefaultCategoryColor;
}

void KOPrefs::setFullName(const QString &name)
{
  mName = name;
}

void KOPrefs::setEmail(const QString &email)
{
  mEmail = email;
}

QString KOPrefs::fullName()
{
  if (mEmailControlCenter) {
    KEMailSettings settings;
    return settings.getSetting(KEMailSettings::RealName);
  } else {
    return mName;
  }
}

QString KOPrefs::email()
{
  if (mEmailControlCenter) {
    KEMailSettings settings;
    return settings.getSetting(KEMailSettings::EmailAddress);
  } else {
    return mEmail;
  }
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/hwpf/hwp/occ/occ_procedures/p8_pm_occ_firinit.C $     */
/*                                                                        */
/* IBM CONFIDENTIAL                                                       */
/*                                                                        */
/* COPYRIGHT International Business Machines Corp. 2013                   */
/*                                                                        */
/* p1                                                                     */
/*                                                                        */
/* Object Code Only (OCO) source materials                                */
/* Licensed Internal Code Source Materials                                */
/* IBM HostBoot Licensed Internal Code                                    */
/*                                                                        */
/* The source code for this program is not published or otherwise         */
/* divested of its trade secrets, irrespective of what has been           */
/* deposited with the U.S. Copyright Office.                              */
/*                                                                        */
/* Origin: 30                                                             */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
// $Id: p8_pm_occ_firinit.C,v 1.12 2013/04/12 01:17:23 stillgs Exp $
// $Source: /afs/awd/projects/eclipz/KnowledgeBase/.cvsroot/eclipz/chips/p8/working/procedures/ipl/fapi/p8_pm_occ_firinit.C,v $
//------------------------------------------------------------------------------
// *! (C) Copyright International Business Machines Corp. 2011
// *! All Rights Reserved -- Property of IBM
// *! *** IBM Confidential ***
//------------------------------------------------------------------------------
// *! OWNER NAME: Jim Yacynych         Email: jimyac@us.ibm.com
// *!
/// \file p8_pm_occ_firinit.C
/// \brief Configures the OCC LFIR Mask and Action

/// \todo
///
/// Procedure Prereq:
///   o System clocks are running
/// \endverbatim
//------------------------------------------------------------------------------

// ----------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------
#include <fapi.H>
#include "p8_scom_addresses.H"
#include "p8_pm_occ_firinit.H"

extern "C" {

using namespace fapi;

// ----------------------------------------------------------------------
// Constant definitions
// ----------------------------------------------------------------------

// ----------------------------------------------------------------------
// Macro definitions
// ----------------------------------------------------------------------

// ----------------------------------------------------------------------
// Global variables
// ----------------------------------------------------------------------

// ----------------------------------------------------------------------
// Function prototypes
// ----------------------------------------------------------------------

// ----------------------------------------------------------------------
// Function definitions
// ----------------------------------------------------------------------

/// \param[in]  i_target            => Chip Target

/// \retval FAPI_RC_SUCCESS
/// \retval ERROR
fapi::ReturnCode
p8_pm_occ_firinit(const fapi::Target& i_target , uint32_t mode)
{
    fapi::ReturnCode     rc;
    ecmdDataBufferBase   fir(64);
    ecmdDataBufferBase   action_0(64);
    ecmdDataBufferBase   action_1(64);
    ecmdDataBufferBase   mask(64);
    uint32_t             e_rc = 0;

    FAPI_DBG("Executing p8_pm_occ_firinit  ....");

    do
    {
       if (mode == PM_RESET)
       {

            e_rc  = mask.flushTo0();
            e_rc |= mask.setBit(0,OCC_FIR_REGISTER_LENGTH);
            if (e_rc)
            {
                rc.setEcmdError(e_rc);
                break;
            }

            // ------------
            // OCC_FIR_MASK
            // ------------
            rc = fapiPutScom(i_target, OCC_LFIR_MASK_0x01010803, mask );
            if (!rc.ok())
            {
	            FAPI_ERR("fapiPutScom(OCC_LFIR_MASK_0x01010803) failed.");
	            break;
            }
        }
        else
        {

            // Clear the FIR
            e_rc |= fir.flushTo0();

            // make action default be RECOV_ATTN - "01"
            e_rc |= action_0.flushTo0();
            e_rc |= action_1.flushTo1();

            // make mask default be unmasked - "0"
            e_rc |= mask.flushTo0()    ;
            if (e_rc)
            {
                rc.setEcmdError(e_rc);
                break;
            }

            // ------------------------------------------------------------------------
            // set the action and mask for the OCC LFIR bits using the following macros
            // ------------------------------------------------------------------------
            //   Action0/1 Setting Macros - 4 possible settings
            //     SET_CHECK_STOP(b) - sets action0/1 to "00" for LFIR bit b
            //     SET_RECOV_ATTN(b) - sets action0/1 to "01" for LFIR bit b
            //     SET_RECOV_INTR(b) - sets action0/1 to "10" for LFIR bit b
            //     SET_MALF_ALERT(b) - sets action0/1 to "11" for LFIR bit b
            //
            //  Mask Setting Macro
            //   SET_FIR_MASKED(b) - sets mask to '1' for LFIR bit b
            // ------------------------------------------------------------------------

            SET_MALF_ALERT(0);          //  0 = occ_fw0
            SET_MALF_ALERT(1);          //  1 = occ_fw1
            SET_MALF_ALERT(2);          //  2 = occ_fw2
            SET_MALF_ALERT(3);          //  3 = occ_fw3
            SET_MALF_ALERT(4);          //  4 = pmc_pore_sw_malf
            SET_MALF_ALERT(5);          //  5 = pmc_occ_hb_malf

            SET_FIR_MASKED(6);          //  6 = pore_gpe0_fatal_err
            SET_FIR_MASKED(7);          //  7 = pore_gpe1_fatal_err
            SET_FIR_MASKED(8);          //  8 = ocb_error

            SET_RECOV_ATTN(9);          //  9 = srt_ue
            SET_RECOV_ATTN(10);         //  10 = srt_ce
            SET_RECOV_ATTN(11);         //  11 = srt_read_error
            SET_RECOV_ATTN(12);         //  12 = srt_write_error
            SET_RECOV_ATTN(13);         //  13 = srt_dataout_perr
            SET_RECOV_ATTN(14);         //  14 = srt_oci_write_data_parity
            SET_RECOV_ATTN(15);         //  15 = srt_oci_be_parity_err
            SET_RECOV_ATTN(16);         //  16 = srt_oci_addr_parity_err

            SET_FIR_MASKED(17);         //  17 = pore_sw_error_err
            SET_FIR_MASKED(18);         //  18 = pore_gpe0_error_err
            SET_FIR_MASKED(19);         //  19 = pore_gpe1_error_err
            SET_FIR_MASKED(20);         //  20 = external_trap
            SET_FIR_MASKED(21);         //  21 = ppc405_core_reset
            SET_FIR_MASKED(22);         //  22 = ppc405_chip_reset
            SET_FIR_MASKED(23);         //  23 = ppc405_system_reset
            SET_FIR_MASKED(24);         //  24 = ppc405_dbgmsrwe
            SET_FIR_MASKED(25);         //  25 = ppc405_dbgstopack

            SET_RECOV_ATTN(26);         //  26 = ocb_db_oci_timeout
            SET_RECOV_ATTN(27);         //  27 = ocb_db_oci_read_data_parity
            SET_RECOV_ATTN(28);         //  28 = ocb_db_oci_slave_error
            SET_RECOV_ATTN(29);         //  29 = ocb_pib_addr_parity_err
            SET_RECOV_ATTN(30);         //  30 = ocb_db_pib_data_parity_err
            SET_RECOV_ATTN(31);         //  31 = ocb_idc0_error
            SET_RECOV_ATTN(32);         //  32 = ocb_idc1_error
            SET_RECOV_ATTN(33);         //  33 = ocb_idc2_error
            SET_RECOV_ATTN(34);         //  34 = ocb_idc3_error
            SET_RECOV_ATTN(35);         //  35 = srt_fsm_err
            SET_RECOV_ATTN(36);         //  36 = jtagacc_err

            SET_FIR_MASKED(37);         //  37 = spare_err_37

            SET_RECOV_ATTN(38);         //  38 = c405_ecc_ue
            SET_RECOV_ATTN(39);         //  39 = c405_ecc_ce

            SET_FIR_MASKED(40);         //  40 = c405_oci_machinecheck

            SET_RECOV_ATTN(41);         //  41 = sram_spare_direct_error0
            SET_RECOV_ATTN(42);         //  42 = sram_spare_direct_error1
            SET_RECOV_ATTN(43);         //  43 = sram_spare_direct_error2
            SET_RECOV_ATTN(44);         //  44 = sram_spare_direct_error3
            SET_RECOV_ATTN(45);         //  45 = slw_ocislv_err
            SET_RECOV_ATTN(46);         //  46 = gpe_ocislv_err
            SET_RECOV_ATTN(47);         //  47 = ocb_ocislv_err
            SET_RECOV_ATTN(48);         //  48 = c405icu_m_timeout
            SET_RECOV_ATTN(49);         //  49 = c405dcu_m_timeout

            SET_FIR_MASKED(50);         //  50 = spare_fir
            SET_FIR_MASKED(51);         //  51 = spare_fir
            SET_FIR_MASKED(52);         //  52 = spare_fir
            SET_FIR_MASKED(53);         //  53 = spare_fir
            SET_FIR_MASKED(54);         //  54 = spare_fir
            SET_FIR_MASKED(55);         //  55 = spare_fir
            SET_FIR_MASKED(56);         //  56 = spare_fir
            SET_FIR_MASKED(57);         //  57 = spare_fir
            SET_FIR_MASKED(58);         //  58 = spare_fir
            SET_FIR_MASKED(59);         //  59 = spare_fir
            SET_FIR_MASKED(60);         //  60 = spare_fir
            SET_FIR_MASKED(61);         //  61 = spare_fir

            SET_RECOV_ATTN(62);         //  62 = fir_parity_err_dup
            SET_RECOV_ATTN(63);         //  63 = fir_parity_err

            if (e_rc)
            {
                rc.setEcmdError(e_rc);
                break;
            }

            // ---------------
            // OCC_FIR - cleared
            // ---------------
            rc = fapiPutScom(i_target, OCC_LFIR_0x01010800, fir);
            if (!rc.ok())
            {
                FAPI_ERR("fapiPutScom(OCC_LFIR_0x01010800) failed.");
                 break;
            }

            FAPI_DBG(" action_0  => 0x%16llx ",  action_0.getDoubleWord(0));
            FAPI_DBG(" action_1  => 0x%16llx ",  action_1.getDoubleWord(0));
            FAPI_DBG(" mask      => 0x%16llx ",  mask.getDoubleWord(0));

            // ---------------
            // OCC_FIR_ACTION0
            // ---------------
            rc = fapiPutScom(i_target, OCC_LFIR_ACT0_0x01010806, action_0 );
            if (!rc.ok())
            {
                FAPI_ERR("fapiPutScom(OCC_LFIR_ACT0_0x01010806) failed.");
                break;
            }

            // ----------------
            // OCC_FIR_ACTION1
            // ----------------
            rc = fapiPutScom(i_target, OCC_LFIR_ACT1_0x01010807, action_1 );
            if (!rc.ok())
            {
                FAPI_ERR("fapiPutScom(OCC_LFIR_ACT1_0x01010807) failed.");
                    break;
            }

            // ------------
            // OCC_FIR_MASK
            // ------------
            rc = fapiPutScom(i_target, OCC_LFIR_MASK_0x01010803, mask );
            if (!rc.ok())
            {
                FAPI_ERR("fapiPutScom(OCC_LFIR_MASK_0x01010803) failed.");
                break;
            }
        }
    } while(0);
    return rc ;
} // end p8_pm_occ_firinit

} //end extern C
<commit_msg>OCC FIR updates (SW218900)<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/hwpf/hwp/occ/occ_procedures/p8_pm_occ_firinit.C $     */
/*                                                                        */
/* IBM CONFIDENTIAL                                                       */
/*                                                                        */
/* COPYRIGHT International Business Machines Corp. 2013                   */
/*                                                                        */
/* p1                                                                     */
/*                                                                        */
/* Object Code Only (OCO) source materials                                */
/* Licensed Internal Code Source Materials                                */
/* IBM HostBoot Licensed Internal Code                                    */
/*                                                                        */
/* The source code for this program is not published or otherwise         */
/* divested of its trade secrets, irrespective of what has been           */
/* deposited with the U.S. Copyright Office.                              */
/*                                                                        */
/* Origin: 30                                                             */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
// $Id: p8_pm_occ_firinit.C,v 1.13 2013/08/06 18:07:35 jimyac Exp $
// $Source: /afs/awd/projects/eclipz/KnowledgeBase/.cvsroot/eclipz/chips/p8/working/procedures/ipl/fapi/p8_pm_occ_firinit.C,v $
//------------------------------------------------------------------------------
// *! (C) Copyright International Business Machines Corp. 2011
// *! All Rights Reserved -- Property of IBM
// *! *** IBM Confidential ***
//------------------------------------------------------------------------------
// *! OWNER NAME: Jim Yacynych         Email: jimyac@us.ibm.com
// *!
/// \file p8_pm_occ_firinit.C
/// \brief Configures the OCC LFIR Mask and Action

/// \todo
///
/// Procedure Prereq:
///   o System clocks are running
/// \endverbatim
//------------------------------------------------------------------------------

// ----------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------
#include <fapi.H>
#include "p8_scom_addresses.H"
#include "p8_pm_occ_firinit.H"

extern "C" {

using namespace fapi;

// ----------------------------------------------------------------------
// Constant definitions
// ----------------------------------------------------------------------

// ----------------------------------------------------------------------
// Macro definitions
// ----------------------------------------------------------------------

// ----------------------------------------------------------------------
// Global variables
// ----------------------------------------------------------------------

// ----------------------------------------------------------------------
// Function prototypes
// ----------------------------------------------------------------------

// ----------------------------------------------------------------------
// Function definitions
// ----------------------------------------------------------------------

/// \param[in]  i_target            => Chip Target

/// \retval FAPI_RC_SUCCESS
/// \retval ERROR
fapi::ReturnCode
p8_pm_occ_firinit(const fapi::Target& i_target , uint32_t mode)
{
    fapi::ReturnCode     rc;
    ecmdDataBufferBase   fir(64);
    ecmdDataBufferBase   action_0(64);
    ecmdDataBufferBase   action_1(64);
    ecmdDataBufferBase   mask(64);
    uint32_t             e_rc = 0;

    FAPI_DBG("Executing p8_pm_occ_firinit  ....");

    do
    {
       if (mode == PM_RESET)
       {

            e_rc  = mask.flushTo0();
            e_rc |= mask.setBit(0,OCC_FIR_REGISTER_LENGTH);
            if (e_rc)
            {
                rc.setEcmdError(e_rc);
                break;
            }

            // ------------
            // OCC_FIR_MASK
            // ------------
            rc = fapiPutScom(i_target, OCC_LFIR_MASK_0x01010803, mask );
            if (!rc.ok())
            {
	            FAPI_ERR("fapiPutScom(OCC_LFIR_MASK_0x01010803) failed.");
	            break;
            }
        }
        else
        {

            // Clear the FIR
            e_rc |= fir.flushTo0();

            // make action default be RECOV_ATTN - "01"
            e_rc |= action_0.flushTo0();
            e_rc |= action_1.flushTo1();

            // make mask default be unmasked - "0"
            e_rc |= mask.flushTo0()    ;
            if (e_rc)
            {
                rc.setEcmdError(e_rc);
                break;
            }

            // ------------------------------------------------------------------------
            // set the action and mask for the OCC LFIR bits using the following macros
            // ------------------------------------------------------------------------
            //   Action0/1 Setting Macros - 4 possible settings
            //     SET_CHECK_STOP(b) - sets action0/1 to "00" for LFIR bit b
            //     SET_RECOV_ATTN(b) - sets action0/1 to "01" for LFIR bit b
            //     SET_RECOV_INTR(b) - sets action0/1 to "10" for LFIR bit b
            //     SET_MALF_ALERT(b) - sets action0/1 to "11" for LFIR bit b
            //
            //  Mask Setting Macro
            //   SET_FIR_MASKED(b) - sets mask to '1' for LFIR bit b
            // ------------------------------------------------------------------------

            SET_MALF_ALERT(0);  SET_FIR_MASKED(0);        //  0 = occ_fw0
            SET_MALF_ALERT(1);  SET_FIR_MASKED(1);        //  1 = occ_fw1
            SET_MALF_ALERT(2);  SET_FIR_MASKED(2);        //  2 = occ_fw2
            SET_MALF_ALERT(3);  SET_FIR_MASKED(3);        //  3 = occ_fw3
            SET_MALF_ALERT(4);  SET_FIR_MASKED(4);        //  4 = pmc_pore_sw_malf
            SET_MALF_ALERT(5);  SET_FIR_MASKED(5);        //  5 = pmc_occ_hb_malf

            SET_RECOV_ATTN(6);  SET_FIR_MASKED(6);        //  6 = pore_gpe0_fatal_err
            SET_RECOV_ATTN(7);  SET_FIR_MASKED(7);        //  7 = pore_gpe1_fatal_err
            SET_RECOV_ATTN(8);  SET_FIR_MASKED(8);        //  8 = ocb_error
            SET_RECOV_ATTN(9);                            //  9 = srt_ue
            SET_RECOV_ATTN(10); SET_FIR_MASKED(10);       //  10 = srt_ce
            SET_RECOV_ATTN(11);                           //  11 = srt_read_error
            SET_RECOV_ATTN(12);                           //  12 = srt_write_error
            SET_RECOV_ATTN(13);                           //  13 = srt_dataout_perr
            SET_RECOV_ATTN(14);                           //  14 = srt_oci_write_data_parity
            SET_RECOV_ATTN(15);                           //  15 = srt_oci_be_parity_err
            SET_RECOV_ATTN(16);                           //  16 = srt_oci_addr_parity_err
            SET_RECOV_ATTN(17); SET_FIR_MASKED(17);       //  17 = pore_sw_error_err
            SET_RECOV_ATTN(18); SET_FIR_MASKED(18);       //  18 = pore_gpe0_error_err
            SET_RECOV_ATTN(19); SET_FIR_MASKED(19);       //  19 = pore_gpe1_error_err
            SET_RECOV_ATTN(20); SET_FIR_MASKED(20);       //  20 = external_trap
            SET_RECOV_ATTN(21); SET_FIR_MASKED(21);       //  21 = ppc405_core_reset
            SET_RECOV_ATTN(22); SET_FIR_MASKED(22);       //  22 = ppc405_chip_reset
            SET_RECOV_ATTN(23); SET_FIR_MASKED(23);       //  23 = ppc405_system_reset
            SET_RECOV_ATTN(24); SET_FIR_MASKED(24);       //  24 = ppc405_dbgmsrwe
            SET_RECOV_ATTN(25); SET_FIR_MASKED(25);       //  25 = ppc405_dbgstopack
            SET_RECOV_ATTN(26);                           //  26 = ocb_db_oci_timeout
            SET_RECOV_ATTN(27);                           //  27 = ocb_db_oci_read_data_parity
            SET_RECOV_ATTN(28);                           //  28 = ocb_db_oci_slave_error
            SET_RECOV_ATTN(29);                           //  29 = ocb_pib_addr_parity_err
            SET_RECOV_ATTN(30);                           //  30 = ocb_db_pib_data_parity_err
            SET_RECOV_ATTN(31);                           //  31 = ocb_idc0_error
            SET_RECOV_ATTN(32);                           //  32 = ocb_idc1_error
            SET_RECOV_ATTN(33);                           //  33 = ocb_idc2_error
            SET_RECOV_ATTN(34);                           //  34 = ocb_idc3_error
            SET_RECOV_ATTN(35);                           //  35 = srt_fsm_err
            SET_RECOV_ATTN(36); SET_FIR_MASKED(36);       //  36 = jtagacc_err
            SET_RECOV_ATTN(37); SET_FIR_MASKED(37);       //  37 = spare_err_37
            SET_RECOV_ATTN(38);                           //  38 = c405_ecc_ue
            SET_RECOV_ATTN(39); SET_FIR_MASKED(39);       //  39 = c405_ecc_ce
            SET_RECOV_ATTN(40); SET_FIR_MASKED(40);       //  40 = c405_oci_machinecheck
            SET_RECOV_ATTN(41);                           //  41 = sram_spare_direct_error0
            SET_RECOV_ATTN(42);                           //  42 = sram_spare_direct_error1
            SET_RECOV_ATTN(43);                           //  43 = sram_spare_direct_error2
            SET_RECOV_ATTN(44);                           //  44 = sram_spare_direct_error3
            SET_RECOV_ATTN(45);                           //  45 = slw_ocislv_err
            SET_RECOV_ATTN(46);                           //  46 = gpe_ocislv_err
            SET_RECOV_ATTN(47);                           //  47 = ocb_ocislv_err
            SET_RECOV_ATTN(48);                           //  48 = c405icu_m_timeout
            SET_RECOV_ATTN(49);                           //  49 = c405dcu_m_timeout
            SET_RECOV_ATTN(50); SET_FIR_MASKED(50);       //  50 = spare_fir
            SET_RECOV_ATTN(51); SET_FIR_MASKED(51);       //  51 = spare_fir
            SET_RECOV_ATTN(52); SET_FIR_MASKED(52);       //  52 = spare_fir
            SET_RECOV_ATTN(53); SET_FIR_MASKED(53);       //  53 = spare_fir
            SET_RECOV_ATTN(54); SET_FIR_MASKED(54);       //  54 = spare_fir
            SET_RECOV_ATTN(55); SET_FIR_MASKED(55);       //  55 = spare_fir
            SET_RECOV_ATTN(56); SET_FIR_MASKED(56);       //  56 = spare_fir
            SET_RECOV_ATTN(57); SET_FIR_MASKED(57);       //  57 = spare_fir
            SET_RECOV_ATTN(58); SET_FIR_MASKED(58);       //  58 = spare_fir
            SET_RECOV_ATTN(59); SET_FIR_MASKED(59);       //  59 = spare_fir
            SET_RECOV_ATTN(60); SET_FIR_MASKED(60);       //  60 = spare_fir
            SET_RECOV_ATTN(61); SET_FIR_MASKED(61);       //  61 = spare_fir
            SET_RECOV_ATTN(62);                           //  62 = fir_parity_err_dup
            SET_RECOV_ATTN(63);                           //  63 = fir_parity_err

            if (e_rc)
            {
                rc.setEcmdError(e_rc);
                break;
            }

            // ---------------
            // OCC_FIR - cleared
            // ---------------
            rc = fapiPutScom(i_target, OCC_LFIR_0x01010800, fir);
            if (!rc.ok())
            {
                FAPI_ERR("fapiPutScom(OCC_LFIR_0x01010800) failed.");
                 break;
            }

            FAPI_DBG(" action_0  => 0x%16llx ",  action_0.getDoubleWord(0));
            FAPI_DBG(" action_1  => 0x%16llx ",  action_1.getDoubleWord(0));
            FAPI_DBG(" mask      => 0x%16llx ",  mask.getDoubleWord(0));

            // ---------------
            // OCC_FIR_ACTION0
            // ---------------
            rc = fapiPutScom(i_target, OCC_LFIR_ACT0_0x01010806, action_0 );
            if (!rc.ok())
            {
                FAPI_ERR("fapiPutScom(OCC_LFIR_ACT0_0x01010806) failed.");
                break;
            }

            // ----------------
            // OCC_FIR_ACTION1
            // ----------------
            rc = fapiPutScom(i_target, OCC_LFIR_ACT1_0x01010807, action_1 );
            if (!rc.ok())
            {
                FAPI_ERR("fapiPutScom(OCC_LFIR_ACT1_0x01010807) failed.");
                    break;
            }

            // ------------
            // OCC_FIR_MASK
            // ------------
            rc = fapiPutScom(i_target, OCC_LFIR_MASK_0x01010803, mask );
            if (!rc.ok())
            {
                FAPI_ERR("fapiPutScom(OCC_LFIR_MASK_0x01010803) failed.");
                break;
            }
        }
    } while(0);
    return rc ;
} // end p8_pm_occ_firinit

} //end extern C
<|endoftext|>