<commit_before>/* Gearman server and library
 * Copyright (C) 2008 Brian Aker, Eric Day
 * All rights reserved.
 *
 * Use and distribution licensed under the BSD license.  See
 * the COPYING file in the parent directory for full text.
 */

#include <config.h>
#include <libtest/test.hpp>

using namespace libtest;

#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/time.h>

#include <libgearman/gearman.h>

#include <libhostile/hostile.h>

#include <tests/start_worker.h>
#include <tests/workers.h>
#include "tests/burnin.h"

#define WORKER_FUNCTION_NAME "foo"

struct client_thread_context_st
{
  size_t count;
  size_t payload_size;

  client_thread_context_st() :
    count(0),
    payload_size(0)
  { }

  void increment()
  {
    count++;
  }
};

extern "C" {

  static void client_cleanup(void *client)
  {
    int oldstate;
    pthread_setcanceltype(PTHREAD_CANCEL_DISABLE, &oldstate);
    gearman_client_free((gearman_client_st *)client);
    pthread_setcanceltype(oldstate, NULL);
  }

  static void *client_thread(void *object)
  {
    client_thread_context_st *success= (client_thread_context_st *)object;
    fatal_assert(success);
    fatal_assert(success->count == 0);

    gearman_return_t rc;
    gearman_client_st *client;
    {
      int oldstate;
      pthread_setcanceltype(PTHREAD_CANCEL_DISABLE, &oldstate);
      client= gearman_client_create(NULL);

      if (client == NULL)
      {
        pthread_exit(0);
      }
      rc= gearman_client_add_server(client, NULL, libtest::default_port());
      pthread_setcanceltype(oldstate, NULL);
    }

    pthread_cleanup_push(client_cleanup, client);

    if (gearman_success(rc))
    {
      gearman_client_set_timeout(client, 400);
      for (size_t x= 0; x < 100; x++)
      {
        int oldstate;
        pthread_setcanceltype(PTHREAD_CANCEL_DISABLE, &oldstate);
        libtest::vchar_t payload;
        payload.resize(success->payload_size);
        void *value= gearman_client_do(client, WORKER_FUNCTION_NAME,
                                       NULL,
                                       &payload[0], payload.size(),
                                       NULL, &rc);
        pthread_setcanceltype(oldstate, NULL);

        if (gearman_success(rc))
        {
          success->increment();
        }

        if (value)
        {
          free(value);
        }
      }
    }

    pthread_cleanup_pop(1);
    pthread_exit(0);
  }
}

static test_return_t worker_ramp_exec(const size_t payload_size)
{
  std::vector<pthread_t> children;
  children.resize(number_of_cpus());

  std::vector<client_thread_context_st>  success;
  success.resize(children.size());

  for (size_t x= 0; x < children.size(); x++)
  {
    success[x].payload_size= payload_size;
    pthread_create(&children[x], NULL, client_thread, &success[x]);
  }

  for (size_t x= 0; x < children.size(); x++)
  {
#if _GNU_SOURCE && defined(TARGET_OS_LINUX) && TARGET_OS_LINUX
    {
      struct timespec ts;

      if (HAVE_LIBRT)
      {
        if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
        {
          Error << strerror(errno);
        }
      }
      else
      {
        struct timeval tv;
        if (gettimeofday(&tv, NULL) == -1)
        {
          Error << strerror(errno);
        }
        TIMEVAL_TO_TIMESPEC(&tv, &ts);
      }

      ts.tv_sec+= 10;

      int error= pthread_timedjoin_np(children[x], NULL, &ts);
      if (error != 0)
      {
        pthread_cancel(children[x]);
        pthread_join(children[x], NULL);
      }
    }
#else
    pthread_join(children[x], NULL);
#endif
  }

  return TEST_SUCCESS;
}

static test_return_t worker_ramp_TEST(void *)
{
  return worker_ramp_exec(0);
}

static test_return_t worker_ramp_1K_TEST(void *)
{
  return worker_ramp_exec(1024);
}

static test_return_t worker_ramp_10K_TEST(void *)
{
  return worker_ramp_exec(1024*10);
}

static test_return_t worker_ramp_SETUP(void *object)
{
  worker_handles_st *handles= (worker_handles_st*)object;

  gearman_function_t echo_react_fn= gearman_function_create(echo_or_react_worker_v2);
  for (uint32_t x= 0; x < 10; x++)
  {
    worker_handle_st *worker;
    if ((worker= test_worker_start(libtest::default_port(), NULL, WORKER_FUNCTION_NAME, echo_react_fn, NULL, gearman_worker_options_t())) == NULL)
    {
      return TEST_FAILURE;
    }
    handles->push(worker);
  }

  return TEST_SUCCESS;
}

static test_return_t worker_ramp_TEARDOWN(void* object)
{
  worker_handles_st *handles= (worker_handles_st*)object;
  handles->reset();

  return TEST_SUCCESS;
}

static test_return_t recv_SETUP(void* object)
{
  test_skip_valgrind();
  test_skip(true, bool(getenv("YATL_RUN_MASSIVE_TESTS")));

  worker_ramp_SETUP(object);
  set_recv_close(true, 20, 20);

  return TEST_SUCCESS;
}

static test_return_t resv_TEARDOWN(void* object)
{
  set_recv_close(true, 0, 0);

  worker_handles_st *handles= (worker_handles_st*)object;
  handles->kill_all();

  return TEST_SUCCESS;
}

static test_return_t send_SETUP(void* object)
{
  test_skip_valgrind();
  test_skip(true, bool(getenv("YATL_RUN_MASSIVE_TESTS")));

  worker_ramp_SETUP(object);
  set_send_close(true, 20, 20);

  return TEST_SUCCESS;
}

static test_return_t send_TEARDOWN(void* object)
{
  set_send_close(true, 0, 0);

  worker_handles_st *handles= (worker_handles_st*)object;
  handles->kill_all();

  return TEST_SUCCESS;
}

/*********************** World functions **************************************/

static void *world_create(server_startup_st& servers, test_return_t& error)
{
  if (server_startup(servers, "gearmand", libtest::default_port(), 0, NULL) == false)
  {
    error= TEST_FAILURE;
    return NULL;
  }

  return new worker_handles_st;
}

static bool world_destroy(void *object)
{
  worker_handles_st *handles= (worker_handles_st *)object;
  delete handles;

  return TEST_SUCCESS;
}

test_st burnin_TESTS[] ={
  {"burnin", 0, burnin_TEST },
  {0, 0, 0}
};

test_st worker_TESTS[] ={
  {"first pass", 0, worker_ramp_TEST },
  {"second pass", 0, worker_ramp_TEST },
  {"first pass 1K jobs", 0, worker_ramp_1K_TEST },
  {"first pass 10K jobs", 0, worker_ramp_10K_TEST },
  {0, 0, 0}
};

collection_st collection[] ={
  {"burnin", burnin_setup, burnin_cleanup, burnin_TESTS },
  {"plain", worker_ramp_SETUP, worker_ramp_TEARDOWN, worker_TESTS },
  {"hostile recv()", recv_SETUP, resv_TEARDOWN, worker_TESTS },
  {"hostile send()", send_SETUP, send_TEARDOWN, worker_TESTS },
  {0, 0, 0, 0}
};

void get_world(Framework *world)
{
  world->collections= collection;
  world->_create= world_create;
  world->_destroy= world_destroy;
}
<commit_msg>Revert change for valgrind/stessworker<commit_after>/* Gearman server and library
 * Copyright (C) 2008 Brian Aker, Eric Day
 * All rights reserved.
 *
 * Use and distribution licensed under the BSD license.  See
 * the COPYING file in the parent directory for full text.
 */

#include <config.h>
#include <libtest/test.hpp>

using namespace libtest;

#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/time.h>

#include <libgearman/gearman.h>

#include <libhostile/hostile.h>

#include <tests/start_worker.h>
#include <tests/workers.h>
#include "tests/burnin.h"

#define WORKER_FUNCTION_NAME "foo"

struct client_thread_context_st
{
  size_t count;
  size_t payload_size;

  client_thread_context_st() :
    count(0),
    payload_size(0)
  { }

  void increment()
  {
    count++;
  }
};

extern "C" {

  static void client_cleanup(void *client)
  {
    int oldstate;
    pthread_setcanceltype(PTHREAD_CANCEL_DISABLE, &oldstate);
    gearman_client_free((gearman_client_st *)client);
    pthread_setcanceltype(oldstate, NULL);
  }

  static void *client_thread(void *object)
  {
    client_thread_context_st *success= (client_thread_context_st *)object;
    fatal_assert(success);
    fatal_assert(success->count == 0);

    gearman_return_t rc;
    gearman_client_st *client;
    {
      int oldstate;
      pthread_setcanceltype(PTHREAD_CANCEL_DISABLE, &oldstate);
      client= gearman_client_create(NULL);

      if (client == NULL)
      {
        pthread_exit(0);
      }
      rc= gearman_client_add_server(client, NULL, libtest::default_port());
      pthread_setcanceltype(oldstate, NULL);
    }

    pthread_cleanup_push(client_cleanup, client);

    if (gearman_success(rc))
    {
      gearman_client_set_timeout(client, 400);
      for (size_t x= 0; x < 100; x++)
      {
        int oldstate;
        pthread_setcanceltype(PTHREAD_CANCEL_DISABLE, &oldstate);
        libtest::vchar_t payload;
        payload.resize(success->payload_size);
        void *value= gearman_client_do(client, WORKER_FUNCTION_NAME,
                                       NULL,
                                       &payload[0], payload.size(),
                                       NULL, &rc);
        pthread_setcanceltype(oldstate, NULL);

        if (gearman_success(rc))
        {
          success->increment();
        }

        if (value)
        {
          free(value);
        }
      }
    }

    pthread_cleanup_pop(1);
    pthread_exit(0);
  }
}

static test_return_t worker_ramp_exec(const size_t payload_size)
{
  std::vector<pthread_t> children;
  children.resize(number_of_cpus());

  std::vector<client_thread_context_st>  success;
  success.resize(children.size());

  for (size_t x= 0; x < children.size(); x++)
  {
    success[x].payload_size= payload_size;
    pthread_create(&children[x], NULL, client_thread, &success[x]);
  }

  for (size_t x= 0; x < children.size(); x++)
  {
#if _GNU_SOURCE && defined(TARGET_OS_LINUX) && TARGET_OS_LINUX
    {
      struct timespec ts;

      if (HAVE_LIBRT)
      {
        if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
        {
          Error << strerror(errno);
        }
      }
      else
      {
        struct timeval tv;
        if (gettimeofday(&tv, NULL) == -1)
        {
          Error << strerror(errno);
        }
        TIMEVAL_TO_TIMESPEC(&tv, &ts);
      }

      ts.tv_sec+= 10;

      int error= pthread_timedjoin_np(children[x], NULL, &ts);
      if (error != 0)
      {
        pthread_cancel(children[x]);
        pthread_join(children[x], NULL);
      }
    }
#else
    pthread_join(children[x], NULL);
#endif
  }

  return TEST_SUCCESS;
}

static test_return_t worker_ramp_TEST(void *)
{
  return worker_ramp_exec(0);
}

static test_return_t worker_ramp_1K_TEST(void *)
{
  return worker_ramp_exec(1024);
}

static test_return_t worker_ramp_10K_TEST(void *)
{
  return worker_ramp_exec(1024*10);
}

static test_return_t worker_ramp_SETUP(void *object)
{
  test_skip_valgrind();

  worker_handles_st *handles= (worker_handles_st*)object;

  gearman_function_t echo_react_fn= gearman_function_create(echo_or_react_worker_v2);
  for (uint32_t x= 0; x < 10; x++)
  {
    worker_handle_st *worker;
    if ((worker= test_worker_start(libtest::default_port(), NULL, WORKER_FUNCTION_NAME, echo_react_fn, NULL, gearman_worker_options_t())) == NULL)
    {
      return TEST_FAILURE;
    }
    handles->push(worker);
  }

  return TEST_SUCCESS;
}

static test_return_t worker_ramp_TEARDOWN(void* object)
{
  worker_handles_st *handles= (worker_handles_st*)object;
  handles->reset();

  return TEST_SUCCESS;
}

static test_return_t recv_SETUP(void* object)
{
  test_skip_valgrind();
  test_skip(true, bool(getenv("YATL_RUN_MASSIVE_TESTS")));

  worker_ramp_SETUP(object);
  set_recv_close(true, 20, 20);

  return TEST_SUCCESS;
}

static test_return_t resv_TEARDOWN(void* object)
{
  set_recv_close(true, 0, 0);

  worker_handles_st *handles= (worker_handles_st*)object;
  handles->kill_all();

  return TEST_SUCCESS;
}

static test_return_t send_SETUP(void* object)
{
  test_skip_valgrind();
  test_skip(true, bool(getenv("YATL_RUN_MASSIVE_TESTS")));

  worker_ramp_SETUP(object);
  set_send_close(true, 20, 20);

  return TEST_SUCCESS;
}

static test_return_t send_TEARDOWN(void* object)
{
  set_send_close(true, 0, 0);

  worker_handles_st *handles= (worker_handles_st*)object;
  handles->kill_all();

  return TEST_SUCCESS;
}

/*********************** World functions **************************************/

static void *world_create(server_startup_st& servers, test_return_t& error)
{
  if (server_startup(servers, "gearmand", libtest::default_port(), 0, NULL) == false)
  {
    error= TEST_FAILURE;
    return NULL;
  }

  return new worker_handles_st;
}

static bool world_destroy(void *object)
{
  worker_handles_st *handles= (worker_handles_st *)object;
  delete handles;

  return TEST_SUCCESS;
}

test_st burnin_TESTS[] ={
  {"burnin", 0, burnin_TEST },
  {0, 0, 0}
};

test_st worker_TESTS[] ={
  {"first pass", 0, worker_ramp_TEST },
  {"second pass", 0, worker_ramp_TEST },
  {"first pass 1K jobs", 0, worker_ramp_1K_TEST },
  {"first pass 10K jobs", 0, worker_ramp_10K_TEST },
  {0, 0, 0}
};

collection_st collection[] ={
  {"burnin", burnin_setup, burnin_cleanup, burnin_TESTS },
  {"plain", worker_ramp_SETUP, worker_ramp_TEARDOWN, worker_TESTS },
  {"hostile recv()", recv_SETUP, resv_TEARDOWN, worker_TESTS },
  {"hostile send()", send_SETUP, send_TEARDOWN, worker_TESTS },
  {0, 0, 0, 0}
};

void get_world(Framework *world)
{
  world->collections= collection;
  world->_create= world_create;
  world->_destroy= world_destroy;
}
<|endoftext|>


<commit_before>//
//  main.cpp
//  C++
//
//  Created by 刘谦 on 8/12/17.
//  Copyright © 2017 qianliu. All rights reserved.
//

#include <iostream>

int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
    return 0;
}
<commit_msg>kth largest better than klog(n) we can have klog(k) with O(k) more space<commit_after>//
//  main.cpp
//  C++
//
//  Created by 刘谦 on 8/12/17.
//  Copyright © 2017 qianliu. All rights reserved.
//

#include <iostream>
#include <vector>
#include <queue>
#include <cassert>

using std::vector;
using std::equal;
using std::priority_queue;
using std::less;

struct element{
    int value;
    int index;
    bool operator < (const element& that) const{
        return value < that.value;
    }
};

vector<int> KthMax(vector<int>& v, int k){
    vector<int> result;
    //while pop out element, push into two child
    priority_queue<element, vector<element>> pqueue;

    if(k == 0) return result; //base case

    pqueue.push({v[0],0});

    while(result.size() < k){
        //pop out
        auto top = pqueue.top();
        pqueue.pop();
        result.push_back(top.value);
        //push in
        int left = top.index * 2 + 1;
        int right = left + 1;
        if(left < v.size()){
            pqueue.push({v[left], left});
        }
        if(right < v.size()){
            pqueue.push({v[right], right});
        }
    }

    return result;
}
int main(int argc, const char * argv[]) {
    // Test 1
    /*
            6
         4     5
       1  2   3  0
    */
    vector<int> v1 = {6, 4, 5, 1, 2, 3, 0};
    vector<int> e1 = {6,5,4,3,2,1,0};
    vector<int> result = KthMax(v1, 7);
    assert(equal(e1.begin(), e1.end(), result.begin()));

    /*
                     10
                  2          9
                2   2      8   8
              2 2  2 2    7 7  7 7
     */
    vector<int> max_heap = {10, 2, 9, 2, 2, 8, 8, 2, 2, 2, 2, 7, 7, 7, 7};
    result = KthMax(max_heap, 3);

    vector<int> expected_result = {10, 9, 8};
    assert(equal(result.begin(), result.end(), expected_result.begin()));
    result = KthMax(max_heap, 5);
    expected_result = {10, 9, 8, 8, 7};
    assert(equal(result.begin(), result.end(), expected_result.begin()));

    max_heap = {97, 84, 93, 83, 81, 90, 79, 83, 55, 42, 21, 73};
    result = KthMax(max_heap, 3);
    expected_result = {97, 93, 90};
    assert(equal(result.begin(), result.end(), expected_result.begin()));

    max_heap = {100, 1, 5, 0, 0};
    result = KthMax(max_heap, 1);
    expected_result = {100};
    assert(equal(result.begin(), result.end(), expected_result.begin()));
    return 0;
}
<|endoftext|>


<commit_before>#include <pddlparse/detail/parsing/Description.h>

#include <pddlparse/AST.h>
#include <pddlparse/ParserException.h>
#include <pddlparse/detail/parsing/Domain.h>
#include <pddlparse/detail/parsing/Problem.h>
#include <pddlparse/detail/parsing/Utils.h>

namespace pddl
{
namespace detail
{

////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Description
//
////////////////////////////////////////////////////////////////////////////////////////////////////

DescriptionParser::DescriptionParser(Context &context)
:	m_context{context},
	m_domainPosition{-1},
	m_problemPosition{-1}
{
}

////////////////////////////////////////////////////////////////////////////////////////////////////

ast::Description DescriptionParser::parse()
{
	auto &tokenizer = m_context.tokenizer;
	tokenizer.removeComments(";", "\n", false);

	findSections();

	if (m_domainPosition == -1)
		throw ParserException("no PDDL domain specified");

	tokenizer.seek(m_domainPosition);

	auto domain = DomainParser(m_context).parse();

	// If no problem is given, return just the domain
	if (m_problemPosition == -1)
		return {std::move(domain), std::experimental::nullopt};

	tokenizer.seek(m_problemPosition);

	auto problem = ProblemParser(m_context, *domain).parse();

	// TODO: check consistency
	// * check typing requirement
	// * check that typing is used consistently
	// * check that constants, variables, and predicates aren't declared twice
	// * check section order
	// * check that preconditions and effects are well-formed
	return {std::move(domain), std::move(problem)};
}

////////////////////////////////////////////////////////////////////////////////////////////////////

void DescriptionParser::findSections()
{
	auto &tokenizer = m_context.tokenizer;

	tokenizer.skipWhiteSpace();

	while (!tokenizer.atEnd())
	{
		const auto position = tokenizer.position();

		tokenizer.expect<std::string>("(");
		tokenizer.expect<std::string>("define");
		tokenizer.expect<std::string>("(");

		if (tokenizer.testAndSkip<std::string>("domain"))
		{
			if (m_domainPosition != -1)
				throw ParserException(tokenizer.location(), "PDDL description may not contain two domains");

			m_domainPosition = position;
			skipSection(tokenizer);
			skipSection(tokenizer);
		}
		else if (m_context.tokenizer.testAndSkip<std::string>("problem"))
		{
			if (m_problemPosition != -1)
				throw ParserException("PDDL description may not contain two problems currently");

			m_problemPosition = position;
			skipSection(tokenizer);
			skipSection(tokenizer);
		}
		else
		{
			const auto sectionIdentifier = tokenizer.get<std::string>();
			throw ParserException(tokenizer.location(), "unknown PDDL section “" + sectionIdentifier + "”");
		}

		tokenizer.skipWhiteSpace();
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////

}
}
<commit_msg>Added compatibility check for unsupported “in-package” sections.<commit_after>#include <pddlparse/detail/parsing/Description.h>

#include <pddlparse/AST.h>
#include <pddlparse/ParserException.h>
#include <pddlparse/detail/parsing/Domain.h>
#include <pddlparse/detail/parsing/Problem.h>
#include <pddlparse/detail/parsing/Utils.h>

namespace pddl
{
namespace detail
{

////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Description
//
////////////////////////////////////////////////////////////////////////////////////////////////////

DescriptionParser::DescriptionParser(Context &context)
:	m_context{context},
	m_domainPosition{-1},
	m_problemPosition{-1}
{
}

////////////////////////////////////////////////////////////////////////////////////////////////////

ast::Description DescriptionParser::parse()
{
	auto &tokenizer = m_context.tokenizer;
	tokenizer.removeComments(";", "\n", false);

	findSections();

	if (m_domainPosition == -1)
		throw ParserException("no PDDL domain specified");

	tokenizer.seek(m_domainPosition);

	auto domain = DomainParser(m_context).parse();

	// If no problem is given, return just the domain
	if (m_problemPosition == -1)
		return {std::move(domain), std::experimental::nullopt};

	tokenizer.seek(m_problemPosition);

	auto problem = ProblemParser(m_context, *domain).parse();

	// TODO: check consistency
	// * check typing requirement
	// * check that typing is used consistently
	// * check that constants, variables, and predicates aren't declared twice
	// * check section order
	// * check that preconditions and effects are well-formed
	return {std::move(domain), std::move(problem)};
}

////////////////////////////////////////////////////////////////////////////////////////////////////

void DescriptionParser::findSections()
{
	auto &tokenizer = m_context.tokenizer;

	tokenizer.skipWhiteSpace();

	while (!tokenizer.atEnd())
	{
		const auto position = tokenizer.position();

		tokenizer.expect<std::string>("(");

		if (tokenizer.testAndReturn<std::string>("in-package"))
		{
			m_context.warningCallback(tokenizer.location(), "ignoring “in-package” section, which is not part of the PDDL 3.1 specification");

			skipSection(tokenizer);
			tokenizer.skipWhiteSpace();

			continue;
		}

		tokenizer.expect<std::string>("define");
		tokenizer.expect<std::string>("(");

		if (tokenizer.testAndSkip<std::string>("domain"))
		{
			if (m_domainPosition != -1)
				throw ParserException(tokenizer.location(), "PDDL description may not contain two domains");

			m_domainPosition = position;
			skipSection(tokenizer);
			skipSection(tokenizer);
		}
		else if (m_context.tokenizer.testAndSkip<std::string>("problem"))
		{
			if (m_problemPosition != -1)
				throw ParserException("PDDL description may not contain two problems currently");

			m_problemPosition = position;
			skipSection(tokenizer);
			skipSection(tokenizer);
		}
		else
		{
			const auto sectionIdentifier = tokenizer.get<std::string>();
			throw ParserException(tokenizer.location(), "unknown PDDL section “" + sectionIdentifier + "”");
		}

		tokenizer.skipWhiteSpace();
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////

}
}
<|endoftext|>


<commit_before>//===========================================
//  Lumina-DE source code
//  Copyright (c) 2014, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "UserItemWidget.h"

UserItemWidget::UserItemWidget(QWidget *parent, QString itemPath, bool isDir, bool goback) : QFrame(parent){
  createWidget();
  //Now fill it appropriately
  if(itemPath.endsWith(".desktop")){
    bool ok = false;
    XDGDesktop item = LXDG::loadDesktopFile(itemPath, ok);
    if(ok){
      icon->setPixmap( LXDG::findIcon(item.icon, "preferences-system-windows-actions").pixmap(32,32) );
      name->setText( this->fontMetrics().elidedText(item.name, Qt::ElideRight, 180) );
    }else{
      icon->setPixmap( LXDG::findIcon("unknown","").pixmap(32,32) );
      name->setText( this->fontMetrics().elidedText(itemPath.section("/",-1), Qt::ElideRight, 180) );
    }
  }else if(isDir){
    if(itemPath.endsWith("/")){ itemPath.chop(1); }
    if(goback){
      icon->setPixmap( LXDG::findIcon("go-previous","").pixmap(32,32) );
      name->setText( tr("Go Back") );
    }else{
      icon->setPixmap( LXDG::findIcon("folder","").pixmap(32,32) );
      name->setText( this->fontMetrics().elidedText(itemPath.section("/",-1), Qt::ElideRight, 180) );
    }
  }else{
    if(itemPath.endsWith("/")){ itemPath.chop(1); }
    icon->setPixmap( LXDG::findMimeIcon(itemPath.section("/",-1).section(".",-1)).pixmap(32,32) );
    name->setText( this->fontMetrics().elidedText(itemPath.section("/",-1), Qt::ElideRight, 180) );
  }
  linkPath = QFile::symLinkTarget(itemPath);
  icon->setWhatsThis(itemPath);
  if(isDir && !linkPath.isEmpty()){ isDir = false; } //not a real directory - just a sym link
  isDirectory = isDir; //save this for later
  isShortcut = itemPath.contains("/home/") && (itemPath.contains("/Desktop/") || itemPath.contains("/.lumina/favorites/") );
  //Now setup the button appropriately
  setupButton(goback);
}

UserItemWidget::UserItemWidget(QWidget *parent, XDGDesktop item) : QFrame(parent){
  createWidget();
  isDirectory = false;
  linkPath = QFile::symLinkTarget(item.filePath);
  isShortcut = item.filePath.contains("/home/") && (item.filePath.contains("/Desktop/") || item.filePath.contains("/.lumina/favorites/") );
  //Now fill it appropriately
  icon->setPixmap( LXDG::findIcon(item.icon,"preferences-system-windows-actions").pixmap(32,32) );
  name->setText( this->fontMetrics().elidedText(item.name, Qt::ElideRight, 180) );
  icon->setWhatsThis(item.filePath);
  //Now setup the button appropriately
  setupButton();

}

UserItemWidget::~UserItemWidget(){
  delete button;
  delete icon;
  delete name;
}

void UserItemWidget::createWidget(){
  //Initialize the widgets
  this->setContentsMargins(0,0,0,0);
  button = new QToolButton(this);
    button->setIconSize( QSize(14,14) );
    button->setAutoRaise(true);
  icon = new QLabel(this);
    icon->setFixedSize( QSize(34,34) );
  name = new QLabel(this);
  //Add them to the layout
  this->setLayout(new QHBoxLayout());
    this->layout()->setContentsMargins(1,1,1,1);
    this->layout()->addWidget(icon);
    this->layout()->addWidget(name);
    this->layout()->addWidget(button);
  //Set a custom object name so this can be tied into the Lumina Theme stylesheets
  this->setObjectName("LuminaUserItemWidget");
  //Install the stylesheet
  //this->setStyleSheet("UserItemWidget{ background: transparent; border-radius: 5px;} UserItemWidget::hover{ background: rgba(255,255,255,200); border-radius: 5px; }");
}

void UserItemWidget::setupButton(bool disable){
  if(disable){
    button->setVisible(false);
  }else if( !isDirectory && isShortcut ){
    //This is a current desktop shortcut -- allow the user to remove it
    button->setWhatsThis("remove");
    if(!linkPath.isEmpty()){
      button->setIcon( LXDG::findIcon("list-remove","") );
      button->setToolTip(tr("Remove Shortcut"));
    }else{
      button->setIcon( LXDG::findIcon("user-trash","") );
      button->setToolTip(tr("Delete File"));
    }
    connect(button, SIGNAL(clicked()), this, SLOT(buttonClicked()) );
  }else if( !QFile::exists( QDir::homePath()+"/Desktop/"+icon->whatsThis().section("/",-1) ) && !QFile::exists( QDir::homePath()+"/.lumina/favorites/"+icon->whatsThis().section("/",-1) ) ){
    //This file does not have a desktop shortcut yet -- allow the user to add it
    button->setWhatsThis("add");
    button->setIcon( LXDG::findIcon("bookmark-toolbar","") );
    button->setToolTip(tr("Create Shortcut"));
    connect(button, SIGNAL(clicked()), this, SLOT(buttonClicked()) );
  }else{
    //This already has a desktop shortcut -- no special actions
    button->setVisible(false);
  }
}

void UserItemWidget::buttonClicked(){
  button->setVisible(false);
  if(button->whatsThis()=="add"){
    QFile::link(icon->whatsThis(), QDir::homePath()+"/.lumina/favorites/"+icon->whatsThis().section("/",-1) );
    emit NewShortcut();
  }else if(button->whatsThis()=="remove"){
    QFile::remove(icon->whatsThis()); //never remove the linkPath - since that is the actual file/dir
    emit RemovedShortcut();
  }
}

void UserItemWidget::ItemClicked(){
  if(!linkPath.isEmpty()){ emit RunItem(linkPath); }
  else{ emit RunItem(icon->whatsThis()); }

}<commit_msg>Make sure that files visible in the userbutton have the appropriate icons based on the mimetype.<commit_after>//===========================================
//  Lumina-DE source code
//  Copyright (c) 2014, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "UserItemWidget.h"

UserItemWidget::UserItemWidget(QWidget *parent, QString itemPath, bool isDir, bool goback) : QFrame(parent){
  createWidget();
  //Now fill it appropriately
  if(itemPath.endsWith(".desktop")){
    bool ok = false;
    XDGDesktop item = LXDG::loadDesktopFile(itemPath, ok);
    if(ok){
      icon->setPixmap( LXDG::findIcon(item.icon, "preferences-system-windows-actions").pixmap(32,32) );
      name->setText( this->fontMetrics().elidedText(item.name, Qt::ElideRight, 180) );
    }else{
      icon->setPixmap( LXDG::findIcon("unknown","").pixmap(32,32) );
      name->setText( this->fontMetrics().elidedText(itemPath.section("/",-1), Qt::ElideRight, 180) );
    }
  }else if(isDir){
    if(itemPath.endsWith("/")){ itemPath.chop(1); }
    if(goback){
      icon->setPixmap( LXDG::findIcon("go-previous","").pixmap(32,32) );
      name->setText( tr("Go Back") );
    }else{
      icon->setPixmap( LXDG::findIcon("folder","").pixmap(32,32) );
      name->setText( this->fontMetrics().elidedText(itemPath.section("/",-1), Qt::ElideRight, 180) );
    }
  }else{
    if(itemPath.endsWith("/")){ itemPath.chop(1); }
    icon->setPixmap( LXDG::findMimeIcon(itemPath.section("/",-1)).pixmap(32,32) );
    name->setText( this->fontMetrics().elidedText(itemPath.section("/",-1), Qt::ElideRight, 180) );
  }
  linkPath = QFile::symLinkTarget(itemPath);
  icon->setWhatsThis(itemPath);
  if(isDir && !linkPath.isEmpty()){ isDir = false; } //not a real directory - just a sym link
  isDirectory = isDir; //save this for later
  isShortcut = itemPath.contains("/home/") && (itemPath.contains("/Desktop/") || itemPath.contains("/.lumina/favorites/") );
  //Now setup the button appropriately
  setupButton(goback);
}

UserItemWidget::UserItemWidget(QWidget *parent, XDGDesktop item) : QFrame(parent){
  createWidget();
  isDirectory = false;
  linkPath = QFile::symLinkTarget(item.filePath);
  isShortcut = item.filePath.contains("/home/") && (item.filePath.contains("/Desktop/") || item.filePath.contains("/.lumina/favorites/") );
  //Now fill it appropriately
  icon->setPixmap( LXDG::findIcon(item.icon,"preferences-system-windows-actions").pixmap(32,32) );
  name->setText( this->fontMetrics().elidedText(item.name, Qt::ElideRight, 180) );
  icon->setWhatsThis(item.filePath);
  //Now setup the button appropriately
  setupButton();

}

UserItemWidget::~UserItemWidget(){
  delete button;
  delete icon;
  delete name;
}

void UserItemWidget::createWidget(){
  //Initialize the widgets
  this->setContentsMargins(0,0,0,0);
  button = new QToolButton(this);
    button->setIconSize( QSize(14,14) );
    button->setAutoRaise(true);
  icon = new QLabel(this);
    icon->setFixedSize( QSize(34,34) );
  name = new QLabel(this);
  //Add them to the layout
  this->setLayout(new QHBoxLayout());
    this->layout()->setContentsMargins(1,1,1,1);
    this->layout()->addWidget(icon);
    this->layout()->addWidget(name);
    this->layout()->addWidget(button);
  //Set a custom object name so this can be tied into the Lumina Theme stylesheets
  this->setObjectName("LuminaUserItemWidget");
  //Install the stylesheet
  //this->setStyleSheet("UserItemWidget{ background: transparent; border-radius: 5px;} UserItemWidget::hover{ background: rgba(255,255,255,200); border-radius: 5px; }");
}

void UserItemWidget::setupButton(bool disable){
  if(disable){
    button->setVisible(false);
  }else if( !isDirectory && isShortcut ){
    //This is a current desktop shortcut -- allow the user to remove it
    button->setWhatsThis("remove");
    if(!linkPath.isEmpty()){
      button->setIcon( LXDG::findIcon("list-remove","") );
      button->setToolTip(tr("Remove Shortcut"));
    }else{
      button->setIcon( LXDG::findIcon("user-trash","") );
      button->setToolTip(tr("Delete File"));
    }
    connect(button, SIGNAL(clicked()), this, SLOT(buttonClicked()) );
  }else if( !QFile::exists( QDir::homePath()+"/Desktop/"+icon->whatsThis().section("/",-1) ) && !QFile::exists( QDir::homePath()+"/.lumina/favorites/"+icon->whatsThis().section("/",-1) ) ){
    //This file does not have a desktop shortcut yet -- allow the user to add it
    button->setWhatsThis("add");
    button->setIcon( LXDG::findIcon("bookmark-toolbar","") );
    button->setToolTip(tr("Create Shortcut"));
    connect(button, SIGNAL(clicked()), this, SLOT(buttonClicked()) );
  }else{
    //This already has a desktop shortcut -- no special actions
    button->setVisible(false);
  }
}

void UserItemWidget::buttonClicked(){
  button->setVisible(false);
  if(button->whatsThis()=="add"){
    QFile::link(icon->whatsThis(), QDir::homePath()+"/.lumina/favorites/"+icon->whatsThis().section("/",-1) );
    emit NewShortcut();
  }else if(button->whatsThis()=="remove"){
    QFile::remove(icon->whatsThis()); //never remove the linkPath - since that is the actual file/dir
    emit RemovedShortcut();
  }
}

void UserItemWidget::ItemClicked(){
  if(!linkPath.isEmpty()){ emit RunItem(linkPath); }
  else{ emit RunItem(icon->whatsThis()); }

}<|endoftext|>


<commit_before>
#include <cstring>
#include <stdexcept>
#include <sys/mman.h>
#include <xf86drm.h>
#include <xf86drmMode.h>
#include <fcntl.h>
#include <unistd.h>
#include <drm_fourcc.h>
#include <drm.h>
#include <drm_mode.h>

#include "kms++.h"

#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))

using namespace std;

namespace kms
{

DumbFramebuffer::DumbFramebuffer(Card &card, uint32_t width, uint32_t height, const string& fourcc)
	:DumbFramebuffer(card, width, height, FourCCToPixelFormat(fourcc))
{
}

DumbFramebuffer::DumbFramebuffer(Card& card, uint32_t width, uint32_t height, PixelFormat format)
	:Framebuffer(card, width, height), m_format(format)
{
	Create();
}

DumbFramebuffer::~DumbFramebuffer()
{
	Destroy();
}

struct FormatPlaneInfo
{
	uint8_t bitspp;	/* bits per (macro) pixel */
	uint8_t xsub;
	uint8_t ysub;
};

struct FormatInfo
{
	uint8_t num_planes;
	struct FormatPlaneInfo planes[4];
};

static const map<PixelFormat, FormatInfo> format_info_array = {
	/* YUV packed */
	{ PixelFormat::UYVY, { 1, { { 32, 2, 1 } }, } },
	{ PixelFormat::YUYV, { 1, { { 32, 2, 1 } }, } },
	{ PixelFormat::YVYU, { 1, { { 32, 2, 1 } }, } },
	{ PixelFormat::VYUY, { 1, { { 32, 2, 1 } }, } },
	/* YUV semi-planar */
	{ PixelFormat::NV12, { 2, { { 8, 1, 1, }, { 16, 2, 2 } }, } },
	{ PixelFormat::NV21, { 2, { { 8, 1, 1, }, { 16, 2, 2 } }, } },
	/* RGB16 */
	{ PixelFormat::RGB565, { 1, { { 16, 1, 1 } }, } },
	/* RGB32 */
	{ PixelFormat::XRGB8888, { 1, { { 32, 1, 1 } }, } },
	{ PixelFormat::XBGR8888, { 1, { { 32, 1, 1 } }, } },
	{ PixelFormat::ARGB8888, { 1, { { 32, 1, 1 } }, } },
	{ PixelFormat::ABGR8888, { 1, { { 32, 1, 1 } }, } },
};

void DumbFramebuffer::Create()
{
	int r;

	const FormatInfo& format_info = format_info_array.at(m_format);

	m_num_planes = format_info.num_planes;

	for (int i = 0; i < format_info.num_planes; ++i) {
		const FormatPlaneInfo& pi = format_info.planes[i];
		FramebufferPlane& plane = m_planes[i];

		/* create dumb buffer */
		struct drm_mode_create_dumb creq = drm_mode_create_dumb();
		creq.width = width() / pi.xsub;
		creq.height = height() / pi.ysub;
		creq.bpp = pi.bitspp;
		r = drmIoctl(card().fd(), DRM_IOCTL_MODE_CREATE_DUMB, &creq);
		if (r)
			throw invalid_argument(string("DRM_IOCTL_MODE_CREATE_DUMB failed") + strerror(errno));

		plane.handle = creq.handle;
		plane.stride = creq.pitch;
		plane.size = creq.height * creq.pitch;
		plane.offset = 0;
		plane.map = 0;
		plane.prime_fd = -1;
	}

	/* create framebuffer object for the dumb-buffer */
	uint32_t bo_handles[4] = { m_planes[0].handle, m_planes[1].handle };
	uint32_t pitches[4] = { m_planes[0].stride, m_planes[1].stride };
	uint32_t offsets[4] = {  m_planes[0].offset, m_planes[1].offset };
	uint32_t id;
	r = drmModeAddFB2(card().fd(), width(), height(), (uint32_t)format(),
			  bo_handles, pitches, offsets, &id, 0);
	if (r)
		throw invalid_argument(string("drmModeAddFB2 failed: ") + strerror(errno));

	set_id(id);
}

void DumbFramebuffer::Destroy()
{
	/* delete framebuffer */
	drmModeRmFB(card().fd(), id());

	for (uint i = 0; i < m_num_planes; ++i) {
		FramebufferPlane& plane = m_planes[i];

		/* unmap buffer */
		munmap(plane.map, plane.size);

		/* delete dumb buffer */
		struct drm_mode_destroy_dumb dreq = drm_mode_destroy_dumb();
		dreq.handle = plane.handle;
		drmIoctl(card().fd(), DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
		if (plane.prime_fd >= 0)
			::close(plane.prime_fd);
	}
}

uint8_t* DumbFramebuffer::map(unsigned plane)
{
	FramebufferPlane& p = m_planes[plane];

	if (p.map)
		return p.map;

	/* prepare buffer for memory mapping */
	struct drm_mode_map_dumb mreq = drm_mode_map_dumb();
	mreq.handle = p.handle;
	int r = drmIoctl(card().fd(), DRM_IOCTL_MODE_MAP_DUMB, &mreq);
	if (r)
		throw invalid_argument(string("DRM_IOCTL_MODE_MAP_DUMB failed") + strerror(errno));

	/* perform actual memory mapping */
	p.map = (uint8_t *)mmap(0, p.size, PROT_READ | PROT_WRITE, MAP_SHARED,
					  card().fd(), mreq.offset);
	if (p.map == MAP_FAILED)
		throw invalid_argument(string("mmap failed: ") + strerror(errno));

	return p.map;
}

int DumbFramebuffer::prime_fd(unsigned int plane)
{
	if (m_planes[plane].prime_fd >= 0)
		return m_planes[plane].prime_fd;

	int r = drmPrimeHandleToFD(card().fd(), m_planes[plane].handle,
				   DRM_CLOEXEC, &m_planes[plane].prime_fd);
	if (r)
		throw std::runtime_error("drmPrimeHandleToFD failed\n");

	return m_planes[plane].prime_fd;
}

}
<commit_msg>DumbFB: don't unmap if not mapped<commit_after>
#include <cstring>
#include <stdexcept>
#include <sys/mman.h>
#include <xf86drm.h>
#include <xf86drmMode.h>
#include <fcntl.h>
#include <unistd.h>
#include <drm_fourcc.h>
#include <drm.h>
#include <drm_mode.h>

#include "kms++.h"

#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))

using namespace std;

namespace kms
{

DumbFramebuffer::DumbFramebuffer(Card &card, uint32_t width, uint32_t height, const string& fourcc)
	:DumbFramebuffer(card, width, height, FourCCToPixelFormat(fourcc))
{
}

DumbFramebuffer::DumbFramebuffer(Card& card, uint32_t width, uint32_t height, PixelFormat format)
	:Framebuffer(card, width, height), m_format(format)
{
	Create();
}

DumbFramebuffer::~DumbFramebuffer()
{
	Destroy();
}

struct FormatPlaneInfo
{
	uint8_t bitspp;	/* bits per (macro) pixel */
	uint8_t xsub;
	uint8_t ysub;
};

struct FormatInfo
{
	uint8_t num_planes;
	struct FormatPlaneInfo planes[4];
};

static const map<PixelFormat, FormatInfo> format_info_array = {
	/* YUV packed */
	{ PixelFormat::UYVY, { 1, { { 32, 2, 1 } }, } },
	{ PixelFormat::YUYV, { 1, { { 32, 2, 1 } }, } },
	{ PixelFormat::YVYU, { 1, { { 32, 2, 1 } }, } },
	{ PixelFormat::VYUY, { 1, { { 32, 2, 1 } }, } },
	/* YUV semi-planar */
	{ PixelFormat::NV12, { 2, { { 8, 1, 1, }, { 16, 2, 2 } }, } },
	{ PixelFormat::NV21, { 2, { { 8, 1, 1, }, { 16, 2, 2 } }, } },
	/* RGB16 */
	{ PixelFormat::RGB565, { 1, { { 16, 1, 1 } }, } },
	/* RGB32 */
	{ PixelFormat::XRGB8888, { 1, { { 32, 1, 1 } }, } },
	{ PixelFormat::XBGR8888, { 1, { { 32, 1, 1 } }, } },
	{ PixelFormat::ARGB8888, { 1, { { 32, 1, 1 } }, } },
	{ PixelFormat::ABGR8888, { 1, { { 32, 1, 1 } }, } },
};

void DumbFramebuffer::Create()
{
	int r;

	const FormatInfo& format_info = format_info_array.at(m_format);

	m_num_planes = format_info.num_planes;

	for (int i = 0; i < format_info.num_planes; ++i) {
		const FormatPlaneInfo& pi = format_info.planes[i];
		FramebufferPlane& plane = m_planes[i];

		/* create dumb buffer */
		struct drm_mode_create_dumb creq = drm_mode_create_dumb();
		creq.width = width() / pi.xsub;
		creq.height = height() / pi.ysub;
		creq.bpp = pi.bitspp;
		r = drmIoctl(card().fd(), DRM_IOCTL_MODE_CREATE_DUMB, &creq);
		if (r)
			throw invalid_argument(string("DRM_IOCTL_MODE_CREATE_DUMB failed") + strerror(errno));

		plane.handle = creq.handle;
		plane.stride = creq.pitch;
		plane.size = creq.height * creq.pitch;
		plane.offset = 0;
		plane.map = 0;
		plane.prime_fd = -1;
	}

	/* create framebuffer object for the dumb-buffer */
	uint32_t bo_handles[4] = { m_planes[0].handle, m_planes[1].handle };
	uint32_t pitches[4] = { m_planes[0].stride, m_planes[1].stride };
	uint32_t offsets[4] = {  m_planes[0].offset, m_planes[1].offset };
	uint32_t id;
	r = drmModeAddFB2(card().fd(), width(), height(), (uint32_t)format(),
			  bo_handles, pitches, offsets, &id, 0);
	if (r)
		throw invalid_argument(string("drmModeAddFB2 failed: ") + strerror(errno));

	set_id(id);
}

void DumbFramebuffer::Destroy()
{
	/* delete framebuffer */
	drmModeRmFB(card().fd(), id());

	for (uint i = 0; i < m_num_planes; ++i) {
		FramebufferPlane& plane = m_planes[i];

		/* unmap buffer */
		if (plane.map)
			munmap(plane.map, plane.size);

		/* delete dumb buffer */
		struct drm_mode_destroy_dumb dreq = drm_mode_destroy_dumb();
		dreq.handle = plane.handle;
		drmIoctl(card().fd(), DRM_IOCTL_MODE_DESTROY_DUMB, &dreq);
		if (plane.prime_fd >= 0)
			::close(plane.prime_fd);
	}
}

uint8_t* DumbFramebuffer::map(unsigned plane)
{
	FramebufferPlane& p = m_planes[plane];

	if (p.map)
		return p.map;

	/* prepare buffer for memory mapping */
	struct drm_mode_map_dumb mreq = drm_mode_map_dumb();
	mreq.handle = p.handle;
	int r = drmIoctl(card().fd(), DRM_IOCTL_MODE_MAP_DUMB, &mreq);
	if (r)
		throw invalid_argument(string("DRM_IOCTL_MODE_MAP_DUMB failed") + strerror(errno));

	/* perform actual memory mapping */
	p.map = (uint8_t *)mmap(0, p.size, PROT_READ | PROT_WRITE, MAP_SHARED,
					  card().fd(), mreq.offset);
	if (p.map == MAP_FAILED)
		throw invalid_argument(string("mmap failed: ") + strerror(errno));

	return p.map;
}

int DumbFramebuffer::prime_fd(unsigned int plane)
{
	if (m_planes[plane].prime_fd >= 0)
		return m_planes[plane].prime_fd;

	int r = drmPrimeHandleToFD(card().fd(), m_planes[plane].handle,
				   DRM_CLOEXEC, &m_planes[plane].prime_fd);
	if (r)
		throw std::runtime_error("drmPrimeHandleToFD failed\n");

	return m_planes[plane].prime_fd;
}

}
<|endoftext|>


<commit_before>// hpi

#include "smd_hpi/src/q_convolution.cc"
<commit_msg>add fully connected and activation to amalgamation<commit_after>// hpi

#include "smd_hpi/src/q_convolution.cc"
#include "smd_hpi/src/q_activation.cc"
#include "smd_hpi/src/q_fully_connected.cc"
<|endoftext|>


<commit_before>/*
  Copyright (C) 2014 Marcus Soll
  All rights reserved.

  You may use this file under the terms of BSD license as follows:

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the Jolla Ltd nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR
  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "cornercore.h"
#include "assemblyaihelper.h"

using AssemblyAI::opponent;

CornerCore::CornerCore()
{
}

bool CornerCore::retirement(Gameboard board, int player)
{
    // The core should retrire when neither the player nor the opponent can get a corner
    return !(board.play(0,0,opponent(player),true) || board.play(7,0,opponent(player),true) || board.play(0,7,opponent(player),true) || board.play(7,7,opponent(player),true))
            && !(board.play(0,0,player,true) || board.play(7,0,player,true) || board.play(0,7,player,true) || board.play(7,7,player,true));
}

bool CornerCore::mistrust(float const* const* const vote, Gameboard board, int player)
{
    // Mistrust if you can get a corner but the proposal doesn't consider it

    if(!(vote[0][0] < 0) && board.play(0,0,player,true))
    {
        return true;
    }
    else if(!(vote[0][7] < 0) && board.play(0,7,player,true))
    {
        return true;
    }
    else if(!(vote[7][0] < 0) && board.play(7,0,player,true))
    {
        return true;
    }
    else if(!(vote[7][7] < 0) && board.play(7,7,player,true))
    {
        return true;
    }

    // Mistrust if a play is proposed where the opponent could get a corner
    for(int x = 0; x < 8; ++x)
    {
        for(int y = 0; y < 8; ++y)
        {
            if(vote[x][y] > 0 && ((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))
            {
                Gameboard testboard = board;
                testboard.play(x,y,player,false);
                if(!(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true)))
                {
                    return true;
                }
            }
        }
    }
    return false;
}

void CornerCore::propose(float ** const vote, Gameboard board, int player)
{
    // Try to get corners
    if(board.play(0,0,player,true))
    {
        vote[0][0] = 1;
    }
    if(board.play(0,7,player,true))
    {
        vote[0][7] = 1;
    }
    if(board.play(7,0,player,true))
    {
        vote[7][0] = 1;
    }
    if(board.play(7,7,player,true))
    {
        vote[7][7] = 1;
    }

    // Propose plays where the opponent can't get a corner
    for(int x = 0; x < 8; ++x)
    {
        for(int y = 0; y < 8; ++y)
        {
            if(vote[x][y] > 0 && ((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))
            {
                Gameboard testboard = board;
                testboard.play(x,y,opponent(player),false);
                if(!(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true)))
                {
                    vote[x][y] = 0.1;
                }
            }
        }
    }
    AssemblyAI::ensureOnePossibleMove(vote,board,player);
}

void CornerCore::correct(float ** const vote, Gameboard board, int player)
{
    // Give Corners a high priority
    vote[0][0] *= Core::_factorLarge;
    vote[0][7] *= Core::_factorLarge;
    vote[7][0] *= Core::_factorLarge;
    vote[7][7] *= Core::_factorLarge;

    // Give plays where an opponent can get a corner a low priority
    for(int x = 0; x < 8; ++x)
    {
        for(int y = 0; y < 8; ++y)
        {
            if(vote[x][y] > 0 && ((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))
            {
                Gameboard testboard = board;
                testboard.play(x,y,opponent(player),false);
                if(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true))
                {
                    vote[x][y] /= Core::_factorLarge;
                }
            }
        }
    }
}

QString CornerCore::name() const
{
    return "Corner Core";
}
<commit_msg>Fixed "Corner Core"<commit_after>/*
  Copyright (C) 2014 Marcus Soll
  All rights reserved.

  You may use this file under the terms of BSD license as follows:

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the Jolla Ltd nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR
  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "cornercore.h"
#include "assemblyaihelper.h"

using AssemblyAI::opponent;

CornerCore::CornerCore()
{
}

bool CornerCore::retirement(Gameboard board, int player)
{
    // The core should retrire when neither the player nor the opponent can get a corner
    return !(board.play(0,0,opponent(player),true) || board.play(7,0,opponent(player),true) || board.play(0,7,opponent(player),true) || board.play(7,7,opponent(player),true))
            && !(board.play(0,0,player,true) || board.play(7,0,player,true) || board.play(0,7,player,true) || board.play(7,7,player,true));
}

bool CornerCore::mistrust(float const* const* const vote, Gameboard board, int player)
{
    // Mistrust if you can get a corner but the proposal doesn't consider it

    if(!(vote[0][0] < 0) && board.play(0,0,player,true))
    {
        return true;
    }
    else if(!(vote[0][7] < 0) && board.play(0,7,player,true))
    {
        return true;
    }
    else if(!(vote[7][0] < 0) && board.play(7,0,player,true))
    {
        return true;
    }
    else if(!(vote[7][7] < 0) && board.play(7,7,player,true))
    {
        return true;
    }

    // Mistrust if a play is proposed where the opponent could get a corner
    for(int x = 0; x < 8; ++x)
    {
        for(int y = 0; y < 8; ++y)
        {
            if(vote[x][y] > 0 && !((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))
            {
                Gameboard testboard = board;
                testboard.play(x,y,player,false);
                if(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true))
                {
                    return true;
                }
            }
        }
    }
    return false;
}

void CornerCore::propose(float ** const vote, Gameboard board, int player)
{
    // Try to get corners
    if(board.play(0,0,player,true))
    {
        vote[0][0] = 1;
    }
    if(board.play(0,7,player,true))
    {
        vote[0][7] = 1;
    }
    if(board.play(7,0,player,true))
    {
        vote[7][0] = 1;
    }
    if(board.play(7,7,player,true))
    {
        vote[7][7] = 1;
    }

    // Propose plays where the opponent can't get a corner
    for(int x = 0; x < 8; ++x)
    {
        for(int y = 0; y < 8; ++y)
        {
            if(vote[x][y] > 0 && ((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))
            {
                Gameboard testboard = board;
                testboard.play(x,y,opponent(player),false);
                if(!(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true)))
                {
                    vote[x][y] = 0.1;
                }
            }
        }
    }
    AssemblyAI::ensureOnePossibleMove(vote,board,player);
}

void CornerCore::correct(float ** const vote, Gameboard board, int player)
{
    // Give Corners a high priority
    vote[0][0] *= Core::_factorLarge;
    vote[0][7] *= Core::_factorLarge;
    vote[7][0] *= Core::_factorLarge;
    vote[7][7] *= Core::_factorLarge;

    // Give plays where an opponent can get a corner a low priority
    for(int x = 0; x < 8; ++x)
    {
        for(int y = 0; y < 8; ++y)
        {
            if(vote[x][y] > 0 && ((x == 0 || x == 7) && (y == 0 || y == 7)) && board.play(x,y,player,true))
            {
                Gameboard testboard = board;
                testboard.play(x,y,opponent(player),false);
                if(testboard.play(0,0,opponent(player),true) || testboard.play(0,7,opponent(player),true) || testboard.play(7,0,opponent(player),true) || testboard.play(7,7,opponent(player),true))
                {
                    vote[x][y] /= Core::_factorLarge;
                }
            }
        }
    }
}

QString CornerCore::name() const
{
    return "Corner Core";
}
<|endoftext|>


<commit_before><commit_msg>small fix<commit_after><|endoftext|>


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

#include "makestep.h"

#include "qt4project.h"
#include "qt4projectmanagerconstants.h"

#include <projectexplorer/projectexplorerconstants.h>

#include <QtCore/QDir>
#include <QtCore/QFileInfo>

using ProjectExplorer::IBuildParserFactory;
using ProjectExplorer::BuildParserInterface;
using ProjectExplorer::Environment;
using ExtensionSystem::PluginManager;
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;

MakeStep::MakeStep(Qt4Project * project)
    : AbstractMakeStep(project)
{

}

MakeStep::~MakeStep()
{

}

bool MakeStep::init(const QString &name)
{
    m_buildConfiguration = name;
    Environment environment = project()->environment(name);
    setEnvironment(name, environment);

    QString workingDirectory;
    if (project()->value(name, "useShadowBuild").toBool())
        workingDirectory = project()->value(name, "buildDirectory").toString();
    if (workingDirectory.isEmpty())
        workingDirectory = QFileInfo(project()->file()->fileName()).absolutePath();
    setWorkingDirectory(name, workingDirectory);

    Qt4Project *qt4project = qobject_cast<Qt4Project *>(project());
    QString makeCmd = qt4project->makeCommand(name);
    if (!value(name, "makeCmd").toString().isEmpty())
        makeCmd = value(name, "makeCmd").toString();
    if (!QFileInfo(makeCmd).isAbsolute()) {
        // Try to detect command in environment
        QString tmp = environment.searchInPath(makeCmd);
        if (tmp == QString::null) {
            emit addToOutputWindow(tr("Could not find make command: %1 "\
                                      "in the build environment").arg(makeCmd));
            return false;
        }
        makeCmd = tmp;
    }
    setCommand(name, makeCmd);

    if (!value(name, "cleanConfig").isValid() && value("clean").isValid() && value("clean").toBool()) {
        // Import old settings
        setValue(name, "cleanConfig", true);
        setValue(name, "makeargs", QStringList() << "clean");
    }
    // If we are cleaning, then make can fail with a error code, but that doesn't mean
    // we should stop the clean queue
    // That is mostly so that rebuild works on a alrady clean project
    setIgnoreReturnValue(name, value(name, "cleanConfig").isValid());
    QStringList args = value(name, "makeargs").toStringList();
    if (!value(name, "cleanConfig").isValid()) {
        if (!qt4project->defaultMakeTarget(name).isEmpty())
            args << qt4project->defaultMakeTarget(name);
    }
    // -w option enables "Enter"/"Leaving directory" messages, which we need for detecting the
    // absolute file path
    // FIXME doing this without the user having a way to override this is rather bad
    // so we only do it for unix and if the user didn't override the make command
    // but for now this is the least invasive change
    ProjectExplorer::ToolChain::ToolChainType t = qobject_cast<Qt4Project *>(project())->toolChain(name)->type();
    if (t != ProjectExplorer::ToolChain::MSVC && t != ProjectExplorer::ToolChain::WINCE) {
        if (value(name, "makeCmd").toString().isEmpty())
            args << "-w";
    }

    setEnabled(name, true);
    setArguments(name, args);

    ProjectExplorer::ToolChain::ToolChainType type = qobject_cast<Qt4Project *>(project())->toolChain(name)->type();
    if ( type == ProjectExplorer::ToolChain::MSVC || type == ProjectExplorer::ToolChain::WINCE)
        setBuildParser(ProjectExplorer::Constants::BUILD_PARSER_MSVC);
    else
        setBuildParser(ProjectExplorer::Constants::BUILD_PARSER_GCC);

    return AbstractMakeStep::init(name);
}

void MakeStep::run(QFutureInterface<bool> & fi)
{
    if (qobject_cast<Qt4Project *>(project())->rootProjectNode()->projectType() == ScriptTemplate) {
        fi.reportResult(true);
        return;
    }

    if (!enabled(m_buildConfiguration)) {
        emit addToOutputWindow(tr("No Makefile found, assuming project is clean."));
        fi.reportResult(true);
        return;
    }

    AbstractMakeStep::run(fi);
}

QString MakeStep::name()
{
    return Constants::MAKESTEP;
}

QString MakeStep::displayName()
{
    return "Make";
}

bool MakeStep::immutable() const
{
    return false;
}

ProjectExplorer::BuildStepConfigWidget *MakeStep::createConfigWidget()
{
    return new MakeStepConfigWidget(this);
}

void MakeStep::setMakeArguments(const QString &buildConfiguration, const QStringList &arguments)
{
    setValue(buildConfiguration, "makeargs", arguments);
    emit changed();
}

MakeStepConfigWidget::MakeStepConfigWidget(MakeStep *makeStep)
    : BuildStepConfigWidget(), m_makeStep(makeStep)
{
    m_ui.setupUi(this);
    connect(m_ui.makeLineEdit, SIGNAL(textEdited(QString)),
            this, SLOT(makeLineEditTextEdited()));
    connect(m_ui.makeArgumentsLineEdit, SIGNAL(textEdited(QString)),
            this, SLOT(makeArgumentsLineEditTextEdited()));

    connect(makeStep, SIGNAL(changed()),
            this, SLOT(update()));
    connect(ProjectExplorer::ProjectExplorerPlugin::instance(), SIGNAL(settingsChanged()),
            this, SLOT(updateMakeOverrideLabel()));
    connect(ProjectExplorer::ProjectExplorerPlugin::instance(), SIGNAL(settingsChanged()),
            this, SLOT(updateDetails()));
}

void MakeStepConfigWidget::updateMakeOverrideLabel()
{
    m_ui.makeLabel->setText(tr("Override %1:").arg(static_cast<Qt4Project *>(m_makeStep->project())->makeCommand(m_buildConfiguration)));
}

void MakeStepConfigWidget::updateDetails()
{
    // TODO reduce heavy code duplication
    QString workingDirectory;
    Qt4Project *pro = static_cast<Qt4Project *>(m_makeStep->project());
    if (pro->value(m_buildConfiguration, "useShadowBuild").toBool())
        workingDirectory = pro->value(m_buildConfiguration, "buildDirectory").toString();
    if (workingDirectory.isEmpty())
        workingDirectory = QFileInfo(pro->file()->fileName()).absolutePath();

    Qt4Project *qt4project = qobject_cast<Qt4Project *>(pro);
    QString makeCmd = qt4project->makeCommand(m_buildConfiguration);
    if (!m_makeStep->value(m_buildConfiguration, "makeCmd").toString().isEmpty())
        makeCmd = m_makeStep->value(m_buildConfiguration, "makeCmd").toString();
    if (!QFileInfo(makeCmd).isAbsolute()) {
        Environment environment = pro->environment(m_buildConfiguration);
        // Try to detect command in environment
        QString tmp = environment.searchInPath(makeCmd);
        if (tmp == QString::null) {
            m_summaryText = tr("Make Step: %1 not found in the environment.").arg(makeCmd);
            emit updateSummary();
            return;
        }
        makeCmd = tmp;
    }
    // -w option enables "Enter"/"Leaving directory" messages, which we need for detecting the
    // absolute file path
    // FIXME doing this without the user having a way to override this is rather bad
    // so we only do it for unix and if the user didn't override the make command
    // but for now this is the least invasive change
    QStringList args = m_makeStep->value(m_buildConfiguration, "makeargs").toStringList();
    ProjectExplorer::ToolChain::ToolChainType t = qobject_cast<Qt4Project *>(pro)->toolChain(m_buildConfiguration)->type();
    if (t != ProjectExplorer::ToolChain::MSVC && t != ProjectExplorer::ToolChain::WINCE) {
        if (m_makeStep->value(m_buildConfiguration, "makeCmd").toString().isEmpty())
            args << "-w";
    }
    m_summaryText = tr("Make: %1 %2 in %3").arg(QFileInfo(makeCmd).fileName(), args.join(" "), workingDirectory);
    emit updateSummary();
}

QString MakeStepConfigWidget::summaryText() const
{
    return m_summaryText;
}

QString MakeStepConfigWidget::displayName() const
{
    return m_makeStep->displayName();
}

void MakeStepConfigWidget::update()
{
    init(m_buildConfiguration);
}

void MakeStepConfigWidget::init(const QString &buildConfiguration)
{
    m_buildConfiguration = buildConfiguration;

    Qt4Project *pro = qobject_cast<Qt4Project *>(m_makeStep->project());
    Q_ASSERT(pro);

    if (!m_makeStep->value(buildConfiguration, "cleanConfig").isValid() && m_makeStep->value("clean").isValid() && m_makeStep->value("clean").toBool()) {
        // Import old settings
        m_makeStep->setValue(buildConfiguration, "cleanConfig", true);
        m_makeStep->setValue(buildConfiguration, "makeargs", QStringList() << "clean");
    }

    updateMakeOverrideLabel();

    const QString &makeCmd = m_makeStep->value(buildConfiguration, "makeCmd").toString();
    m_ui.makeLineEdit->setText(makeCmd);

    const QStringList &makeArguments =
            m_makeStep->value(buildConfiguration, "makeargs").toStringList();
    m_ui.makeArgumentsLineEdit->setText(ProjectExplorer::Environment::joinArgumentList(makeArguments));
    updateDetails();
}

void MakeStepConfigWidget::makeLineEditTextEdited()
{
    Q_ASSERT(!m_buildConfiguration.isNull());
    m_makeStep->setValue(m_buildConfiguration, "makeCmd", m_ui.makeLineEdit->text());
    updateDetails();
}

void MakeStepConfigWidget::makeArgumentsLineEditTextEdited()
{
    Q_ASSERT(!m_buildConfiguration.isNull());
    m_makeStep->setValue(m_buildConfiguration, "makeargs",
                         ProjectExplorer::Environment::parseCombinedArgString(m_ui.makeArgumentsLineEdit->text()));
    updateDetails();
}

///
// MakeStep
///

MakeStepFactory::MakeStepFactory()
{
}

MakeStepFactory::~MakeStepFactory()
{
}

bool MakeStepFactory::canCreate(const QString & name) const
{
    return (name == Constants::MAKESTEP);
}

ProjectExplorer::BuildStep * MakeStepFactory::create(ProjectExplorer::Project * pro, const QString & name) const
{
    Q_UNUSED(name)
    return new MakeStep(static_cast<Qt4Project *>(pro));
}

QStringList MakeStepFactory::canCreateForProject(ProjectExplorer::Project *pro) const
{
    if (qobject_cast<Qt4Project *>(pro))
        return QStringList() << Constants::MAKESTEP;
    else
        return QStringList();
}

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

#include "makestep.h"

#include "qt4project.h"
#include "qt4projectmanagerconstants.h"

#include <projectexplorer/projectexplorerconstants.h>

#include <QtCore/QDir>
#include <QtCore/QFileInfo>

using ProjectExplorer::IBuildParserFactory;
using ProjectExplorer::BuildParserInterface;
using ProjectExplorer::Environment;
using ExtensionSystem::PluginManager;
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;

MakeStep::MakeStep(Qt4Project * project)
    : AbstractMakeStep(project)
{

}

MakeStep::~MakeStep()
{

}

bool MakeStep::init(const QString &name)
{
    m_buildConfiguration = name;
    Environment environment = project()->environment(name);
    setEnvironment(name, environment);

    QString workingDirectory;
    if (project()->value(name, "useShadowBuild").toBool())
        workingDirectory = project()->value(name, "buildDirectory").toString();
    if (workingDirectory.isEmpty())
        workingDirectory = QFileInfo(project()->file()->fileName()).absolutePath();
    setWorkingDirectory(name, workingDirectory);

    Qt4Project *qt4project = qobject_cast<Qt4Project *>(project());
    QString makeCmd = qt4project->makeCommand(name);
    if (!value(name, "makeCmd").toString().isEmpty())
        makeCmd = value(name, "makeCmd").toString();
    if (!QFileInfo(makeCmd).isAbsolute()) {
        // Try to detect command in environment
        QString tmp = environment.searchInPath(makeCmd);
        if (tmp == QString::null) {
            emit addToOutputWindow(tr("Could not find make command: %1 "\
                                      "in the build environment").arg(makeCmd));
            return false;
        }
        makeCmd = tmp;
    }
    setCommand(name, makeCmd);

    if (!value(name, "cleanConfig").isValid() && value("clean").isValid() && value("clean").toBool()) {
        // Import old settings
        setValue(name, "cleanConfig", true);
        setValue(name, "makeargs", QStringList() << "clean");
    }
    // If we are cleaning, then make can fail with a error code, but that doesn't mean
    // we should stop the clean queue
    // That is mostly so that rebuild works on a alrady clean project
    setIgnoreReturnValue(name, value(name, "cleanConfig").isValid());
    QStringList args = value(name, "makeargs").toStringList();
    if (!value(name, "cleanConfig").isValid()) {
        if (!qt4project->defaultMakeTarget(name).isEmpty())
            args << qt4project->defaultMakeTarget(name);
    }
    // -w option enables "Enter"/"Leaving directory" messages, which we need for detecting the
    // absolute file path
    // FIXME doing this without the user having a way to override this is rather bad
    // so we only do it for unix and if the user didn't override the make command
    // but for now this is the least invasive change
    ProjectExplorer::ToolChain::ToolChainType t = qobject_cast<Qt4Project *>(project())->toolChain(name)->type();
    if (t != ProjectExplorer::ToolChain::MSVC && t != ProjectExplorer::ToolChain::WINCE) {
        if (value(name, "makeCmd").toString().isEmpty())
            args << "-w";
    }

    setEnabled(name, true);
    setArguments(name, args);

    ProjectExplorer::ToolChain::ToolChainType type = qobject_cast<Qt4Project *>(project())->toolChain(name)->type();
    if ( type == ProjectExplorer::ToolChain::MSVC || type == ProjectExplorer::ToolChain::WINCE)
        setBuildParser(ProjectExplorer::Constants::BUILD_PARSER_MSVC);
    else
        setBuildParser(ProjectExplorer::Constants::BUILD_PARSER_GCC);

    return AbstractMakeStep::init(name);
}

void MakeStep::run(QFutureInterface<bool> & fi)
{
    if (qobject_cast<Qt4Project *>(project())->rootProjectNode()->projectType() == ScriptTemplate) {
        fi.reportResult(true);
        return;
    }

    if (!enabled(m_buildConfiguration)) {
        emit addToOutputWindow(tr("No Makefile found, assuming project is clean."));
        fi.reportResult(true);
        return;
    }

    AbstractMakeStep::run(fi);
}

QString MakeStep::name()
{
    return Constants::MAKESTEP;
}

QString MakeStep::displayName()
{
    return "Make";
}

bool MakeStep::immutable() const
{
    return false;
}

ProjectExplorer::BuildStepConfigWidget *MakeStep::createConfigWidget()
{
    return new MakeStepConfigWidget(this);
}

void MakeStep::setMakeArguments(const QString &buildConfiguration, const QStringList &arguments)
{
    setValue(buildConfiguration, "makeargs", arguments);
    emit changed();
}

MakeStepConfigWidget::MakeStepConfigWidget(MakeStep *makeStep)
    : BuildStepConfigWidget(), m_makeStep(makeStep)
{
    m_ui.setupUi(this);
    connect(m_ui.makeLineEdit, SIGNAL(textEdited(QString)),
            this, SLOT(makeLineEditTextEdited()));
    connect(m_ui.makeArgumentsLineEdit, SIGNAL(textEdited(QString)),
            this, SLOT(makeArgumentsLineEditTextEdited()));

    connect(makeStep, SIGNAL(changed()),
            this, SLOT(update()));
    connect(ProjectExplorer::ProjectExplorerPlugin::instance(), SIGNAL(settingsChanged()),
            this, SLOT(updateMakeOverrideLabel()));
    connect(ProjectExplorer::ProjectExplorerPlugin::instance(), SIGNAL(settingsChanged()),
            this, SLOT(updateDetails()));
}

void MakeStepConfigWidget::updateMakeOverrideLabel()
{
    m_ui.makeLabel->setText(tr("Override %1:").arg(static_cast<Qt4Project *>(m_makeStep->project())->makeCommand(m_buildConfiguration)));
}

void MakeStepConfigWidget::updateDetails()
{
    // TODO reduce heavy code duplication
    QString workingDirectory;
    Qt4Project *pro = static_cast<Qt4Project *>(m_makeStep->project());
    if (pro->value(m_buildConfiguration, "useShadowBuild").toBool())
        workingDirectory = pro->value(m_buildConfiguration, "buildDirectory").toString();
    if (workingDirectory.isEmpty())
        workingDirectory = QFileInfo(pro->file()->fileName()).absolutePath();

    Qt4Project *qt4project = qobject_cast<Qt4Project *>(pro);
    QString makeCmd = qt4project->makeCommand(m_buildConfiguration);
    if (!m_makeStep->value(m_buildConfiguration, "makeCmd").toString().isEmpty())
        makeCmd = m_makeStep->value(m_buildConfiguration, "makeCmd").toString();
    if (!QFileInfo(makeCmd).isAbsolute()) {
        Environment environment = pro->environment(m_buildConfiguration);
        // Try to detect command in environment
        QString tmp = environment.searchInPath(makeCmd);
        if (tmp == QString::null) {
            m_summaryText = tr("Make Step: %1 not found in the environment.").arg(makeCmd);
            emit updateSummary();
            return;
        }
        makeCmd = tmp;
    }
    // -w option enables "Enter"/"Leaving directory" messages, which we need for detecting the
    // absolute file path
    // FIXME doing this without the user haaving a way to override this is rather bad
    // so we only do it for unix and if the user didn't override the make command
    // but for now this is the least invasive change
    QStringList args = m_makeStep->value(m_buildConfiguration, "makeargs").toStringList();
    ProjectExplorer::ToolChain::ToolChainType t = qobject_cast<Qt4Project *>(pro)->toolChain(m_buildConfiguration)->type();
    if (t != ProjectExplorer::ToolChain::MSVC && t != ProjectExplorer::ToolChain::WINCE) {
        if (m_makeStep->value(m_buildConfiguration, "makeCmd").toString().isEmpty())
            args << "-w";
    }
    m_summaryText = tr("Make: %1 %2 in %3").arg(QFileInfo(makeCmd).fileName(), args.join(" "),
                                                       QDir::toNativeSeparators(workingDirectory));
    emit updateSummary();
}

QString MakeStepConfigWidget::summaryText() const
{
    return m_summaryText;
}

QString MakeStepConfigWidget::displayName() const
{
    return m_makeStep->displayName();
}

void MakeStepConfigWidget::update()
{
    init(m_buildConfiguration);
}

void MakeStepConfigWidget::init(const QString &buildConfiguration)
{
    m_buildConfiguration = buildConfiguration;

    Qt4Project *pro = qobject_cast<Qt4Project *>(m_makeStep->project());
    Q_ASSERT(pro);

    if (!m_makeStep->value(buildConfiguration, "cleanConfig").isValid() && m_makeStep->value("clean").isValid() && m_makeStep->value("clean").toBool()) {
        // Import old settings
        m_makeStep->setValue(buildConfiguration, "cleanConfig", true);
        m_makeStep->setValue(buildConfiguration, "makeargs", QStringList() << "clean");
    }

    updateMakeOverrideLabel();

    const QString &makeCmd = m_makeStep->value(buildConfiguration, "makeCmd").toString();
    m_ui.makeLineEdit->setText(makeCmd);

    const QStringList &makeArguments =
            m_makeStep->value(buildConfiguration, "makeargs").toStringList();
    m_ui.makeArgumentsLineEdit->setText(ProjectExplorer::Environment::joinArgumentList(makeArguments));
    updateDetails();
}

void MakeStepConfigWidget::makeLineEditTextEdited()
{
    Q_ASSERT(!m_buildConfiguration.isNull());
    m_makeStep->setValue(m_buildConfiguration, "makeCmd", m_ui.makeLineEdit->text());
    updateDetails();
}

void MakeStepConfigWidget::makeArgumentsLineEditTextEdited()
{
    Q_ASSERT(!m_buildConfiguration.isNull());
    m_makeStep->setValue(m_buildConfiguration, "makeargs",
                         ProjectExplorer::Environment::parseCombinedArgString(m_ui.makeArgumentsLineEdit->text()));
    updateDetails();
}

///
// MakeStep
///

MakeStepFactory::MakeStepFactory()
{
}

MakeStepFactory::~MakeStepFactory()
{
}

bool MakeStepFactory::canCreate(const QString & name) const
{
    return (name == Constants::MAKESTEP);
}

ProjectExplorer::BuildStep * MakeStepFactory::create(ProjectExplorer::Project * pro, const QString & name) const
{
    Q_UNUSED(name)
    return new MakeStep(static_cast<Qt4Project *>(pro));
}

QStringList MakeStepFactory::canCreateForProject(ProjectExplorer::Project *pro) const
{
    if (qobject_cast<Qt4Project *>(pro))
        return QStringList() << Constants::MAKESTEP;
    else
        return QStringList();
}

QString MakeStepFactory::displayNameForName(const QString &name) const
{
    Q_UNUSED(name)
    return tr("Make");
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "tooltip.h"
#include "tips.h"
#include "tipcontents.h"
#include "tipfactory.h"
#include "effects.h"
#include "reuse.h"

#include <QtCore/QString>
#include <QtGui/QColor>
#include <QtGui/QApplication>
#include <QtGui/QKeyEvent>
#include <QtGui/QMouseEvent>

using namespace TextEditor;
using namespace Internal;

ToolTip::ToolTip() : m_tipFactory(new TipFactory), m_tip(0), m_widget(0)
{
    connect(&m_showTimer, SIGNAL(timeout()), this, SLOT(hideTipImmediately()));
    connect(&m_hideDelayTimer, SIGNAL(timeout()), this, SLOT(hideTipImmediately()));
}

ToolTip::~ToolTip()
{
    m_tip = 0;
    delete m_tipFactory;
}

ToolTip *ToolTip::instance()
{
    static ToolTip tooltip;
    return &tooltip;
}

void ToolTip::show(const QPoint &pos, const TipContent &content, QWidget *w, const QRect &rect)
{
    if (acceptShow(content, pos, w, rect)) {
#ifndef Q_WS_WIN
        m_tip = m_tipFactory->createTip(content, w);
#else
        m_tip = m_tipFactory->createTip(
            content, QApplication::desktop()->screen(Internal::screenNumber(pos, w)));
#endif
        setUp(pos, content, w, rect);
        qApp->installEventFilter(this);
        showTip();
    }
}

void ToolTip::show(const QPoint &pos, const TipContent &content, QWidget *w)
{
    show(pos, content, w, QRect());
}

bool ToolTip::acceptShow(const TipContent &content,
                         const QPoint &pos,
                         QWidget *w,
                         const QRect &rect)
{
    if (!validateContent(content))
        return false;

    if (isVisible()) {
        if (m_tip->handleContentReplacement(content)) {
            // Reuse current tip.
            QPoint localPos = pos;
            if (w)
                localPos = w->mapFromGlobal(pos);
            if (tipChanged(localPos, content, w)) {
                setUp(pos, content, w, rect);
            }
            return false;
        }
        hideTipImmediately();
    }
    return true;
}

bool ToolTip::validateContent(const TipContent &content)
{
    if (!content.isValid()) {
        if (isVisible())
            hideTipWithDelay();
        return false;
    }
    return true;
}

void ToolTip::setUp(const QPoint &pos, const TipContent &content, QWidget *w, const QRect &rect)
{
    m_tip->setContent(content);
    m_tip->configure(pos, w);

    placeTip(pos, w);
    setTipRect(w, rect);

    if (m_hideDelayTimer.isActive())
        m_hideDelayTimer.stop();
    m_showTimer.start(content.showTime());
}

bool ToolTip::tipChanged(const QPoint &pos, const TipContent &content, QWidget *w) const
{
    if (!m_tip->content().equals(content) || m_widget != w)
        return true;
    if (!m_rect.isNull())
        return !m_rect.contains(pos);
    return false;
}

void ToolTip::setTipRect(QWidget *w, const QRect &rect)
{
    if (!m_rect.isNull() && !w)
        qWarning("ToolTip::show: Cannot pass null widget if rect is set");
    else{
        m_widget = w;
        m_rect = rect;
    }
}

bool ToolTip::isVisible() const
{
    return m_tip && m_tip->isVisible();
}

void ToolTip::showTip()
{
#if !defined(QT_NO_EFFECTS) && !defined(Q_WS_MAC)
    if (QApplication::isEffectEnabled(Qt::UI_FadeTooltip))
        qFadeEffect(m_tip);
    else if (QApplication::isEffectEnabled(Qt::UI_AnimateTooltip))
        qScrollEffect(m_tip);
    else
        m_tip->show();
#else
    m_tip->show();
#endif
}

void ToolTip::hide()
{
    hideTipWithDelay();
}

void ToolTip::hideTipWithDelay()
{
    if (!m_hideDelayTimer.isActive())
        m_hideDelayTimer.start(300);
}

void ToolTip::hideTipImmediately()
{
    if (m_tip) {
        m_tip->close();
        m_tip->deleteLater();
        m_tip = 0;
    }
    m_showTimer.stop();
    m_hideDelayTimer.stop();
    qApp->removeEventFilter(this);
}

void ToolTip::placeTip(const QPoint &pos, QWidget *w)
{
    QRect screen = Internal::screenGeometry(pos, w);
    QPoint p = pos;
    p += QPoint(2,
#ifdef Q_WS_WIN
                21
#else
                16
#endif
                );

    if (p.x() + m_tip->width() > screen.x() + screen.width())
        p.rx() -= 4 + m_tip->width();
    if (p.y() + m_tip->height() > screen.y() + screen.height())
        p.ry() -= 24 + m_tip->height();
    if (p.y() < screen.y())
        p.setY(screen.y());
    if (p.x() + m_tip->width() > screen.x() + screen.width())
        p.setX(screen.x() + screen.width() - m_tip->width());
    if (p.x() < screen.x())
        p.setX(screen.x());
    if (p.y() + m_tip->height() > screen.y() + screen.height())
        p.setY(screen.y() + screen.height() - m_tip->height());

    m_tip->move(p);
}

bool ToolTip::eventFilter(QObject *o, QEvent *event)
{
    switch (event->type()) {
#ifdef Q_WS_MAC
    case QEvent::KeyPress:
    case QEvent::KeyRelease: {
        int key = static_cast<QKeyEvent *>(event)->key();
        Qt::KeyboardModifiers mody = static_cast<QKeyEvent *>(event)->modifiers();
        if (!(mody & Qt::KeyboardModifierMask)
            && key != Qt::Key_Shift && key != Qt::Key_Control
            && key != Qt::Key_Alt && key != Qt::Key_Meta)
            hideTipWithDelay();
        break;
    }
#endif
    case QEvent::Leave:
        hideTipWithDelay();
        break;
    case QEvent::WindowActivate:
    case QEvent::WindowDeactivate:
    case QEvent::MouseButtonPress:
    case QEvent::MouseButtonRelease:
    case QEvent::MouseButtonDblClick:
    case QEvent::FocusIn:
    case QEvent::FocusOut:
    case QEvent::Wheel:
        hideTipImmediately();
        break;

    case QEvent::MouseMove:
        if (o == m_widget &&
            !m_rect.isNull() &&
            !m_rect.contains(static_cast<QMouseEvent*>(event)->pos())) {
            hideTipWithDelay();
        }
    default:
        break;
    }
    return false;
}

QFont ToolTip::font() const
{
    return QApplication::font("QTipLabel");
}

void ToolTip::setFont(const QFont &font)
{
    QApplication::setFont(font, "QTipLabel");
}
<commit_msg>Tooltips: Prevent cluttering when showing with effects<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "tooltip.h"
#include "tips.h"
#include "tipcontents.h"
#include "tipfactory.h"
#include "effects.h"
#include "reuse.h"

#include <QtCore/QString>
#include <QtGui/QColor>
#include <QtGui/QApplication>
#include <QtGui/QKeyEvent>
#include <QtGui/QMouseEvent>

using namespace TextEditor;
using namespace Internal;

ToolTip::ToolTip() : m_tipFactory(new TipFactory), m_tip(0), m_widget(0)
{
    connect(&m_showTimer, SIGNAL(timeout()), this, SLOT(hideTipImmediately()));
    connect(&m_hideDelayTimer, SIGNAL(timeout()), this, SLOT(hideTipImmediately()));
}

ToolTip::~ToolTip()
{
    m_tip = 0;
    delete m_tipFactory;
}

ToolTip *ToolTip::instance()
{
    static ToolTip tooltip;
    return &tooltip;
}

void ToolTip::show(const QPoint &pos, const TipContent &content, QWidget *w, const QRect &rect)
{
    if (acceptShow(content, pos, w, rect)) {
#ifndef Q_WS_WIN
        m_tip = m_tipFactory->createTip(content, w);
#else
        m_tip = m_tipFactory->createTip(
            content, QApplication::desktop()->screen(Internal::screenNumber(pos, w)));
#endif
        setUp(pos, content, w, rect);
        qApp->installEventFilter(this);
        showTip();
    }
}

void ToolTip::show(const QPoint &pos, const TipContent &content, QWidget *w)
{
    show(pos, content, w, QRect());
}

bool ToolTip::acceptShow(const TipContent &content,
                         const QPoint &pos,
                         QWidget *w,
                         const QRect &rect)
{
    if (!validateContent(content))
        return false;

    if (isVisible()) {
        if (m_tip->handleContentReplacement(content)) {
            // Reuse current tip.
            QPoint localPos = pos;
            if (w)
                localPos = w->mapFromGlobal(pos);
            if (tipChanged(localPos, content, w))
                setUp(pos, content, w, rect);
            return false;
        }
        hideTipImmediately();
    }
#if !defined(QT_NO_EFFECTS) && !defined(Q_WS_MAC)
    // While the effect takes places it might be that although the widget is actually on
    // screen the isVisible method doesn't return true.
    else if (m_tip
             && (QApplication::isEffectEnabled(Qt::UI_FadeTooltip)
                 || QApplication::isEffectEnabled(Qt::UI_AnimateTooltip))) {
        hideTipImmediately();
    }
#endif
    return true;
}

bool ToolTip::validateContent(const TipContent &content)
{
    if (!content.isValid()) {
        if (isVisible())
            hideTipWithDelay();
        return false;
    }
    return true;
}

void ToolTip::setUp(const QPoint &pos, const TipContent &content, QWidget *w, const QRect &rect)
{
    m_tip->setContent(content);
    m_tip->configure(pos, w);

    placeTip(pos, w);
    setTipRect(w, rect);

    if (m_hideDelayTimer.isActive())
        m_hideDelayTimer.stop();
    m_showTimer.start(content.showTime());
}

bool ToolTip::tipChanged(const QPoint &pos, const TipContent &content, QWidget *w) const
{
    if (!m_tip->content().equals(content) || m_widget != w)
        return true;
    if (!m_rect.isNull())
        return !m_rect.contains(pos);
    return false;
}

void ToolTip::setTipRect(QWidget *w, const QRect &rect)
{
    if (!m_rect.isNull() && !w)
        qWarning("ToolTip::show: Cannot pass null widget if rect is set");
    else{
        m_widget = w;
        m_rect = rect;
    }
}

bool ToolTip::isVisible() const
{
    return m_tip && m_tip->isVisible();
}

void ToolTip::showTip()
{
#if !defined(QT_NO_EFFECTS) && !defined(Q_WS_MAC)
    if (QApplication::isEffectEnabled(Qt::UI_FadeTooltip))
        qFadeEffect(m_tip);
    else if (QApplication::isEffectEnabled(Qt::UI_AnimateTooltip))
        qScrollEffect(m_tip);
    else
        m_tip->show();
#else
    m_tip->show();
#endif
}

void ToolTip::hide()
{
    hideTipWithDelay();
}

void ToolTip::hideTipWithDelay()
{
    if (!m_hideDelayTimer.isActive())
        m_hideDelayTimer.start(300);
}

void ToolTip::hideTipImmediately()
{
    if (m_tip) {
        m_tip->close();
        m_tip->deleteLater();
        m_tip = 0;
    }
    m_showTimer.stop();
    m_hideDelayTimer.stop();
    qApp->removeEventFilter(this);
}

void ToolTip::placeTip(const QPoint &pos, QWidget *w)
{
    QRect screen = Internal::screenGeometry(pos, w);
    QPoint p = pos;
    p += QPoint(2,
#ifdef Q_WS_WIN
                21
#else
                16
#endif
                );

    if (p.x() + m_tip->width() > screen.x() + screen.width())
        p.rx() -= 4 + m_tip->width();
    if (p.y() + m_tip->height() > screen.y() + screen.height())
        p.ry() -= 24 + m_tip->height();
    if (p.y() < screen.y())
        p.setY(screen.y());
    if (p.x() + m_tip->width() > screen.x() + screen.width())
        p.setX(screen.x() + screen.width() - m_tip->width());
    if (p.x() < screen.x())
        p.setX(screen.x());
    if (p.y() + m_tip->height() > screen.y() + screen.height())
        p.setY(screen.y() + screen.height() - m_tip->height());

    m_tip->move(p);
}

bool ToolTip::eventFilter(QObject *o, QEvent *event)
{
    switch (event->type()) {
#ifdef Q_WS_MAC
    case QEvent::KeyPress:
    case QEvent::KeyRelease: {
        int key = static_cast<QKeyEvent *>(event)->key();
        Qt::KeyboardModifiers mody = static_cast<QKeyEvent *>(event)->modifiers();
        if (!(mody & Qt::KeyboardModifierMask)
            && key != Qt::Key_Shift && key != Qt::Key_Control
            && key != Qt::Key_Alt && key != Qt::Key_Meta)
            hideTipWithDelay();
        break;
    }
#endif
    case QEvent::Leave:
        hideTipWithDelay();
        break;
    case QEvent::WindowActivate:
    case QEvent::WindowDeactivate:
    case QEvent::MouseButtonPress:
    case QEvent::MouseButtonRelease:
    case QEvent::MouseButtonDblClick:
    case QEvent::FocusIn:
    case QEvent::FocusOut:
    case QEvent::Wheel:
        hideTipImmediately();
        break;

    case QEvent::MouseMove:
        if (o == m_widget &&
            !m_rect.isNull() &&
            !m_rect.contains(static_cast<QMouseEvent*>(event)->pos())) {
            hideTipWithDelay();
        }
    default:
        break;
    }
    return false;
}

QFont ToolTip::font() const
{
    return QApplication::font("QTipLabel");
}

void ToolTip::setFont(const QFont &font)
{
    QApplication::setFont(font, "QTipLabel");
}
<|endoftext|>