<commit_before>// Copyright (c) 2022 Ultimaker B.V.
// CuraEngine is released under the terms of the AGPLv3 or higher.

#include "WallsComputation.h" //Unit under test.
#include "InsetOrderOptimizer.h" //Unit also under test.
#include "settings/Settings.h" //Settings to generate walls with.
#include "sliceDataStorage.h" //Sl
#include "utils/polygon.h" //To create example polygons.
#include <gtest/gtest.h>
#include <unordered_set>

#ifdef WALLS_COMPUTATION_TEST_SVG_OUTPUT
#include "utils/SVG.h"
#include "utils/polygon.h"
#include <cstdlib>
#endif // WALLS_COMPUTATION_TEST_SVG_OUTPUT

// NOLINTBEGIN(*-magic-numbers)
namespace cura
{
/*!
 * Fixture that provides a basis for testing wall computation.
 */
class WallsComputationTest : public testing::Test
{
public:
    /*!
     * Settings to slice with. This is linked in the walls_computation fixture.
     */
    Settings settings;

    /*!
     * WallsComputation instance to test with. The layer index will be 100.
     */
    WallsComputation walls_computation;

    /*!
     * Basic 10x10mm square shape to work with.
     */
    Polygons square_shape;

    /*!
     * A rectangle enclosing two triangular holes;
     */
    Polygons ff_holes;

    WallsComputationTest() : walls_computation(settings, LayerIndex(100))
    {
        square_shape.emplace_back();
        square_shape.back().emplace_back(0, 0);
        square_shape.back().emplace_back(MM2INT(10), 0);
        square_shape.back().emplace_back(MM2INT(10), MM2INT(10));
        square_shape.back().emplace_back(0, MM2INT(10));

        ff_holes.emplace_back();
        ff_holes.back().emplace_back(0, 0);
        ff_holes.back().emplace_back(10000, 0);
        ff_holes.back().emplace_back(10000, 5000);
        ff_holes.back().emplace_back(0, 5000);
        ff_holes.emplace_back();
        ff_holes.back().emplace_back(1000, 1000);
        ff_holes.back().emplace_back(1000, 4000);
        ff_holes.back().emplace_back(4000, 2500);
        ff_holes.emplace_back();
        ff_holes.back().emplace_back(6000, 1000);
        ff_holes.back().emplace_back(6000, 4000);
        ff_holes.back().emplace_back(9000, 2500);

        // Settings for a simple 2 walls, about as basic as possible.
        settings.add("alternate_extra_perimeter", "false");
        settings.add("fill_outline_gaps", "false");
        settings.add("initial_layer_line_width_factor", "100");
        settings.add("magic_spiralize", "false");
        settings.add("meshfix_maximum_deviation", "0.1");
        settings.add("meshfix_maximum_extrusion_area_deviation", "0.01");
        settings.add("meshfix_maximum_resolution", "0.01");
        settings.add("min_bead_width", "0");
        settings.add("min_feature_size", "0");
        settings.add("wall_0_extruder_nr", "0");
        settings.add("wall_0_inset", "0");
        settings.add("wall_line_count", "2");
        settings.add("wall_line_width_0", "0.4");
        settings.add("wall_line_width_x", "0.4");
        settings.add("wall_transition_angle", "10");
        settings.add("wall_transition_filter_distance", "1");
        settings.add("wall_transition_filter_deviation", ".2");
        settings.add("wall_transition_length", "1");
        settings.add("wall_x_extruder_nr", "0");
        settings.add("wall_distribution_count", "2");
    }
};

/*!
 * Tests if something is generated in the basic happy case.
 */
TEST_F(WallsComputationTest, GenerateWallsForLayerSinglePart)
{
    SliceLayer layer;
    layer.parts.emplace_back();
    SliceLayerPart& part = layer.parts.back();
    part.outline.add(square_shape);

    // Run the test.
    walls_computation.generateWalls(&layer);

    // Verify that something was generated.
    EXPECT_FALSE(part.wall_toolpaths.empty()) << "There must be some walls.";
    EXPECT_GT(part.print_outline.area(), 0) << "The print outline must encompass the outer wall, so it must be more than 0.";
    EXPECT_LE(part.print_outline.area(), square_shape.area()) << "The print outline must stay within the bounds of the original part.";
    EXPECT_GT(part.inner_area.area(), 0) << "The inner area must be within the innermost wall. There are not enough walls to fill the entire part, so there is a positive inner area.";
    EXPECT_EQ(layer.parts.size(), 1) << "There is still just 1 part.";
}

/*!
 * Tests if the inner area is properly set.
 */
TEST_F(WallsComputationTest, GenerateWallsZeroWalls)
{
    settings.add("wall_line_count", "0");
    SliceLayer layer;
    layer.parts.emplace_back();
    SliceLayerPart& part = layer.parts.back();
    part.outline.add(square_shape);

    // Run the test.
    walls_computation.generateWalls(&layer);

    // Verify that there is still an inner area, outline and parts.
    EXPECT_EQ(part.inner_area.area(), square_shape.area()) << "There are no walls, so the inner area (for infill/skin) needs to be the entire part.";
    EXPECT_EQ(part.print_outline.area(), square_shape.area()) << "There are no walls, so the print outline encompasses the inner area exactly.";
    EXPECT_EQ(part.outline.area(), square_shape.area()) << "The outline is not modified.";
    EXPECT_EQ(layer.parts.size(), 1) << "There is still just 1 part.";
}

/*!
 * Tests if the inner area is properly set.
 */
TEST_F(WallsComputationTest, WallToolPathsGetWeakOrder)
{
    settings.add("wall_line_count", "5");
    SliceLayer layer;
    layer.parts.emplace_back();
    SliceLayerPart& part = layer.parts.back();
    part.outline.add(ff_holes);

    // Run the test.
    walls_computation.generateWalls(&layer);

    const bool outer_to_inner = false;
    std::vector<const ExtrusionLine*> all_paths;
    for (auto& inset : part.wall_toolpaths)
    {
        for (auto& line : inset)
        {
            all_paths.emplace_back(&line);
        }
    }
    std::unordered_set<std::pair<const ExtrusionLine*, const ExtrusionLine*>> order = InsetOrderOptimizer::getRegionOrder(all_paths, outer_to_inner);

    // Verify that something was generated.
    EXPECT_FALSE(part.wall_toolpaths.empty()) << "There must be some walls.";
    EXPECT_GT(part.print_outline.area(), 0) << "The print outline must encompass the outer wall, so it must be more than 0.";
    EXPECT_LE(part.print_outline.area(), ff_holes.area()) << "The print outline must stay within the bounds of the original part.";
    EXPECT_GE(part.inner_area.area(), 0) << "The inner area can never have negative area.";
    EXPECT_EQ(layer.parts.size(), 1) << "There is still just 1 part.";

#ifdef WALLS_COMPUTATION_TEST_SVG_OUTPUT
    {
        SVG svg("/tmp/wall_order.svg", AABB(part.outline));
        for (const VariableWidthLines& inset : part.wall_toolpaths)
        {
            for (const ExtrusionLine& line : inset)
            {
                if (line.is_odd)
                {
                    svg.writePolyline(line.toPolygon(), SVG::Color::YELLOW);
                    svg.writePoints(line.toPolygon(), true);
                }
                else
                    svg.writePolygon(line.toPolygon(), SVG::Color::GREEN);
            }
        }
        svg.writePolygons(part.outline, SVG::Color::RED);
        svg.writePolygons(part.inner_area, SVG::Color::YELLOW);
        svg.nextLayer();
        for (auto [first, second] : order)
        {
            if (! second->is_odd)
                svg.writeArrow(first->front().p, (++second->begin())->p, SVG::Color::BLUE);
        }
        svg.nextLayer();
        for (auto [first, second] : order)
        {
            if (second->is_odd)
                svg.writeArrow(first->front().p, (++second->begin())->p, SVG::Color::MAGENTA);
        }
    }
#endif // WALLS_COMPUTATION_TEST_SVG_OUTPUT

    size_t n_paths = 0;
    for (auto& lines : part.wall_toolpaths)
    {
        for (auto& line : lines)
        {
            if (! line.empty())
            {
                n_paths++;
            }
        }
    }
    EXPECT_GT(order.size(), 0) << "There should be ordered pairs!";
    std::unordered_set<const ExtrusionLine*> has_order_info(part.wall_toolpaths.size());
    for (auto [from, to] : order)
    {
        EXPECT_FALSE(from->is_odd) << "Odd gap filler lines are never required to go before anything.";
        has_order_info.emplace(from);
        has_order_info.emplace(to);
    }
    EXPECT_EQ(has_order_info.size(), n_paths) << "Every path should have order information.";
}

} // namespace cura
// NOLINTEND(*-magic-numbers)
<commit_msg>Fix unit test: Different settings for same calculation.<commit_after>// Copyright (c) 2022 Ultimaker B.V.
// CuraEngine is released under the terms of the AGPLv3 or higher.

#include "WallsComputation.h" //Unit under test.
#include "InsetOrderOptimizer.h" //Unit also under test.
#include "settings/Settings.h" //Settings to generate walls with.
#include "sliceDataStorage.h" //Sl
#include "utils/polygon.h" //To create example polygons.
#include <gtest/gtest.h>
#include <unordered_set>

#ifdef WALLS_COMPUTATION_TEST_SVG_OUTPUT
#include "utils/SVG.h"
#include "utils/polygon.h"
#include <cstdlib>
#endif // WALLS_COMPUTATION_TEST_SVG_OUTPUT

// NOLINTBEGIN(*-magic-numbers)
namespace cura
{
/*!
 * Fixture that provides a basis for testing wall computation.
 */
class WallsComputationTest : public testing::Test
{
public:
    /*!
     * Settings to slice with. This is linked in the walls_computation fixture.
     */
    Settings settings;

    /*!
     * WallsComputation instance to test with. The layer index will be 100.
     */
    WallsComputation walls_computation;

    /*!
     * Basic 10x10mm square shape to work with.
     */
    Polygons square_shape;

    /*!
     * A rectangle enclosing two triangular holes;
     */
    Polygons ff_holes;

    WallsComputationTest() : walls_computation(settings, LayerIndex(100))
    {
        square_shape.emplace_back();
        square_shape.back().emplace_back(0, 0);
        square_shape.back().emplace_back(MM2INT(10), 0);
        square_shape.back().emplace_back(MM2INT(10), MM2INT(10));
        square_shape.back().emplace_back(0, MM2INT(10));

        ff_holes.emplace_back();
        ff_holes.back().emplace_back(0, 0);
        ff_holes.back().emplace_back(10000, 0);
        ff_holes.back().emplace_back(10000, 5000);
        ff_holes.back().emplace_back(0, 5000);
        ff_holes.emplace_back();
        ff_holes.back().emplace_back(1000, 1000);
        ff_holes.back().emplace_back(1000, 4000);
        ff_holes.back().emplace_back(4000, 2500);
        ff_holes.emplace_back();
        ff_holes.back().emplace_back(6000, 1000);
        ff_holes.back().emplace_back(6000, 4000);
        ff_holes.back().emplace_back(9000, 2500);

        // Settings for a simple 2 walls, about as basic as possible.
        settings.add("alternate_extra_perimeter", "false");
        settings.add("fill_outline_gaps", "false");
        settings.add("initial_layer_line_width_factor", "100");
        settings.add("magic_spiralize", "false");
        settings.add("meshfix_maximum_deviation", "0.1");
        settings.add("meshfix_maximum_extrusion_area_deviation", "0.01");
        settings.add("meshfix_maximum_resolution", "0.01");
        settings.add("min_bead_width", "0");
        settings.add("min_feature_size", "0");
        settings.add("wall_0_extruder_nr", "0");
        settings.add("wall_0_inset", "0");
        settings.add("wall_line_count", "2");
        settings.add("wall_line_width_0", "0.4");
        settings.add("wall_line_width_x", "0.4");
        settings.add("min_even_wall_line_width", "0.34");
        settings.add("min_odd_wall_line_width", "0.34");
        settings.add("wall_transition_angle", "10");
        settings.add("wall_transition_filter_distance", "1");
        settings.add("wall_transition_filter_deviation", ".2");
        settings.add("wall_transition_length", "1");
        settings.add("wall_x_extruder_nr", "0");
        settings.add("wall_distribution_count", "2");
    }
};

/*!
 * Tests if something is generated in the basic happy case.
 */
TEST_F(WallsComputationTest, GenerateWallsForLayerSinglePart)
{
    SliceLayer layer;
    layer.parts.emplace_back();
    SliceLayerPart& part = layer.parts.back();
    part.outline.add(square_shape);

    // Run the test.
    walls_computation.generateWalls(&layer);

    // Verify that something was generated.
    EXPECT_FALSE(part.wall_toolpaths.empty()) << "There must be some walls.";
    EXPECT_GT(part.print_outline.area(), 0) << "The print outline must encompass the outer wall, so it must be more than 0.";
    EXPECT_LE(part.print_outline.area(), square_shape.area()) << "The print outline must stay within the bounds of the original part.";
    EXPECT_GT(part.inner_area.area(), 0) << "The inner area must be within the innermost wall. There are not enough walls to fill the entire part, so there is a positive inner area.";
    EXPECT_EQ(layer.parts.size(), 1) << "There is still just 1 part.";
}

/*!
 * Tests if the inner area is properly set.
 */
TEST_F(WallsComputationTest, GenerateWallsZeroWalls)
{
    settings.add("wall_line_count", "0");
    SliceLayer layer;
    layer.parts.emplace_back();
    SliceLayerPart& part = layer.parts.back();
    part.outline.add(square_shape);

    // Run the test.
    walls_computation.generateWalls(&layer);

    // Verify that there is still an inner area, outline and parts.
    EXPECT_EQ(part.inner_area.area(), square_shape.area()) << "There are no walls, so the inner area (for infill/skin) needs to be the entire part.";
    EXPECT_EQ(part.print_outline.area(), square_shape.area()) << "There are no walls, so the print outline encompasses the inner area exactly.";
    EXPECT_EQ(part.outline.area(), square_shape.area()) << "The outline is not modified.";
    EXPECT_EQ(layer.parts.size(), 1) << "There is still just 1 part.";
}

/*!
 * Tests if the inner area is properly set.
 */
TEST_F(WallsComputationTest, WallToolPathsGetWeakOrder)
{
    settings.add("wall_line_count", "5");
    SliceLayer layer;
    layer.parts.emplace_back();
    SliceLayerPart& part = layer.parts.back();
    part.outline.add(ff_holes);

    // Run the test.
    walls_computation.generateWalls(&layer);

    const bool outer_to_inner = false;
    std::vector<const ExtrusionLine*> all_paths;
    for (auto& inset : part.wall_toolpaths)
    {
        for (auto& line : inset)
        {
            all_paths.emplace_back(&line);
        }
    }
    std::unordered_set<std::pair<const ExtrusionLine*, const ExtrusionLine*>> order = InsetOrderOptimizer::getRegionOrder(all_paths, outer_to_inner);

    // Verify that something was generated.
    EXPECT_FALSE(part.wall_toolpaths.empty()) << "There must be some walls.";
    EXPECT_GT(part.print_outline.area(), 0) << "The print outline must encompass the outer wall, so it must be more than 0.";
    EXPECT_LE(part.print_outline.area(), ff_holes.area()) << "The print outline must stay within the bounds of the original part.";
    EXPECT_GE(part.inner_area.area(), 0) << "The inner area can never have negative area.";
    EXPECT_EQ(layer.parts.size(), 1) << "There is still just 1 part.";

#ifdef WALLS_COMPUTATION_TEST_SVG_OUTPUT
    {
        SVG svg("/tmp/wall_order.svg", AABB(part.outline));
        for (const VariableWidthLines& inset : part.wall_toolpaths)
        {
            for (const ExtrusionLine& line : inset)
            {
                if (line.is_odd)
                {
                    svg.writePolyline(line.toPolygon(), SVG::Color::YELLOW);
                    svg.writePoints(line.toPolygon(), true);
                }
                else
                    svg.writePolygon(line.toPolygon(), SVG::Color::GREEN);
            }
        }
        svg.writePolygons(part.outline, SVG::Color::RED);
        svg.writePolygons(part.inner_area, SVG::Color::YELLOW);
        svg.nextLayer();
        for (auto [first, second] : order)
        {
            if (! second->is_odd)
                svg.writeArrow(first->front().p, (++second->begin())->p, SVG::Color::BLUE);
        }
        svg.nextLayer();
        for (auto [first, second] : order)
        {
            if (second->is_odd)
                svg.writeArrow(first->front().p, (++second->begin())->p, SVG::Color::MAGENTA);
        }
    }
#endif // WALLS_COMPUTATION_TEST_SVG_OUTPUT

    size_t n_paths = 0;
    for (auto& lines : part.wall_toolpaths)
    {
        for (auto& line : lines)
        {
            if (! line.empty())
            {
                n_paths++;
            }
        }
    }
    EXPECT_GT(order.size(), 0) << "There should be ordered pairs!";
    std::unordered_set<const ExtrusionLine*> has_order_info(part.wall_toolpaths.size());
    for (auto [from, to] : order)
    {
        EXPECT_FALSE(from->is_odd) << "Odd gap filler lines are never required to go before anything.";
        has_order_info.emplace(from);
        has_order_info.emplace(to);
    }
    EXPECT_EQ(has_order_info.size(), n_paths) << "Every path should have order information.";
}

} // namespace cura
// NOLINTEND(*-magic-numbers)
<|endoftext|>


<commit_before>// @(#)root/auth:$Id$
// Author: G. Ganis   08/07/2005

/*************************************************************************
 * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TRootSecContext                                                      //
//                                                                      //
// Special implementation of TSecContext                                //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "RConfigure.h"

#include <stdlib.h>

#include "TError.h"
#include "TRootSecContext.h"
#include "TROOT.h"
#include "TSocket.h"
#include "TUrl.h"
#include "TVirtualMutex.h"

ClassImp(TRootSecContext);

////////////////////////////////////////////////////////////////////////////////
/// Ctor for SecContext object.

   TRootSecContext::TRootSecContext(const char *user, const char *host, Int_t meth,
                                    Int_t offset, const char *id,
                                    const char *token, TDatime expdate,
                                    void *ctx, Int_t key)
      : TSecContext(user, host, meth, offset, id, token, expdate, ctx)
{
   R__ASSERT(gROOT);

   fRSAKey  = key;
   fMethodName = TAuthenticate::GetAuthMethod(fMethod);
}

////////////////////////////////////////////////////////////////////////////////
/// Ctor for SecContext object.
/// User and host from url = user@host .

TRootSecContext::TRootSecContext(const char *url, Int_t meth, Int_t offset,
                                 const char *id, const char *token,
                                 TDatime expdate, void *ctx, Int_t key)
   : TSecContext(url, meth, offset, id, token, expdate, ctx)
{
   R__ASSERT(gROOT);

   fRSAKey  = key;
   fMethodName = TAuthenticate::GetAuthMethod(fMethod);
}

////////////////////////////////////////////////////////////////////////////////
/// Dtor: delete (deActivate, local/remote cleanup, list removal)
/// all what is still active

TRootSecContext::~TRootSecContext()
{
   TSecContext::Cleanup();
}

////////////////////////////////////////////////////////////////////////////////
/// Set OffSet to -1 and expiring Date to default
/// Remove from the list
/// If globus, cleanup local stuff
/// If Opt contains "C" or "c", ask for remote cleanup
/// If Opt contains "R" or "r", remove from the list
/// Default Opt="CR"

void TRootSecContext::DeActivate(Option_t *Opt)
{
   // Ask remote cleanup of this context
   Bool_t clean = (strstr(Opt,"C") || strstr(Opt,"c"));
   if (clean && fOffSet > -1)
      CleanupSecContext(kFALSE);

   // Cleanup TPwdCtx object fro UsrPwd and SRP
   if (fMethod == TAuthenticate::kClear ||
       fMethod == TAuthenticate::kSRP)
      if (fContext) {
         delete (TPwdCtx *)fContext;
         fContext = 0;
      }

   // Cleanup globus security context if needed
   if (fMethod == TAuthenticate::kGlobus && fContext) {
      GlobusAuth_t globusAuthHook = TAuthenticate::GetGlobusAuthHook();
      if (globusAuthHook != 0) {
         TString det("context");
         TString us("-1");
         (*globusAuthHook)((TAuthenticate *)fContext,us,det);
         fContext = 0;
      }
   }

   Bool_t remove = (strstr(Opt,"R") || strstr(Opt,"r"));
   if (remove && fOffSet > -1){
      R__LOCKGUARD(gROOTMutex);
      // Remove from the global list
      gROOT->GetListOfSecContexts()->Remove(this);
      // Remove also from local lists in THostAuth objects
      TAuthenticate::RemoveSecContext(this);
   }

   // Set inactive
   fOffSet  = -1;
   fExpDate = kROOTTZERO;

}

////////////////////////////////////////////////////////////////////////////////
/// Ask remote client to cleanup security context 'ctx'
/// If 'all', all sec context with the same host as ctx
/// are cleaned.

Bool_t TRootSecContext::CleanupSecContext(Bool_t all)
{
   Bool_t cleaned = kFALSE;

   // Nothing to do if inactive ...
   if (!IsActive())
      return kTRUE;

   // Contact remote services that used this context,
   // starting from the last ...
   TIter last(fCleanup,kIterBackward);
   TSecContextCleanup *nscc = 0;
   while ((nscc = (TSecContextCleanup *)last()) && !cleaned) {

      // First check if remote daemon supports cleaning
      Int_t srvtyp = nscc->GetType();
      Int_t rproto = nscc->GetProtocol();
      Int_t level = 2;
      if ((srvtyp == TSocket::kROOTD && rproto < 10) ||
          (srvtyp == TSocket::kPROOFD && rproto < 9))
         level = 1;
      if ((srvtyp == TSocket::kROOTD && rproto < 8) ||
          (srvtyp == TSocket::kPROOFD && rproto < 7))
         level = 0;
      if (level) {
         Int_t port = nscc->GetPort();

         TSocket *news = new TSocket(fHost.Data(),port,-1);

         if (news && news->IsValid()) {
            if (srvtyp == TSocket::kPROOFD) {
               news->SetOption(kNoDelay, 1);
               news->Send("cleaning request");
            } else
               news->SetOption(kNoDelay, 0);

            // Backward compatibility: send socket size
            if (srvtyp == TSocket::kROOTD && level == 1)
               news->Send((Int_t)0, (Int_t)0);

            if (all || level == 1) {
               news->Send(Form("%d",TAuthenticate::fgProcessID), kROOTD_CLEANUP);
               cleaned = kTRUE;
            } else {
               news->Send(Form("%d %d %d %s", TAuthenticate::fgProcessID, fMethod,
                               fOffSet, fUser.Data()), kROOTD_CLEANUP);
               if (TAuthenticate::SecureSend(news, 1, fRSAKey,
                                             (char *)(fToken.Data())) == -1) {
                  Info("CleanupSecContext", "problems secure-sending token");
               } else {
                  cleaned = kTRUE;
               }
            }
            if (cleaned && gDebug > 2) {
               char srvname[3][10] = {"sockd", "rootd", "proofd"};
               Info("CleanupSecContext",
                    "remote %s notified for cleanup (%s,%d)",
                    srvname[srvtyp],fHost.Data(),port);
            }
         }
         SafeDelete(news);
      }
   }

   if (!cleaned)
      if (gDebug > 2)
         Info("CleanupSecContext",
              "unable to open valid socket for cleanup for %s", fHost.Data());

   return cleaned;
}

////////////////////////////////////////////////////////////////////////////////
/// If opt is "F" (default) print object content.
/// If opt is "<number>" print in special form for calls within THostAuth
/// with cardinality <number>
/// If opt is "S" prints short in-line form for calls within TFTP,
/// TSlave, TProof ...

void TRootSecContext::Print(Option_t *opt) const
{
   // Check if option is numeric
   Int_t ord = -1, i = 0;
   for (; i < (Int_t)strlen(opt); i++) {
      if (opt[i] < 48 || opt[i] > 57) {
         ord = -2;
         break;
      }
   }
   // If numeric get the cardinality and prepare the strings
   if (ord == -1)
      ord = atoi(opt);

   if (!strncasecmp(opt,"F",1)) {
      Info("Print",
           "+------------------------------------------------------+");
      Info("Print",
           "+ Host:%s Method:%d (%s) User:'%s'",
           GetHost(), fMethod, GetMethodName(),
           fUser.Data());
      Info("Print",
           "+         OffSet:%d Id: '%s'", fOffSet, fID.Data());
      if (fOffSet > -1)
         Info("Print",
              "+         Expiration time: %s",fExpDate.AsString());
      Info("Print",
           "+------------------------------------------------------+");
   } else if (!strncasecmp(opt,"S",1)) {
      if (fOffSet > -1) {
         if (fID.BeginsWith("AFS"))
            Printf("Security context:     Method: AFS, not reusable");
         else
            Printf("Security context:     Method: %d (%s) expiring on %s",
                   fMethod, GetMethodName(),
                   fExpDate.AsString());
      } else {
         Printf("Security context:     Method: %d (%s) not reusable",
                fMethod, GetMethodName());
      }
   } else {
      // special printing form for THostAuth
      Info("PrintEstblshed","+ %d \t h:%s met:%d (%s) us:'%s'",
                               ord, GetHost(), fMethod, GetMethodName(),
                               fUser.Data());
      Info("PrintEstblshed","+ \t offset:%d id: '%s'", fOffSet, fID.Data());
      if (fOffSet > -1)
         Info("PrintEstblshed","+ \t expiring: %s",fExpDate.AsString());
   }
}

////////////////////////////////////////////////////////////////////////////////
/// Returns short string with relevant information about this
/// security context

const char *TRootSecContext::AsString(TString &out)
{
   if (fOffSet > -1) {
      if (fID.BeginsWith("AFS"))
         out = Form("Method: AFS, not reusable");
      else {
         char expdate[32];
         out = Form("Method: %d (%s) expiring on %s",
                    fMethod, GetMethodName(), fExpDate.AsString(expdate));
      }
   } else {
      if (fOffSet == -1)
         out = Form("Method: %d (%s) not reusable", fMethod, GetMethodName());
      else if (fOffSet == -3)
         out = Form("Method: %d (%s) authorized by /etc/hosts.equiv or $HOME/.rhosts",
                    fMethod, GetMethodName());
      else if (fOffSet == -4)
         out = Form("No authentication required remotely");
   }
   return out.Data();
}
<commit_msg>define kROOTTZERO at TRootSecContext as well<commit_after>// @(#)root/auth:$Id$
// Author: G. Ganis   08/07/2005

/*************************************************************************
 * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TRootSecContext                                                      //
//                                                                      //
// Special implementation of TSecContext                                //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "RConfigure.h"

#include <stdlib.h>

#include "TError.h"
#include "TRootSecContext.h"
#include "TROOT.h"
#include "TSocket.h"
#include "TUrl.h"
#include "TVirtualMutex.h"

const TDatime kROOTTZERO = 788914800;

ClassImp(TRootSecContext);

////////////////////////////////////////////////////////////////////////////////
/// Ctor for SecContext object.

   TRootSecContext::TRootSecContext(const char *user, const char *host, Int_t meth,
                                    Int_t offset, const char *id,
                                    const char *token, TDatime expdate,
                                    void *ctx, Int_t key)
      : TSecContext(user, host, meth, offset, id, token, expdate, ctx)
{
   R__ASSERT(gROOT);

   fRSAKey  = key;
   fMethodName = TAuthenticate::GetAuthMethod(fMethod);
}

////////////////////////////////////////////////////////////////////////////////
/// Ctor for SecContext object.
/// User and host from url = user@host .

TRootSecContext::TRootSecContext(const char *url, Int_t meth, Int_t offset,
                                 const char *id, const char *token,
                                 TDatime expdate, void *ctx, Int_t key)
   : TSecContext(url, meth, offset, id, token, expdate, ctx)
{
   R__ASSERT(gROOT);

   fRSAKey  = key;
   fMethodName = TAuthenticate::GetAuthMethod(fMethod);
}

////////////////////////////////////////////////////////////////////////////////
/// Dtor: delete (deActivate, local/remote cleanup, list removal)
/// all what is still active

TRootSecContext::~TRootSecContext()
{
   TSecContext::Cleanup();
}

////////////////////////////////////////////////////////////////////////////////
/// Set OffSet to -1 and expiring Date to default
/// Remove from the list
/// If globus, cleanup local stuff
/// If Opt contains "C" or "c", ask for remote cleanup
/// If Opt contains "R" or "r", remove from the list
/// Default Opt="CR"

void TRootSecContext::DeActivate(Option_t *Opt)
{
   // Ask remote cleanup of this context
   Bool_t clean = (strstr(Opt,"C") || strstr(Opt,"c"));
   if (clean && fOffSet > -1)
      CleanupSecContext(kFALSE);

   // Cleanup TPwdCtx object fro UsrPwd and SRP
   if (fMethod == TAuthenticate::kClear ||
       fMethod == TAuthenticate::kSRP)
      if (fContext) {
         delete (TPwdCtx *)fContext;
         fContext = 0;
      }

   // Cleanup globus security context if needed
   if (fMethod == TAuthenticate::kGlobus && fContext) {
      GlobusAuth_t globusAuthHook = TAuthenticate::GetGlobusAuthHook();
      if (globusAuthHook != 0) {
         TString det("context");
         TString us("-1");
         (*globusAuthHook)((TAuthenticate *)fContext,us,det);
         fContext = 0;
      }
   }

   Bool_t remove = (strstr(Opt,"R") || strstr(Opt,"r"));
   if (remove && fOffSet > -1){
      R__LOCKGUARD(gROOTMutex);
      // Remove from the global list
      gROOT->GetListOfSecContexts()->Remove(this);
      // Remove also from local lists in THostAuth objects
      TAuthenticate::RemoveSecContext(this);
   }

   // Set inactive
   fOffSet  = -1;
   fExpDate = kROOTTZERO;

}

////////////////////////////////////////////////////////////////////////////////
/// Ask remote client to cleanup security context 'ctx'
/// If 'all', all sec context with the same host as ctx
/// are cleaned.

Bool_t TRootSecContext::CleanupSecContext(Bool_t all)
{
   Bool_t cleaned = kFALSE;

   // Nothing to do if inactive ...
   if (!IsActive())
      return kTRUE;

   // Contact remote services that used this context,
   // starting from the last ...
   TIter last(fCleanup,kIterBackward);
   TSecContextCleanup *nscc = 0;
   while ((nscc = (TSecContextCleanup *)last()) && !cleaned) {

      // First check if remote daemon supports cleaning
      Int_t srvtyp = nscc->GetType();
      Int_t rproto = nscc->GetProtocol();
      Int_t level = 2;
      if ((srvtyp == TSocket::kROOTD && rproto < 10) ||
          (srvtyp == TSocket::kPROOFD && rproto < 9))
         level = 1;
      if ((srvtyp == TSocket::kROOTD && rproto < 8) ||
          (srvtyp == TSocket::kPROOFD && rproto < 7))
         level = 0;
      if (level) {
         Int_t port = nscc->GetPort();

         TSocket *news = new TSocket(fHost.Data(),port,-1);

         if (news && news->IsValid()) {
            if (srvtyp == TSocket::kPROOFD) {
               news->SetOption(kNoDelay, 1);
               news->Send("cleaning request");
            } else
               news->SetOption(kNoDelay, 0);

            // Backward compatibility: send socket size
            if (srvtyp == TSocket::kROOTD && level == 1)
               news->Send((Int_t)0, (Int_t)0);

            if (all || level == 1) {
               news->Send(Form("%d",TAuthenticate::fgProcessID), kROOTD_CLEANUP);
               cleaned = kTRUE;
            } else {
               news->Send(Form("%d %d %d %s", TAuthenticate::fgProcessID, fMethod,
                               fOffSet, fUser.Data()), kROOTD_CLEANUP);
               if (TAuthenticate::SecureSend(news, 1, fRSAKey,
                                             (char *)(fToken.Data())) == -1) {
                  Info("CleanupSecContext", "problems secure-sending token");
               } else {
                  cleaned = kTRUE;
               }
            }
            if (cleaned && gDebug > 2) {
               char srvname[3][10] = {"sockd", "rootd", "proofd"};
               Info("CleanupSecContext",
                    "remote %s notified for cleanup (%s,%d)",
                    srvname[srvtyp],fHost.Data(),port);
            }
         }
         SafeDelete(news);
      }
   }

   if (!cleaned)
      if (gDebug > 2)
         Info("CleanupSecContext",
              "unable to open valid socket for cleanup for %s", fHost.Data());

   return cleaned;
}

////////////////////////////////////////////////////////////////////////////////
/// If opt is "F" (default) print object content.
/// If opt is "<number>" print in special form for calls within THostAuth
/// with cardinality <number>
/// If opt is "S" prints short in-line form for calls within TFTP,
/// TSlave, TProof ...

void TRootSecContext::Print(Option_t *opt) const
{
   // Check if option is numeric
   Int_t ord = -1, i = 0;
   for (; i < (Int_t)strlen(opt); i++) {
      if (opt[i] < 48 || opt[i] > 57) {
         ord = -2;
         break;
      }
   }
   // If numeric get the cardinality and prepare the strings
   if (ord == -1)
      ord = atoi(opt);

   if (!strncasecmp(opt,"F",1)) {
      Info("Print",
           "+------------------------------------------------------+");
      Info("Print",
           "+ Host:%s Method:%d (%s) User:'%s'",
           GetHost(), fMethod, GetMethodName(),
           fUser.Data());
      Info("Print",
           "+         OffSet:%d Id: '%s'", fOffSet, fID.Data());
      if (fOffSet > -1)
         Info("Print",
              "+         Expiration time: %s",fExpDate.AsString());
      Info("Print",
           "+------------------------------------------------------+");
   } else if (!strncasecmp(opt,"S",1)) {
      if (fOffSet > -1) {
         if (fID.BeginsWith("AFS"))
            Printf("Security context:     Method: AFS, not reusable");
         else
            Printf("Security context:     Method: %d (%s) expiring on %s",
                   fMethod, GetMethodName(),
                   fExpDate.AsString());
      } else {
         Printf("Security context:     Method: %d (%s) not reusable",
                fMethod, GetMethodName());
      }
   } else {
      // special printing form for THostAuth
      Info("PrintEstblshed","+ %d \t h:%s met:%d (%s) us:'%s'",
                               ord, GetHost(), fMethod, GetMethodName(),
                               fUser.Data());
      Info("PrintEstblshed","+ \t offset:%d id: '%s'", fOffSet, fID.Data());
      if (fOffSet > -1)
         Info("PrintEstblshed","+ \t expiring: %s",fExpDate.AsString());
   }
}

////////////////////////////////////////////////////////////////////////////////
/// Returns short string with relevant information about this
/// security context

const char *TRootSecContext::AsString(TString &out)
{
   if (fOffSet > -1) {
      if (fID.BeginsWith("AFS"))
         out = Form("Method: AFS, not reusable");
      else {
         char expdate[32];
         out = Form("Method: %d (%s) expiring on %s",
                    fMethod, GetMethodName(), fExpDate.AsString(expdate));
      }
   } else {
      if (fOffSet == -1)
         out = Form("Method: %d (%s) not reusable", fMethod, GetMethodName());
      else if (fOffSet == -3)
         out = Form("Method: %d (%s) authorized by /etc/hosts.equiv or $HOME/.rhosts",
                    fMethod, GetMethodName());
      else if (fOffSet == -4)
         out = Form("No authentication required remotely");
   }
   return out.Data();
}
<|endoftext|>


<commit_before>/****************** <VPR heading BEGIN do not edit this line> *****************
 *
 * VR Juggler Portable Runtime
 *
 * Original Authors:
 *   Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 ****************** <VPR heading END do not edit this line> ******************/

/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2003 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vpr/vprConfig.h>

#if defined(HAVE_BACKTRACE)
#include <sys/types.h>
#include <unistd.h>
#include <execinfo.h>

#include <string>
#include <sstream>
#endif

#if (! defined(__INTEL_COMPILER) && defined(__GNUC__) && \
     ((__GNUC__ == 3 && __GNUC_MINOR__ >= 3) || __GNUC__ > 3)) || \
    (defined(__INTEL_COMPILER) && __INTEL_COMPILER >= 810 && defined(__GNUC__))

#define USE_CXA_DEMANGLE 1
#include <cxxabi.h>

#endif

#include <vpr/SystemBase.h>

namespace
{

std::string demangleTraceString(char* traceLine)
{
#ifdef USE_CXA_DEMANGLE
   // Try to extract the mangled name from the line (if it exists)
   // and replace it with a demangled version of the name.
   // Example: build.linux/stuff/classfile(_ZN4vpr11Someing33methodEv+0xd3) [0x80cfa29]

   std::string trace_line(traceLine);
   std::string mangled_name, demangled_name;

   unsigned start(std::string::npos), end(std::string::npos);
   start = trace_line.find("(_");
   if(std::string::npos != start)
   {
      end = trace_line.find_first_of("+)",start);
   }

   if(std::string::npos != end)
   {
      mangled_name.assign(trace_line, start+1, end-start-1);
      int status;
      char* demangled_buf = abi::__cxa_demangle(mangled_name.c_str(), NULL,
                                                NULL, &status);
      if(0==status)
      {
         demangled_name = std::string(demangled_buf);
         free(demangled_buf);

         trace_line.replace(start+1, (end-start-1), demangled_name);
      }
      else if(-1==status)
      {
//         std::cerr << "vpr::SystemBase::dmangleTraceString: "
//                   << "A memory allocation failiure occurred.\n";
      }
      else if(-2 == status)
      {
//         std::cerr << "vpr::SystemBase::demangleTraceString: mangled_name "
//                   << "is not a valid name under the C++ ABI mangling '
//                   << "rules.\n";
      }
      else if(-3 == status)
      {
//         std::cerr << "vpr::SystemBase::demangleTraceString: One of the "
//                   << "arguments is invalid.\n";
      }
   }

//   trace_line += std::string(" mangle:") + mangled_name +
//                 std::string(" demangled:") + demangled_name;
   return trace_line;

#else
   return std::string(traceLine);
#endif
}

}

namespace vpr
{

std::string SystemBase::getCallStack()
{
   std::string ret_stack("Stack trace:\n   <Call stack printing not supported>\n");

#if defined(HAVE_BACKTRACE)
   void* trace_syms[100];
   size_t size;
   char** strings;

   pid_t cur_pid = getpid();
   size = backtrace(trace_syms, 100);
   strings = backtrace_symbols(trace_syms, size);

   std::ostringstream trace_stream;
   trace_stream << "Stack trace: thread: " << cur_pid << std::endl;

   for (size_t i = 0; i < size; ++i)
   {
      trace_stream << "   " << i << ":" << demangleTraceString(strings[i])
                   << std::endl;
   }

   free(strings);

   ret_stack = trace_stream.str();
#endif

   return ret_stack;
}

}
<commit_msg>Staticize demangleTraceString() since nothing else is using it.<commit_after>/****************** <VPR heading BEGIN do not edit this line> *****************
 *
 * VR Juggler Portable Runtime
 *
 * Original Authors:
 *   Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 ****************** <VPR heading END do not edit this line> ******************/

/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2003 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vpr/vprConfig.h>

#if defined(HAVE_BACKTRACE)
#include <sys/types.h>
#include <unistd.h>
#include <execinfo.h>

#include <string>
#include <sstream>
#endif

#if (! defined(__INTEL_COMPILER) && defined(__GNUC__) && \
     ((__GNUC__ == 3 && __GNUC_MINOR__ >= 3) || __GNUC__ > 3)) || \
    (defined(__INTEL_COMPILER) && __INTEL_COMPILER >= 810 && defined(__GNUC__))

#define USE_CXA_DEMANGLE 1
#include <cxxabi.h>

#endif

#include <vpr/SystemBase.h>

namespace
{

static std::string demangleTraceString(char* traceLine)
{
#ifdef USE_CXA_DEMANGLE
   // Try to extract the mangled name from the line (if it exists)
   // and replace it with a demangled version of the name.
   // Example: build.linux/stuff/classfile(_ZN4vpr11Someing33methodEv+0xd3) [0x80cfa29]

   std::string trace_line(traceLine);
   std::string mangled_name, demangled_name;

   unsigned start(std::string::npos), end(std::string::npos);
   start = trace_line.find("(_");
   if(std::string::npos != start)
   {
      end = trace_line.find_first_of("+)",start);
   }

   if(std::string::npos != end)
   {
      mangled_name.assign(trace_line, start+1, end-start-1);
      int status;
      char* demangled_buf = abi::__cxa_demangle(mangled_name.c_str(), NULL,
                                                NULL, &status);
      if(0==status)
      {
         demangled_name = std::string(demangled_buf);
         free(demangled_buf);

         trace_line.replace(start+1, (end-start-1), demangled_name);
      }
      else if(-1==status)
      {
//         std::cerr << "vpr::SystemBase::dmangleTraceString: "
//                   << "A memory allocation failiure occurred.\n";
      }
      else if(-2 == status)
      {
//         std::cerr << "vpr::SystemBase::demangleTraceString: mangled_name "
//                   << "is not a valid name under the C++ ABI mangling '
//                   << "rules.\n";
      }
      else if(-3 == status)
      {
//         std::cerr << "vpr::SystemBase::demangleTraceString: One of the "
//                   << "arguments is invalid.\n";
      }
   }

//   trace_line += std::string(" mangle:") + mangled_name +
//                 std::string(" demangled:") + demangled_name;
   return trace_line;

#else
   return std::string(traceLine);
#endif
}

}

namespace vpr
{

std::string SystemBase::getCallStack()
{
   std::string ret_stack("Stack trace:\n   <Call stack printing not supported>\n");

#if defined(HAVE_BACKTRACE)
   void* trace_syms[100];
   size_t size;
   char** strings;

   pid_t cur_pid = getpid();
   size = backtrace(trace_syms, 100);
   strings = backtrace_symbols(trace_syms, size);

   std::ostringstream trace_stream;
   trace_stream << "Stack trace: thread: " << cur_pid << std::endl;

   for (size_t i = 0; i < size; ++i)
   {
      trace_stream << "   " << i << ":" << demangleTraceString(strings[i])
                   << std::endl;
   }

   free(strings);

   ret_stack = trace_stream.str();
#endif

   return ret_stack;
}

}
<|endoftext|>


<commit_before><commit_msg>Don't hang during DiskCacheEntryTest.CancelSparseIO on infinitely fast disks.<commit_after><|endoftext|>


<commit_before>#include "musicquerytablewidget.h"
#include "musicdownloadqueryfactory.h"
#include "musicitemdelegate.h"
#include "musicgiflabelwidget.h"

#include <QActionGroup>

MusicQueryTableWidget::MusicQueryTableWidget(QWidget *parent)
    : MusicFillItemTableWidget(parent)
{
    m_downLoadManager = nullptr;
}

MusicQueryTableWidget::~MusicQueryTableWidget()
{
    delete m_downLoadManager;
}

QString MusicQueryTableWidget::getClassName()
{
    return staticMetaObject.className();
}

void MusicQueryTableWidget::setQueryInput(MusicDownLoadQueryThreadAbstract *query)
{
    delete m_downLoadManager;
    m_downLoadManager = query;
    connect(m_downLoadManager, SIGNAL(clearAllItems()), SLOT(clearAllItems()));
    connect(m_downLoadManager, SIGNAL(createSearchedItems(QString,QString,QString)),
                               SLOT(createSearchedItems(QString,QString,QString)));
}

void MusicQueryTableWidget::contextMenuEvent(QContextMenuEvent *event)
{
    Q_UNUSED(event);
}

MusicQueryItemTableWidget::MusicQueryItemTableWidget(QWidget *parent)
    : MusicQueryTableWidget(parent)
{
    m_loadingLabel = new MusicGifLabelWidget(MusicGifLabelWidget::Gif_Cicle_Blue, this);
    m_actionGroup = new QActionGroup(this);
    m_labelDelegate = new MusicLabelDelegate(this);
    connect(m_actionGroup, SIGNAL(triggered(QAction*)), SLOT(actionGroupClick(QAction*)));
    connect(this, SIGNAL(cellDoubleClicked(int,int)), SLOT(itemDoubleClicked(int,int)));
}

MusicQueryItemTableWidget::~MusicQueryItemTableWidget()
{
    delete m_loadingLabel;
    delete m_actionGroup;
    delete m_labelDelegate;
}

QString MusicQueryItemTableWidget::getClassName()
{
    return staticMetaObject.className();
}

void MusicQueryItemTableWidget::startSearchQuery(const QString &text)
{
    Q_UNUSED(text);
    MusicDownLoadQueryThreadAbstract *d = M_DOWNLOAD_QUERY_PTR->getQueryThread(this);
    connect(d, SIGNAL(downLoadDataChanged(QString)), SLOT(createFinishedItem()));
    setQueryInput( d );
}

void MusicQueryItemTableWidget::clearAllItems()
{
    if(rowCount() > 0)
    {
        setItemDelegateForRow(rowCount() - 1, nullptr);
    }
    MusicAbstractTableWidget::clear();
}

void MusicQueryItemTableWidget::actionGroupClick(QAction *action)
{
    int row = currentRow();
    if( row < 0 || (row >= rowCount() - 1))
    {
        return;
    }

    QString songName = (row != -1 && rowCount() > 0) ? item(row, 1)->toolTip() : QString();
    QString artistName = (row != -1 && rowCount() > 0) ? item(row, 2)->toolTip() : QString();

    switch( action->data().toInt() )
    {
        case 0: musicDownloadLocal(row); break;
        case 1: emit restartSearchQuery(songName); break;
        case 2: emit restartSearchQuery(artistName); break;
        case 3: emit restartSearchQuery(songName + "-" + artistName); break;
    }
}

void MusicQueryItemTableWidget::createFinishedItem()
{
    m_loadingLabel->hide();
    m_loadingLabel->stop();

    if(rowCount() <= 0)
    {
        setRowCount(1);
    }

    int count = rowCount() - 1;
    setSpan(count, 0, 1, columnCount());

    for(int i=0; i<columnCount(); ++i)
    {
        setItem(count, i, new QTableWidgetItem);
    }

    QTableWidgetItem *it = item(count, 0);
    if(it)
    {
        it->setData(MUSIC_TEXTS_ROLE, tr("No More Data"));
        setItemDelegateForRow(count, m_labelDelegate);
    }
}

void MusicQueryItemTableWidget::createContextMenu(QMenu &menu)
{
    menu.setStyleSheet(MusicUIObject::MMenuStyle02);
    m_actionGroup->addAction(menu.addAction(tr("musicDownload")))->setData(0);

    menu.addSeparator();

    QString songName = currentRow() != -1 && rowCount() > 0 ?
                item(currentRow(), 1)->toolTip() : QString();
    QString artistName = currentRow() != -1 && rowCount() > 0 ?
                item(currentRow(), 2)->toolTip() : QString();
    m_actionGroup->addAction(menu.addAction(tr("search '%1'").arg(songName)))->setData(1);
    m_actionGroup->addAction(menu.addAction(tr("search '%1'").arg(artistName)))->setData(2);
    m_actionGroup->addAction(menu.addAction(tr("search '%1 - %2'").arg(songName).arg(artistName)))->setData(3);
}

void MusicQueryItemTableWidget::resizeEvent(QResizeEvent *event)
{
    MusicQueryTableWidget::resizeEvent(event);
    m_loadingLabel->move((width() - m_loadingLabel->width())/2, (height() - m_loadingLabel->height())/2);
}
<commit_msg>Optimized the query item label[800156]<commit_after>#include "musicquerytablewidget.h"
#include "musicdownloadqueryfactory.h"
#include "musicitemdelegate.h"
#include "musicgiflabelwidget.h"

#include <QActionGroup>

MusicQueryTableWidget::MusicQueryTableWidget(QWidget *parent)
    : MusicFillItemTableWidget(parent)
{
    m_downLoadManager = nullptr;
}

MusicQueryTableWidget::~MusicQueryTableWidget()
{
    delete m_downLoadManager;
}

QString MusicQueryTableWidget::getClassName()
{
    return staticMetaObject.className();
}

void MusicQueryTableWidget::setQueryInput(MusicDownLoadQueryThreadAbstract *query)
{
    delete m_downLoadManager;
    m_downLoadManager = query;
    connect(m_downLoadManager, SIGNAL(clearAllItems()), SLOT(clearAllItems()));
    connect(m_downLoadManager, SIGNAL(createSearchedItems(QString,QString,QString)),
                               SLOT(createSearchedItems(QString,QString,QString)));
}

void MusicQueryTableWidget::contextMenuEvent(QContextMenuEvent *event)
{
    Q_UNUSED(event);
}

MusicQueryItemTableWidget::MusicQueryItemTableWidget(QWidget *parent)
    : MusicQueryTableWidget(parent)
{
    m_loadingLabel = new MusicGifLabelWidget(MusicGifLabelWidget::Gif_Cicle_Blue, this);
    m_actionGroup = new QActionGroup(this);
    m_labelDelegate = new MusicLabelDelegate(this);
    connect(m_actionGroup, SIGNAL(triggered(QAction*)), SLOT(actionGroupClick(QAction*)));
    connect(this, SIGNAL(cellDoubleClicked(int,int)), SLOT(itemDoubleClicked(int,int)));
}

MusicQueryItemTableWidget::~MusicQueryItemTableWidget()
{
    delete m_loadingLabel;
    delete m_actionGroup;
    delete m_labelDelegate;
}

QString MusicQueryItemTableWidget::getClassName()
{
    return staticMetaObject.className();
}

void MusicQueryItemTableWidget::startSearchQuery(const QString &text)
{
    Q_UNUSED(text);
    MusicDownLoadQueryThreadAbstract *d = M_DOWNLOAD_QUERY_PTR->getQueryThread(this);
    connect(d, SIGNAL(downLoadDataChanged(QString)), SLOT(createFinishedItem()));
    setQueryInput( d );
}

void MusicQueryItemTableWidget::clearAllItems()
{
    if(rowCount() > 0)
    {
        setItemDelegateForRow(rowCount() - 1, nullptr);
    }
    MusicAbstractTableWidget::clear();
}

void MusicQueryItemTableWidget::actionGroupClick(QAction *action)
{
    int row = currentRow();
    if( row < 0 || (row >= rowCount() - 1))
    {
        return;
    }

    QString songName = (row != -1 && rowCount() > 0) ? item(row, 1)->toolTip() : QString();
    QString artistName = (row != -1 && rowCount() > 0) ? item(row, 2)->toolTip() : QString();

    switch( action->data().toInt() )
    {
        case 0: musicDownloadLocal(row); break;
        case 1: emit restartSearchQuery(songName); break;
        case 2: emit restartSearchQuery(artistName); break;
        case 3: emit restartSearchQuery(songName + "-" + artistName); break;
    }
}

void MusicQueryItemTableWidget::createFinishedItem()
{
    m_loadingLabel->hide();
    m_loadingLabel->stop();

    setRowCount(rowCount() + 1);
    int count = rowCount() - 1;
    for(int i=0; i<columnCount(); ++i)
    {
        setItem(count, i, new QTableWidgetItem);
    }
    setSpan(count, 0, 1, columnCount());

    QTableWidgetItem *it = item(count, 0);
    if(it)
    {
        it->setData(MUSIC_TEXTS_ROLE, tr("No More Data"));
        setItemDelegateForRow(count, m_labelDelegate);
    }
}

void MusicQueryItemTableWidget::createContextMenu(QMenu &menu)
{
    menu.setStyleSheet(MusicUIObject::MMenuStyle02);
    m_actionGroup->addAction(menu.addAction(tr("musicDownload")))->setData(0);

    menu.addSeparator();

    QString songName = currentRow() != -1 && rowCount() > 0 ?
                item(currentRow(), 1)->toolTip() : QString();
    QString artistName = currentRow() != -1 && rowCount() > 0 ?
                item(currentRow(), 2)->toolTip() : QString();
    m_actionGroup->addAction(menu.addAction(tr("search '%1'").arg(songName)))->setData(1);
    m_actionGroup->addAction(menu.addAction(tr("search '%1'").arg(artistName)))->setData(2);
    m_actionGroup->addAction(menu.addAction(tr("search '%1 - %2'").arg(songName).arg(artistName)))->setData(3);
}

void MusicQueryItemTableWidget::resizeEvent(QResizeEvent *event)
{
    MusicQueryTableWidget::resizeEvent(event);
    m_loadingLabel->move((width() - m_loadingLabel->width())/2, (height() - m_loadingLabel->height())/2);
}
<|endoftext|>


<commit_before>/** @file gsBlockOp.cpp

    @brief Simple class create a block preconditioner structure.

    This file is part of the G+Smo library.

    This Source Code Form is subject to the terms of the Mozilla Public
    License, v. 2.0. If a copy of the MPL was not distributed with this
    file, You can obtain one at http://mozilla.org/MPL/2.0/.

    Author(s): J. Sogn
*/
#include <gsSolver/gsBlockPreconditioner.h>

namespace gismo
{

gsBlockOp::gsBlockOp(index_t nRows, index_t nCols)
{
    blockPrec.resize(nRows, nCols);
    blockTargetPositions.setZero(nCols);
    blockInputPositions.setZero(nRows);
    // Fill up all block entries with null pointers.
    for (index_t i = 0; i < nRows; ++i)
        for (index_t j = 0; j < nCols; ++j)
            blockPrec(i,j).reset();
}

void gsBlockOp::addOperator(index_t row, index_t col, const BasePtr& op)
{
    GISMO_ASSERT( row >= 0 && row < blockPrec.rows(), "The given row is not feasible." );
    GISMO_ASSERT( col >= 0 && col < blockPrec.cols(), "The given column is not feasible." );
    GISMO_ASSERT( op->rows() == blockTargetPositions[row] || blockTargetPositions[row] == 0,
                  "The size of the given preconditioner does not fit to the other preconditioners in the same row." );
    GISMO_ASSERT( op->cols() == blockTargetPositions[col] || blockTargetPositions[col] == 0,
                  "The size of the given preconditioner does not fit to the other preconditioners in the same column." );

    blockPrec(row, col) = op;
    blockTargetPositions[row] = op->rows();
    blockInputPositions[col] = op->cols();
}

void gsBlockOp::apply(const gsMatrix<real_t> & input, gsMatrix<real_t> & result) const
{
    result.setZero(blockTargetPositions.sum(), input.cols());
    gsVector<index_t> singleCol(1);
    singleCol <<  input.cols();
    gsMatrix<real_t>::BlockView resultBlocks= result.blockView(blockTargetPositions, singleCol);

    for (index_t i = 0; i < blockPrec.rows() ; ++i)
    {
        index_t inputIndex = 0;
        for (index_t j = 0; j < blockPrec.cols(); ++j)
        {
            if (!blockPrec(i,j))// if the block is a null pointer
            {
                inputIndex += blockInputPositions(j);
                continue;
            }

            gsMatrix<real_t> tmp_result;
            blockPrec(i,j)->apply(input.block(inputIndex,0,blockInputPositions(j),input.cols()),tmp_result);
            resultBlocks(i) += tmp_result;
            inputIndex += blockInputPositions(j);
        }
    }
}

const gsBlockOp::BasePtr & gsBlockOp::getOperator(index_t row, index_t col) const
{
    GISMO_ASSERT(blockPrec(row, col)!=NULL, "No linear operator exists in this block");
    return blockPrec(row,col);
}

}

<commit_msg>small fix<commit_after>/** @file gsBlockOp.cpp

    @brief Simple class create a block preconditioner structure.

    This file is part of the G+Smo library.

    This Source Code Form is subject to the terms of the Mozilla Public
    License, v. 2.0. If a copy of the MPL was not distributed with this
    file, You can obtain one at http://mozilla.org/MPL/2.0/.

    Author(s): J. Sogn
*/
#include <gsSolver/gsBlockPreconditioner.h>

namespace gismo
{

gsBlockOp::gsBlockOp(index_t nRows, index_t nCols)
{
    blockPrec.resize(nRows, nCols);
    blockTargetPositions.setZero(nCols);
    blockInputPositions.setZero(nRows);
    // Fill up all block entries with null pointers.
    for (index_t i = 0; i < nRows; ++i)
        for (index_t j = 0; j < nCols; ++j)
            blockPrec(i,j).reset();
}

void gsBlockOp::addOperator(index_t row, index_t col, const BasePtr& op)
{
    GISMO_ASSERT( row >= 0 && row < blockPrec.rows(), "The given row is not feasible." );
    GISMO_ASSERT( col >= 0 && col < blockPrec.cols(), "The given column is not feasible." );
    GISMO_ASSERT( op->rows() == blockTargetPositions[row] || blockTargetPositions[row] == 0,
                  "The size of the given preconditioner does not fit to the other preconditioners in the same row." );
    GISMO_ASSERT( op->cols() == blockTargetPositions[col] || blockTargetPositions[col] == 0,
                  "The size of the given preconditioner does not fit to the other preconditioners in the same column." );

    blockPrec(row, col) = op;
    blockTargetPositions[row] = op->rows();
    blockInputPositions[col] = op->cols();
}

void gsBlockOp::apply(const gsMatrix<real_t> & input, gsMatrix<real_t> & result) const
{
    result.setZero(blockTargetPositions.sum(), input.cols());
    gsVector<index_t> singleCol(1);
    singleCol <<  input.cols();
    gsMatrix<real_t>::BlockView resultBlocks= result.blockView(blockTargetPositions, singleCol);

    for (index_t i = 0; i < blockPrec.rows() ; ++i)
    {
        index_t inputIndex = 0;
        for (index_t j = 0; j < blockPrec.cols(); ++j)
        {
            if (!blockPrec(i,j))// if the block is a null pointer
            {
                inputIndex += blockInputPositions(j);
                continue;
            }

            gsMatrix<real_t> tmp_result;
            blockPrec(i,j)->apply(input.block(inputIndex,0,blockInputPositions(j),input.cols()),tmp_result);
            resultBlocks(i) += tmp_result;
            inputIndex += blockInputPositions(j);
        }
    }
}

const gsBlockOp::BasePtr & gsBlockOp::getOperator(index_t row, index_t col) const
{
    GISMO_ASSERT((bool)blockPrec(row, col)!=0, "No linear operator exists in this block");
    return blockPrec(row,col);
}

}

<|endoftext|>


<commit_before><commit_msg>[Second attempt]<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Utils/CardSetUtils.hpp>

#include <Rosetta/Actions/Draw.hpp>
#include <Rosetta/Cards/Cards.hpp>

using namespace RosettaStone;
using namespace PlayerTasks;
using namespace SimpleTasks;

TEST(Expert1CardsGen, CS2_028)
{
    GameConfig config;
    config.player1Class = CardClass::MAGE;
    config.player2Class = CardClass::PALADIN;
    config.startPlayer = PlayerType::PLAYER1;
    config.doFillDecks = true;
    config.autoRun = false;

    Game game(config);
    game.StartGame();

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetOpponentPlayer();
    curPlayer.SetTotalMana(10);
    curPlayer.SetUsedMana(0);
    opPlayer.SetTotalMana(10);
    opPlayer.SetUsedMana(0);

    auto& opField = opPlayer.GetField();

    const auto card1 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Blizzard"));
    const auto card2 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre"));
    const auto card3 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Wolfrider"));

    Task::Run(curPlayer, EndTurnTask());
    game.ProcessUntil(Step::MAIN_START);

    Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card2));
    Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card3));
    EXPECT_EQ(opField.GetNumOfMinions(), 2u);

    Task::Run(opPlayer, EndTurnTask());
    game.ProcessUntil(Step::MAIN_START);

    Task::Run(curPlayer, PlayCardTask::Spell(curPlayer, card1));
    EXPECT_EQ(opField.GetNumOfMinions(), 1u);
    EXPECT_EQ(opField.GetMinion(0)->GetHealth(), 5);
    EXPECT_EQ(opField.GetMinion(0)->GetGameTag(GameTag::FROZEN), 1);
    EXPECT_EQ(opPlayer.GetHero()->GetHealth(), 30);
    EXPECT_EQ(opPlayer.GetHero()->GetGameTag(GameTag::FROZEN), 0);
}

TEST(Expert1CardsGen, CS2_151)
{
    GameConfig config;
    config.player1Class = CardClass::PALADIN;
    config.player2Class = CardClass::WARRIOR;
    config.startPlayer = PlayerType::PLAYER1;
    config.doFillDecks = true;
    config.autoRun = false;

    Game game(config);
    game.StartGame();
    game.ProcessUntil(Step::MAIN_START);

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetOpponentPlayer();
    curPlayer.SetTotalMana(10);
    curPlayer.SetUsedMana(0);
    opPlayer.SetTotalMana(10);
    opPlayer.SetUsedMana(0);

    auto& curField = curPlayer.GetField();

    const auto card1 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Silver Hand Knight"));

    Task::Run(curPlayer, PlayCardTask::Minion(curPlayer, card1));
    EXPECT_EQ(curField.GetMinion(0)->GetAttack(), 4);
    EXPECT_EQ(curField.GetMinion(0)->GetHealth(), 4);
    EXPECT_EQ(curField.GetMinion(1)->GetAttack(), 2);
    EXPECT_EQ(curField.GetMinion(1)->GetHealth(), 2);
}

TEST(Expert1CardsGen, CS2_117)
{
    GameConfig config;
    config.player1Class = CardClass::PALADIN;
    config.player2Class = CardClass::WARRIOR;
    config.startPlayer = PlayerType::PLAYER1;
    config.doFillDecks = true;
    config.autoRun = false;

    Game game(config);
    game.StartGame();
    game.ProcessUntil(Step::MAIN_START);

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetOpponentPlayer();
    curPlayer.SetTotalMana(10);
    curPlayer.SetUsedMana(0);
    opPlayer.SetTotalMana(10);
    opPlayer.SetUsedMana(0);
    curPlayer.GetHero()->SetDamage(10);

    auto& opField = opPlayer.GetField();

    const auto card1 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Earthen Ring Farseer"));
    const auto card2 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Earthen Ring Farseer"));
    const auto card3 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));

    Task::Run(curPlayer, EndTurnTask());
    game.ProcessUntil(Step::MAIN_START);

    Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card3));
    opField.GetMinion(0)->SetDamage(1);

    Task::Run(opPlayer, EndTurnTask());
    game.ProcessUntil(Step::MAIN_START);

    Task::Run(curPlayer, PlayCardTask::MinionTarget(curPlayer, card1,
                                                    curPlayer.GetHero()));
    EXPECT_EQ(curPlayer.GetHero()->GetHealth(), 23);

    Task::Run(curPlayer, PlayCardTask::MinionTarget(curPlayer, card2, card3));
    EXPECT_EQ(opField.GetMinion(0)->GetHealth(), 2);
}

TEST(Expert1CardsGen, EX1_012)
{
    GameConfig config;
    config.player1Class = CardClass::MAGE;
    config.player2Class = CardClass::PALADIN;
    config.startPlayer = PlayerType::PLAYER1;
    config.doFillDecks = true;
    config.autoRun = false;

    Game game(config);
    game.StartGame();
    game.ProcessUntil(Step::MAIN_START);

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetOpponentPlayer();
    curPlayer.SetTotalMana(10);
    curPlayer.SetUsedMana(0);
    opPlayer.SetTotalMana(10);
    opPlayer.SetUsedMana(0);

    auto& curField = curPlayer.GetField();
    auto& opField = opPlayer.GetField();

    const auto card1 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Bloodmage Thalnos"));
    const auto card2 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Blizzard"));
    const auto card3 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre"));
    const auto card4 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Wolfrider"));
    const auto card5 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Wolfrider"));

    Task::Run(curPlayer, EndTurnTask());
    game.ProcessUntil(Step::MAIN_START);

    Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card3));
    Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card4));
    EXPECT_EQ(opField.GetNumOfMinions(), 2u);

    Task::Run(opPlayer, EndTurnTask());
    game.ProcessUntil(Step::MAIN_START);

    Task::Run(curPlayer, PlayCardTask::Minion(curPlayer, card1));
    EXPECT_EQ(curPlayer.currentSpellPower, 1);

    Task::Run(curPlayer, PlayCardTask::Spell(curPlayer, card2));
    EXPECT_EQ(opField.GetNumOfMinions(), 1u);
    EXPECT_EQ(opField.GetMinion(0)->GetHealth(), 4);
    EXPECT_EQ(opField.GetMinion(0)->GetGameTag(GameTag::FROZEN), 1);

    Task::Run(curPlayer, EndTurnTask());
    game.ProcessUntil(Step::MAIN_START);

    Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card5));
    Task::Run(opPlayer, AttackTask(card5, card1));
    EXPECT_EQ(curField.GetNumOfMinions(), 0u);
    EXPECT_EQ(curPlayer.currentSpellPower, 0);
    EXPECT_EQ(curPlayer.GetHand().GetNumOfCards(), 6u);
}<commit_msg>test: Add test code for checking frozen state<commit_after>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Utils/CardSetUtils.hpp>

#include <Rosetta/Actions/Draw.hpp>
#include <Rosetta/Cards/Cards.hpp>

using namespace RosettaStone;
using namespace PlayerTasks;
using namespace SimpleTasks;

TEST(Expert1CardsGen, CS2_028)
{
    GameConfig config;
    config.player1Class = CardClass::MAGE;
    config.player2Class = CardClass::PALADIN;
    config.startPlayer = PlayerType::PLAYER1;
    config.doFillDecks = true;
    config.autoRun = false;

    Game game(config);
    game.StartGame();

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetOpponentPlayer();
    curPlayer.SetTotalMana(10);
    curPlayer.SetUsedMana(0);
    opPlayer.SetTotalMana(10);
    opPlayer.SetUsedMana(0);

    auto& opField = opPlayer.GetField();

    const auto card1 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Blizzard"));
    const auto card2 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre"));
    const auto card3 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Wolfrider"));

    Task::Run(curPlayer, EndTurnTask());
    game.ProcessUntil(Step::MAIN_START);

    Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card2));
    Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card3));
    EXPECT_EQ(opField.GetNumOfMinions(), 2u);

    Task::Run(opPlayer, EndTurnTask());
    game.ProcessUntil(Step::MAIN_START);

    Task::Run(curPlayer, PlayCardTask::Spell(curPlayer, card1));
    EXPECT_EQ(opField.GetNumOfMinions(), 1u);
    EXPECT_EQ(opField.GetMinion(0)->GetHealth(), 5);
    EXPECT_EQ(opField.GetMinion(0)->GetGameTag(GameTag::FROZEN), 1);
    EXPECT_EQ(opPlayer.GetHero()->GetHealth(), 30);
    EXPECT_EQ(opPlayer.GetHero()->GetGameTag(GameTag::FROZEN), 0);

    Task::Run(curPlayer, EndTurnTask());
    game.ProcessUntil(Step::MAIN_START);

    Task::Run(opPlayer, AttackTask(card2, curPlayer.GetHero()));
    EXPECT_EQ(opField.GetMinion(0)->GetGameTag(GameTag::FROZEN), 1);
    EXPECT_EQ(curPlayer.GetHero()->GetHealth(), 30);

    Task::Run(opPlayer, EndTurnTask());
    game.ProcessUntil(Step::MAIN_START);

    EXPECT_EQ(opField.GetMinion(0)->GetGameTag(GameTag::FROZEN), 0);
}

TEST(Expert1CardsGen, CS2_151)
{
    GameConfig config;
    config.player1Class = CardClass::PALADIN;
    config.player2Class = CardClass::WARRIOR;
    config.startPlayer = PlayerType::PLAYER1;
    config.doFillDecks = true;
    config.autoRun = false;

    Game game(config);
    game.StartGame();
    game.ProcessUntil(Step::MAIN_START);

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetOpponentPlayer();
    curPlayer.SetTotalMana(10);
    curPlayer.SetUsedMana(0);
    opPlayer.SetTotalMana(10);
    opPlayer.SetUsedMana(0);

    auto& curField = curPlayer.GetField();

    const auto card1 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Silver Hand Knight"));

    Task::Run(curPlayer, PlayCardTask::Minion(curPlayer, card1));
    EXPECT_EQ(curField.GetMinion(0)->GetAttack(), 4);
    EXPECT_EQ(curField.GetMinion(0)->GetHealth(), 4);
    EXPECT_EQ(curField.GetMinion(1)->GetAttack(), 2);
    EXPECT_EQ(curField.GetMinion(1)->GetHealth(), 2);
}

TEST(Expert1CardsGen, CS2_117)
{
    GameConfig config;
    config.player1Class = CardClass::PALADIN;
    config.player2Class = CardClass::WARRIOR;
    config.startPlayer = PlayerType::PLAYER1;
    config.doFillDecks = true;
    config.autoRun = false;

    Game game(config);
    game.StartGame();
    game.ProcessUntil(Step::MAIN_START);

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetOpponentPlayer();
    curPlayer.SetTotalMana(10);
    curPlayer.SetUsedMana(0);
    opPlayer.SetTotalMana(10);
    opPlayer.SetUsedMana(0);
    curPlayer.GetHero()->SetDamage(10);

    auto& opField = opPlayer.GetField();

    const auto card1 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Earthen Ring Farseer"));
    const auto card2 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Earthen Ring Farseer"));
    const auto card3 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Acidic Swamp Ooze"));

    Task::Run(curPlayer, EndTurnTask());
    game.ProcessUntil(Step::MAIN_START);

    Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card3));
    opField.GetMinion(0)->SetDamage(1);

    Task::Run(opPlayer, EndTurnTask());
    game.ProcessUntil(Step::MAIN_START);

    Task::Run(curPlayer, PlayCardTask::MinionTarget(curPlayer, card1,
                                                    curPlayer.GetHero()));
    EXPECT_EQ(curPlayer.GetHero()->GetHealth(), 23);

    Task::Run(curPlayer, PlayCardTask::MinionTarget(curPlayer, card2, card3));
    EXPECT_EQ(opField.GetMinion(0)->GetHealth(), 2);
}

TEST(Expert1CardsGen, EX1_012)
{
    GameConfig config;
    config.player1Class = CardClass::MAGE;
    config.player2Class = CardClass::PALADIN;
    config.startPlayer = PlayerType::PLAYER1;
    config.doFillDecks = true;
    config.autoRun = false;

    Game game(config);
    game.StartGame();
    game.ProcessUntil(Step::MAIN_START);

    Player& curPlayer = game.GetCurrentPlayer();
    Player& opPlayer = game.GetOpponentPlayer();
    curPlayer.SetTotalMana(10);
    curPlayer.SetUsedMana(0);
    opPlayer.SetTotalMana(10);
    opPlayer.SetUsedMana(0);

    auto& curField = curPlayer.GetField();
    auto& opField = opPlayer.GetField();

    const auto card1 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Bloodmage Thalnos"));
    const auto card2 = Generic::DrawCard(
        curPlayer, Cards::GetInstance().FindCardByName("Blizzard"));
    const auto card3 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Boulderfist Ogre"));
    const auto card4 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Wolfrider"));
    const auto card5 = Generic::DrawCard(
        opPlayer, Cards::GetInstance().FindCardByName("Wolfrider"));

    Task::Run(curPlayer, EndTurnTask());
    game.ProcessUntil(Step::MAIN_START);

    Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card3));
    Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card4));
    EXPECT_EQ(opField.GetNumOfMinions(), 2u);

    Task::Run(opPlayer, EndTurnTask());
    game.ProcessUntil(Step::MAIN_START);

    Task::Run(curPlayer, PlayCardTask::Minion(curPlayer, card1));
    EXPECT_EQ(curPlayer.currentSpellPower, 1);

    Task::Run(curPlayer, PlayCardTask::Spell(curPlayer, card2));
    EXPECT_EQ(opField.GetNumOfMinions(), 1u);
    EXPECT_EQ(opField.GetMinion(0)->GetHealth(), 4);
    EXPECT_EQ(opField.GetMinion(0)->GetGameTag(GameTag::FROZEN), 1);

    Task::Run(curPlayer, EndTurnTask());
    game.ProcessUntil(Step::MAIN_START);

    Task::Run(opPlayer, PlayCardTask::Minion(opPlayer, card5));
    Task::Run(opPlayer, AttackTask(card5, card1));
    EXPECT_EQ(curField.GetNumOfMinions(), 0u);
    EXPECT_EQ(curPlayer.currentSpellPower, 0);
    EXPECT_EQ(curPlayer.GetHand().GetNumOfCards(), 6u);
}<|endoftext|>


<commit_before>#include <windows.h>
#include <string>
#include <sstream>
#include <vector>
#include <codecvt>
#include <iostream>
#include <fstream>
#include <cstdio>

#include <iostream>
#include <fstream>
using namespace std;

inline wstring s2ws(const std::string& str)
{
    typedef codecvt_utf8<wchar_t> convert_typeX;
    wstring_convert<convert_typeX, wchar_t> converterX;
    return converterX.from_bytes(str);
}

#define BUFSIZE 4096
int main(int argc, char** argv)
{
    char chBuf[BUFSIZE];
    unsigned long dwRead = 1;
    BOOL fSuccess = true;
    HANDLE hStdin;
    bool writeToConsole;
    bool writeToFile;
    string consoleName;
    HANDLE out;
    HANDLE fileHandle;
    WORD color;

    if(argc > 4)
    {
        consoleName = string(argv[1]);
        color = atoi(argv[2]);
        writeToConsole = atoi(argv[3]);
        writeToFile = atoi(argv[4]);

        // For some reason this represents the pipe, gg
        hStdin = GetStdHandle(STD_INPUT_HANDLE);
        if(hStdin == INVALID_HANDLE_VALUE)
        {
            ExitProcess(1);
        }
    }
    else
    {
        return 1;
    }

    if(writeToConsole)
    {
        out = CreateFile(TEXT("CONOUT$"), GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);

        if(out == INVALID_HANDLE_VALUE)
        {
            return 1;
        }
        SetConsoleTitle(s2ws(consoleName).c_str());
        SetConsoleTextAttribute(out, color);
    }
    else
    {
        FreeConsole();
    }

    if(writeToFile)
    {
        // Create log folder
        CreateDirectory(L"logs", NULL);

        // Build logfilename
        struct tm now;
        time_t time_create = time(NULL);
        localtime_s(&now, &time_create);
        consoleName = string("logs/" + std::to_string(now.tm_hour) + "." + std::to_string(now.tm_min) + "-" + consoleName);
        consoleName.append(".txt");

        // Create the file
        fileHandle = CreateFile(s2ws(consoleName).c_str(), GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_ALWAYS, 0, 0);
        if(fileHandle == INVALID_HANDLE_VALUE)
        {
            return 1;
        }
    }

    while(true)
    {
        if(!fSuccess || !dwRead)
        {
            break;
        }
        fSuccess = ReadFile(hStdin, chBuf, BUFSIZE, &dwRead, NULL);

        if(writeToConsole)
        {
            WriteFile(out, chBuf, dwRead, &dwRead, 0);
        }

        if(writeToFile)
        {
            WriteFile(fileHandle, chBuf, dwRead, &dwRead, 0);
        }
    }
    return 1;
}<commit_msg>Better logfilename and some code cleanup<commit_after>#include <windows.h>
#include <string>
#include <sstream>
#include <vector>
#include <codecvt>
#include <iostream>
#include <fstream>
#include <cstdio>

#include <iostream>
#include <fstream>
using namespace std;

inline wstring s2ws(const std::string& str)
{
    typedef codecvt_utf8<wchar_t> convert_typeX;
    wstring_convert<convert_typeX, wchar_t> converterX;
    return converterX.from_bytes(str);
}

inline string getTwoDigit(const int& value)
{
    if(value < 10)
    {
        return string("0" + value);
    }
    return to_string(value);
}

inline string buildLogFileName(const string& p_consoleName)
{
    struct tm now;
    time_t time_create = time(NULL);
    localtime_s(&now, &time_create);

    string fileName = string("logs/");
    fileName.append(getTwoDigit(now.tm_year + 1900) + "-");
    fileName.append(getTwoDigit(now.tm_mon + 1) + "-");
    fileName.append(getTwoDigit(now.tm_mday) + "_");
    fileName.append(getTwoDigit(now.tm_hour) + ".");
    fileName.append(getTwoDigit(now.tm_min));
    fileName.append("__" + p_consoleName);
    fileName.append(".txt");
    return fileName;
}

#define BUFSIZE 4096
int main(int argc, char** argv)
{
    char chBuf[BUFSIZE];
    unsigned long dwRead = 1;
    BOOL fSuccess = true;
    HANDLE hStdin;
    bool writeToConsole;
    bool writeToFile;
    string consoleName;
    HANDLE out;
    HANDLE fileHandle;
    WORD color;

    if(argc > 4)
    {
        // TODORT Handle client and server logs
        consoleName = string(argv[1]);
        color = atoi(argv[2]);
        writeToConsole = atoi(argv[3]);
        writeToFile = atoi(argv[4]);

        // For some reason this represents the pipe, gg
        hStdin = GetStdHandle(STD_INPUT_HANDLE);
        if(hStdin == INVALID_HANDLE_VALUE)
        {
#ifdef _DEBUG
            system("pause");
#endif
            ExitProcess(1); // TODORT more info
        }
    }
    else
    {
#ifdef _DEBUG
        system("pause");
#endif
        ExitProcess(1); // TODORT more info
    }

    if(writeToConsole)
    {
        out = CreateFile(TEXT("CONOUT$"), GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);

        if(out == INVALID_HANDLE_VALUE)
        {
            writeToConsole = false;
        }
        SetConsoleTitle(s2ws(consoleName).c_str());
        SetConsoleTextAttribute(out, color);
    }
    else
    {
        FreeConsole();
    }

    if(writeToFile)
    {
        // Create log folder
        CreateDirectory(L"logs", NULL);

        // Build logfilename
        const string& fileName = buildLogFileName(consoleName);

        // Create the file
        fileHandle = CreateFile(s2ws(fileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_ALWAYS, 0, 0);
        // TODO Add check to create another logfile if one already exists, because two clients may be runned at the same computer.

        if(fileHandle == INVALID_HANDLE_VALUE)
        {
            writeToFile = false;
        }
    }

    if(!writeToFile || !writeToConsole)
    {
#ifdef _DEBUG
        system("pause");
#endif
        ExitProcess(1); // TODORT more info
    }

    while(true)
    {
        if(!fSuccess || !dwRead)
        {
            break;
        }
        fSuccess = ReadFile(hStdin, chBuf, BUFSIZE, &dwRead, NULL);

        if(writeToConsole)
        {
            WriteFile(out, chBuf, dwRead, &dwRead, 0);
        }

        if(writeToFile)
        {
            WriteFile(fileHandle, chBuf, dwRead, &dwRead, 0);
        }
    }
    return 0;
}<|endoftext|>


<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"

#include "GridMesh.h"
#include "CameraLandscape.h"
#include "cinder/MotionManager.h"
#include "cinder/Capture.h"
#include "cinder/Log.h"
#include "GridTexture.h"

using namespace ci;
using namespace ci::app;
using namespace std;

using namespace soso;

class GridSpaceApp : public App {
public:
	void setup() override;
	void mouseDown( MouseEvent event ) override;
	void update() override;
	void draw() override;

	void blurInput();
private:
	GridMesh				mesh;
	CameraLandscape landscape;
	CaptureRef			capture;
	CameraPersp			camera;
	GridTextureRef	gridTexture;
	gl::FboRef			blurredBuffer;
	gl::GlslProgRef	downsampleProg;
};

void GridSpaceApp::setup()
{
	mesh.setup();

	MotionManager::enable();

	GLint size;
	glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size );
	CI_LOG_I( "Max texture size: " << size );

	auto target = vec3( 50, 5, 50 );
	camera.lookAt( vec3( 0 ), target, vec3( 0, 1, 0 ) );
	camera.setPerspective( 60, getWindowAspectRatio(), 0.1f, 1000 );

	try {
		auto front_facing_camera = ([] {
			auto &devices = Capture::getDevices();
			auto first_device = devices.front();
			for( auto device : devices ) {
				if( device->isFrontFacing() ) {
					return device;
				}
			}
			return first_device;
		}());

		capture = Capture::create( 480, 360, front_facing_camera );
		capture->start();
		const auto divisions = 8;
		const auto size = divisions * capture->getSize();
		gridTexture = make_shared<GridTexture>( size.x, size.y, divisions );

		auto color_format = gl::Texture::Format();
		auto fbo_format = gl::Fbo::Format().disableDepth().colorTexture( color_format );
		blurredBuffer = gl::Fbo::create( size.x / (divisions * 2), size.y / (divisions * 2), fbo_format );
	}
	catch( ci::Exception &exc ) {
		CI_LOG_E( "Error using device camera: " << exc.what() );
	}

	downsampleProg = gl::GlslProg::create( loadAsset( "blur.vs" ), loadAsset( "blur.fs" ) );
//	landscape.setup( gridTexture->getTexture() );
	landscape.setup( blurredBuffer->getColorTexture() );
}

void GridSpaceApp::mouseDown( MouseEvent event )
{
}

void GridSpaceApp::update()
{
	if( MotionManager::isDataAvailable() ) {
		auto r = MotionManager::getRotation();
		camera.setOrientation( r );
	}

	if( capture->checkNewFrame() ) {
		gridTexture->update( *capture->getSurface() );
		blurInput();
	}
}

void GridSpaceApp::blurInput()
{
	auto index = gridTexture->getCurrentIndex();
	auto size = blurredBuffer->getSize() / 8;

	gl::ScopedMatrices matrices;
	gl::ScopedTextureBind tex0( gridTexture->getTexture(), 0 );
	gl::ScopedGlslProg prog( downsampleProg );
	gl::ScopedViewport view( gridTexture->getIndexOffset( size, index ), size );
	gl::ScopedFramebuffer fbo( blurredBuffer );

	downsampleProg->uniform( "uSampler", 0 );
	downsampleProg->uniform( "uFrameIndex", (float)index );

	gl::drawSolidRect( Rectf( -1, -1, 1, 1 ), vec2( 0, 0 ), vec2( 1, 1 ) );
}

void GridSpaceApp::draw()
{
	gl::clear( Color( 0, 0, 0 ) );
	gl::enableDepthRead();
	gl::enableDepthWrite();

	gl::setMatrices( camera );
	landscape.draw( gridTexture->getCurrentIndex() );
	mesh.draw();

	if( gridTexture->getTexture() ) {
		auto size = vec2(192, 108) * 0.8f;
		gl::ScopedMatrices mat;
		gl::setMatricesWindow( app::getWindowSize() );
		gl::draw( gridTexture->getTexture(), Rectf( vec2(0), size ) );

		gl::translate( size * vec2(1, 0) );
		gl::draw( blurredBuffer->getColorTexture(), Rectf( vec2(0), size ) );
	}
}

CINDER_APP( GridSpaceApp, RendererGl )
<commit_msg>Fix popping issue.<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"

#include "GridMesh.h"
#include "CameraLandscape.h"
#include "cinder/MotionManager.h"
#include "cinder/Capture.h"
#include "cinder/Log.h"
#include "GridTexture.h"

using namespace ci;
using namespace ci::app;
using namespace std;

using namespace soso;

class GridSpaceApp : public App {
public:
	void setup() override;
	void mouseDown( MouseEvent event ) override;
	void update() override;
	void draw() override;

	void blurInput();
private:
	GridMesh				mesh;
	CameraLandscape landscape;
	CaptureRef			capture;
	CameraPersp			camera;
	GridTextureRef	gridTexture;
	gl::FboRef			blurredBuffer;
	gl::GlslProgRef	downsampleProg;
};

void GridSpaceApp::setup()
{
	mesh.setup();

	MotionManager::enable();

	GLint size;
	glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size );
	CI_LOG_I( "Max texture size: " << size );

	auto target = vec3( 50, 5, 50 );
	camera.lookAt( vec3( 0 ), target, vec3( 0, 1, 0 ) );
	camera.setPerspective( 60, getWindowAspectRatio(), 0.1f, 1000 );

	try {
		auto front_facing_camera = ([] {
			auto &devices = Capture::getDevices();
			auto first_device = devices.front();
			for( auto device : devices ) {
				if( device->isFrontFacing() ) {
					return device;
				}
			}
			return first_device;
		}());

		capture = Capture::create( 480, 360, front_facing_camera );
		capture->start();
		const auto divisions = 8;
		const auto size = divisions * capture->getSize();
		gridTexture = make_shared<GridTexture>( size.x, size.y, divisions );

		auto color_format = gl::Texture::Format();
		auto fbo_format = gl::Fbo::Format().disableDepth().colorTexture( color_format );
		blurredBuffer = gl::Fbo::create( size.x / (divisions), size.y / (divisions), fbo_format );
	}
	catch( ci::Exception &exc ) {
		CI_LOG_E( "Error using device camera: " << exc.what() );
	}

	downsampleProg = gl::GlslProg::create( loadAsset( "blur.vs" ), loadAsset( "blur.fs" ) );
//	landscape.setup( gridTexture->getTexture() );
	landscape.setup( blurredBuffer->getColorTexture() );
}

void GridSpaceApp::mouseDown( MouseEvent event )
{
}

void GridSpaceApp::update()
{
	if( MotionManager::isDataAvailable() ) {
		auto r = MotionManager::getRotation();
		camera.setOrientation( r );
	}

	if( capture->checkNewFrame() ) {
		gridTexture->update( *capture->getSurface() );
		blurInput();
	}
}

void GridSpaceApp::blurInput()
{
	auto index = gridTexture->getCurrentIndex();
	auto size = blurredBuffer->getSize() / 8;

	gl::ScopedMatrices matrices;
	gl::ScopedTextureBind tex0( gridTexture->getTexture(), 0 );
	gl::ScopedGlslProg prog( downsampleProg );
	gl::ScopedViewport view( gridTexture->getIndexOffset( size, index ), size );
	gl::ScopedFramebuffer fbo( blurredBuffer );

	downsampleProg->uniform( "uSampler", 0 );
	downsampleProg->uniform( "uFrameIndex", (float)index );

	gl::drawSolidRect( Rectf( -1, -1, 1, 1 ), vec2( 0, 0 ), vec2( 1, 1 ) );
}

void GridSpaceApp::draw()
{
	gl::clear( Color( 0, 0, 0 ) );
	gl::enableDepthRead();
	gl::enableDepthWrite();

	gl::setMatrices( camera );
	landscape.draw( gridTexture->getCurrentIndex() );
	mesh.draw();

	if( gridTexture->getTexture() ) {
		auto size = vec2(192, 108) * 0.8f;
		gl::ScopedMatrices mat;
		gl::setMatricesWindow( app::getWindowSize() );
		gl::draw( gridTexture->getTexture(), Rectf( vec2(0), size ) );

		gl::translate( size * vec2(1, 0) );
		gl::draw( blurredBuffer->getColorTexture(), Rectf( vec2(0), size ) );
	}
}

CINDER_APP( GridSpaceApp, RendererGl )
<|endoftext|>


<commit_before>#include "core_include/api.h"
#include "core_include/rect.h"
#include "core_include/cmd_target.h"
#include "core_include/wnd.h"
#include "core_include/surface.h"
#include "core_include/resource.h"
#include "core_include/word.h"
#include "core_include/msg.h"
#include "core_include/display.h"
#include "core_include/theme.h"
#include "widgets_include/label.h"
#include "widgets_include/button.h"
#include <stdlib.h>
#include <stdio.h>

const int UI_WIDTH = 240;
const int UI_HEIGHT = 320;

//////////////////////// define widgets & map message ////////////////////////
enum WND_ID
{
	ID_ROOT = 1,
	ID_LABEL1,
	ID_LABEL2,
	ID_LABEL3,
	ID_BUTTON1,
	ID_BUTTON2,
	ID_BUTTON3
};

class c_myUI : public c_wnd
{
	virtual c_wnd* clone() { return new c_myUI(); }
	virtual void on_paint(void)
	{
		c_rect rect;
		get_screen_rect(rect);
		m_surface->fill_rect(rect, GL_RGB(0, 0, 0), m_z_order);
	}
	void on_clicked(unsigned int ctrl_id) {
		static int sum1, sum2, sum3;
		static char str1[8], str2[8], str3[8];
		c_button* button = (c_button*)get_wnd_ptr(ctrl_id);
		switch (ctrl_id)
		{
		case ID_BUTTON1:
			sprintf(str1, "%d", ++sum1);
			button->set_str(str1);
			break;
		case ID_BUTTON2:
			sprintf(str2, "%d", ++sum2);
			button->set_str(str2);
			break;
		case ID_BUTTON3:
			sprintf(str3, "%d", ++sum3);
			button->set_str(str3);
			break;
		}
		button->show_window();
	}
	GL_DECLARE_MESSAGE_MAP()//delcare message
};

//map message
GL_BEGIN_MESSAGE_MAP(c_myUI)
ON_GL_BN_CLICKED(ID_BUTTON1, c_myUI::on_clicked)
ON_GL_BN_CLICKED(ID_BUTTON2, c_myUI::on_clicked)
ON_GL_BN_CLICKED(ID_BUTTON3, c_myUI::on_clicked)
GL_END_MESSAGE_MAP()

//////////////////////// layout UI ////////////////////////
static c_myUI s_myUI;
static c_label s_label1, s_label2, s_label3;
static c_button s_button1, s_button2, s_button3;
static WND_TREE s_myUI_children[] =
{
	{&s_label1, ID_LABEL1, "a: <<", 20, 20, 80, 40, NULL},
	{&s_label2, ID_LABEL2, "d: >>", 20, 140, 80, 40, NULL},
	{&s_label3, ID_LABEL3, "s: click", 20, 260, 80, 40, NULL},

	{&s_button1, ID_BUTTON1, "0", 140, 20, 80, 40, NULL},
	{&s_button2, ID_BUTTON2, "0", 140, 140, 80, 40, NULL},
	{&s_button3, ID_BUTTON3, "0", 140, 260, 80, 40, NULL},
	{ NULL,0,0,0,0,0,0 }
};

//////////////////////// start UI ////////////////////////
extern const FONT_INFO Consolas_28;
void load_resource()
{
	c_theme::add_font(FONT_DEFAULT, &Consolas_28);
	//for button
	c_theme::add_color(COLOR_WND_FONT, GL_RGB(0, 0, 0));
	c_theme::add_color(COLOR_WND_NORMAL, GL_RGB(255, 255, 255));
	c_theme::add_color(COLOR_WND_PUSHED, GL_RGB(128, 128, 128));
	c_theme::add_color(COLOR_WND_FOCUS, GL_RGB(0, 255, 0));
	c_theme::add_color(COLOR_WND_BORDER, GL_RGB(0, 255, 0));
}

static c_display* s_display;
void create_ui(void* phy_fb, int screen_width, int screen_height, int color_bytes, struct EXTERNAL_GFX_OP* gfx_op)
{
	load_resource();
	s_display = new c_display(phy_fb, screen_width, screen_height, UI_WIDTH, UI_HEIGHT, color_bytes, 1, gfx_op);
	c_surface* surface = s_display->alloc_surface(&s_myUI, Z_ORDER_LEVEL_0);
	surface->set_active(true);
	s_myUI.set_surface(surface);
	s_myUI.connect(NULL, ID_ROOT, 0, 0, 0, UI_WIDTH, UI_HEIGHT, s_myUI_children);
	s_myUI.show_window();
}

//////////////////////// interface for all platform ////////////////////////
extern "C" void startHelloNoTouch(void* phy_fb, int width, int height, int color_bytes, struct EXTERNAL_GFX_OP* gfx_op)
{
	create_ui(phy_fb, width, height, color_bytes, gfx_op);
}

extern "C" void sendTouch2HelloNoTouch(int x, int y, bool is_down)
{
	is_down ? s_myUI.on_touch(x, y, TOUCH_DOWN) : s_myUI.on_touch(x, y, TOUCH_UP);
}

extern "C" void sendKey2HelloNoTouch(unsigned int key)
{
	s_myUI.on_key(KEY_TYPE(key));
}

int captureUiOfHelloNoTouch()
{
	return s_display->snap_shot("snap_short.bmp");
}
<commit_msg>fix color configure for HelloNoTouch<commit_after>#include "core_include/api.h"
#include "core_include/rect.h"
#include "core_include/cmd_target.h"
#include "core_include/wnd.h"
#include "core_include/surface.h"
#include "core_include/resource.h"
#include "core_include/word.h"
#include "core_include/msg.h"
#include "core_include/display.h"
#include "core_include/theme.h"
#include "widgets_include/label.h"
#include "widgets_include/button.h"
#include <stdlib.h>
#include <stdio.h>

const int UI_WIDTH = 240;
const int UI_HEIGHT = 320;

//////////////////////// define widgets & map message ////////////////////////
enum WND_ID
{
	ID_ROOT = 1,
	ID_LABEL1,
	ID_LABEL2,
	ID_LABEL3,
	ID_BUTTON1,
	ID_BUTTON2,
	ID_BUTTON3
};

class c_myUI : public c_wnd
{
	virtual c_wnd* clone() { return new c_myUI(); }
	virtual void on_paint(void)
	{
		c_rect rect;
		get_screen_rect(rect);
		m_surface->fill_rect(rect, GL_RGB(0, 0, 0), m_z_order);
	}
	void on_clicked(unsigned int ctrl_id) {
		static int sum1, sum2, sum3;
		static char str1[8], str2[8], str3[8];
		c_button* button = (c_button*)get_wnd_ptr(ctrl_id);
		switch (ctrl_id)
		{
		case ID_BUTTON1:
			sprintf(str1, "%d", ++sum1);
			button->set_str(str1);
			break;
		case ID_BUTTON2:
			sprintf(str2, "%d", ++sum2);
			button->set_str(str2);
			break;
		case ID_BUTTON3:
			sprintf(str3, "%d", ++sum3);
			button->set_str(str3);
			break;
		}
		button->show_window();
	}
	GL_DECLARE_MESSAGE_MAP()//delcare message
};

//map message
GL_BEGIN_MESSAGE_MAP(c_myUI)
ON_GL_BN_CLICKED(ID_BUTTON1, c_myUI::on_clicked)
ON_GL_BN_CLICKED(ID_BUTTON2, c_myUI::on_clicked)
ON_GL_BN_CLICKED(ID_BUTTON3, c_myUI::on_clicked)
GL_END_MESSAGE_MAP()

//////////////////////// layout UI ////////////////////////
static c_myUI s_myUI;
static c_label s_label1, s_label2, s_label3;
static c_button s_button1, s_button2, s_button3;
static WND_TREE s_myUI_children[] =
{
	{&s_label1, ID_LABEL1, "a: <<", 20, 20, 80, 40, NULL},
	{&s_label2, ID_LABEL2, "d: >>", 20, 140, 80, 40, NULL},
	{&s_label3, ID_LABEL3, "s: click", 20, 260, 80, 40, NULL},

	{&s_button1, ID_BUTTON1, "0", 140, 20, 80, 40, NULL},
	{&s_button2, ID_BUTTON2, "0", 140, 140, 80, 40, NULL},
	{&s_button3, ID_BUTTON3, "0", 140, 260, 80, 40, NULL},
	{ NULL,0,0,0,0,0,0 }
};

//////////////////////// start UI ////////////////////////
extern const FONT_INFO Consolas_28;
void load_resource()
{
	c_theme::add_font(FONT_DEFAULT, &Consolas_28);
	//for button
	c_theme::add_color(COLOR_WND_FONT, GL_RGB(255, 255, 243));
	c_theme::add_color(COLOR_WND_NORMAL, GL_RGB(59, 75, 94));
	c_theme::add_color(COLOR_WND_PUSHED, GL_RGB(33, 42, 53));
	c_theme::add_color(COLOR_WND_FOCUS, GL_RGB(78, 198, 76));
	c_theme::add_color(COLOR_WND_BORDER, GL_RGB(46, 59, 73));
}

static c_display* s_display;
void create_ui(void* phy_fb, int screen_width, int screen_height, int color_bytes, struct EXTERNAL_GFX_OP* gfx_op)
{
	load_resource();
	s_display = new c_display(phy_fb, screen_width, screen_height, UI_WIDTH, UI_HEIGHT, color_bytes, 1, gfx_op);
	c_surface* surface = s_display->alloc_surface(&s_myUI, Z_ORDER_LEVEL_0);
	surface->set_active(true);
	s_myUI.set_surface(surface);
	s_myUI.connect(NULL, ID_ROOT, 0, 0, 0, UI_WIDTH, UI_HEIGHT, s_myUI_children);
	s_myUI.show_window();
}

//////////////////////// interface for all platform ////////////////////////
extern "C" void startHelloNoTouch(void* phy_fb, int width, int height, int color_bytes, struct EXTERNAL_GFX_OP* gfx_op)
{
	create_ui(phy_fb, width, height, color_bytes, gfx_op);
}

extern "C" void sendTouch2HelloNoTouch(int x, int y, bool is_down)
{
	is_down ? s_myUI.on_touch(x, y, TOUCH_DOWN) : s_myUI.on_touch(x, y, TOUCH_UP);
}

extern "C" void sendKey2HelloNoTouch(unsigned int key)
{
	s_myUI.on_key(KEY_TYPE(key));
}

int captureUiOfHelloNoTouch()
{
	return s_display->snap_shot("snap_short.bmp");
}
<|endoftext|>