<commit_before>/*
 * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
 * All rights reserved.
 *
 * This library/application is free software; you can redistribute and/or modify it under the terms of
 * the license that is included with this library/application in the file license.txt.
 */

//--- standard modules used ----------------------------------------------------
#include "Anything.h"
#include "SSLSocket.h"
#include "SSLModule.h"
#include "Dbg.h"

//--- test modules used --------------------------------------------------------
#include "TestSuite.h"

//--- module under test --------------------------------------------------------
#include "RequestListener.h"

//--- interface include --------------------------------------------------------
#include "SSLListenerPoolTest.h"
#include "ListenerPoolTest.h"

//---- SSLListenerPoolTest ----------------------------------------------------------------
SSLListenerPoolTest::SSLListenerPoolTest(TString tname) : ListenerPoolTest(tname)
{
	StartTrace(SSLListenerPoolTest.Ctor);
}

SSLListenerPoolTest::~SSLListenerPoolTest()
{
	StartTrace(SSLListenerPoolTest.Dtor);
}

void SSLListenerPoolTest::PoolTest()
{
	StartTrace(SSLListenerPoolTest.PoolTest);
	Anything config;
	config.Append("TCP5010");
	config.Append("TCP5011");
	config.Append("TCP5012");
	config.Append("TCP5013");
	config.Append("TCP5014");
	config.Append("TCP5015");
	config.Append("TCP5016");
	config.Append("TCP5017");
	config.Append("TCP5018");
	config.Append("TCP5019");
	config.Append("TCP5020");

	TestCallBackFactory *tcbf = new TestCallBackFactory;
	ListenerPool lpToTest(tcbf);

	if ( t_assertm( lpToTest.Init(config.GetSize(), config), "Init should work") && t_assertm(lpToTest.Start(false, 0, 0) == 0, "Start should work")) {
		DoTestConnect();
		if (t_assertm(lpToTest.Terminate(1, 10) == 0, "Terminate failed")) {
			t_assertm(lpToTest.Join() == 0, "Join failed");
			Anything result = tcbf->GetResult();
			t_assert(result.Contains("5010_timeout_0"));
			t_assert(result.Contains("5011_timeout_0"));
			t_assert(result.Contains("5012_timeout_0"));
			t_assert(result.Contains("5013_timeout_0"));
			t_assert(result.Contains("5014_timeout_0"));
			t_assert(result.Contains("5010_timeout_1000"));
			t_assert(result.Contains("5011_timeout_1000"));
			t_assert(result.Contains("5012_timeout_1000"));
			t_assert(result.Contains("5012_timeout_2000"));
			t_assert(result.Contains("5011_timeout_2000"));
			t_assert(result.Contains("5016_timeout_1000"));
			t_assert(result.Contains("5017_timeout_1000"));
			t_assert(result.Contains("5020_timeout_0"));
		}
	}
	Anything failures = tcbf->GetFailures();
	t_assertm(failures.GetSize() == 0, "Receivers encountered a least one error");
	if (failures.GetSize()) {
		TraceAny(failures, "EYECATCHER Receivers encountered the following errors");
	}
}

void SSLListenerPoolTest::DoTestConnect()
{
	StartTrace(SSLListenerPoolTest.DoTestConnect);
	FOREACH_ENTRY("SSLListenerPoolTest", cConfig, cName) {
		TraceAny(cConfig, "cConfig");
		Trace(cConfig["SSLConnector"].AsLong(1));
		if ( cConfig["SSLConnector"].AsLong(1) == 1 ) {
			if ( cConfig["ConnectorToUse"].AsString() != "" ) {
				// deep clone, no side effect when adding Timeout
				Anything connectorConfig = fTestCaseConfig[cConfig["ConnectorToUse"].AsString()].DeepClone();
				if ( cConfig.IsDefined("TimeoutToUse") ) {
					connectorConfig["Timeout"] = cConfig["TimeoutToUse"].AsLong(0L);
				}
				if ( cConfig.IsDefined("UseThreadLocalMemory") ) {
					connectorConfig["UseThreadLocalMemory"] = cConfig["UseThreadLocalMemory"].AsLong(0L);
				}
				SSLConnector sc(connectorConfig);
				if ( cConfig["DoSendReceiveWithFailure"].AsLong(0) ) {
					DoSendReceiveWithFailure(&sc, cConfig["Data"].DeepClone(),
											 cConfig["IOSGoodAfterSend"].AsLong(0),
											 cConfig["IOSGoodBeforeSend"].AsLong(1));
				} else {
					DoSendReceive(&sc, cConfig["Data"].DeepClone());
				}
			} else {
				SSLConnector sc("localhost", cConfig["PortToUse"].AsLong(0), cConfig["TimeoutToUse"].AsLong(0),
								(SSL_CTX *) NULL, (const char *) NULL, 0L, cConfig["UseThreadLocalMemory"].AsBool(0));
				if ( cConfig["DoSendReceiveWithFailure"].AsLong(0) ) {
					DoSendReceiveWithFailure(&sc, cConfig["Data"].DeepClone(),
											 cConfig["IOSGoodAfterSend"].AsLong(0),
											 cConfig["IOSGoodBeforeSend"].AsLong(1));
				} else {
					DoSendReceive(&sc, cConfig["Data"].DeepClone());
				}
			}
		} else {
			Trace("Using configured NON SSL connector");
			Connector c("localhost", cConfig["PortToUse"].AsLong(0L), cConfig["TimeoutToUse"].AsLong(0L), String(), 0L, cConfig["UseThreadLocalMemory"].AsBool(0));
			if ( cConfig["DoSendReceiveWithFailure"].AsLong(0) ) {
				DoSendReceiveWithFailure(&c, cConfig["Data"].DeepClone(),
										 cConfig["IOSGoodAfterSend"].AsLong(0),
										 cConfig["IOSGoodBeforeSend"].AsLong(1));
			} else {
				DoSendReceive(&c, cConfig["Data"].DeepClone());
			}
		}
	}
}

// builds up a suite of testcases, add a line for each testmethod
Test *SSLListenerPoolTest::suite ()
{
	StartTrace(SSLListenerPoolTest.suite);
	TestSuite *testSuite = new TestSuite;

	testSuite->addTest (NEW_CASE(SSLListenerPoolTest, PoolTest));
//#if !defined(WIN32)
//	testSuite->addTest (NEW_CASE(SSLListenerPoolTest, InitFailureTest)); // test does not work on WIN32
//#endif
	testSuite->addTest (NEW_CASE(SSLListenerPoolTest, NullCallBackFactoryTest));
	testSuite->addTest (NEW_CASE(SSLListenerPoolTest, InitFailureNullAcceptorTest));
	return testSuite;

} // suite
<commit_msg>allow multiple connects with a given connector.   This allowes session resumpition testing<commit_after>/*
 * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
 * All rights reserved.
 *
 * This library/application is free software; you can redistribute and/or modify it under the terms of
 * the license that is included with this library/application in the file license.txt.
 */

//--- standard modules used ----------------------------------------------------
#include "Anything.h"
#include "SSLSocket.h"
#include "SSLModule.h"
#include "Dbg.h"

//--- test modules used --------------------------------------------------------
#include "TestSuite.h"

//--- module under test --------------------------------------------------------
#include "RequestListener.h"

//--- interface include --------------------------------------------------------
#include "SSLListenerPoolTest.h"
#include "ListenerPoolTest.h"

//---- SSLListenerPoolTest ----------------------------------------------------------------
SSLListenerPoolTest::SSLListenerPoolTest(TString tname) : ListenerPoolTest(tname)
{
	StartTrace(SSLListenerPoolTest.Ctor);
}

SSLListenerPoolTest::~SSLListenerPoolTest()
{
	StartTrace(SSLListenerPoolTest.Dtor);
}

void SSLListenerPoolTest::PoolTest()
{
	StartTrace(SSLListenerPoolTest.PoolTest);
	Anything config;
	config.Append("TCP5010");
	config.Append("TCP5011");
	config.Append("TCP5012");
	config.Append("TCP5013");
	config.Append("TCP5014");
	config.Append("TCP5015");
	config.Append("TCP5016");
	config.Append("TCP5017");
	config.Append("TCP5018");
	config.Append("TCP5019");
	config.Append("TCP5020");

	TestCallBackFactory *tcbf = new TestCallBackFactory;
	ListenerPool lpToTest(tcbf);

	if ( t_assertm( lpToTest.Init(config.GetSize(), config), "Init should work") && t_assertm(lpToTest.Start(false, 0, 0) == 0, "Start should work")) {
		DoTestConnect();
		if (t_assertm(lpToTest.Terminate(1, 10) == 0, "Terminate failed")) {
			t_assertm(lpToTest.Join() == 0, "Join failed");
			Anything result = tcbf->GetResult();
			t_assert(result.Contains("5010_timeout_0"));
			t_assert(result.Contains("5011_timeout_0"));
			t_assert(result.Contains("5012_timeout_0"));
			t_assert(result.Contains("5013_timeout_0"));
			t_assert(result.Contains("5014_timeout_0"));
			t_assert(result.Contains("5010_timeout_1000"));
			t_assert(result.Contains("5011_timeout_1000"));
			t_assert(result.Contains("5012_timeout_1000"));
			t_assert(result.Contains("5012_timeout_2000"));
			t_assert(result.Contains("5011_timeout_2000"));
			t_assert(result.Contains("5016_timeout_1000"));
			t_assert(result.Contains("5017_timeout_1000"));
			t_assert(result.Contains("5020_timeout_0"));
		}
	}
	Anything failures = tcbf->GetFailures();
	t_assertm(failures.GetSize() == 0, "Receivers encountered a least one error");
	if (failures.GetSize()) {
		TraceAny(failures, "EYECATCHER Receivers encountered the following errors");
	}
}

void SSLListenerPoolTest::DoTestConnect()
{
	StartTrace(SSLListenerPoolTest.DoTestConnect);
	FOREACH_ENTRY("SSLListenerPoolTest", cConfig, cName) {
		TraceAny(cConfig, "cConfig");
		Trace(cConfig["SSLConnector"].AsLong(1));
		Anything data = cConfig["Data"].DeepClone();
		long connectsToDo = cConfig["NumberOfConnects"].AsLong(1L);
		for ( long l = 0; l < connectsToDo; l++ ) {
			Trace("At connect Nr.: " << l);
			if ( ((connectsToDo - 1) == l) && data.IsDefined("LastChecksToDo") ) {
				data["ChecksToDo"] = data["LastChecksToDo"];
			}
			if ( cConfig["SSLConnector"].AsLong(1) == 1 ) {
				if ( cConfig["ConnectorToUse"].AsString() != "" ) {
					// deep clone, no side effect when adding Timeout
					Anything connectorConfig = fTestCaseConfig[cConfig["ConnectorToUse"].AsString()].DeepClone();
					if ( cConfig.IsDefined("TimeoutToUse") ) {
						connectorConfig["Timeout"] = cConfig["TimeoutToUse"].AsLong(0L);
					}
					if ( cConfig.IsDefined("UseThreadLocalMemory") ) {
						connectorConfig["UseThreadLocalMemory"] = cConfig["UseThreadLocalMemory"].AsLong(0L);
					}
					SSLConnector sc(connectorConfig);
					if ( cConfig["DoSendReceiveWithFailure"].AsLong(0) ) {
						DoSendReceiveWithFailure(&sc, data,
												 cConfig["IOSGoodAfterSend"].AsLong(0),
												 cConfig["IOSGoodBeforeSend"].AsLong(1));
					} else {
						DoSendReceive(&sc, data);
					}
				} else {
					SSLConnector sc("localhost", cConfig["PortToUse"].AsLong(0), cConfig["TimeoutToUse"].AsLong(0),
									(SSL_CTX *) NULL, (const char *) NULL, 0L, cConfig["UseThreadLocalMemory"].AsBool(0));

					if ( cConfig["DoSendReceiveWithFailure"].AsLong(0) ) {
						DoSendReceiveWithFailure(&sc, data,
												 cConfig["IOSGoodAfterSend"].AsLong(0),
												 cConfig["IOSGoodBeforeSend"].AsLong(1));
					} else {
						DoSendReceive(&sc, data);
					}
				}
			} else {
				Trace("Using configured NON SSL connector");
				Connector c("localhost", cConfig["PortToUse"].AsLong(0L), cConfig["TimeoutToUse"].AsLong(0L), String(), 0L, cConfig["UseThreadLocalMemory"].AsBool(0));
				if ( cConfig["DoSendReceiveWithFailure"].AsLong(0) ) {
					DoSendReceiveWithFailure(&c, data,
											 cConfig["IOSGoodAfterSend"].AsLong(0),
											 cConfig["IOSGoodBeforeSend"].AsLong(1));
				} else {
					DoSendReceive(&c, data);
				}
			}
		}
	}
}

// builds up a suite of testcases, add a line for each testmethod
Test *SSLListenerPoolTest::suite ()
{
	StartTrace(SSLListenerPoolTest.suite);
	TestSuite *testSuite = new TestSuite;

	testSuite->addTest (NEW_CASE(SSLListenerPoolTest, PoolTest));
//#if !defined(WIN32)
//	testSuite->addTest (NEW_CASE(SSLListenerPoolTest, InitFailureTest)); // test does not work on WIN32
//#endif
	testSuite->addTest (NEW_CASE(SSLListenerPoolTest, NullCallBackFactoryTest));
	testSuite->addTest (NEW_CASE(SSLListenerPoolTest, InitFailureNullAcceptorTest));
	return testSuite;

} // suite
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include<cmath>
#include "Planner.h"
#include "Build_Map.h"

int main() {
  double xy_res=0.25;
  double z_res=0.25;
  double margin=0.2;
  std::vector<double>Boundary={0.0,-5.0,0.0,10.0,20.0,6.0};
  std::vector<std::vector<double>>Obstacle={{0.0,2.0,0.0,10.0,2.5,1.5},{0.0,2.0,4.5,10.0,2.5,6.0},{0.0,2.0,1.5,3.0,2.5,4.5}};
  Planner Plan;

  //Map_Build

  Build_Map Map=Build_Map(Boundary,xy_res,z_res,margin);

  std::vector<int>World=Map.World_Dimensions();
  Plan.Set_World_Size( {World[0],World[1],World[2]});

  for ( const std::vector<double> &v : Obstacle )
  {
    std::vector<int>Obstacle_Extrema=Map.Build_Obstacle(v);
    for(int Counter_X=Obstacle_Extrema[0];Counter_X!=Obstacle_Extrema[3];Counter_X++){
      for(int Counter_Y=Obstacle_Extrema[1];Counter_Y!=Obstacle_Extrema[4];Counter_Y++){
        for(int Counter_Z=Obstacle_Extrema[2];Counter_Z!=Obstacle_Extrema[5];Counter_Z++){
          Plan.Add_Collision({Counter_X,Counter_Y,Counter_Z});
        }
      }
    }
  }

// Calculations
Plan.Set_Heuristic(Heuristic::Euclidean);
std::cout << "Calculating Shortest path ... \n";
std::vector<double>Start={0,0.5,3};
std::vector<double>Goal={3.9,6.4,0};
std::vector<int>Start_Node=Map.Build_Node(Start);
std::vector<int>Goal_Node=Map.Build_Node(Goal);
auto path = Plan.findPath( {Start_Node[0],Start_Node[1],Start_Node[2]},{Goal_Node[0],Goal_Node[1],Goal_Node[2]});
for (auto& coordinate : path) {
  std::vector<int>Discrete_Node={coordinate.x,coordinate.y,coordinate.z};
  std::vector<double>Coordinates=Map.Get_Coordinate(Discrete_Node);
  std::cout<<Coordinates[0]<<" "<<Coordinates[1]<<" "<<Coordinates[2]<<"\n";
}
}
<commit_msg>Changed the value returned by main() to 0. Task_ID:QA_2_02<commit_after>#include <iostream>
#include <vector>
#include<cmath>
#include "Planner.h"
#include "Build_Map.h"

int main() {
  double xy_res=0.25;
  double z_res=0.25;
  double margin=0.2;
  std::vector<double>Boundary={0.0,-5.0,0.0,10.0,20.0,6.0};
  std::vector<std::vector<double>>Obstacle={{0.0,2.0,0.0,10.0,2.5,1.5},{0.0,2.0,4.5,10.0,2.5,6.0},{0.0,2.0,1.5,3.0,2.5,4.5}};
  Planner Plan;

  //Map_Build

  Build_Map Map=Build_Map(Boundary,xy_res,z_res,margin);

  std::vector<int>World=Map.World_Dimensions();
  Plan.Set_World_Size( {World[0],World[1],World[2]});

  for ( const std::vector<double> &v : Obstacle )
  {
    std::vector<int>Obstacle_Extrema=Map.Build_Obstacle(v);
    for(int Counter_X=Obstacle_Extrema[0];Counter_X!=Obstacle_Extrema[3];Counter_X++){
      for(int Counter_Y=Obstacle_Extrema[1];Counter_Y!=Obstacle_Extrema[4];Counter_Y++){
        for(int Counter_Z=Obstacle_Extrema[2];Counter_Z!=Obstacle_Extrema[5];Counter_Z++){
          Plan.Add_Collision({Counter_X,Counter_Y,Counter_Z});
        }
      }
    }
  }

// Calculations
Plan.Set_Heuristic(Heuristic::Euclidean);
std::cout << "Calculating Shortest path ... \n";
std::vector<double>Start={0,0.5,3};
std::vector<double>Goal={3.9,6.4,0};
std::vector<int>Start_Node=Map.Build_Node(Start);
std::vector<int>Goal_Node=Map.Build_Node(Goal);
auto path = Plan.findPath( {Start_Node[0],Start_Node[1],Start_Node[2]},{Goal_Node[0],Goal_Node[1],Goal_Node[2]});
for (auto& coordinate : path) {
  std::vector<int>Discrete_Node={coordinate.x,coordinate.y,coordinate.z};
  std::vector<double>Coordinates=Map.Get_Coordinate(Discrete_Node);
  std::cout<<Coordinates[0]<<" "<<Coordinates[1]<<" "<<Coordinates[2]<<"\n";
}
return 0;
}
<|endoftext|>


<commit_before>#include "SkCanvas.h"
#include "SkDocument.h"
#include "SkFontMgr.h"
#include "SkGradientShader.h"
#include "SkPaint.h"
#include "SkStream.h"
#include "SkString.h"
#include "SkTypeface.h"
#include <hb.h>
#include <hb-ft.h>
#include <cairo.h>
#include <cairo-ft.h>

class Placement {
  FT_Library ft_library;
  FT_Face ft_face;
  hb_font_t *hb_font;
  hb_buffer_t *hb_buffer;

  const char *fontfile;
  const char *text;
  unsigned len;

  double font_size;

  hb_glyph_position_t *pos;
  hb_glyph_info_t *info;

  public:
  Placement(const char *_fontfile, const char *_text, double _font_size) {
    fontfile = _fontfile;
    text = _text;
    font_size = _font_size;
    FT_Error ft_error;

    if ((ft_error = FT_Init_FreeType (&ft_library)))
      abort();
    if ((ft_error = FT_New_Face (ft_library, fontfile, 0, &ft_face)))
      abort();
    if ((ft_error = FT_Set_Char_Size (ft_face, font_size*64, font_size*64, 0, 0)))
      abort();

    /* Create hb-ft font. */
    hb_font = hb_ft_font_create (ft_face, NULL);

    /* Create hb-buffer and populate. */
    hb_buffer = hb_buffer_create ();
    hb_buffer_add_utf8 (hb_buffer, text, -1, 0, -1);
    hb_buffer_guess_segment_properties (hb_buffer);

    /* Shape it! */
    hb_shape (hb_font, hb_buffer, NULL, 0);

    /* Get glyph information and positions out of the buffer. */
    len = hb_buffer_get_length (hb_buffer);
    info = hb_buffer_get_glyph_infos (hb_buffer, NULL);
    pos = hb_buffer_get_glyph_positions (hb_buffer, NULL);

    /* Print them out as is. */
    printf ("Raw buffer contents:\n");
    for (unsigned int i = 0; i < len; i++)
    {
      hb_codepoint_t gid   = info[i].codepoint;
      unsigned int cluster = info[i].cluster;
      double x_advance = pos[i].x_advance / 64.;
      double y_advance = pos[i].y_advance / 64.;
      double x_offset  = pos[i].x_offset / 64.;
      double y_offset  = pos[i].y_offset / 64.;

      char glyphname[32];
      hb_font_get_glyph_name (hb_font, gid, glyphname, sizeof (glyphname));

      printf ("glyph='%s' cluster=%d  advance=(%g,%g) offset=(%g,%g)\n",
              glyphname, cluster, x_advance, y_advance, x_offset, y_offset);
    }
  } // end of Placement

  ~Placement() {
    hb_buffer_destroy (hb_buffer);
    hb_font_destroy (hb_font);

    FT_Done_Face (ft_face);
    FT_Done_FreeType (ft_library);
  }

  void DrawGlyphsUsingCairo(double margin) {
    /* Draw, using cairo. */
    double width = 2 * margin;
    double height = 2 * margin;
    for (unsigned int i = 0; i < len; i++)
    {
      width  += pos[i].x_advance / 64.;
      height -= pos[i].y_advance / 64.;
    }
    if (HB_DIRECTION_IS_HORIZONTAL (hb_buffer_get_direction(hb_buffer)))
      height += font_size;
    else
      width  += font_size;

    /* Set up cairo surface. */
    cairo_surface_t *cairo_surface;
    cairo_surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
                            ceil(width),
                            ceil(height));
    cairo_t *cr;
    cr = cairo_create (cairo_surface);
    cairo_set_source_rgba (cr, 1., 1., 1., 1.);
    cairo_paint (cr);
    cairo_set_source_rgba (cr, 0., 0., 0., 1.);
    cairo_translate (cr, margin, margin);

    /* Set up cairo font face. */
    cairo_font_face_t *cairo_face;
    cairo_face = cairo_ft_font_face_create_for_ft_face (ft_face, 0);
    cairo_set_font_face (cr, cairo_face);
    cairo_set_font_size (cr, font_size);

    /* Set up baseline. */
    if (HB_DIRECTION_IS_HORIZONTAL (hb_buffer_get_direction(hb_buffer)))
    {
      cairo_font_extents_t font_extents;
      cairo_font_extents (cr, &font_extents);
      double baseline = (font_size - font_extents.height) * .5 + font_extents.ascent;
      cairo_translate (cr, 0, baseline);
    }
    else
    {
      cairo_translate (cr, font_size * .5, 0);
    }

    cairo_glyph_t *cairo_glyphs = cairo_glyph_allocate (len);
    double current_x = 0;
    double current_y = 0;
    for (unsigned int i = 0; i < len; i++)
    {
      cairo_glyphs[i].index = info[i].codepoint;
      cairo_glyphs[i].x = current_x + pos[i].x_offset / 64.;
      cairo_glyphs[i].y = -(current_y + pos[i].y_offset / 64.);
      current_x += pos[i].x_advance / 64.;
      current_y += pos[i].y_advance / 64.;
    }
    cairo_show_glyphs (cr, cairo_glyphs, len);
    cairo_glyph_free (cairo_glyphs);

    cairo_surface_write_to_png (cairo_surface, "out-cairo.png");

    cairo_font_face_destroy (cairo_face);
    cairo_destroy (cr);
    cairo_surface_destroy (cairo_surface);
  } // end of DrawGlyphsUsingCairo

  bool DrawGlyphsUsingSkia(SkWStream* outputStream) {
    sk_sp<SkDocument> pdfDocument(SkDocument::CreatePDF(outputStream));
    typedef SkDocument::Attribute Attr;
    Attr pdf_info[] = {
        Attr(SkString("Title"),    SkString("....")),
        Attr(SkString("Author"),   SkString("....")),
        Attr(SkString("Subject"),  SkString("....")),
        Attr(SkString("Keywords"), SkString("....")),
        Attr(SkString("Creator"),  SkString("....")),
    };
    int pdf_infoCount = sizeof(pdf_info) / sizeof(pdf_info[0]);
    SkTime::DateTime now;
    SkTime::GetDateTime(&now);
    pdfDocument->setMetadata(pdf_info, pdf_infoCount, &now, &now);

    int numberOfPages = 1;
    for (int page = 0; page < numberOfPages; ++page) {
      SkScalar pageWidth = SkIntToScalar(800);
      SkScalar pageHeight = SkIntToScalar(600);
      SkCanvas* pageCanvas = pdfDocument->beginPage(pageWidth, pageHeight);

      SkScalar s = SkIntToScalar(600);
      static const SkPoint     kPts0[] = { { 0, 0 }, { s, s } };
      static const SkScalar    kPos[] = { 0, SK_Scalar1/2, SK_Scalar1 };
      static const SkColor kColors0[] = {0x80F00080, 0xF0F08000, 0x800080F0 };

      SkPaint paint;
      paint.setShader(SkGradientShader::MakeLinear(
          kPts0, kColors0, kPos, SK_ARRAY_COUNT(kColors0),
          SkShader::kClamp_TileMode));
      pageCanvas->drawPaint(paint);

      SkPaint textPaint;
      // Draw a message with a nice black paint.
      textPaint.setFlags(
          SkPaint::kAntiAlias_Flag |
          SkPaint::kSubpixelText_Flag |
          SkPaint::kUnderlineText_Flag);   // ... avoid waggly text when rotating.
      textPaint.setColor(SK_ColorBLACK);
      textPaint.setTextSize(font_size);
      pageCanvas->save();
      pageCanvas->translate(40, 20);
      pageCanvas->rotate(45.0f);
      SkAutoTUnref<SkFontMgr> fm(SkFontMgr::RefDefault());
      SkTypeface * typeface = SkTypeface::CreateFromFile(fontfile, 0);
      textPaint.setTypeface(typeface);

      pageCanvas->drawText(text, strlen(text), 0, 0, textPaint);

      SkPoint *skpos = (SkPoint*)malloc(sizeof(SkPoint) * len);

      double current_x = 10;
      double current_y = 50;

      SkPaint glyphPaint(textPaint);
      glyphPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
      SkAutoSTMalloc<128, uint16_t> glyphStorage(len);
      uint16_t* glyphs = glyphStorage.get();
      for (unsigned int i = 0; i < len; i++)
      {
        glyphs[i] = info[i].codepoint;
        skpos[i] = SkPoint::Make(
          current_x + pos[i].x_offset / 64.,
          current_y - pos[i].y_offset / 64.);
        current_x += pos[i].x_advance / 64.;
        current_y += pos[i].y_advance / 64.;
      }

      pageCanvas->drawPosText(glyphs, len * sizeof(uint16_t), skpos, glyphPaint);
      pageCanvas->restore();

      free(skpos);

      pdfDocument->endPage();
    }
    return pdfDocument->close();
  } // end of DrawGlyphsUsingSkia
}; // end of Placement class

int main(int argc, char** argv) {
    SkPaint paint;
    paint.setColor(SK_ColorRED);

    SkString* str = new SkString();
    paint.toString(str);

    fprintf(stdout, "%s\n", str->c_str());

    // CreateAndPlaceGlyphs(36, 36 * .5, "fonts/TSCu_SaiIndira.ttf", "டஉடு");
    // CreateAndPlaceGlyphs(36, 36 * .5, "fonts/DejaVuSans.ttf", "حرف‌باز");
    // Placement placement("fonts/NotoNastaliqUrdu-Regular.ttf", "حرف‌باز Привет, Вася! Hello, world! டஉடு", 24 /* font_size */);
    Placement placement("fonts/NotoNastaliqUrdu-Regular.ttf", "حرف‌باز", 24 /* font_size */);
    placement.DrawGlyphsUsingCairo(24 * .5 /* margin */);
    placement.DrawGlyphsUsingSkia(new SkFILEWStream("out-skiahf.pdf"));

    return 0;
}
<commit_msg>Create Config.<commit_after>#include "SkCanvas.h"
#include "SkDocument.h"
#include "SkFontMgr.h"
#include "SkGradientShader.h"
#include "SkPaint.h"
#include "SkStream.h"
#include "SkString.h"
#include "SkTypeface.h"
#include <hb.h>
#include <hb-ft.h>
#include <cairo.h>
#include <cairo-ft.h>

struct Config {
  double page_width;
  double page_height;

  SkString title;
  SkString author;
  SkString subject;
  SkString keywords;
  SkString creator;

  std::string font_file;
  double font_size;

  Config(int argc, char **argv) :
    page_width(800.f), page_height(600.f),
    title("..."), author("..."), subject("..."), keywords("..."),
    creator("..."),
    font_file("fonts/NotoNastaliqUrdu-Regular.ttf"),
    font_size(24.0f) {
    for (int i = 1; i < argc; i++) {
      printf("Config arg[%d]=%s\n", argc, argv[i]);
      if (*argv[i] == '-') {
        char option_char = *(argv[i] + 1);
        if (i >= argc) {
          break;
        }
        const char *option_value = argv[i + 1];
        printf("\toption_char=%c\n", option_char);
        printf("\toption_value=%s\n", option_value);
        switch (option_char) {
          case 'w':
            page_width = atof(option_value);
            i++;
            break;
          case 'h':
            page_height = atof(option_value);
            i++;
            break;
          case 't':
            title = option_value;
            i++;
            break;
          case 'a':
            author = option_value;
            i++;
            break;
          case 's':
            subject = option_value;
            i++;
            break;
          case 'k':
            keywords = option_value;
            i++;
            break;
          case 'c':
            creator = option_value;
            i++;
            break;

          case 'f':
            font_file = option_value;
            i++;
            break;
          case 'z':
            font_size = atof(option_value);
            i++;
            break;
          default:
            printf("Unrecognized option: %c. Skipping.\n", option_char);
        }
      }
    }

  } // end of Config::Config
};

class Placement {
  Config config;

  FT_Library ft_library;
  FT_Face ft_face;
  hb_font_t *hb_font;
  hb_buffer_t *hb_buffer;

  const char *text;
  unsigned len;

  hb_glyph_position_t *pos;
  hb_glyph_info_t *info;

 public:
  Placement(Config &_config, const char *_text) : config(_config) {
    text = _text;
    FT_Error ft_error;

    if ((ft_error = FT_Init_FreeType (&ft_library)))
      abort();
    if ((ft_error = FT_New_Face (ft_library, config.font_file.c_str(), 0, &ft_face)))
      abort();
    if ((ft_error = FT_Set_Char_Size (ft_face, config.font_size*64,
        config.font_size*64, 0, 0)))
      abort();

    /* Create hb-ft font. */
    hb_font = hb_ft_font_create (ft_face, NULL);

    /* Create hb-buffer and populate. */
    hb_buffer = hb_buffer_create ();
    hb_buffer_add_utf8 (hb_buffer, text, -1, 0, -1);
    hb_buffer_guess_segment_properties (hb_buffer);

    /* Shape it! */
    hb_shape (hb_font, hb_buffer, NULL, 0);

    dump_hb_buffer(hb_buffer);
  } // end of Placement

  ~Placement() {
    hb_buffer_destroy (hb_buffer);
    hb_font_destroy (hb_font);

    FT_Done_Face (ft_face);
    FT_Done_FreeType (ft_library);
  }

  void DrawGlyphsUsingCairo(double margin) {
    /* Draw, using cairo. */
    double width = 2 * margin;
    double height = 2 * margin;
    for (unsigned int i = 0; i < len; i++)
    {
      width  += pos[i].x_advance / 64.;
      height -= pos[i].y_advance / 64.;
    }
    if (HB_DIRECTION_IS_HORIZONTAL (hb_buffer_get_direction(hb_buffer)))
      height += config.font_size;
    else
      width  += config.font_size;

    /* Set up cairo surface. */
    cairo_surface_t *cairo_surface;
    cairo_surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
                            ceil(width),
                            ceil(height));
    cairo_t *cr;
    cr = cairo_create (cairo_surface);
    cairo_set_source_rgba (cr, 1., 1., 1., 1.);
    cairo_paint (cr);
    cairo_set_source_rgba (cr, 0., 0., 0., 1.);
    cairo_translate (cr, margin, margin);

    /* Set up cairo font face. */
    cairo_font_face_t *cairo_face;
    cairo_face = cairo_ft_font_face_create_for_ft_face (ft_face, 0);
    cairo_set_font_face (cr, cairo_face);
    cairo_set_font_size (cr, config.font_size);

    /* Set up baseline. */
    if (HB_DIRECTION_IS_HORIZONTAL (hb_buffer_get_direction(hb_buffer)))
    {
      cairo_font_extents_t font_extents;
      cairo_font_extents (cr, &font_extents);
      double baseline = (config.font_size - font_extents.height) * .5 + font_extents.ascent;
      cairo_translate (cr, 0, baseline);
    }
    else
    {
      cairo_translate (cr, config.font_size * .5, 0);
    }

    cairo_glyph_t *cairo_glyphs = cairo_glyph_allocate (len);
    double current_x = 0;
    double current_y = 0;
    for (unsigned int i = 0; i < len; i++)
    {
      cairo_glyphs[i].index = info[i].codepoint;
      cairo_glyphs[i].x = current_x + pos[i].x_offset / 64.;
      cairo_glyphs[i].y = -(current_y + pos[i].y_offset / 64.);
      current_x += pos[i].x_advance / 64.;
      current_y += pos[i].y_advance / 64.;
    }
    cairo_show_glyphs (cr, cairo_glyphs, len);
    cairo_glyph_free (cairo_glyphs);

    cairo_surface_write_to_png (cairo_surface, "out-cairo.png");

    cairo_font_face_destroy (cairo_face);
    cairo_destroy (cr);
    cairo_surface_destroy (cairo_surface);
  } // end of DrawGlyphsUsingCairo

  bool DrawGlyphsUsingSkia(SkWStream* outputStream) {
    sk_sp<SkDocument> pdfDocument(SkDocument::CreatePDF(outputStream));
    typedef SkDocument::Attribute Attr;
    Attr pdf_info[] = {
        Attr(SkString("Title"),    config.title),
        Attr(SkString("Author"),   config.author),
        Attr(SkString("Subject"),  config.subject),
        Attr(SkString("Keywords"), config.keywords),
        Attr(SkString("Creator"),  config.creator),
    };
    int pdf_infoCount = sizeof(pdf_info) / sizeof(pdf_info[0]);
    std::unique_ptr<SkTime::DateTime> now = GetCurrentDateTime();

    pdfDocument->setMetadata(pdf_info, pdf_infoCount, now.get(), now.get());

    int numberOfPages = 1;
    for (int page = 0; page < numberOfPages; ++page) {
      SkScalar pageWidth = SkIntToScalar(800);
      SkScalar pageHeight = SkIntToScalar(600);
      SkCanvas* pageCanvas = pdfDocument->beginPage(pageWidth, pageHeight);

      SkScalar s = SkIntToScalar(600);
      static const SkPoint     kPts0[] = { { 0, 0 }, { s, s } };
      static const SkScalar    kPos[] = { 0, SK_Scalar1/2, SK_Scalar1 };
      static const SkColor kColors0[] = {0x80F00080, 0xF0F08000, 0x800080F0 };

      SkPaint paint;
      paint.setShader(SkGradientShader::MakeLinear(
          kPts0, kColors0, kPos, SK_ARRAY_COUNT(kColors0),
          SkShader::kClamp_TileMode));
      pageCanvas->drawPaint(paint);

      SkPaint textPaint;
      // Draw a message with a nice black paint.
      textPaint.setFlags(
          SkPaint::kAntiAlias_Flag |
          SkPaint::kSubpixelText_Flag | // ... avoid waggly text when rotating.
          SkPaint::kUnderlineText_Flag);
      textPaint.setColor(SK_ColorBLACK);
      textPaint.setTextSize(config.font_size);
      pageCanvas->save();
      pageCanvas->translate(40, 20);
      pageCanvas->rotate(45.0f);
      SkAutoTUnref<SkFontMgr> fm(SkFontMgr::RefDefault());
      SkTypeface * typeface = SkTypeface::CreateFromFile(config.font_file.c_str(), 0);
      textPaint.setTypeface(typeface);

      pageCanvas->drawText(text, strlen(text), 0, 0, textPaint);

      SkPoint *skpos = (SkPoint*)malloc(sizeof(SkPoint) * len);

      double current_x = 10;
      double current_y = 50;

      SkPaint glyphPaint(textPaint);
      glyphPaint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
      SkAutoSTMalloc<128, uint16_t> glyphStorage(len);
      uint16_t* glyphs = glyphStorage.get();
      for (unsigned int i = 0; i < len; i++)
      {
        glyphs[i] = info[i].codepoint;
        skpos[i] = SkPoint::Make(
          current_x + pos[i].x_offset / 64.,
          current_y - pos[i].y_offset / 64.);
        current_x += pos[i].x_advance / 64.;
        current_y += pos[i].y_advance / 64.;
      }

      pageCanvas->drawPosText(glyphs, len * sizeof(uint16_t), skpos, glyphPaint);
      pageCanvas->restore();

      free(skpos);

      pdfDocument->endPage();
    }
    return pdfDocument->close();
  } // end of DrawGlyphsUsingSkia

private:
  void dump_hb_buffer(hb_buffer_t *hb_buffer) {
    /* Get glyph information and positions out of the buffer. */
    len = hb_buffer_get_length (hb_buffer);
    info = hb_buffer_get_glyph_infos (hb_buffer, NULL);
    pos = hb_buffer_get_glyph_positions (hb_buffer, NULL);

    /* Print them out as is. */
    printf ("Raw buffer contents:\n");
    for (unsigned int i = 0; i < len; i++)
    {
      hb_codepoint_t gid   = info[i].codepoint;
      unsigned int cluster = info[i].cluster;
      double x_advance = pos[i].x_advance / 64.;
      double y_advance = pos[i].y_advance / 64.;
      double x_offset  = pos[i].x_offset / 64.;
      double y_offset  = pos[i].y_offset / 64.;

      char glyphname[32];
      hb_font_get_glyph_name (hb_font, gid, glyphname, sizeof (glyphname));

      printf ("glyph='%s' cluster=%d  advance=(%g,%g) offset=(%g,%g)\n",
              glyphname, cluster, x_advance, y_advance, x_offset, y_offset);
    }
  }

  std::unique_ptr<SkTime::DateTime> GetCurrentDateTime() {
    time_t m_time;
    time(&m_time);
    struct tm* tstruct;
    tstruct = gmtime(&m_time);

    std::unique_ptr<SkTime::DateTime> now(new SkTime::DateTime());
    now->fTimeZoneMinutes = 0;
    now->fYear       = tstruct->tm_year + 1900;
    now->fMonth      = SkToU8(tstruct->tm_mon + 1);
    now->fDayOfWeek  = SkToU8(tstruct->tm_wday);
    now->fDay        = SkToU8(tstruct->tm_mday);
    now->fHour       = SkToU8(tstruct->tm_hour);
    now->fMinute     = SkToU8(tstruct->tm_min);
    now->fSecond     = SkToU8(tstruct->tm_sec);
    return now;
  }
}; // end of Placement class

int main(int argc, char** argv) {
    Config config(argc, argv);

    SkPaint paint;
    paint.setColor(SK_ColorRED);

    SkString* str = new SkString();
    paint.toString(str);

    fprintf(stdout, "%s\n", str->c_str());

    // CreateAndPlaceGlyphs(36, 36 * .5, "fonts/TSCu_SaiIndira.ttf", "டஉடு");
    // CreateAndPlaceGlyphs(36, 36 * .5, "fonts/DejaVuSans.ttf", "حرف‌باز");
    // Placement placement("fonts/NotoNastaliqUrdu-Regular.ttf", "حرف‌باز Привет, Вася! Hello, world! டஉடு", 24 /* font_size */);
    Placement placement(config, "حرف‌باز");
    placement.DrawGlyphsUsingCairo(24 * .5 /* margin */);
    placement.DrawGlyphsUsingSkia(new SkFILEWStream("out-skiahf.pdf"));

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cmath>

using namespace std;

int width = 35;
int lenght = 70;

// void initMatrix(int* matrix){
//  for (int i = 0; i<width;++i){
//      for (int j; j<lenght;++i){
//          matrix[i][j] = 0;
//      }
//  }
// }

// void printMat(int matrix[width][]){
//  for (int i = 0; i<width;++i){
//      for (int j; j<lenght;++i){
//          cout<< matrix[i][j]<< " ";
//      }
//      cout<<endl;
//  }
// }

int main(int argc, char const *argv[])
{

    //-------------------------MATINIT---------------------
    int matrix[width][lenght];
    int calc=0;//Nombre de cases utilisables
    float diameterFactor = 46.0/100.0;// Normalement c'est la moitié de la longueur/largeur
    int delta = 1/2; //Delta qui permet d'éviter les bugs lors de l'affichage de la matrice

    for (int i = 0; i<width;++i){
        for (int j=0; j<lenght;++j){
            matrix[i][j] = 0;
            // equation d'une ellipse non centrée : (x-h)²/a² + (x-k)²/b²
            //avec x = i, h et k sont les coord du centre, a et b les demi longueurs de l'ellipse
            float result = pow(i-width/2.0, 2)/pow(diameterFactor*width, 2);
            result+= pow(j-lenght/2.0, 2)/pow(diameterFactor*lenght, 2);
            if (i%2 !=0){
                result -= delta;
            }
            if (result>1){//Si on est à l'extérieur de l'ellipse
                matrix[i][j] = 1;
                calc++;
            }
    //----------------------------GOALS---------------------------------
            if( i == width/2){
                if (j == lenght/15 + lenght/20 or j == lenght*14/15 - lenght/20){
                    matrix[i][j] = 2;//goal central
                }
            }
            if (i == width/2 - width/15 or i== width/2 + width/15){
                if(j == 2 * lenght/15 or j == 13 * lenght/15){
                    matrix[i][j] = 2;//goals latéraux
                }
            }
        }
    }
    //---------------------------PRINT----------------------------
    for (int i = 0; i<width;++i){
        if (i%2 != 0){
            cout<<" ";
        }
        for (int j=0; j<lenght;++j){

            if (matrix[i][j] == 0){
                cout<< "\u2B21"<<" ";
            }
            else{
                cout <<"\u2B22"<<" ";
            }

            //cout<< matrix[i][j]<<" ";
        }
        cout<<endl;
    }
    cout<<calc<<endl;//nbre de cases utilisables
    return 0;
}

<commit_msg>[code] removes test file for matrice generation.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <qt/bitcoinunits.h>

#include <primitives/transaction.h>

#include <QStringList>

BitcoinUnits::BitcoinUnits(QObject *parent):
        QAbstractListModel(parent),
        unitlist(availableUnits())
{
}

QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
    QList<BitcoinUnits::Unit> unitlist;
    unitlist.append(GRS);
    unitlist.append(mGRS);
    unitlist.append(uGRS);
    return unitlist;
}

bool BitcoinUnits::valid(int unit)
{
    switch(unit)
    {
    case GRS:
    case mGRS:
    case uGRS:
        return true;
    default:
        return false;
    }
}

QString BitcoinUnits::longName(int unit)
{
    switch(unit)
    {
    case GRS: return QString("GRS");
    case mGRS: return QString("mGRS");
    case uGRS: return QString::fromUtf8("μGRS");
    default: return QString("???");
    }
}

QString BitcoinUnits::shortName(int unit)
{
    switch(unit)
    {
    case uGRS: return QString::fromUtf8("bits");
    default:   return longName(unit);
    }
}

QString BitcoinUnits::description(int unit)
{
    switch(unit)
    {
    case GRS: return QString("Groestlcoins");
    case mGRS: return QString("Milli-Groestlcoins (1 / 1" THIN_SP_UTF8 "000)");
    case uGRS: return QString("Micro-Groestlcoins (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)");
    default: return QString("???");
    }
}

qint64 BitcoinUnits::factor(int unit)
{
    switch(unit)
    {
    case GRS:  return 100000000;
    case mGRS: return 100000;
    case uGRS: return 100;
    default:   return 100000000;
    }
}

int BitcoinUnits::decimals(int unit)
{
    switch(unit)
    {
    case GRS: return 8;
    case mGRS: return 5;
    case uGRS: return 2;
    default: return 0;
    }
}

QString BitcoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators)
{
    // Note: not using straight sprintf here because we do NOT want
    // localized number formatting.
    if(!valid(unit))
        return QString(); // Refuse to format invalid unit
    qint64 n = (qint64)nIn;
    qint64 coin = factor(unit);
    int num_decimals = decimals(unit);
    qint64 n_abs = (n > 0 ? n : -n);
    qint64 quotient = n_abs / coin;
    qint64 remainder = n_abs % coin;
    QString quotient_str = QString::number(quotient);
    QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');

    // Use SI-style thin space separators as these are locale independent and can't be
    // confused with the decimal marker.
    QChar thin_sp(THIN_SP_CP);
    int q_size = quotient_str.size();
    if (separators == separatorAlways || (separators == separatorStandard && q_size > 4))
        for (int i = 3; i < q_size; i += 3)
            quotient_str.insert(q_size - i, thin_sp);

    if (n < 0)
        quotient_str.insert(0, '-');
    else if (fPlus && n > 0)
        quotient_str.insert(0, '+');
    return quotient_str + QString(".") + remainder_str;
}

// NOTE: Using formatWithUnit in an HTML context risks wrapping
// quantities at the thousands separator. More subtly, it also results
// in a standard space rather than a thin space, due to a bug in Qt's
// XML whitespace canonicalisation
//
// Please take care to use formatHtmlWithUnit instead, when
// appropriate.

QString BitcoinUnits::formatWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
    return format(unit, amount, plussign, separators) + QString(" ") + shortName(unit);
}

QString BitcoinUnits::formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
    QString str(formatWithUnit(unit, amount, plussign, separators));
    str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML));
    return QString("%1").arg(str);
}

bool BitcoinUnits::parse(int unit, const QString &value, CAmount *val_out)
{
    if(!valid(unit) || value.isEmpty())
        return false; // Refuse to parse invalid unit or empty string
    int num_decimals = decimals(unit);

    // Ignore spaces and thin spaces when parsing
    QStringList parts = removeSpaces(value).split(".");

    if(parts.size() > 2)
    {
        return false; // More than one dot
    }
    QString whole = parts[0];
    QString decimals;

    if(parts.size() > 1)
    {
        decimals = parts[1];
    }
    if(decimals.size() > num_decimals)
    {
        return false; // Exceeds max precision
    }
    bool ok = false;
    QString str = whole + decimals.leftJustified(num_decimals, '0');

    if(str.size() > 18)
    {
        return false; // Longer numbers will exceed 63 bits
    }
    CAmount retvalue(str.toLongLong(&ok));
    if(val_out)
    {
        *val_out = retvalue;
    }
    return ok;
}

QString BitcoinUnits::getAmountColumnTitle(int unit)
{
    QString amountTitle = QObject::tr("Amount");
    if (BitcoinUnits::valid(unit))
    {
        amountTitle += " ("+BitcoinUnits::shortName(unit) + ")";
    }
    return amountTitle;
}

int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return unitlist.size();
}

QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
    int row = index.row();
    if(row >= 0 && row < unitlist.size())
    {
        Unit unit = unitlist.at(row);
        switch(role)
        {
        case Qt::EditRole:
        case Qt::DisplayRole:
            return QVariant(longName(unit));
        case Qt::ToolTipRole:
            return QVariant(description(unit));
        case UnitRole:
            return QVariant(static_cast<int>(unit));
        }
    }
    return QVariant();
}

CAmount BitcoinUnits::maxMoney()
{
    return MAX_MONEY;
}
<commit_msg>Change short unit name 'bits'->'groestls'<commit_after>// Copyright (c) 2011-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <qt/bitcoinunits.h>

#include <primitives/transaction.h>

#include <QStringList>

BitcoinUnits::BitcoinUnits(QObject *parent):
        QAbstractListModel(parent),
        unitlist(availableUnits())
{
}

QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
    QList<BitcoinUnits::Unit> unitlist;
    unitlist.append(GRS);
    unitlist.append(mGRS);
    unitlist.append(uGRS);
    return unitlist;
}

bool BitcoinUnits::valid(int unit)
{
    switch(unit)
    {
    case GRS:
    case mGRS:
    case uGRS:
        return true;
    default:
        return false;
    }
}

QString BitcoinUnits::longName(int unit)
{
    switch(unit)
    {
    case GRS: return QString("GRS");
    case mGRS: return QString("mGRS");
    case uGRS: return QString::fromUtf8("μGRS");
    default: return QString("???");
    }
}

QString BitcoinUnits::shortName(int unit)
{
    switch(unit)
    {
    case uGRS: return QString::fromUtf8("groestls");
    default:   return longName(unit);
    }
}

QString BitcoinUnits::description(int unit)
{
    switch(unit)
    {
    case GRS: return QString("Groestlcoins");
    case mGRS: return QString("Milli-Groestlcoins (1 / 1" THIN_SP_UTF8 "000)");
    case uGRS: return QString("Micro-Groestlcoins (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)");
    default: return QString("???");
    }
}

qint64 BitcoinUnits::factor(int unit)
{
    switch(unit)
    {
    case GRS:  return 100000000;
    case mGRS: return 100000;
    case uGRS: return 100;
    default:   return 100000000;
    }
}

int BitcoinUnits::decimals(int unit)
{
    switch(unit)
    {
    case GRS: return 8;
    case mGRS: return 5;
    case uGRS: return 2;
    default: return 0;
    }
}

QString BitcoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators)
{
    // Note: not using straight sprintf here because we do NOT want
    // localized number formatting.
    if(!valid(unit))
        return QString(); // Refuse to format invalid unit
    qint64 n = (qint64)nIn;
    qint64 coin = factor(unit);
    int num_decimals = decimals(unit);
    qint64 n_abs = (n > 0 ? n : -n);
    qint64 quotient = n_abs / coin;
    qint64 remainder = n_abs % coin;
    QString quotient_str = QString::number(quotient);
    QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');

    // Use SI-style thin space separators as these are locale independent and can't be
    // confused with the decimal marker.
    QChar thin_sp(THIN_SP_CP);
    int q_size = quotient_str.size();
    if (separators == separatorAlways || (separators == separatorStandard && q_size > 4))
        for (int i = 3; i < q_size; i += 3)
            quotient_str.insert(q_size - i, thin_sp);

    if (n < 0)
        quotient_str.insert(0, '-');
    else if (fPlus && n > 0)
        quotient_str.insert(0, '+');
    return quotient_str + QString(".") + remainder_str;
}

// NOTE: Using formatWithUnit in an HTML context risks wrapping
// quantities at the thousands separator. More subtly, it also results
// in a standard space rather than a thin space, due to a bug in Qt's
// XML whitespace canonicalisation
//
// Please take care to use formatHtmlWithUnit instead, when
// appropriate.

QString BitcoinUnits::formatWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
    return format(unit, amount, plussign, separators) + QString(" ") + shortName(unit);
}

QString BitcoinUnits::formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
    QString str(formatWithUnit(unit, amount, plussign, separators));
    str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML));
    return QString("%1").arg(str);
}

bool BitcoinUnits::parse(int unit, const QString &value, CAmount *val_out)
{
    if(!valid(unit) || value.isEmpty())
        return false; // Refuse to parse invalid unit or empty string
    int num_decimals = decimals(unit);

    // Ignore spaces and thin spaces when parsing
    QStringList parts = removeSpaces(value).split(".");

    if(parts.size() > 2)
    {
        return false; // More than one dot
    }
    QString whole = parts[0];
    QString decimals;

    if(parts.size() > 1)
    {
        decimals = parts[1];
    }
    if(decimals.size() > num_decimals)
    {
        return false; // Exceeds max precision
    }
    bool ok = false;
    QString str = whole + decimals.leftJustified(num_decimals, '0');

    if(str.size() > 18)
    {
        return false; // Longer numbers will exceed 63 bits
    }
    CAmount retvalue(str.toLongLong(&ok));
    if(val_out)
    {
        *val_out = retvalue;
    }
    return ok;
}

QString BitcoinUnits::getAmountColumnTitle(int unit)
{
    QString amountTitle = QObject::tr("Amount");
    if (BitcoinUnits::valid(unit))
    {
        amountTitle += " ("+BitcoinUnits::shortName(unit) + ")";
    }
    return amountTitle;
}

int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return unitlist.size();
}

QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
    int row = index.row();
    if(row >= 0 && row < unitlist.size())
    {
        Unit unit = unitlist.at(row);
        switch(role)
        {
        case Qt::EditRole:
        case Qt::DisplayRole:
            return QVariant(longName(unit));
        case Qt::ToolTipRole:
            return QVariant(description(unit));
        case UnitRole:
            return QVariant(static_cast<int>(unit));
        }
    }
    return QVariant();
}

CAmount BitcoinUnits::maxMoney()
{
    return MAX_MONEY;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include "bitcoin-config.h"
#endif

#include "optionsmodel.h"

#include "bitcoinunits.h"
#include "guiutil.h"

#include "init.h"
#include "main.h"
#include "net.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#include "walletdb.h"
#endif

#include <QNetworkProxy>
#include <QSettings>
#include <QStringList>

OptionsModel::OptionsModel(QObject *parent) :
    QAbstractListModel(parent)
{
    Init();
}

// Writes all missing QSettings with their default values
void OptionsModel::Init()
{
    QSettings settings;

    // Ensure restart flag is unset on client startup
    setRestartRequired(false);

    // These are Qt-only settings:

    // Window
    if (!settings.contains("fMinimizeToTray"))
        settings.setValue("fMinimizeToTray", false);
    fMinimizeToTray = settings.value("fMinimizeToTray").toBool();

    if (!settings.contains("fMinimizeOnClose"))
        settings.setValue("fMinimizeOnClose", false);
    fMinimizeOnClose = settings.value("fMinimizeOnClose").toBool();

    // Display
    if (!settings.contains("nDisplayUnit"))
        settings.setValue("nDisplayUnit", BitcoinUnits::BTC);
    nDisplayUnit = settings.value("nDisplayUnit").toInt();

    if (!settings.contains("bDisplayAddresses"))
        settings.setValue("bDisplayAddresses", false);
    bDisplayAddresses = settings.value("bDisplayAddresses", false).toBool();

    if (!settings.contains("fCoinControlFeatures"))
        settings.setValue("fCoinControlFeatures", false);
    fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool();

    // These are shared with the core or have a command-line parameter
    // and we want command-line parameters to overwrite the GUI settings.
    //
    // If setting doesn't exist create it with defaults.
    //
    // If SoftSetArg() or SoftSetBoolArg() return false we were overridden
    // by command-line and show this in the UI.

    // Main
#ifdef ENABLE_WALLET
    if (!settings.contains("nTransactionFee"))
        settings.setValue("nTransactionFee", 0);
#endif

    if (!settings.contains("nDatabaseCache"))
        settings.setValue("nDatabaseCache", 25);
    if (!SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString()))
        strOverriddenByCommandLine += "-dbcache ";

    if (!settings.contains("nThreadsScriptVerif"))
        settings.setValue("nThreadsScriptVerif", 0);
    if (!SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString()))
        strOverriddenByCommandLine += "-par ";

    // Network
    if (!settings.contains("fUseUPnP"))
#ifdef USE_UPNP
        settings.setValue("fUseUPnP", true);
#else
        settings.setValue("fUseUPnP", false);
#endif
    if (!SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool()))
        strOverriddenByCommandLine += "-upnp ";

    if (!settings.contains("fUseProxy"))
        settings.setValue("fUseProxy", false);
    if (!settings.contains("addrProxy"))
        settings.setValue("addrProxy", "127.0.0.1:9050");
    // Only try to set -proxy, if user has enabled fUseProxy
    if (settings.value("fUseProxy").toBool() && !SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString()))
        strOverriddenByCommandLine += "-proxy ";
    if (!settings.contains("nSocksVersion"))
        settings.setValue("nSocksVersion", 5);
    // Only try to set -socks, if user has enabled fUseProxy
    if (settings.value("fUseProxy").toBool() && !SoftSetArg("-socks", settings.value("nSocksVersion").toString().toStdString()))
        strOverriddenByCommandLine += "-socks ";

    // Display
    if (!settings.contains("language"))
        settings.setValue("language", "");
    if (!SoftSetArg("-lang", settings.value("language").toString().toStdString()))
        strOverriddenByCommandLine += "-lang";

    language = settings.value("language").toString();
}

void OptionsModel::Reset()
{
    QSettings settings;

    // Remove all entries from our QSettings object
    settings.clear();

    // default setting for OptionsModel::StartAtStartup - disabled
    if (GUIUtil::GetStartOnSystemStartup())
        GUIUtil::SetStartOnSystemStartup(false);

    // Ensure Upgrade() is not running again by setting the bImportFinished flag
    settings.setValue("bImportFinished", true);
}

void OptionsModel::Upgrade()
{
    QSettings settings;

    // Already upgraded
    if (settings.contains("bImportFinished"))
        return;

    settings.setValue("bImportFinished", true);

#ifdef ENABLE_WALLET
    // Move settings from old wallet.dat (if any):
    CWalletDB walletdb(strWalletFile);

    QList<QString> intOptions;
    intOptions << "nDisplayUnit" << "nTransactionFee";
    foreach(QString key, intOptions)
    {
        int value = 0;
        if (walletdb.ReadSetting(key.toStdString(), value))
        {
            settings.setValue(key, value);
            walletdb.EraseSetting(key.toStdString());
        }
    }
    QList<QString> boolOptions;
    boolOptions << "bDisplayAddresses" << "fMinimizeToTray" << "fMinimizeOnClose" << "fUseProxy" << "fUseUPnP";
    foreach(QString key, boolOptions)
    {
        bool value = false;
        if (walletdb.ReadSetting(key.toStdString(), value))
        {
            settings.setValue(key, value);
            walletdb.EraseSetting(key.toStdString());
        }
    }
    try
    {
        CAddress addrProxyAddress;
        if (walletdb.ReadSetting("addrProxy", addrProxyAddress))
        {
            settings.setValue("addrProxy", addrProxyAddress.ToStringIPPort().c_str());
            walletdb.EraseSetting("addrProxy");
        }
    }
    catch (std::ios_base::failure &e)
    {
        // 0.6.0rc1 saved this as a CService, which causes failure when parsing as a CAddress
        CService addrProxy;
        if (walletdb.ReadSetting("addrProxy", addrProxy))
        {
            settings.setValue("addrProxy", addrProxy.ToStringIPPort().c_str());
            walletdb.EraseSetting("addrProxy");
        }
    }
#endif

    Init();
}

int OptionsModel::rowCount(const QModelIndex & parent) const
{
    return OptionIDRowCount;
}

// read QSettings values and return them
QVariant OptionsModel::data(const QModelIndex & index, int role) const
{
    if(role == Qt::EditRole)
    {
        QSettings settings;
        switch(index.row())
        {
        case StartAtStartup:
            return GUIUtil::GetStartOnSystemStartup();
        case MinimizeToTray:
            return fMinimizeToTray;
        case MapPortUPnP:
#ifdef USE_UPNP
            return settings.value("fUseUPnP");
#else
            return false;
#endif
        case MinimizeOnClose:
            return fMinimizeOnClose;

        // default proxy
        case ProxyUse:
            return settings.value("fUseProxy", false);
        case ProxyIP: {
            // contains IP at index 0 and port at index 1
            QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
            return strlIpPort.at(0);
        }
        case ProxyPort: {
            // contains IP at index 0 and port at index 1
            QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
            return strlIpPort.at(1);
        }
        case ProxySocksVersion:
            return settings.value("nSocksVersion", 5);

#ifdef ENABLE_WALLET
        case Fee:
            // Attention: Init() is called before nTransactionFee is set in AppInit2()!
            // To ensure we can change the fee on-the-fly update our QSetting when
            // opening OptionsDialog, which queries Fee via the mapper.
            if (nTransactionFee != settings.value("nTransactionFee").toLongLong())
                settings.setValue("nTransactionFee", (qint64)nTransactionFee);
            // Todo: Consider to revert back to use just nTransactionFee here, if we don't want
            // -paytxfee to update our QSettings!
            return settings.value("nTransactionFee");
#endif
        case DisplayUnit:
            return nDisplayUnit;
        case DisplayAddresses:
            return bDisplayAddresses;
        case Language:
            return settings.value("language");
        case CoinControlFeatures:
            return fCoinControlFeatures;
        case DatabaseCache:
            return settings.value("nDatabaseCache");
        case ThreadsScriptVerif:
            return settings.value("nThreadsScriptVerif");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// write QSettings values
bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
    bool successful = true; /* set to false on parse error */
    if(role == Qt::EditRole)
    {
        QSettings settings;
        switch(index.row())
        {
        case StartAtStartup:
            successful = GUIUtil::SetStartOnSystemStartup(value.toBool());
            break;
        case MinimizeToTray:
            fMinimizeToTray = value.toBool();
            settings.setValue("fMinimizeToTray", fMinimizeToTray);
            break;
        case MapPortUPnP: // core option - can be changed on-the-fly
            settings.setValue("fUseUPnP", value.toBool());
            MapPort(value.toBool());
            break;
        case MinimizeOnClose:
            fMinimizeOnClose = value.toBool();
            settings.setValue("fMinimizeOnClose", fMinimizeOnClose);
            break;

        // default proxy
        case ProxyUse:
            if (settings.value("fUseProxy") != value) {
                settings.setValue("fUseProxy", value.toBool());
                setRestartRequired(true);
            }
            break;
        case ProxyIP: {
            // contains current IP at index 0 and current port at index 1
            QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
            // if that key doesn't exist or has a changed IP
            if (!settings.contains("addrProxy") || strlIpPort.at(0) != value.toString()) {
                // construct new value from new IP and current port
                QString strNewValue = value.toString() + ":" + strlIpPort.at(1);
                settings.setValue("addrProxy", strNewValue);
                setRestartRequired(true);
            }
        }
        break;
        case ProxyPort: {
            // contains current IP at index 0 and current port at index 1
            QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
            // if that key doesn't exist or has a changed port
            if (!settings.contains("addrProxy") || strlIpPort.at(1) != value.toString()) {
                // construct new value from current IP and new port
                QString strNewValue = strlIpPort.at(0) + ":" + value.toString();
                settings.setValue("addrProxy", strNewValue);
                setRestartRequired(true);
            }
        }
        break;
        case ProxySocksVersion: {
            if (settings.value("nSocksVersion") != value) {
                settings.setValue("nSocksVersion", value.toInt());
                setRestartRequired(true);
            }
        }
        break;
#ifdef ENABLE_WALLET
        case Fee: // core option - can be changed on-the-fly
            // Todo: Add is valid check  and warn via message, if not
            nTransactionFee = value.toLongLong();
            settings.setValue("nTransactionFee", (qint64)nTransactionFee);
            emit transactionFeeChanged(nTransactionFee);
            break;
#endif
        case DisplayUnit:
            nDisplayUnit = value.toInt();
            settings.setValue("nDisplayUnit", nDisplayUnit);
            emit displayUnitChanged(nDisplayUnit);
            break;
        case DisplayAddresses:
            bDisplayAddresses = value.toBool();
            settings.setValue("bDisplayAddresses", bDisplayAddresses);
            break;
        case Language:
            if (settings.value("language") != value) {
                settings.setValue("language", value);
                setRestartRequired(true);
            }
            break;
        case CoinControlFeatures:
            fCoinControlFeatures = value.toBool();
            settings.setValue("fCoinControlFeatures", fCoinControlFeatures);
            emit coinControlFeaturesChanged(fCoinControlFeatures);
            break;
        case DatabaseCache:
            if (settings.value("nDatabaseCache") != value) {
                settings.setValue("nDatabaseCache", value);
                setRestartRequired(true);
            }
            break;
        case ThreadsScriptVerif:
            if (settings.value("nThreadsScriptVerif") != value) {
                settings.setValue("nThreadsScriptVerif", value);
                setRestartRequired(true);
            }
            break;
        default:
            break;
        }
    }
    emit dataChanged(index, index);

    return successful;
}

bool OptionsModel::getProxySettings(QNetworkProxy& proxy) const
{
    // Directly query current base proxy, because
    // GUI settings can be overridden with -proxy.
    proxyType curProxy;
    if (GetProxy(NET_IPV4, curProxy)) {
        if (curProxy.second == 5) {
            proxy.setType(QNetworkProxy::Socks5Proxy);
            proxy.setHostName(QString::fromStdString(curProxy.first.ToStringIP()));
            proxy.setPort(curProxy.first.GetPort());

            return true;
        }
        else
            return false;
    }
    else
        proxy.setType(QNetworkProxy::NoProxy);

    return true;
}

void OptionsModel::setRestartRequired(bool fRequired)
{
    QSettings settings;
    return settings.setValue("fRestartRequired", fRequired);
}

bool OptionsModel::isRestartRequired()
{
    QSettings settings;
    return settings.value("fRestartRequired", false).toBool();
}
<commit_msg>[Qt] Fix nTransactionFee in qt-settings<commit_after>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include "bitcoin-config.h"
#endif

#include "optionsmodel.h"

#include "bitcoinunits.h"
#include "guiutil.h"

#include "init.h"
#include "main.h"
#include "net.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#include "walletdb.h"
#endif

#include <QNetworkProxy>
#include <QSettings>
#include <QStringList>

OptionsModel::OptionsModel(QObject *parent) :
    QAbstractListModel(parent)
{
    Init();
}

// Writes all missing QSettings with their default values
void OptionsModel::Init()
{
    QSettings settings;

    // Ensure restart flag is unset on client startup
    setRestartRequired(false);

    // These are Qt-only settings:

    // Window
    if (!settings.contains("fMinimizeToTray"))
        settings.setValue("fMinimizeToTray", false);
    fMinimizeToTray = settings.value("fMinimizeToTray").toBool();

    if (!settings.contains("fMinimizeOnClose"))
        settings.setValue("fMinimizeOnClose", false);
    fMinimizeOnClose = settings.value("fMinimizeOnClose").toBool();

    // Display
    if (!settings.contains("nDisplayUnit"))
        settings.setValue("nDisplayUnit", BitcoinUnits::BTC);
    nDisplayUnit = settings.value("nDisplayUnit").toInt();

    if (!settings.contains("bDisplayAddresses"))
        settings.setValue("bDisplayAddresses", false);
    bDisplayAddresses = settings.value("bDisplayAddresses", false).toBool();

    if (!settings.contains("fCoinControlFeatures"))
        settings.setValue("fCoinControlFeatures", false);
    fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool();

    // These are shared with the core or have a command-line parameter
    // and we want command-line parameters to overwrite the GUI settings.
    //
    // If setting doesn't exist create it with defaults.
    //
    // If SoftSetArg() or SoftSetBoolArg() return false we were overridden
    // by command-line and show this in the UI.

    // Main
#ifdef ENABLE_WALLET
    if (!settings.contains("nTransactionFee"))
        settings.setValue("nTransactionFee", 0);
    nTransactionFee = settings.value("nTransactionFee").toLongLong(); // if -paytxfee is set, this will be overridden later in init.cpp
    if (mapArgs.count("-paytxfee"))
        strOverriddenByCommandLine += "-paytxfee ";
#endif

    if (!settings.contains("nDatabaseCache"))
        settings.setValue("nDatabaseCache", 25);
    if (!SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString()))
        strOverriddenByCommandLine += "-dbcache ";

    if (!settings.contains("nThreadsScriptVerif"))
        settings.setValue("nThreadsScriptVerif", 0);
    if (!SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString()))
        strOverriddenByCommandLine += "-par ";

    // Network
    if (!settings.contains("fUseUPnP"))
#ifdef USE_UPNP
        settings.setValue("fUseUPnP", true);
#else
        settings.setValue("fUseUPnP", false);
#endif
    if (!SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool()))
        strOverriddenByCommandLine += "-upnp ";

    if (!settings.contains("fUseProxy"))
        settings.setValue("fUseProxy", false);
    if (!settings.contains("addrProxy"))
        settings.setValue("addrProxy", "127.0.0.1:9050");
    // Only try to set -proxy, if user has enabled fUseProxy
    if (settings.value("fUseProxy").toBool() && !SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString()))
        strOverriddenByCommandLine += "-proxy ";
    if (!settings.contains("nSocksVersion"))
        settings.setValue("nSocksVersion", 5);
    // Only try to set -socks, if user has enabled fUseProxy
    if (settings.value("fUseProxy").toBool() && !SoftSetArg("-socks", settings.value("nSocksVersion").toString().toStdString()))
        strOverriddenByCommandLine += "-socks ";

    // Display
    if (!settings.contains("language"))
        settings.setValue("language", "");
    if (!SoftSetArg("-lang", settings.value("language").toString().toStdString()))
        strOverriddenByCommandLine += "-lang";

    language = settings.value("language").toString();
}

void OptionsModel::Reset()
{
    QSettings settings;

    // Remove all entries from our QSettings object
    settings.clear();

    // default setting for OptionsModel::StartAtStartup - disabled
    if (GUIUtil::GetStartOnSystemStartup())
        GUIUtil::SetStartOnSystemStartup(false);

    // Ensure Upgrade() is not running again by setting the bImportFinished flag
    settings.setValue("bImportFinished", true);
}

void OptionsModel::Upgrade()
{
    QSettings settings;

    // Already upgraded
    if (settings.contains("bImportFinished"))
        return;

    settings.setValue("bImportFinished", true);

#ifdef ENABLE_WALLET
    // Move settings from old wallet.dat (if any):
    CWalletDB walletdb(strWalletFile);

    QList<QString> intOptions;
    intOptions << "nDisplayUnit" << "nTransactionFee";
    foreach(QString key, intOptions)
    {
        int value = 0;
        if (walletdb.ReadSetting(key.toStdString(), value))
        {
            settings.setValue(key, value);
            walletdb.EraseSetting(key.toStdString());
        }
    }
    QList<QString> boolOptions;
    boolOptions << "bDisplayAddresses" << "fMinimizeToTray" << "fMinimizeOnClose" << "fUseProxy" << "fUseUPnP";
    foreach(QString key, boolOptions)
    {
        bool value = false;
        if (walletdb.ReadSetting(key.toStdString(), value))
        {
            settings.setValue(key, value);
            walletdb.EraseSetting(key.toStdString());
        }
    }
    try
    {
        CAddress addrProxyAddress;
        if (walletdb.ReadSetting("addrProxy", addrProxyAddress))
        {
            settings.setValue("addrProxy", addrProxyAddress.ToStringIPPort().c_str());
            walletdb.EraseSetting("addrProxy");
        }
    }
    catch (std::ios_base::failure &e)
    {
        // 0.6.0rc1 saved this as a CService, which causes failure when parsing as a CAddress
        CService addrProxy;
        if (walletdb.ReadSetting("addrProxy", addrProxy))
        {
            settings.setValue("addrProxy", addrProxy.ToStringIPPort().c_str());
            walletdb.EraseSetting("addrProxy");
        }
    }
#endif

    Init();
}

int OptionsModel::rowCount(const QModelIndex & parent) const
{
    return OptionIDRowCount;
}

// read QSettings values and return them
QVariant OptionsModel::data(const QModelIndex & index, int role) const
{
    if(role == Qt::EditRole)
    {
        QSettings settings;
        switch(index.row())
        {
        case StartAtStartup:
            return GUIUtil::GetStartOnSystemStartup();
        case MinimizeToTray:
            return fMinimizeToTray;
        case MapPortUPnP:
#ifdef USE_UPNP
            return settings.value("fUseUPnP");
#else
            return false;
#endif
        case MinimizeOnClose:
            return fMinimizeOnClose;

        // default proxy
        case ProxyUse:
            return settings.value("fUseProxy", false);
        case ProxyIP: {
            // contains IP at index 0 and port at index 1
            QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
            return strlIpPort.at(0);
        }
        case ProxyPort: {
            // contains IP at index 0 and port at index 1
            QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
            return strlIpPort.at(1);
        }
        case ProxySocksVersion:
            return settings.value("nSocksVersion", 5);

#ifdef ENABLE_WALLET
        case Fee:
            // Attention: Init() is called before nTransactionFee is set in AppInit2()!
            // To ensure we can change the fee on-the-fly update our QSetting when
            // opening OptionsDialog, which queries Fee via the mapper.
            if (nTransactionFee != settings.value("nTransactionFee").toLongLong())
                settings.setValue("nTransactionFee", (qint64)nTransactionFee);
            // Todo: Consider to revert back to use just nTransactionFee here, if we don't want
            // -paytxfee to update our QSettings!
            return settings.value("nTransactionFee");
#endif
        case DisplayUnit:
            return nDisplayUnit;
        case DisplayAddresses:
            return bDisplayAddresses;
        case Language:
            return settings.value("language");
        case CoinControlFeatures:
            return fCoinControlFeatures;
        case DatabaseCache:
            return settings.value("nDatabaseCache");
        case ThreadsScriptVerif:
            return settings.value("nThreadsScriptVerif");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// write QSettings values
bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
    bool successful = true; /* set to false on parse error */
    if(role == Qt::EditRole)
    {
        QSettings settings;
        switch(index.row())
        {
        case StartAtStartup:
            successful = GUIUtil::SetStartOnSystemStartup(value.toBool());
            break;
        case MinimizeToTray:
            fMinimizeToTray = value.toBool();
            settings.setValue("fMinimizeToTray", fMinimizeToTray);
            break;
        case MapPortUPnP: // core option - can be changed on-the-fly
            settings.setValue("fUseUPnP", value.toBool());
            MapPort(value.toBool());
            break;
        case MinimizeOnClose:
            fMinimizeOnClose = value.toBool();
            settings.setValue("fMinimizeOnClose", fMinimizeOnClose);
            break;

        // default proxy
        case ProxyUse:
            if (settings.value("fUseProxy") != value) {
                settings.setValue("fUseProxy", value.toBool());
                setRestartRequired(true);
            }
            break;
        case ProxyIP: {
            // contains current IP at index 0 and current port at index 1
            QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
            // if that key doesn't exist or has a changed IP
            if (!settings.contains("addrProxy") || strlIpPort.at(0) != value.toString()) {
                // construct new value from new IP and current port
                QString strNewValue = value.toString() + ":" + strlIpPort.at(1);
                settings.setValue("addrProxy", strNewValue);
                setRestartRequired(true);
            }
        }
        break;
        case ProxyPort: {
            // contains current IP at index 0 and current port at index 1
            QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
            // if that key doesn't exist or has a changed port
            if (!settings.contains("addrProxy") || strlIpPort.at(1) != value.toString()) {
                // construct new value from current IP and new port
                QString strNewValue = strlIpPort.at(0) + ":" + value.toString();
                settings.setValue("addrProxy", strNewValue);
                setRestartRequired(true);
            }
        }
        break;
        case ProxySocksVersion: {
            if (settings.value("nSocksVersion") != value) {
                settings.setValue("nSocksVersion", value.toInt());
                setRestartRequired(true);
            }
        }
        break;
#ifdef ENABLE_WALLET
        case Fee: // core option - can be changed on-the-fly
            // Todo: Add is valid check  and warn via message, if not
            nTransactionFee = value.toLongLong();
            settings.setValue("nTransactionFee", (qint64)nTransactionFee);
            emit transactionFeeChanged(nTransactionFee);
            break;
#endif
        case DisplayUnit:
            nDisplayUnit = value.toInt();
            settings.setValue("nDisplayUnit", nDisplayUnit);
            emit displayUnitChanged(nDisplayUnit);
            break;
        case DisplayAddresses:
            bDisplayAddresses = value.toBool();
            settings.setValue("bDisplayAddresses", bDisplayAddresses);
            break;
        case Language:
            if (settings.value("language") != value) {
                settings.setValue("language", value);
                setRestartRequired(true);
            }
            break;
        case CoinControlFeatures:
            fCoinControlFeatures = value.toBool();
            settings.setValue("fCoinControlFeatures", fCoinControlFeatures);
            emit coinControlFeaturesChanged(fCoinControlFeatures);
            break;
        case DatabaseCache:
            if (settings.value("nDatabaseCache") != value) {
                settings.setValue("nDatabaseCache", value);
                setRestartRequired(true);
            }
            break;
        case ThreadsScriptVerif:
            if (settings.value("nThreadsScriptVerif") != value) {
                settings.setValue("nThreadsScriptVerif", value);
                setRestartRequired(true);
            }
            break;
        default:
            break;
        }
    }
    emit dataChanged(index, index);

    return successful;
}

bool OptionsModel::getProxySettings(QNetworkProxy& proxy) const
{
    // Directly query current base proxy, because
    // GUI settings can be overridden with -proxy.
    proxyType curProxy;
    if (GetProxy(NET_IPV4, curProxy)) {
        if (curProxy.second == 5) {
            proxy.setType(QNetworkProxy::Socks5Proxy);
            proxy.setHostName(QString::fromStdString(curProxy.first.ToStringIP()));
            proxy.setPort(curProxy.first.GetPort());

            return true;
        }
        else
            return false;
    }
    else
        proxy.setType(QNetworkProxy::NoProxy);

    return true;
}

void OptionsModel::setRestartRequired(bool fRequired)
{
    QSettings settings;
    return settings.setValue("fRestartRequired", fRequired);
}

bool OptionsModel::isRestartRequired()
{
    QSettings settings;
    return settings.value("fRestartRequired", false).toBool();
}
<|endoftext|>


<commit_before>#include <ctime>

unsigned runningTimeMs()
{
    return clock()*1000/CLOCKS_PER_SEC;
}
<commit_msg>Running Time thread safe fix<commit_after>#include <chrono>
using namespace std::chrono;

static auto startupTime = system_clock::now();

unsigned runningTimeMs()
{
    auto currentTime = system_clock::now();
    auto dT = duration_cast<milliseconds>(currentTime - startupTime);
    unsigned rVal = dT.count();
    return rVal;
}
<|endoftext|>