<commit_before>// Copyright (c) 2012 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 "ui/views/controls/progress_bar.h"

#include <algorithm>
#include <string>

#include "base/logging.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "third_party/skia/include/effects/SkBlurMaskFilter.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
#include "ui/base/accessibility/accessible_view_state.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/font.h"
#include "ui/gfx/insets.h"
#include "ui/views/background.h"
#include "ui/views/border.h"
#include "ui/views/painter.h"

namespace {

// Corner radius for the progress bar's border.
const int kCornerRadius = 3;

// Progress bar's border width.
const int kBorderWidth = 1;

const SkColor kBarColorStart = SkColorSetRGB(81, 138, 223);
const SkColor kBarColorEnd = SkColorSetRGB(51, 103, 205);
const SkColor kBackgroundColorStart = SkColorSetRGB(212, 212, 212);
const SkColor kBackgroundColorEnd = SkColorSetRGB(252, 252, 252);
const SkColor kBorderColor = SkColorSetRGB(144, 144, 144);

void AddRoundRectPathWithPadding(int x, int y,
                                 int w, int h,
                                 int corner_radius,
                                 SkScalar padding,
                                 SkPath* path) {
  DCHECK(path);
  SkRect rect;
  rect.set(
      SkIntToScalar(x) + padding, SkIntToScalar(y) + padding,
      SkIntToScalar(x + w) - padding, SkIntToScalar(y + h) - padding);
  path->addRoundRect(
      rect,
      SkIntToScalar(corner_radius) - padding,
      SkIntToScalar(corner_radius) - padding);
}

void AddRoundRectPath(int x, int y,
                      int w, int h,
                      int corner_radius,
                      SkPath* path) {
  AddRoundRectPathWithPadding(x, y, w, h, corner_radius, SK_ScalarHalf, path);
}

void FillRoundRect(gfx::Canvas* canvas,
                   int x, int y,
                   int w, int h,
                   int corner_radius,
                   const SkColor colors[],
                   const SkScalar points[],
                   int count,
                   bool gradient_horizontal) {
  SkPath path;
  AddRoundRectPath(x, y, w, h, corner_radius, &path);
  SkPaint paint;
  paint.setStyle(SkPaint::kFill_Style);
  paint.setFlags(SkPaint::kAntiAlias_Flag);

  SkPoint p[2];
  p[0].iset(x, y);
  if (gradient_horizontal) {
    p[1].iset(x + w, y);
  } else {
    p[1].iset(x, y + h);
  }
  SkShader* s = SkGradientShader::CreateLinear(
      p, colors, points, count, SkShader::kClamp_TileMode, NULL);
  paint.setShader(s);
  // Need to unref shader, otherwise never deleted.
  s->unref();

  canvas->DrawPath(path, paint);
}

void FillRoundRect(gfx::Canvas* canvas,
                   int x, int y,
                   int w, int h,
                   int corner_radius,
                   SkColor gradient_start_color,
                   SkColor gradient_end_color,
                   bool gradient_horizontal) {
  if (gradient_start_color != gradient_end_color) {
    SkColor colors[2] = { gradient_start_color, gradient_end_color };
    FillRoundRect(canvas, x, y, w, h, corner_radius,
                  colors, NULL, 2, gradient_horizontal);
  } else {
    SkPath path;
    AddRoundRectPath(x, y, w, h, corner_radius, &path);
    SkPaint paint;
    paint.setStyle(SkPaint::kFill_Style);
    paint.setFlags(SkPaint::kAntiAlias_Flag);
    paint.setColor(gradient_start_color);
    canvas->DrawPath(path, paint);
  }
}

void StrokeRoundRect(gfx::Canvas* canvas,
                     int x, int y,
                     int w, int h,
                     int corner_radius,
                     SkColor stroke_color,
                     int stroke_width) {
  SkPath path;
  AddRoundRectPath(x, y, w, h, corner_radius, &path);
  SkPaint paint;
  paint.setShader(NULL);
  paint.setColor(stroke_color);
  paint.setStyle(SkPaint::kStroke_Style);
  paint.setFlags(SkPaint::kAntiAlias_Flag);
  paint.setStrokeWidth(SkIntToScalar(stroke_width));
  canvas->DrawPath(path, paint);
}

}  // namespace

namespace views {

// static
const char ProgressBar::kViewClassName[] = "views/ProgressBar";

ProgressBar::ProgressBar()
    : min_display_value_(0.0),
      max_display_value_(1.0),
      current_value_(0.0) {
}

ProgressBar::~ProgressBar() {
}

void ProgressBar::SetDisplayRange(double min_display_value,
                                  double max_display_value) {
  if (min_display_value != min_display_value_ ||
      max_display_value != max_display_value_) {
    DCHECK(min_display_value < max_display_value);
    min_display_value_ = min_display_value;
    max_display_value_ = max_display_value;
    SchedulePaint();
  }
}

void ProgressBar::SetValue(double value) {
  if (value != current_value_) {
    current_value_ = value;
    SchedulePaint();
  }
}

void ProgressBar::SetTooltipText(const string16& tooltip_text) {
  tooltip_text_ = tooltip_text;
}

bool ProgressBar::GetTooltipText(const gfx::Point& p, string16* tooltip) const {
  DCHECK(tooltip);
  *tooltip = tooltip_text_;
  return !tooltip_text_.empty();
}

void ProgressBar::GetAccessibleState(ui::AccessibleViewState* state) {
  state->role = ui::AccessibilityTypes::ROLE_PROGRESSBAR;
  state->state = ui::AccessibilityTypes::STATE_READONLY;
}

gfx::Size ProgressBar::GetPreferredSize() {
  return gfx::Size(100, 16);
}

std::string ProgressBar::GetClassName() const {
  return kViewClassName;
}

void ProgressBar::OnPaint(gfx::Canvas* canvas) {
  const double capped_value = std::min(
      std::max(current_value_, min_display_value_), max_display_value_);
  const double capped_fraction =
      (capped_value - min_display_value_) /
      (max_display_value_ - min_display_value_);
  const int progress_width = static_cast<int>(width() * capped_fraction + 0.5);

#if defined(OS_CHROMEOS)
  const SkColor background_colors[] = {
    SkColorSetRGB(0xBB, 0xBB, 0xBB),
    SkColorSetRGB(0xE7, 0xE7, 0xE7),
    SkColorSetRGB(0xFE, 0xFE, 0xFE)
  };

  const SkScalar background_points[] = {
    SkDoubleToScalar(0),
    SkDoubleToScalar(0.1),
    SkDoubleToScalar(1)
  };
  const SkColor background_border_color = SkColorSetRGB(0xA1, 0xA1, 0xA1);

  // Draw background.
  FillRoundRect(canvas,
                0, 0, width(), height(),
                kCornerRadius,
                background_colors,
                background_points,
                arraysize(background_colors),
                false);
  StrokeRoundRect(canvas,
                  0, 0,
                  width(), height(),
                  kCornerRadius,
                  background_border_color,
                  kBorderWidth);

  if (progress_width > 1) {
    const SkColor bar_color_start = enabled() ?
        SkColorSetRGB(100, 116, 147) :
        SkColorSetRGB(229, 232, 237);
    const SkColor bar_color_end = enabled() ?
        SkColorSetRGB(65, 73, 87) :
        SkColorSetRGB(224, 225, 227);

    const SkColor bar_outer_color = enabled() ?
        SkColorSetRGB(0x4A, 0x4A, 0x4A) :
        SkColorSetARGB(0x80, 0x4A, 0x4A, 0x4A);

    const SkColor bar_inner_border_color =
        SkColorSetARGB(0x3F, 0xFF, 0xFF, 0xFF);  // 0.25 white
    const SkColor bar_inner_shadow_color =
        SkColorSetARGB(0x54, 0xFF, 0xFF, 0xFF);  // 0.33 white

    // Draw bar background
    FillRoundRect(canvas,
                  0, 0, progress_width, height(),
                  kCornerRadius,
                  bar_color_start,
                  bar_color_end,
                  false);

    // Draw inner stroke and shadow if wide enough.
    if (progress_width > 2 * kBorderWidth) {
      canvas->Save();

      SkPath inner_path;
      AddRoundRectPathWithPadding(
          0, 0, progress_width, height(),
          kCornerRadius,
          SkIntToScalar(kBorderWidth),
          &inner_path);
      canvas->ClipPath(inner_path);

      // Draw bar inner stroke
      StrokeRoundRect(canvas,
                      kBorderWidth, kBorderWidth,
                      progress_width - 2 * kBorderWidth,
                      height() - 2 * kBorderWidth,
                      kCornerRadius - kBorderWidth,
                      bar_inner_border_color,
                      kBorderWidth);

      // Draw bar inner shadow
      StrokeRoundRect(canvas,
                      0, kBorderWidth, progress_width, height(),
                      kCornerRadius,
                      bar_inner_shadow_color,
                      kBorderWidth);

      canvas->Restore();
    }

    // Draw bar stroke
    StrokeRoundRect(canvas,
                    0, 0, progress_width, height(),
                    kCornerRadius,
                    bar_outer_color,
                    kBorderWidth);
  }
#else
  FillRoundRect(canvas, 0, 0, width(), height(), kCornerRadius,
                kBackgroundColorStart, kBackgroundColorEnd, false);

  if (progress_width > 1) {
    FillRoundRect(canvas, 0, 0, progress_width, height(), kCornerRadius,
                  kBarColorStart, kBarColorEnd, false);
  }
  StrokeRoundRect(canvas, 0, 0, width(), height(), kCornerRadius,
                  kBorderColor, kBorderWidth);
#endif
}

}  // namespace views
<commit_msg>views: Remove unused includes from progress_bar.cc.<commit_after>// Copyright (c) 2012 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 "ui/views/controls/progress_bar.h"

#include <algorithm>
#include <string>

#include "base/logging.h"
#include "third_party/skia/include/effects/SkGradientShader.h"
#include "ui/base/accessibility/accessible_view_state.h"
#include "ui/gfx/canvas.h"

namespace {

// Corner radius for the progress bar's border.
const int kCornerRadius = 3;

// Progress bar's border width.
const int kBorderWidth = 1;

const SkColor kBarColorStart = SkColorSetRGB(81, 138, 223);
const SkColor kBarColorEnd = SkColorSetRGB(51, 103, 205);
const SkColor kBackgroundColorStart = SkColorSetRGB(212, 212, 212);
const SkColor kBackgroundColorEnd = SkColorSetRGB(252, 252, 252);
const SkColor kBorderColor = SkColorSetRGB(144, 144, 144);

void AddRoundRectPathWithPadding(int x, int y,
                                 int w, int h,
                                 int corner_radius,
                                 SkScalar padding,
                                 SkPath* path) {
  DCHECK(path);
  SkRect rect;
  rect.set(
      SkIntToScalar(x) + padding, SkIntToScalar(y) + padding,
      SkIntToScalar(x + w) - padding, SkIntToScalar(y + h) - padding);
  path->addRoundRect(
      rect,
      SkIntToScalar(corner_radius) - padding,
      SkIntToScalar(corner_radius) - padding);
}

void AddRoundRectPath(int x, int y,
                      int w, int h,
                      int corner_radius,
                      SkPath* path) {
  AddRoundRectPathWithPadding(x, y, w, h, corner_radius, SK_ScalarHalf, path);
}

void FillRoundRect(gfx::Canvas* canvas,
                   int x, int y,
                   int w, int h,
                   int corner_radius,
                   const SkColor colors[],
                   const SkScalar points[],
                   int count,
                   bool gradient_horizontal) {
  SkPath path;
  AddRoundRectPath(x, y, w, h, corner_radius, &path);
  SkPaint paint;
  paint.setStyle(SkPaint::kFill_Style);
  paint.setFlags(SkPaint::kAntiAlias_Flag);

  SkPoint p[2];
  p[0].iset(x, y);
  if (gradient_horizontal) {
    p[1].iset(x + w, y);
  } else {
    p[1].iset(x, y + h);
  }
  SkShader* s = SkGradientShader::CreateLinear(
      p, colors, points, count, SkShader::kClamp_TileMode, NULL);
  paint.setShader(s);
  // Need to unref shader, otherwise never deleted.
  s->unref();

  canvas->DrawPath(path, paint);
}

void FillRoundRect(gfx::Canvas* canvas,
                   int x, int y,
                   int w, int h,
                   int corner_radius,
                   SkColor gradient_start_color,
                   SkColor gradient_end_color,
                   bool gradient_horizontal) {
  if (gradient_start_color != gradient_end_color) {
    SkColor colors[2] = { gradient_start_color, gradient_end_color };
    FillRoundRect(canvas, x, y, w, h, corner_radius,
                  colors, NULL, 2, gradient_horizontal);
  } else {
    SkPath path;
    AddRoundRectPath(x, y, w, h, corner_radius, &path);
    SkPaint paint;
    paint.setStyle(SkPaint::kFill_Style);
    paint.setFlags(SkPaint::kAntiAlias_Flag);
    paint.setColor(gradient_start_color);
    canvas->DrawPath(path, paint);
  }
}

void StrokeRoundRect(gfx::Canvas* canvas,
                     int x, int y,
                     int w, int h,
                     int corner_radius,
                     SkColor stroke_color,
                     int stroke_width) {
  SkPath path;
  AddRoundRectPath(x, y, w, h, corner_radius, &path);
  SkPaint paint;
  paint.setShader(NULL);
  paint.setColor(stroke_color);
  paint.setStyle(SkPaint::kStroke_Style);
  paint.setFlags(SkPaint::kAntiAlias_Flag);
  paint.setStrokeWidth(SkIntToScalar(stroke_width));
  canvas->DrawPath(path, paint);
}

}  // namespace

namespace views {

// static
const char ProgressBar::kViewClassName[] = "views/ProgressBar";

ProgressBar::ProgressBar()
    : min_display_value_(0.0),
      max_display_value_(1.0),
      current_value_(0.0) {
}

ProgressBar::~ProgressBar() {
}

void ProgressBar::SetDisplayRange(double min_display_value,
                                  double max_display_value) {
  if (min_display_value != min_display_value_ ||
      max_display_value != max_display_value_) {
    DCHECK(min_display_value < max_display_value);
    min_display_value_ = min_display_value;
    max_display_value_ = max_display_value;
    SchedulePaint();
  }
}

void ProgressBar::SetValue(double value) {
  if (value != current_value_) {
    current_value_ = value;
    SchedulePaint();
  }
}

void ProgressBar::SetTooltipText(const string16& tooltip_text) {
  tooltip_text_ = tooltip_text;
}

bool ProgressBar::GetTooltipText(const gfx::Point& p, string16* tooltip) const {
  DCHECK(tooltip);
  *tooltip = tooltip_text_;
  return !tooltip_text_.empty();
}

void ProgressBar::GetAccessibleState(ui::AccessibleViewState* state) {
  state->role = ui::AccessibilityTypes::ROLE_PROGRESSBAR;
  state->state = ui::AccessibilityTypes::STATE_READONLY;
}

gfx::Size ProgressBar::GetPreferredSize() {
  return gfx::Size(100, 16);
}

std::string ProgressBar::GetClassName() const {
  return kViewClassName;
}

void ProgressBar::OnPaint(gfx::Canvas* canvas) {
  const double capped_value = std::min(
      std::max(current_value_, min_display_value_), max_display_value_);
  const double capped_fraction =
      (capped_value - min_display_value_) /
      (max_display_value_ - min_display_value_);
  const int progress_width = static_cast<int>(width() * capped_fraction + 0.5);

#if defined(OS_CHROMEOS)
  const SkColor background_colors[] = {
    SkColorSetRGB(0xBB, 0xBB, 0xBB),
    SkColorSetRGB(0xE7, 0xE7, 0xE7),
    SkColorSetRGB(0xFE, 0xFE, 0xFE)
  };

  const SkScalar background_points[] = {
    SkDoubleToScalar(0),
    SkDoubleToScalar(0.1),
    SkDoubleToScalar(1)
  };
  const SkColor background_border_color = SkColorSetRGB(0xA1, 0xA1, 0xA1);

  // Draw background.
  FillRoundRect(canvas,
                0, 0, width(), height(),
                kCornerRadius,
                background_colors,
                background_points,
                arraysize(background_colors),
                false);
  StrokeRoundRect(canvas,
                  0, 0,
                  width(), height(),
                  kCornerRadius,
                  background_border_color,
                  kBorderWidth);

  if (progress_width > 1) {
    const SkColor bar_color_start = enabled() ?
        SkColorSetRGB(100, 116, 147) :
        SkColorSetRGB(229, 232, 237);
    const SkColor bar_color_end = enabled() ?
        SkColorSetRGB(65, 73, 87) :
        SkColorSetRGB(224, 225, 227);

    const SkColor bar_outer_color = enabled() ?
        SkColorSetRGB(0x4A, 0x4A, 0x4A) :
        SkColorSetARGB(0x80, 0x4A, 0x4A, 0x4A);

    const SkColor bar_inner_border_color =
        SkColorSetARGB(0x3F, 0xFF, 0xFF, 0xFF);  // 0.25 white
    const SkColor bar_inner_shadow_color =
        SkColorSetARGB(0x54, 0xFF, 0xFF, 0xFF);  // 0.33 white

    // Draw bar background
    FillRoundRect(canvas,
                  0, 0, progress_width, height(),
                  kCornerRadius,
                  bar_color_start,
                  bar_color_end,
                  false);

    // Draw inner stroke and shadow if wide enough.
    if (progress_width > 2 * kBorderWidth) {
      canvas->Save();

      SkPath inner_path;
      AddRoundRectPathWithPadding(
          0, 0, progress_width, height(),
          kCornerRadius,
          SkIntToScalar(kBorderWidth),
          &inner_path);
      canvas->ClipPath(inner_path);

      // Draw bar inner stroke
      StrokeRoundRect(canvas,
                      kBorderWidth, kBorderWidth,
                      progress_width - 2 * kBorderWidth,
                      height() - 2 * kBorderWidth,
                      kCornerRadius - kBorderWidth,
                      bar_inner_border_color,
                      kBorderWidth);

      // Draw bar inner shadow
      StrokeRoundRect(canvas,
                      0, kBorderWidth, progress_width, height(),
                      kCornerRadius,
                      bar_inner_shadow_color,
                      kBorderWidth);

      canvas->Restore();
    }

    // Draw bar stroke
    StrokeRoundRect(canvas,
                    0, 0, progress_width, height(),
                    kCornerRadius,
                    bar_outer_color,
                    kBorderWidth);
  }
#else
  FillRoundRect(canvas, 0, 0, width(), height(), kCornerRadius,
                kBackgroundColorStart, kBackgroundColorEnd, false);

  if (progress_width > 1) {
    FillRoundRect(canvas, 0, 0, progress_width, height(), kCornerRadius,
                  kBarColorStart, kBarColorEnd, false);
  }
  StrokeRoundRect(canvas, 0, 0, width(), height(), kCornerRadius,
                  kBorderColor, kBorderWidth);
#endif
}

}  // namespace views
<|endoftext|>


<commit_before>/*
 *
 *  Copyright 2013 Mario Alviano, Carmine Dodaro, and Francesco Ricca.
 *
 *  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 "Dimacs.h"

#include "../Solver.h"
#include "../Clause.h"
#include "../util/Constants.h"
#include "../util/ErrorMessage.h"
#include "../util/Trace.h"
#include "../util/Options.h"

#include <cassert>
#include <sstream>
#include <unordered_set>
using namespace std;

Dimacs::Dimacs(
    Solver& s ) : solver( s )
{
}

//
//DimacsFormat::DimacsFormat(
//    ProgramBuilder* p ) : programBuilder( p ), weighted( false ),
//                          cnfWeighted( false ), maxWeight( 0 )
//{
//}
//

void
Dimacs::parse()
{
    this->parse( cin );
}

void
Dimacs::parse(
    istream& input )
{
    char type;

    while( input >> type )
    {
        switch ( type )
        {
        case COMMENT_DIMACS:
            readComment( input );
            break;

        case FORMULA_INFO_DIMACS:
            readFormulaInfo( input );
            insertVariables( numberOfVariables );
            readAllClauses( input );
            break;

        default:
            ErrorMessage::errorDuringParsing( "Unexpected symbol.");
        }
    }
    if( !input.good() && !input.eof() )
    {
        ErrorMessage::errorDuringParsing( "Unexpected symbol.");
    }
}

void
Dimacs::readComment(
    istream & input )
{
    char buf[ 10240 ];

    input.getline( buf, 10240 );
    if( input.gcount() > 10239 )
        ErrorMessage::errorDuringParsing( "Comment too long.");
}

void
Dimacs::readFormulaInfo(
    istream& input )
{
    char type;
    input >> type;

//    if( type == 'w' )
//    {
//        weighted = true;
//        input >> type;
//        if( type != 'c' )
//        {
//            cerr << ERRORPARSING << endl;
//            exit( 0 );
//        }
//    }
    /*else*/
    if( type != 'c' )
    {
        ErrorMessage::errorDuringParsing( "Expected a 'c'.");
    }

    input >> type;
    if( type != 'n' )
    {
        ErrorMessage::errorDuringParsing( "Expected a 'n'.");
    }

    input >> type;
    if( type != 'f' )
    {
        ErrorMessage::errorDuringParsing( "Expected a 'f'.");
    }

    input >> numberOfVariables;
    input >> numberOfClauses;

//    if( weighted )
//        input >> maxWeight;
//    else if( wasp::options.dimacsMaxsat )
//    {
//        weighted = true;
//        cnfWeighted = true;
//        maxWeight = 2;
//    }
}

void
Dimacs::readAllClauses(
    istream& input )
{
//    if( !weighted )
//    {
    trace_msg( parser, 1, "Starting iteration on " << numberOfClauses << " clauses.");
    for( unsigned int i = 0; i < numberOfClauses; i++ )
    {
        readClause( input );
    }
//    }
//    else if( !cnfWeighted )
//    {
//        for( unsigned int i = 0; i < numberOfClauses; i++ )
//        {
//            readClauseWeighted( input );
//        }
//    }
//    else
//    {
//        for( unsigned int i = 0; i < numberOfClauses; i++ )
//        {
//            readClauseCnfWeighted( input );
//        }
//    }

//    for( unsigned int i = 1; i <= numberOfVariables; i++ )
//    {
//        if( variablesAppearingWithBothPolarity.find( i ) == variablesAppearingWithBothPolarity.end() )
//        {
//            if( readVariables.find( i ) != readVariables.end() )
//            {
//                programBuilder->addTrueSupportedAtom( i );
//            }
//            else
//            {
//                programBuilder->addFalseAtom( i );
//            }
//        }
//    }
}

void
Dimacs::readClause(
    istream& input )
{
    unordered_set< int > tempSet;

    bool trivial = false;

    Clause* clause = new Clause();

    //a variable containing the literal to read
    int next;

    //read the next literal
    input >> next;

    if( next == 0 )
    {
        ErrorMessage::errorDuringParsing( "Empty clause are not allowed.");
    }

    //storing the first literal in case the clause is unary.
    int firstLiteral = next;
    do
    {
        assert( next != 0 );

        //insert the current literal in the set
        tempSet.insert( next );

        //if the opposite literal was already in the set the clause is a tautology
        if( tempSet.find( -next ) != tempSet.end() )
            trivial = true;

        //add the literal in the clause
        clause->addLiteral( solver.getLiteral( next ) );

        //read the next literal
        input >> next;

      //do while next is not 0
    } while( next != 0 );

    if( clause->size() == 1 )
    {
        assert( firstLiteral != 0 );
        trivial = true;
        if( addedLiterals.insert( firstLiteral ).second )
        {
            trace_msg( parser, 2, "Unary clause with literal " << firstLiteral << ". Adding literal to the solver." );
            solver.addTrueLiteral( solver.getLiteral( firstLiteral ) );
        }
        else
        {
            trace_msg( parser, 2, "Found duplicated unary clause with literal " << firstLiteral << ". Skipping this clause." );
        }
    }

    //if the clause is not trivial add it in the formula
    if( !trivial )
    {
        trace_msg( parser, 1, "Adding clause " << *clause << " in solver.");
        solver.addClause( clause );
        clause->attachClause();
    }
    else
    {
        trace_msg( parser, 1, "Deleting clause " << *clause << " because is trivial." );
        delete clause;
    }
}
//
//void
//DimacsFormat::readClauseWeighted(
//    istream& input )
//{
//    unordered_set< int > tempSet;
//    unsigned int weight;
//    input >> weight;
//
//    if( weight == maxWeight )
//    {
//        readClause( input );
//        return;
//    }
//
//    List< int > clause;
//    bool trivial = false;
//
//    int next;
//    input >> next;
//    do
//    {
//        assert( next != 0 );
//
//        tempSet.insert( next );
//
//        if( tempSet.find( -next ) != tempSet.end() )
//            trivial = true;
//
//        //Change polarity
//        clause.push_back( -next );
//        input >> next;
//    } while( next != 0 );
//
//    if( trivial )
//        return;
//
//    WeakConstraint* w;
//    if( wasp::options.weakConstraintsHeuristic || clause.size() == 1 )
//        w = programBuilder->startWeakConstraint( clause.size() + 1, weight, 1 );
//    else
//        w = programBuilder->startWeakConstraint( clause.size(), weight, 1 );
//
//    while( !clause.empty() )
//    {
//        int id = clause.front();
//        if( readVariables.find( id ) != readVariables.end() )
//            variablesAppearingWithBothPolarity.insert( abs( id ) );
//        readVariables.insert( -id );
//
//        if( id < 0 )
//            programBuilder->addLiteralInWeakConstraint( w, -id, false );
//        else
//            programBuilder->addLiteralInWeakConstraint( w, id, true );
//        clause.pop_front();
//    }
//    programBuilder->endWeakConstraint( w );
//
//    assert( clause.empty() );
//}
//
//void
//DimacsFormat::readClauseCnfWeighted(
//    istream& input )
//{
//    List< int > clause;
//    bool trivial = false;
//    unordered_set< int > tempSet;
//
//    int next;
//    input >> next;
//    do
//    {
//        assert( next != 0 );
//
//        tempSet.insert( next );
//
//        if( tempSet.find( -next ) != tempSet.end() )
//            trivial = true;
//
//        //Change polarity
//        clause.push_back( -next );
//        input >> next;
//    } while( next != 0 );
//
//    if( trivial )
//        return;
//
//    WeakConstraint* w;
//    if( wasp::options.weakConstraintsHeuristic || clause.size() == 1 )
//        w = programBuilder->startWeakConstraint( clause.size() + 1, 1, 1 );
//    else
//        w = programBuilder->startWeakConstraint( clause.size(), 1, 1 );
//
//    while( !clause.empty() )
//    {
//        int id = clause.front();
//
//        if( readVariables.find( id ) != readVariables.end() )
//            variablesAppearingWithBothPolarity.insert( abs( id ) );
//        readVariables.insert( -id );
//
//        if( id < 0 )
//            programBuilder->addLiteralInWeakConstraint( w, -id, false );
//        else
//            programBuilder->addLiteralInWeakConstraint( w, id, true );
//        clause.pop_front();
//    }
//    programBuilder->endWeakConstraint( w );
//
//    assert( clause.empty() );
//}

void
Dimacs::insertVariables(
    unsigned int numberOfVariables )
{
    trace_msg( parser, 1, "Adding " << numberOfVariables << " variables." );
    for( unsigned int i = 1; i <= numberOfVariables; i++ )
    {
        stringstream ss;
        ss << i;
        solver.addVariable( ss.str() );
    }
}<commit_msg>Fixed bug when reading comments on dimacs input. Added a test case for it.<commit_after>/*
 *
 *  Copyright 2013 Mario Alviano, Carmine Dodaro, and Francesco Ricca.
 *
 *  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 "Dimacs.h"

#include "../Solver.h"
#include "../Clause.h"
#include "../util/Constants.h"
#include "../util/ErrorMessage.h"
#include "../util/Trace.h"
#include "../util/Options.h"

#include <cassert>
#include <sstream>
#include <unordered_set>
using namespace std;

Dimacs::Dimacs(
    Solver& s ) : solver( s )
{
}

//
//DimacsFormat::DimacsFormat(
//    ProgramBuilder* p ) : programBuilder( p ), weighted( false ),
//                          cnfWeighted( false ), maxWeight( 0 )
//{
//}
//

void
Dimacs::parse()
{
    this->parse( cin );
}

void
Dimacs::parse(
    istream& input )
{
    char type;

    while( input >> type )
    {
        switch ( type )
        {
        case COMMENT_DIMACS:
            readComment( input );
            break;

        case FORMULA_INFO_DIMACS:
            readFormulaInfo( input );
            insertVariables( numberOfVariables );
            //readAllClauses( input );
            break;

        default:
			input.putback( type );
			readClause( input );
            //ErrorMessage::errorDuringParsing( "Unexpected symbol.");
        }
    }
    if( !input.good() && !input.eof() )
    {
        ErrorMessage::errorDuringParsing( "Unexpected symbol.");
    }
}

void
Dimacs::readComment(
    istream & input )
{
    char buf[ 10240 ];

    input.getline( buf, 10240 );
    if( input.gcount() > 10239 )
        ErrorMessage::errorDuringParsing( "Comment too long.");
}

void
Dimacs::readFormulaInfo(
    istream& input )
{
    char type;
    input >> type;

//    if( type == 'w' )
//    {
//        weighted = true;
//        input >> type;
//        if( type != 'c' )
//        {
//            cerr << ERRORPARSING << endl;
//            exit( 0 );
//        }
//    }
    /*else*/
    if( type != 'c' )
    {
        ErrorMessage::errorDuringParsing( "Expected a 'c'.");
    }

    input >> type;
    if( type != 'n' )
    {
        ErrorMessage::errorDuringParsing( "Expected a 'n'.");
    }

    input >> type;
    if( type != 'f' )
    {
        ErrorMessage::errorDuringParsing( "Expected a 'f'.");
    }

    input >> numberOfVariables;
    input >> numberOfClauses;

//    if( weighted )
//        input >> maxWeight;
//    else if( wasp::options.dimacsMaxsat )
//    {
//        weighted = true;
//        cnfWeighted = true;
//        maxWeight = 2;
//    }
}

void
Dimacs::readAllClauses(
    istream& input )
{
//    if( !weighted )
//    {
    trace_msg( parser, 1, "Starting iteration on " << numberOfClauses << " clauses.");
    for( unsigned int i = 0; i < numberOfClauses; i++ )
    {
        readClause( input );
    }
//    }
//    else if( !cnfWeighted )
//    {
//        for( unsigned int i = 0; i < numberOfClauses; i++ )
//        {
//            readClauseWeighted( input );
//        }
//    }
//    else
//    {
//        for( unsigned int i = 0; i < numberOfClauses; i++ )
//        {
//            readClauseCnfWeighted( input );
//        }
//    }

//    for( unsigned int i = 1; i <= numberOfVariables; i++ )
//    {
//        if( variablesAppearingWithBothPolarity.find( i ) == variablesAppearingWithBothPolarity.end() )
//        {
//            if( readVariables.find( i ) != readVariables.end() )
//            {
//                programBuilder->addTrueSupportedAtom( i );
//            }
//            else
//            {
//                programBuilder->addFalseAtom( i );
//            }
//        }
//    }
}

void
Dimacs::readClause(
    istream& input )
{
    unordered_set< int > tempSet;

    bool trivial = false;

    Clause* clause = new Clause();

    //a variable containing the literal to read
    int next;

    //read the next literal
    input >> next;

    if( next == 0 )
    {
        ErrorMessage::errorDuringParsing( "Empty clause are not allowed.");
    }

    //storing the first literal in case the clause is unary.
    int firstLiteral = next;
    do
    {
        assert( next != 0 );

        //insert the current literal in the set
        tempSet.insert( next );

        //if the opposite literal was already in the set the clause is a tautology
        if( tempSet.find( -next ) != tempSet.end() )
            trivial = true;

        //add the literal in the clause
        clause->addLiteral( solver.getLiteral( next ) );

        //read the next literal
        input >> next;

      //do while next is not 0
    } while( next != 0 );

    if( clause->size() == 1 )
    {
        assert( firstLiteral != 0 );
        trivial = true;
        if( addedLiterals.insert( firstLiteral ).second )
        {
            trace_msg( parser, 2, "Unary clause with literal " << firstLiteral << ". Adding literal to the solver." );
            solver.addTrueLiteral( solver.getLiteral( firstLiteral ) );
        }
        else
        {
            trace_msg( parser, 2, "Found duplicated unary clause with literal " << firstLiteral << ". Skipping this clause." );
        }
    }

    //if the clause is not trivial add it in the formula
    if( !trivial )
    {
        trace_msg( parser, 1, "Adding clause " << *clause << " in solver.");
        solver.addClause( clause );
        clause->attachClause();
    }
    else
    {
        trace_msg( parser, 1, "Deleting clause " << *clause << " because is trivial." );
        delete clause;
    }
}
//
//void
//DimacsFormat::readClauseWeighted(
//    istream& input )
//{
//    unordered_set< int > tempSet;
//    unsigned int weight;
//    input >> weight;
//
//    if( weight == maxWeight )
//    {
//        readClause( input );
//        return;
//    }
//
//    List< int > clause;
//    bool trivial = false;
//
//    int next;
//    input >> next;
//    do
//    {
//        assert( next != 0 );
//
//        tempSet.insert( next );
//
//        if( tempSet.find( -next ) != tempSet.end() )
//            trivial = true;
//
//        //Change polarity
//        clause.push_back( -next );
//        input >> next;
//    } while( next != 0 );
//
//    if( trivial )
//        return;
//
//    WeakConstraint* w;
//    if( wasp::options.weakConstraintsHeuristic || clause.size() == 1 )
//        w = programBuilder->startWeakConstraint( clause.size() + 1, weight, 1 );
//    else
//        w = programBuilder->startWeakConstraint( clause.size(), weight, 1 );
//
//    while( !clause.empty() )
//    {
//        int id = clause.front();
//        if( readVariables.find( id ) != readVariables.end() )
//            variablesAppearingWithBothPolarity.insert( abs( id ) );
//        readVariables.insert( -id );
//
//        if( id < 0 )
//            programBuilder->addLiteralInWeakConstraint( w, -id, false );
//        else
//            programBuilder->addLiteralInWeakConstraint( w, id, true );
//        clause.pop_front();
//    }
//    programBuilder->endWeakConstraint( w );
//
//    assert( clause.empty() );
//}
//
//void
//DimacsFormat::readClauseCnfWeighted(
//    istream& input )
//{
//    List< int > clause;
//    bool trivial = false;
//    unordered_set< int > tempSet;
//
//    int next;
//    input >> next;
//    do
//    {
//        assert( next != 0 );
//
//        tempSet.insert( next );
//
//        if( tempSet.find( -next ) != tempSet.end() )
//            trivial = true;
//
//        //Change polarity
//        clause.push_back( -next );
//        input >> next;
//    } while( next != 0 );
//
//    if( trivial )
//        return;
//
//    WeakConstraint* w;
//    if( wasp::options.weakConstraintsHeuristic || clause.size() == 1 )
//        w = programBuilder->startWeakConstraint( clause.size() + 1, 1, 1 );
//    else
//        w = programBuilder->startWeakConstraint( clause.size(), 1, 1 );
//
//    while( !clause.empty() )
//    {
//        int id = clause.front();
//
//        if( readVariables.find( id ) != readVariables.end() )
//            variablesAppearingWithBothPolarity.insert( abs( id ) );
//        readVariables.insert( -id );
//
//        if( id < 0 )
//            programBuilder->addLiteralInWeakConstraint( w, -id, false );
//        else
//            programBuilder->addLiteralInWeakConstraint( w, id, true );
//        clause.pop_front();
//    }
//    programBuilder->endWeakConstraint( w );
//
//    assert( clause.empty() );
//}

void
Dimacs::insertVariables(
    unsigned int numberOfVariables )
{
    trace_msg( parser, 1, "Adding " << numberOfVariables << " variables." );
    for( unsigned int i = 1; i <= numberOfVariables; i++ )
    {
        stringstream ss;
        ss << i;
        solver.addVariable( ss.str() );
    }
}
<|endoftext|>


<commit_before>//===- unittests/Driver/MultilibTest.cpp --- Multilib tests ---------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Unit tests for Multilib and MultilibSet
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/Multilib.h"
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "gtest/gtest.h"

using namespace clang::driver;
using namespace clang;

TEST(MultilibTest, MultilibValidity) {

  ASSERT_TRUE(Multilib().isValid()) << "Empty multilib is not valid";

  ASSERT_TRUE(Multilib().flag("+foo").isValid())
      << "Single indicative flag is not valid";

  ASSERT_TRUE(Multilib().flag("-foo").isValid())
      << "Single contraindicative flag is not valid";

  ASSERT_FALSE(Multilib().flag("+foo").flag("-foo").isValid())
      << "Conflicting flags should invalidate the Multilib";

  ASSERT_TRUE(Multilib().flag("+foo").flag("+foo").isValid())
      << "Multilib should be valid even if it has the same flag twice";

  ASSERT_TRUE(Multilib().flag("+foo").flag("-foobar").isValid())
      << "Seemingly conflicting prefixes shouldn't actually conflict";
}

TEST(MultilibTest, OpEqReflexivity1) {
  Multilib M;
  ASSERT_TRUE(M == M) << "Multilib::operator==() is not reflexive";
}

TEST(MultilibTest, OpEqReflexivity2) {
  ASSERT_TRUE(Multilib() == Multilib())
      << "Separately constructed default multilibs are not equal";
}

TEST(MultilibTest, OpEqReflexivity3) {
  Multilib M1, M2;
  M1.flag("+foo");
  M2.flag("+foo");
  ASSERT_TRUE(M1 == M2) << "Multilibs with the same flag should be the same";
}

TEST(MultilibTest, OpEqInequivalence1) {
  Multilib M1, M2;
  M1.flag("+foo");
  M2.flag("-foo");
  ASSERT_FALSE(M1 == M2) << "Multilibs with conflicting flags are not the same";
  ASSERT_FALSE(M2 == M1)
      << "Multilibs with conflicting flags are not the same (commuted)";
}

TEST(MultilibTest, OpEqInequivalence2) {
  Multilib M1, M2;
  M2.flag("+foo");
  ASSERT_FALSE(M1 == M2) << "Flags make Multilibs different";
}

TEST(MultilibTest, OpEqEquivalence1) {
  Multilib M1, M2;
  M1.flag("+foo");
  M2.flag("+foo").flag("+foo");
  ASSERT_TRUE(M1 == M2) << "Flag duplication shouldn't affect equivalence";
  ASSERT_TRUE(M2 == M1)
      << "Flag duplication shouldn't affect equivalence (commuted)";
}

TEST(MultilibTest, OpEqEquivalence2) {
  Multilib M1("64");
  Multilib M2;
  M2.gccSuffix("/64");
  ASSERT_TRUE(M1 == M2)
      << "Constructor argument must match Multilib::gccSuffix()";
  ASSERT_TRUE(M2 == M1)
      << "Constructor argument must match Multilib::gccSuffix() (commuted)";
}

TEST(MultilibTest, OpEqEquivalence3) {
  Multilib M1("", "32");
  Multilib M2;
  M2.osSuffix("/32");
  ASSERT_TRUE(M1 == M2)
      << "Constructor argument must match Multilib::osSuffix()";
  ASSERT_TRUE(M2 == M1)
      << "Constructor argument must match Multilib::osSuffix() (commuted)";
}

TEST(MultilibTest, OpEqEquivalence4) {
  Multilib M1("", "", "16");
  Multilib M2;
  M2.includeSuffix("/16");
  ASSERT_TRUE(M1 == M2)
      << "Constructor argument must match Multilib::includeSuffix()";
  ASSERT_TRUE(M2 == M1)
      << "Constructor argument must match Multilib::includeSuffix() (commuted)";
}

TEST(MultilibTest, OpEqInequivalence3) {
  Multilib M1("foo");
  Multilib M2("bar");
  ASSERT_FALSE(M1 == M2) << "Differing gccSuffixes should be different";
  ASSERT_FALSE(M2 == M1)
      << "Differing gccSuffixes should be different (commuted)";
}

TEST(MultilibTest, OpEqInequivalence4) {
  Multilib M1("", "foo");
  Multilib M2("", "bar");
  ASSERT_FALSE(M1 == M2) << "Differing osSuffixes should be different";
  ASSERT_FALSE(M2 == M1)
      << "Differing osSuffixes should be different (commuted)";
}

TEST(MultilibTest, OpEqInequivalence5) {
  Multilib M1("", "", "foo");
  Multilib M2("", "", "bar");
  ASSERT_FALSE(M1 == M2) << "Differing includeSuffixes should be different";
  ASSERT_FALSE(M2 == M1)
      << "Differing includeSuffixes should be different (commuted)";
}

TEST(MultilibTest, Construction1) {
  Multilib M("gcc64", "os64", "inc64");
  ASSERT_TRUE(M.gccSuffix() == "/gcc64");
  ASSERT_TRUE(M.osSuffix() == "/os64");
  ASSERT_TRUE(M.includeSuffix() == "/inc64");
}

TEST(MultilibTest, Construction2) {
  Multilib M1;
  Multilib M2("");
  Multilib M3("", "");
  Multilib M4("", "", "");
  ASSERT_TRUE(M1 == M2)
      << "Default arguments to Multilib constructor broken (first argument)";
  ASSERT_TRUE(M1 == M3)
      << "Default arguments to Multilib constructor broken (second argument)";
  ASSERT_TRUE(M1 == M4)
      << "Default arguments to Multilib constructor broken (third argument)";
}

TEST(MultilibTest, Construction3) {
  Multilib M = Multilib().flag("+f1").flag("+f2").flag("-f3");
  for (Multilib::flags_list::const_iterator I = M.flags().begin(),
                                            E = M.flags().end();
       I != E; ++I) {
    ASSERT_TRUE(llvm::StringSwitch<bool>(*I)
                    .Cases("+f1", "+f2", "-f3", true)
                    .Default(false));
  }
}

static bool hasFlag(const Multilib &M, StringRef Flag) {
  for (Multilib::flags_list::const_iterator I = M.flags().begin(),
                                            E = M.flags().end();
       I != E; ++I) {
    if (*I == Flag)
      return true;
    else if (StringRef(*I).substr(1) == Flag.substr(1))
      return false;
  }
  return false;
}

TEST(MultilibTest, SetConstruction1) {
  // Single maybe
  MultilibSet MS;
  ASSERT_TRUE(MS.size() == 0);
  MS.Maybe(Multilib("64").flag("+m64"));
  ASSERT_TRUE(MS.size() == 2);
  for (MultilibSet::const_iterator I = MS.begin(), E = MS.end(); I != E; ++I) {
    if (I->gccSuffix() == "/64")
      ASSERT_TRUE(I->flags()[0] == "+m64");
    else if (I->gccSuffix() == "")
      ASSERT_TRUE(I->flags()[0] == "-m64");
    else
      FAIL() << "Unrecognized gccSufix: " << I->gccSuffix();
  }
}

TEST(MultilibTest, SetConstruction2) {
  // Double maybe
  MultilibSet MS;
  MS.Maybe(Multilib("sof").flag("+sof"));
  MS.Maybe(Multilib("el").flag("+EL"));
  ASSERT_TRUE(MS.size() == 4);
  for (MultilibSet::const_iterator I = MS.begin(), E = MS.end(); I != E; ++I) {
    ASSERT_TRUE(I->isValid()) << "Multilb " << *I << " should be valid";
    ASSERT_TRUE(llvm::StringSwitch<bool>(I->gccSuffix())
                    .Cases("", "/sof", "/el", "/sof/el", true)
                    .Default(false))
        << "Multilib " << *I << " wasn't expected";
    ASSERT_TRUE(llvm::StringSwitch<bool>(I->gccSuffix())
                    .Case("", hasFlag(*I, "-sof"))
                    .Case("/sof", hasFlag(*I, "+sof"))
                    .Case("/el", hasFlag(*I, "-sof"))
                    .Case("/sof/el", hasFlag(*I, "+sof"))
                    .Default(false))
        << "Multilib " << *I << " didn't have the appropriate {+,-}sof flag";
    ASSERT_TRUE(llvm::StringSwitch<bool>(I->gccSuffix())
                    .Case("", hasFlag(*I, "-EL"))
                    .Case("/sof", hasFlag(*I, "-EL"))
                    .Case("/el", hasFlag(*I, "+EL"))
                    .Case("/sof/el", hasFlag(*I, "+EL"))
                    .Default(false))
        << "Multilib " << *I << " didn't have the appropriate {+,-}EL flag";
  }
}

TEST(MultilibTest, SetPushback) {
  MultilibSet MS;
  MS.push_back(Multilib("one"));
  MS.push_back(Multilib("two"));
  ASSERT_TRUE(MS.size() == 2);
  for (MultilibSet::const_iterator I = MS.begin(), E = MS.end(); I != E; ++I) {
    ASSERT_TRUE(llvm::StringSwitch<bool>(I->gccSuffix())
                    .Cases("/one", "/two", true)
                    .Default(false));
  }
  MS.clear();
  ASSERT_TRUE(MS.size() == 0);
}

TEST(MultilibTest, SetRegexFilter) {
  MultilibSet MS;
  MS.Maybe(Multilib("one"));
  MS.Maybe(Multilib("two"));
  MS.Maybe(Multilib("three"));
  ASSERT_EQ(MS.size(), (unsigned)2 * 2 * 2)
      << "Size before filter was incorrect. Contents:\n" << MS;
  MS.FilterOut("/one/two/three");
  ASSERT_EQ(MS.size(), (unsigned)2 * 2 * 2 - 1)
      << "Size after filter was incorrect. Contents:\n" << MS;
  for (MultilibSet::const_iterator I = MS.begin(), E = MS.end(); I != E; ++I) {
    ASSERT_TRUE(I->gccSuffix() != "/one/two/three")
        << "The filter should have removed " << *I;
  }
}

TEST(MultilibTest, SetFilterObject) {
  // Filter object
  struct StartsWithP : public MultilibSet::FilterCallback {
    bool operator()(const Multilib &M) const override {
      return StringRef(M.gccSuffix()).startswith("/p");
    }
  };
  MultilibSet MS;
  MS.Maybe(Multilib("orange"));
  MS.Maybe(Multilib("pear"));
  MS.Maybe(Multilib("plum"));
  ASSERT_EQ((int)MS.size(), 1 /* Default */ +
                            1 /* pear */ +
                            1 /* plum */ +
                            1 /* pear/plum */ +
                            1 /* orange */ +
                            1 /* orange/pear */ +
                            1 /* orange/plum */ +
                            1 /* orange/pear/plum */ )
      << "Size before filter was incorrect. Contents:\n" << MS;
  MS.FilterOut(StartsWithP());
  ASSERT_EQ((int)MS.size(), 1 /* Default */ +
                            1 /* orange */ +
                            1 /* orange/pear */ +
                            1 /* orange/plum */ +
                            1 /* orange/pear/plum */ )
      << "Size after filter was incorrect. Contents:\n" << MS;
  for (MultilibSet::const_iterator I = MS.begin(), E = MS.end(); I != E; ++I) {
    ASSERT_FALSE(StringRef(I->gccSuffix()).startswith("/p"))
        << "The filter should have removed " << *I;
  }
}

TEST(MultilibTest, SetSelection1) {
  MultilibSet MS1 = MultilibSet()
    .Maybe(Multilib("64").flag("+m64"));

  Multilib::flags_list FlagM64;
  FlagM64.push_back("+m64");
  Multilib SelectionM64;
  ASSERT_TRUE(MS1.select(FlagM64, SelectionM64))
      << "Flag set was {\"+m64\"}, but selection not found";
  ASSERT_TRUE(SelectionM64.gccSuffix() == "/64")
      << "Selection picked " << SelectionM64 << " which was not expected";

  Multilib::flags_list FlagNoM64;
  FlagNoM64.push_back("-m64");
  Multilib SelectionNoM64;
  ASSERT_TRUE(MS1.select(FlagNoM64, SelectionNoM64))
      << "Flag set was {\"-m64\"}, but selection not found";
  ASSERT_TRUE(SelectionNoM64.gccSuffix() == "")
      << "Selection picked " << SelectionNoM64 << " which was not expected";
}

TEST(MultilibTest, SetSelection2) {
  MultilibSet MS2 = MultilibSet()
    .Maybe(Multilib("el").flag("+EL"))
    .Maybe(Multilib("sf").flag("+SF"));

  for (unsigned I = 0; I < 4; ++I) {
    bool IsEL = I & 0x1;
    bool IsSF = I & 0x2;
    Multilib::flags_list Flags;
    if (IsEL)
      Flags.push_back("+EL");
    else
      Flags.push_back("-EL");

    if (IsSF)
      Flags.push_back("+SF");
    else
      Flags.push_back("-SF");

    Multilib Selection;
    ASSERT_TRUE(MS2.select(Flags, Selection)) << "Selection failed for "
                                              << (IsEL ? "+EL" : "-EL") << " "
                                              << (IsSF ? "+SF" : "-SF");

    std::string Suffix;
    if (IsEL)
      Suffix += "/el";
    if (IsSF)
      Suffix += "/sf";

    ASSERT_EQ(Selection.gccSuffix(), Suffix) << "Selection picked " << Selection
                                             << " which was not expected ";
  }
}

TEST(MultilibTest, SetCombineWith) {
  MultilibSet Coffee;
  Coffee.push_back(Multilib("coffee"));
  MultilibSet Milk;
  Milk.push_back(Multilib("milk"));
  MultilibSet Latte;
  ASSERT_EQ(Latte.size(), (unsigned)0);
  Latte.combineWith(Coffee);
  ASSERT_EQ(Latte.size(), (unsigned)1);
  Latte.combineWith(Milk);
  ASSERT_EQ(Latte.size(), (unsigned)2);
}
<commit_msg>Update unit test for r232916.<commit_after>//===- unittests/Driver/MultilibTest.cpp --- Multilib tests ---------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Unit tests for Multilib and MultilibSet
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/Multilib.h"
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "gtest/gtest.h"

using namespace clang::driver;
using namespace clang;

TEST(MultilibTest, MultilibValidity) {

  ASSERT_TRUE(Multilib().isValid()) << "Empty multilib is not valid";

  ASSERT_TRUE(Multilib().flag("+foo").isValid())
      << "Single indicative flag is not valid";

  ASSERT_TRUE(Multilib().flag("-foo").isValid())
      << "Single contraindicative flag is not valid";

  ASSERT_FALSE(Multilib().flag("+foo").flag("-foo").isValid())
      << "Conflicting flags should invalidate the Multilib";

  ASSERT_TRUE(Multilib().flag("+foo").flag("+foo").isValid())
      << "Multilib should be valid even if it has the same flag twice";

  ASSERT_TRUE(Multilib().flag("+foo").flag("-foobar").isValid())
      << "Seemingly conflicting prefixes shouldn't actually conflict";
}

TEST(MultilibTest, OpEqReflexivity1) {
  Multilib M;
  ASSERT_TRUE(M == M) << "Multilib::operator==() is not reflexive";
}

TEST(MultilibTest, OpEqReflexivity2) {
  ASSERT_TRUE(Multilib() == Multilib())
      << "Separately constructed default multilibs are not equal";
}

TEST(MultilibTest, OpEqReflexivity3) {
  Multilib M1, M2;
  M1.flag("+foo");
  M2.flag("+foo");
  ASSERT_TRUE(M1 == M2) << "Multilibs with the same flag should be the same";
}

TEST(MultilibTest, OpEqInequivalence1) {
  Multilib M1, M2;
  M1.flag("+foo");
  M2.flag("-foo");
  ASSERT_FALSE(M1 == M2) << "Multilibs with conflicting flags are not the same";
  ASSERT_FALSE(M2 == M1)
      << "Multilibs with conflicting flags are not the same (commuted)";
}

TEST(MultilibTest, OpEqInequivalence2) {
  Multilib M1, M2;
  M2.flag("+foo");
  ASSERT_FALSE(M1 == M2) << "Flags make Multilibs different";
}

TEST(MultilibTest, OpEqEquivalence1) {
  Multilib M1, M2;
  M1.flag("+foo");
  M2.flag("+foo").flag("+foo");
  ASSERT_TRUE(M1 == M2) << "Flag duplication shouldn't affect equivalence";
  ASSERT_TRUE(M2 == M1)
      << "Flag duplication shouldn't affect equivalence (commuted)";
}

TEST(MultilibTest, OpEqEquivalence2) {
  Multilib M1("64");
  Multilib M2;
  M2.gccSuffix("/64");
  ASSERT_TRUE(M1 == M2)
      << "Constructor argument must match Multilib::gccSuffix()";
  ASSERT_TRUE(M2 == M1)
      << "Constructor argument must match Multilib::gccSuffix() (commuted)";
}

TEST(MultilibTest, OpEqEquivalence3) {
  Multilib M1("", "32");
  Multilib M2;
  M2.osSuffix("/32");
  ASSERT_TRUE(M1 == M2)
      << "Constructor argument must match Multilib::osSuffix()";
  ASSERT_TRUE(M2 == M1)
      << "Constructor argument must match Multilib::osSuffix() (commuted)";
}

TEST(MultilibTest, OpEqEquivalence4) {
  Multilib M1("", "", "16");
  Multilib M2;
  M2.includeSuffix("/16");
  ASSERT_TRUE(M1 == M2)
      << "Constructor argument must match Multilib::includeSuffix()";
  ASSERT_TRUE(M2 == M1)
      << "Constructor argument must match Multilib::includeSuffix() (commuted)";
}

TEST(MultilibTest, OpEqInequivalence3) {
  Multilib M1("foo");
  Multilib M2("bar");
  ASSERT_FALSE(M1 == M2) << "Differing gccSuffixes should be different";
  ASSERT_FALSE(M2 == M1)
      << "Differing gccSuffixes should be different (commuted)";
}

TEST(MultilibTest, OpEqInequivalence4) {
  Multilib M1("", "foo");
  Multilib M2("", "bar");
  ASSERT_FALSE(M1 == M2) << "Differing osSuffixes should be different";
  ASSERT_FALSE(M2 == M1)
      << "Differing osSuffixes should be different (commuted)";
}

TEST(MultilibTest, OpEqInequivalence5) {
  Multilib M1("", "", "foo");
  Multilib M2("", "", "bar");
  ASSERT_FALSE(M1 == M2) << "Differing includeSuffixes should be different";
  ASSERT_FALSE(M2 == M1)
      << "Differing includeSuffixes should be different (commuted)";
}

TEST(MultilibTest, Construction1) {
  Multilib M("gcc64", "os64", "inc64");
  ASSERT_TRUE(M.gccSuffix() == "/gcc64");
  ASSERT_TRUE(M.osSuffix() == "/os64");
  ASSERT_TRUE(M.includeSuffix() == "/inc64");
}

TEST(MultilibTest, Construction2) {
  Multilib M1;
  Multilib M2("");
  Multilib M3("", "");
  Multilib M4("", "", "");
  ASSERT_TRUE(M1 == M2)
      << "Default arguments to Multilib constructor broken (first argument)";
  ASSERT_TRUE(M1 == M3)
      << "Default arguments to Multilib constructor broken (second argument)";
  ASSERT_TRUE(M1 == M4)
      << "Default arguments to Multilib constructor broken (third argument)";
}

TEST(MultilibTest, Construction3) {
  Multilib M = Multilib().flag("+f1").flag("+f2").flag("-f3");
  for (Multilib::flags_list::const_iterator I = M.flags().begin(),
                                            E = M.flags().end();
       I != E; ++I) {
    ASSERT_TRUE(llvm::StringSwitch<bool>(*I)
                    .Cases("+f1", "+f2", "-f3", true)
                    .Default(false));
  }
}

static bool hasFlag(const Multilib &M, StringRef Flag) {
  for (Multilib::flags_list::const_iterator I = M.flags().begin(),
                                            E = M.flags().end();
       I != E; ++I) {
    if (*I == Flag)
      return true;
    else if (StringRef(*I).substr(1) == Flag.substr(1))
      return false;
  }
  return false;
}

TEST(MultilibTest, SetConstruction1) {
  // Single maybe
  MultilibSet MS;
  ASSERT_TRUE(MS.size() == 0);
  MS.Maybe(Multilib("64").flag("+m64"));
  ASSERT_TRUE(MS.size() == 2);
  for (MultilibSet::const_iterator I = MS.begin(), E = MS.end(); I != E; ++I) {
    if (I->gccSuffix() == "/64")
      ASSERT_TRUE(I->flags()[0] == "+m64");
    else if (I->gccSuffix() == "")
      ASSERT_TRUE(I->flags()[0] == "-m64");
    else
      FAIL() << "Unrecognized gccSufix: " << I->gccSuffix();
  }
}

TEST(MultilibTest, SetConstruction2) {
  // Double maybe
  MultilibSet MS;
  MS.Maybe(Multilib("sof").flag("+sof"));
  MS.Maybe(Multilib("el").flag("+EL"));
  ASSERT_TRUE(MS.size() == 4);
  for (MultilibSet::const_iterator I = MS.begin(), E = MS.end(); I != E; ++I) {
    ASSERT_TRUE(I->isValid()) << "Multilb " << *I << " should be valid";
    ASSERT_TRUE(llvm::StringSwitch<bool>(I->gccSuffix())
                    .Cases("", "/sof", "/el", "/sof/el", true)
                    .Default(false))
        << "Multilib " << *I << " wasn't expected";
    ASSERT_TRUE(llvm::StringSwitch<bool>(I->gccSuffix())
                    .Case("", hasFlag(*I, "-sof"))
                    .Case("/sof", hasFlag(*I, "+sof"))
                    .Case("/el", hasFlag(*I, "-sof"))
                    .Case("/sof/el", hasFlag(*I, "+sof"))
                    .Default(false))
        << "Multilib " << *I << " didn't have the appropriate {+,-}sof flag";
    ASSERT_TRUE(llvm::StringSwitch<bool>(I->gccSuffix())
                    .Case("", hasFlag(*I, "-EL"))
                    .Case("/sof", hasFlag(*I, "-EL"))
                    .Case("/el", hasFlag(*I, "+EL"))
                    .Case("/sof/el", hasFlag(*I, "+EL"))
                    .Default(false))
        << "Multilib " << *I << " didn't have the appropriate {+,-}EL flag";
  }
}

TEST(MultilibTest, SetPushback) {
  MultilibSet MS;
  MS.push_back(Multilib("one"));
  MS.push_back(Multilib("two"));
  ASSERT_TRUE(MS.size() == 2);
  for (MultilibSet::const_iterator I = MS.begin(), E = MS.end(); I != E; ++I) {
    ASSERT_TRUE(llvm::StringSwitch<bool>(I->gccSuffix())
                    .Cases("/one", "/two", true)
                    .Default(false));
  }
  MS.clear();
  ASSERT_TRUE(MS.size() == 0);
}

TEST(MultilibTest, SetRegexFilter) {
  MultilibSet MS;
  MS.Maybe(Multilib("one"));
  MS.Maybe(Multilib("two"));
  MS.Maybe(Multilib("three"));
  ASSERT_EQ(MS.size(), (unsigned)2 * 2 * 2)
      << "Size before filter was incorrect. Contents:\n" << MS;
  MS.FilterOut("/one/two/three");
  ASSERT_EQ(MS.size(), (unsigned)2 * 2 * 2 - 1)
      << "Size after filter was incorrect. Contents:\n" << MS;
  for (MultilibSet::const_iterator I = MS.begin(), E = MS.end(); I != E; ++I) {
    ASSERT_TRUE(I->gccSuffix() != "/one/two/three")
        << "The filter should have removed " << *I;
  }
}

TEST(MultilibTest, SetFilterObject) {
  MultilibSet MS;
  MS.Maybe(Multilib("orange"));
  MS.Maybe(Multilib("pear"));
  MS.Maybe(Multilib("plum"));
  ASSERT_EQ((int)MS.size(), 1 /* Default */ +
                            1 /* pear */ +
                            1 /* plum */ +
                            1 /* pear/plum */ +
                            1 /* orange */ +
                            1 /* orange/pear */ +
                            1 /* orange/plum */ +
                            1 /* orange/pear/plum */ )
      << "Size before filter was incorrect. Contents:\n" << MS;
  MS.FilterOut([](const Multilib &M) {
    return StringRef(M.gccSuffix()).startswith("/p");
  });
  ASSERT_EQ((int)MS.size(), 1 /* Default */ +
                            1 /* orange */ +
                            1 /* orange/pear */ +
                            1 /* orange/plum */ +
                            1 /* orange/pear/plum */ )
      << "Size after filter was incorrect. Contents:\n" << MS;
  for (MultilibSet::const_iterator I = MS.begin(), E = MS.end(); I != E; ++I) {
    ASSERT_FALSE(StringRef(I->gccSuffix()).startswith("/p"))
        << "The filter should have removed " << *I;
  }
}

TEST(MultilibTest, SetSelection1) {
  MultilibSet MS1 = MultilibSet()
    .Maybe(Multilib("64").flag("+m64"));

  Multilib::flags_list FlagM64;
  FlagM64.push_back("+m64");
  Multilib SelectionM64;
  ASSERT_TRUE(MS1.select(FlagM64, SelectionM64))
      << "Flag set was {\"+m64\"}, but selection not found";
  ASSERT_TRUE(SelectionM64.gccSuffix() == "/64")
      << "Selection picked " << SelectionM64 << " which was not expected";

  Multilib::flags_list FlagNoM64;
  FlagNoM64.push_back("-m64");
  Multilib SelectionNoM64;
  ASSERT_TRUE(MS1.select(FlagNoM64, SelectionNoM64))
      << "Flag set was {\"-m64\"}, but selection not found";
  ASSERT_TRUE(SelectionNoM64.gccSuffix() == "")
      << "Selection picked " << SelectionNoM64 << " which was not expected";
}

TEST(MultilibTest, SetSelection2) {
  MultilibSet MS2 = MultilibSet()
    .Maybe(Multilib("el").flag("+EL"))
    .Maybe(Multilib("sf").flag("+SF"));

  for (unsigned I = 0; I < 4; ++I) {
    bool IsEL = I & 0x1;
    bool IsSF = I & 0x2;
    Multilib::flags_list Flags;
    if (IsEL)
      Flags.push_back("+EL");
    else
      Flags.push_back("-EL");

    if (IsSF)
      Flags.push_back("+SF");
    else
      Flags.push_back("-SF");

    Multilib Selection;
    ASSERT_TRUE(MS2.select(Flags, Selection)) << "Selection failed for "
                                              << (IsEL ? "+EL" : "-EL") << " "
                                              << (IsSF ? "+SF" : "-SF");

    std::string Suffix;
    if (IsEL)
      Suffix += "/el";
    if (IsSF)
      Suffix += "/sf";

    ASSERT_EQ(Selection.gccSuffix(), Suffix) << "Selection picked " << Selection
                                             << " which was not expected ";
  }
}

TEST(MultilibTest, SetCombineWith) {
  MultilibSet Coffee;
  Coffee.push_back(Multilib("coffee"));
  MultilibSet Milk;
  Milk.push_back(Multilib("milk"));
  MultilibSet Latte;
  ASSERT_EQ(Latte.size(), (unsigned)0);
  Latte.combineWith(Coffee);
  ASSERT_EQ(Latte.size(), (unsigned)1);
  Latte.combineWith(Milk);
  ASSERT_EQ(Latte.size(), (unsigned)2);
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <fstream>

#include <SFML/Window/Event.hpp>

#include "inputcatcher.h"
#include "datastructures.h"
#include "renderer.h"
#include "networking/clientnetworker.h"
#include "ingameelements/character.h"
#include "global_constants.h"
#include "global.h"

InputCatcher::InputCatcher()
{
    std::ifstream configfile("config.json");
    config << configfile;
    configfile.close();
}

InputCatcher::~InputCatcher()
{

}

void InputCatcher::updatekey(std::string keylabel, bool &key)
{
    int code1 = config.at(keylabel);
    int code2 = config.at(keylabel+"_alt1");
    int code3 = config.at(keylabel+"_alt2");

    if (sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(code1))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(code2))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(code3)))
    {
        key = true;
    }
    else
    {
        key = false;
    }
}

void InputCatcher::run(sf::RenderWindow &window, Gamestate &state, Networker &networker, Renderer &renderer,
                       EntityPtr myself)
{
    InputContainer heldkeys;
    heldkeys.reset();

    Player &player = state.get<Player>(myself);

    sf::Event event;
    // Go through all events that have been stacking up since last time
    while (window.pollEvent(event))
    {
        // FIXME: This newclass thing is an ugly placeholder,
        // when you replace it with a real class menu don't do it like this
        Heroclass newclass = player.heroclass;
        switch (event.type)
        {
            case sf::Event::Closed:
                window.close();
                break;

            case sf::Event::Resized:
                renderer.WINDOW_WIDTH = event.size.width;
                renderer.WINDOW_HEIGHT = event.size.height;
                renderer.resetcamera();
                break;

            case sf::Event::KeyPressed:
                switch (event.key.code)
                {
                    case sf::Keyboard::Escape:
                        window.close();
                        break;

                    case sf::Keyboard::F9:
                        // Zooming in for sprite analysis purposes
                        if (renderer.VIEWPORT_WIDTH != 960)
                        {
                            renderer.VIEWPORT_WIDTH = 960;
                        }
                        else
                        {
                            renderer.VIEWPORT_WIDTH = 300;
                        }
                        renderer.resetcamera();

                    case sf::Keyboard::Num1:
                        newclass = MCCREE;
                        break;

                    case sf::Keyboard::Num2:
                        newclass = REINHARDT;
                        break;

                    case sf::Keyboard::Num3:
                        newclass = LUCIO;
                        break;

                    default:
                        break;
                }
                if (newclass != player.heroclass)
                {
                    // Player desires a class change
                    if (state.engine.isserver)
                    {
                        player.changeclass(state, newclass);
                        networker.sendbuffer.write<uint8_t>(PLAYER_CHANGECLASS);
                        networker.sendbuffer.write<uint8_t>(state.findplayerid(player.id));
                        networker.sendbuffer.write<uint8_t>(static_cast<uint8_t>(newclass));
                    }
                    else
                    {
                        networker.sendbuffer.write<uint8_t>(PLAYER_CHANGECLASS);
                        networker.sendbuffer.write<uint8_t>(static_cast<uint8_t>(newclass));
                    }
                }
                break;

            default:
                // Ignore other events
                break;
        }
    }

    updatekey("jump", heldkeys.JUMP);
    updatekey("crouch", heldkeys.CROUCH);
    updatekey("left", heldkeys.LEFT);
    updatekey("right", heldkeys.RIGHT);
    updatekey("ability1", heldkeys.ABILITY_1);
    updatekey("ability2", heldkeys.ABILITY_2);
    updatekey("ultimate", heldkeys.ULTIMATE);
    updatekey("reload", heldkeys.RELOAD);

    if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
    {
        heldkeys.PRIMARY_FIRE = true;
    }
    if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
    {
        heldkeys.SECONDARY_FIRE = true;
    }

    if (state.exists(player.character))
    {
        Character &c = player.getcharacter(state);

        sf::Vector2f mousepos = window.mapPixelToCoords(sf::Mouse::getPosition(window));

        // Set the input for our current character
        c.setinput(state, heldkeys, mousepos.x, mousepos.y);

        // If this is a client, send the input off to the server
        if (not state.engine.isserver)
        {
            ClientNetworker &n = reinterpret_cast<ClientNetworker&>(networker);
            n.sendinput(heldkeys, mousepos.x, mousepos.y);
        }
    }
}
<commit_msg>Added hack to make game close on escape.<commit_after>#include <cstdio>
#include <fstream>

#include <SFML/Window/Event.hpp>

#include "inputcatcher.h"
#include "datastructures.h"
#include "renderer.h"
#include "networking/clientnetworker.h"
#include "ingameelements/character.h"
#include "global_constants.h"
#include "global.h"

InputCatcher::InputCatcher()
{
    std::ifstream configfile("config.json");
    config << configfile;
    configfile.close();
}

InputCatcher::~InputCatcher()
{

}

void InputCatcher::updatekey(std::string keylabel, bool &key)
{
    int code1 = config.at(keylabel);
    int code2 = config.at(keylabel+"_alt1");
    int code3 = config.at(keylabel+"_alt2");

    if (sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(code1))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(code2))
        or sf::Keyboard::isKeyPressed(static_cast<sf::Keyboard::Key>(code3)))
    {
        key = true;
    }
    else
    {
        key = false;
    }
}

void InputCatcher::run(sf::RenderWindow &window, Gamestate &state, Networker &networker, Renderer &renderer,
                       EntityPtr myself)
{
    InputContainer heldkeys;
    heldkeys.reset();

    Player &player = state.get<Player>(myself);

    sf::Event event;
    // Go through all events that have been stacking up since last time
    while (window.pollEvent(event))
    {
        // FIXME: This newclass thing is an ugly placeholder,
        // when you replace it with a real class menu don't do it like this
        Heroclass newclass = player.heroclass;
        switch (event.type)
        {
            case sf::Event::Closed:
                window.close();
                Global::logging().panic(__FILE__, __LINE__, "Game closed.");
                break;

            case sf::Event::Resized:
                renderer.WINDOW_WIDTH = event.size.width;
                renderer.WINDOW_HEIGHT = event.size.height;
                renderer.resetcamera();
                break;

            case sf::Event::KeyPressed:
                switch (event.key.code)
                {
                    case sf::Keyboard::Escape:
                        window.close();
                        Global::logging().panic(__FILE__, __LINE__, "Game closed.");
                        break;

                    case sf::Keyboard::F9:
                        // Zooming in for sprite analysis purposes
                        if (renderer.VIEWPORT_WIDTH != 960)
                        {
                            renderer.VIEWPORT_WIDTH = 960;
                        }
                        else
                        {
                            renderer.VIEWPORT_WIDTH = 300;
                        }
                        renderer.resetcamera();

                    case sf::Keyboard::Num1:
                        newclass = MCCREE;
                        break;

                    case sf::Keyboard::Num2:
                        newclass = REINHARDT;
                        break;

                    case sf::Keyboard::Num3:
                        newclass = LUCIO;
                        break;

                    default:
                        break;
                }
                if (newclass != player.heroclass)
                {
                    // Player desires a class change
                    if (state.engine.isserver)
                    {
                        player.changeclass(state, newclass);
                        networker.sendbuffer.write<uint8_t>(PLAYER_CHANGECLASS);
                        networker.sendbuffer.write<uint8_t>(state.findplayerid(player.id));
                        networker.sendbuffer.write<uint8_t>(static_cast<uint8_t>(newclass));
                    }
                    else
                    {
                        networker.sendbuffer.write<uint8_t>(PLAYER_CHANGECLASS);
                        networker.sendbuffer.write<uint8_t>(static_cast<uint8_t>(newclass));
                    }
                }
                break;

            default:
                // Ignore other events
                break;
        }
    }

    updatekey("jump", heldkeys.JUMP);
    updatekey("crouch", heldkeys.CROUCH);
    updatekey("left", heldkeys.LEFT);
    updatekey("right", heldkeys.RIGHT);
    updatekey("ability1", heldkeys.ABILITY_1);
    updatekey("ability2", heldkeys.ABILITY_2);
    updatekey("ultimate", heldkeys.ULTIMATE);
    updatekey("reload", heldkeys.RELOAD);

    if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
    {
        heldkeys.PRIMARY_FIRE = true;
    }
    if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
    {
        heldkeys.SECONDARY_FIRE = true;
    }

    if (state.exists(player.character))
    {
        Character &c = player.getcharacter(state);

        sf::Vector2f mousepos = window.mapPixelToCoords(sf::Mouse::getPosition(window));

        // Set the input for our current character
        c.setinput(state, heldkeys, mousepos.x, mousepos.y);

        // If this is a client, send the input off to the server
        if (not state.engine.isserver)
        {
            ClientNetworker &n = reinterpret_cast<ClientNetworker&>(networker);
            n.sendinput(heldkeys, mousepos.x, mousepos.y);
        }
    }
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "profilehighlighter.h"

#include <QtCore/QRegExp>
#include <QtGui/QColor>
#include <QtGui/QTextDocument>
#include <QtGui/QTextEdit>

using namespace Qt4ProjectManager::Internal;

const char *const variables[] = {
    "CCFLAG",
    "CONFIG",
    "DEFINES",
    "DEF_FILE",
    "DEPENDPATH",
    "DEPLOYMENT",
    "DESTDIR",
    "DESTDIR_TARGET",
    "DISTFILES",
    "DLLDESTDIR",
    "FORMS",
    "HEADERS",
    "ICON",
    "INCLUDEPATH",
    "INSTALLS",
    "LEXSOURCES",
    "LIBS",
    "MAKEFILE",
    "MOC_DIR",
    "OBJECTIVE_HEADERS",
    "OBJECTIVE_SOURCES",
    "OBJECTS",
    "OBJECTS_DIR",
    "OBJMOC",
    "OTHER_FILES",
    "PKGCONFIG",
    "POST_TARGETDEPS",
    "PRECOMPILED_HEADER",
    "PRE_TARGETDEPS",
    "QMAKE",
    "QMAKESPEC",
    "QT",
    "RCC_DIR",
    "RC_FILE",
    "REQUIRES",
    "RESOURCES",
    "RES_FILE",
    "SOURCES",
    "SRCMOC",
    "STATECHARTS",
    "SUBDIRS",
    "TARGET",
    "TARGET.CAPABILITY",
    "TARGET.EPOCHEAPSIZE",
    "TARGET.UID3",
    "TARGET_EXT",
    "TARGET_x",
    "TARGET_x.y.z",
    "TEMPLATE",
    "TRANSLATIONS",
    "UI_DIR",
    "UI_HEADERS_DIR",
    "UI_SOURCES_DIR",
    "VER_MAJ",
    "VER_MIN",
    "VER_PAT",
    "VERSION",
    "VPATH",
    "YACCSOURCES",
    0
};

const char *const functions[] = {
    "basename",
    "CONFIG",
    "contains",
    "count",
    "dirname",
    "error",
    "exists",
    "find",
    "for",
    "include",
    "infile",
    "isEmpty",
    "join",
    "member",
    "message",
    "prompt",
    "quote",
    "sprintf",
    "system",
    "unique",
    "warning",
    0
};

struct KeywordHelper
{
    inline KeywordHelper(const QString &word) : needle(word) {}
    const QString needle;
};

static bool operator<(const KeywordHelper &helper, const char *kw)
{
    return helper.needle < QLatin1String(kw);
}

static bool operator<(const char *kw, const KeywordHelper &helper)
{
    return QLatin1String(kw) < helper.needle;
}

static bool isVariable(const QString &word)
{
    const char *const *start = &variables[0];
    const char *const *end = &variables[sizeof variables / sizeof variables[0] - 1];
    const char *const *kw = qBinaryFind(start, end, KeywordHelper(word));
    return *kw != 0;
}

static bool isFunction(const QString &word)
{
    const char *const *start = &functions[0];
    const char *const *end = &functions[sizeof functions / sizeof functions[0] - 1];
    const char *const *kw = qBinaryFind(start, end, KeywordHelper(word));
    return *kw != 0;
}

ProFileHighlighter::ProFileHighlighter(QTextDocument *document) :
    QSyntaxHighlighter(document)
{
}

void ProFileHighlighter::highlightBlock(const QString &text)
{
    if (text.isEmpty())
        return;

    QString buf;
    bool inCommentMode = false;

    QTextCharFormat emptyFormat;
    int i = 0;
    for (;;) {
        const QChar c = text.at(i);
        if (inCommentMode) {
            setFormat(i, 1, m_formats[ProfileCommentFormat]);
        } else {
            if (c.isLetter() || c == '_' || c == '.' || c.isDigit()) {
                buf += c;
                setFormat(i - buf.length()+1, buf.length(), emptyFormat);
                if (!buf.isEmpty() && isFunction(buf))
                    setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileFunctionFormat]);
                else if (!buf.isEmpty() && isVariable(buf))
                    setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileVariableFormat]);
            } else if (c == '(') {
                if (!buf.isEmpty() && isFunction(buf))
                    setFormat(i - buf.length(), buf.length(), m_formats[ProfileFunctionFormat]);
                buf.clear();
            } else if (c == '#') {
                inCommentMode = true;
                setFormat(i, 1, m_formats[ProfileCommentFormat]);
                buf.clear();
            } else {
                if (!buf.isEmpty() && isVariable(buf))
                    setFormat(i - buf.length(), buf.length(), m_formats[ProfileVariableFormat]);
                buf.clear();
            }
        }
        i++;
        if (i >= text.length())
            break;
    }
}

<commit_msg>Add variable "MOBILITY" to be highlighted.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "profilehighlighter.h"

#include <QtCore/QRegExp>
#include <QtGui/QColor>
#include <QtGui/QTextDocument>
#include <QtGui/QTextEdit>

using namespace Qt4ProjectManager::Internal;

const char *const variables[] = {
    "CCFLAG",
    "CONFIG",
    "DEFINES",
    "DEF_FILE",
    "DEPENDPATH",
    "DEPLOYMENT",
    "DESTDIR",
    "DESTDIR_TARGET",
    "DISTFILES",
    "DLLDESTDIR",
    "FORMS",
    "HEADERS",
    "ICON",
    "INCLUDEPATH",
    "INSTALLS",
    "LEXSOURCES",
    "LIBS",
    "MAKEFILE",
    "MOBILITY",
    "MOC_DIR",
    "OBJECTIVE_HEADERS",
    "OBJECTIVE_SOURCES",
    "OBJECTS",
    "OBJECTS_DIR",
    "OBJMOC",
    "OTHER_FILES",
    "PKGCONFIG",
    "POST_TARGETDEPS",
    "PRECOMPILED_HEADER",
    "PRE_TARGETDEPS",
    "QMAKE",
    "QMAKESPEC",
    "QT",
    "RCC_DIR",
    "RC_FILE",
    "REQUIRES",
    "RESOURCES",
    "RES_FILE",
    "SOURCES",
    "SRCMOC",
    "STATECHARTS",
    "SUBDIRS",
    "TARGET",
    "TARGET.CAPABILITY",
    "TARGET.EPOCHEAPSIZE",
    "TARGET.UID3",
    "TARGET_EXT",
    "TARGET_x",
    "TARGET_x.y.z",
    "TEMPLATE",
    "TRANSLATIONS",
    "UI_DIR",
    "UI_HEADERS_DIR",
    "UI_SOURCES_DIR",
    "VER_MAJ",
    "VER_MIN",
    "VER_PAT",
    "VERSION",
    "VPATH",
    "YACCSOURCES",
    0
};

const char *const functions[] = {
    "basename",
    "CONFIG",
    "contains",
    "count",
    "dirname",
    "error",
    "exists",
    "find",
    "for",
    "include",
    "infile",
    "isEmpty",
    "join",
    "member",
    "message",
    "prompt",
    "quote",
    "sprintf",
    "system",
    "unique",
    "warning",
    0
};

struct KeywordHelper
{
    inline KeywordHelper(const QString &word) : needle(word) {}
    const QString needle;
};

static bool operator<(const KeywordHelper &helper, const char *kw)
{
    return helper.needle < QLatin1String(kw);
}

static bool operator<(const char *kw, const KeywordHelper &helper)
{
    return QLatin1String(kw) < helper.needle;
}

static bool isVariable(const QString &word)
{
    const char *const *start = &variables[0];
    const char *const *end = &variables[sizeof variables / sizeof variables[0] - 1];
    const char *const *kw = qBinaryFind(start, end, KeywordHelper(word));
    return *kw != 0;
}

static bool isFunction(const QString &word)
{
    const char *const *start = &functions[0];
    const char *const *end = &functions[sizeof functions / sizeof functions[0] - 1];
    const char *const *kw = qBinaryFind(start, end, KeywordHelper(word));
    return *kw != 0;
}

ProFileHighlighter::ProFileHighlighter(QTextDocument *document) :
    QSyntaxHighlighter(document)
{
}

void ProFileHighlighter::highlightBlock(const QString &text)
{
    if (text.isEmpty())
        return;

    QString buf;
    bool inCommentMode = false;

    QTextCharFormat emptyFormat;
    int i = 0;
    for (;;) {
        const QChar c = text.at(i);
        if (inCommentMode) {
            setFormat(i, 1, m_formats[ProfileCommentFormat]);
        } else {
            if (c.isLetter() || c == '_' || c == '.' || c.isDigit()) {
                buf += c;
                setFormat(i - buf.length()+1, buf.length(), emptyFormat);
                if (!buf.isEmpty() && isFunction(buf))
                    setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileFunctionFormat]);
                else if (!buf.isEmpty() && isVariable(buf))
                    setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileVariableFormat]);
            } else if (c == '(') {
                if (!buf.isEmpty() && isFunction(buf))
                    setFormat(i - buf.length(), buf.length(), m_formats[ProfileFunctionFormat]);
                buf.clear();
            } else if (c == '#') {
                inCommentMode = true;
                setFormat(i, 1, m_formats[ProfileCommentFormat]);
                buf.clear();
            } else {
                if (!buf.isEmpty() && isVariable(buf))
                    setFormat(i - buf.length(), buf.length(), m_formats[ProfileVariableFormat]);
                buf.clear();
            }
        }
        i++;
        if (i >= text.length())
            break;
    }
}

<|endoftext|>