<commit_before>/*************************************************************************
 *
 *  $RCSfile: javatype.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 03:14:13 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef INCLUDED_codemaker_source_javamaker_javatype_hxx
#define INCLUDED_codemaker_source_javamaker_javatype_hxx

namespace codemaker { class GeneratedTypeSet; }
namespace rtl { class OString; }
class JavaOptions;
class TypeManager;

bool produceType(
    rtl::OString const & type, TypeManager & manager,
    codemaker::GeneratedTypeSet & generated, JavaOptions * options);

#endif
<commit_msg>INTEGRATION: CWS sdksample (1.4.14); FILE MERGED 2004/07/05 11:02:56 jsc 1.4.14.1: #i30954# use registry keys directly instead of typenames<commit_after>/*************************************************************************
 *
 *  $RCSfile: javatype.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-01-31 15:30:05 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef INCLUDED_codemaker_source_javamaker_javatype_hxx
#define INCLUDED_codemaker_source_javamaker_javatype_hxx

namespace codemaker { class GeneratedTypeSet; }
namespace rtl { class OString; }
class JavaOptions;
class TypeManager;
class RegistryKey;

bool produceType(
    rtl::OString const & type, TypeManager const & manager,
    codemaker::GeneratedTypeSet & generated, JavaOptions * pOptions);

bool produceType(RegistryKey& typeName, bool bIsExtraType, TypeManager const & typeMgr,
                 codemaker::GeneratedTypeSet & generated,
                 JavaOptions* pOptions);

#endif
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "test-harness.h"
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>
#include <map>
#include <cstring>
#include <testcase.h>

namespace TestHarness
{

typedef std::map<int, TestCase> RunningTestCases;

namespace
{
const char* RED_COLOR="\e[1;31m";
const char* GREEN_COLOR="\e[1;32m";
const char* ASCII_RESET="\e[0m";
const char* ASCII_BOLD="\e[1m";
}

int RunTestCase( struct ::testcase_s& testCase )
{
  int result = EXIT_STATUS_TESTCASE_FAILED;

// dont want to catch exception as we want to be able to get
// gdb stack trace from the first error
// by default tests should all always pass with no exceptions
  if( testCase.startup )
  {
    testCase.startup();
  }
  result = testCase.function();
  if( testCase.cleanup )
  {
    testCase.cleanup();
  }

  return result;
}

int RunTestCaseInChildProcess( struct ::testcase_s& testCase, bool suppressOutput )
{
  int testResult = EXIT_STATUS_TESTCASE_FAILED;

  int pid = fork();
  if( pid == 0 ) // Child process
  {
    if( suppressOutput )
    {
      close(STDOUT_FILENO);
      close(STDERR_FILENO);
    }
    exit( RunTestCase( testCase ) );
  }
  else if(pid == -1)
  {
    perror("fork");
    exit(EXIT_STATUS_FORK_FAILED);
  }
  else // Parent process
  {
    int status = 0;
    int childPid = waitpid(-1, &status, 0);
    if( childPid == -1 )
    {
      perror("waitpid");
      exit(EXIT_STATUS_WAITPID_FAILED);
    }
    if( WIFEXITED(status) )
    {
      if( childPid > 0 )
      {
        testResult = WEXITSTATUS(status);
        if( testResult )
        {
          printf("Test case %s failed: %d\n", testCase.name, testResult);
        }
      }
    }
    else if(WIFSIGNALED(status) )
    {
      testResult = EXIT_STATUS_TESTCASE_ABORTED;

#ifdef WCOREDUMP
      if(WCOREDUMP(status))
      {
        printf("Test case %s crashed\n", testCase.name);
      }
#endif
      printf("Test case %s exited with signal %s\n", testCase.name, strsignal(WTERMSIG(status)));
    }
    else if(WIFSTOPPED(status))
    {
      printf("Test case %s stopped with signal %s\n", testCase.name, strsignal(WSTOPSIG(status)));
    }
  }
  return testResult;
}

void OutputStatistics( int numPasses, int numFailures )
{
  const char* failureColor = GREEN_COLOR;
  if( numFailures > 0 )
  {
    failureColor = RED_COLOR;
  }
  printf("\rNumber of test passes:   %s%4d (%5.2f%%)%s\n", ASCII_BOLD, numPasses, 100.0f * (float)numPasses / (numPasses+numFailures),  ASCII_RESET);
  printf("%sNumber of test failures:%s %s%4d%s\n", failureColor, ASCII_RESET, ASCII_BOLD, numFailures, ASCII_RESET);

}

int RunAll(const char* processName, ::testcase tc_array[], bool reRunFailed)
{
  int numFailures = 0;
  int numPasses = 0;

  // Run test cases in child process( to kill output/handle signals ), but run serially.
  for( unsigned int i=0; tc_array[i].name; i++)
  {
    int result = RunTestCaseInChildProcess( tc_array[i], true );
    if( result == 0 )
    {
      numPasses++;
    }
    else
    {
      numFailures++;
    }
  }

  OutputStatistics(numPasses, numFailures);

  return numFailures;
}

// Constantly runs up to MAX_NUM_CHILDREN processes
int RunAllInParallel(  const char* processName, ::testcase tc_array[], bool reRunFailed)
{
  int numFailures = 0;
  int numPasses = 0;

  RunningTestCases children;
  std::vector<int> failedTestCases;

  // Fork up to MAX_NUM_CHILDREN processes, then
  // wait. As soon as a proc completes, fork the next.

  int nextTestCase = 0;
  int numRunningChildren = 0;

  while( tc_array[nextTestCase].name || numRunningChildren > 0)
  {
    // Create more children (up to the max number or til the end of the array)
    while( numRunningChildren < MAX_NUM_CHILDREN && tc_array[nextTestCase].name )
    {
      int pid = fork();
      if( pid == 0 ) // Child process
      {
        close(STDOUT_FILENO);
        close(STDERR_FILENO);
        exit( RunTestCase( tc_array[nextTestCase] ) );
      }
      else if(pid == -1)
      {
        perror("fork");
        exit(EXIT_STATUS_FORK_FAILED);
      }
      else // Parent process
      {
        TestCase tc(nextTestCase, tc_array[nextTestCase].name);
        children[pid] = tc;
        nextTestCase++;
        numRunningChildren++;
      }
    }

    // Wait for the next child to finish

    int status=0;
    int childPid = waitpid(-1, &status, 0);
    if( childPid == -1 )
    {
      perror("waitpid");
      exit(EXIT_STATUS_WAITPID_FAILED);
    }

    if( WIFEXITED(status) )
    {
      if( childPid > 0 )
      {
        int testResult = WEXITSTATUS(status);
        if( testResult )
        {
          printf("Test case %s failed: %d\n", children[childPid].testCaseName, testResult);
          failedTestCases.push_back(children[childPid].testCase);
          numFailures++;
        }
        else
        {
          numPasses++;
        }
        numRunningChildren--;
      }
    }

    else if( WIFSIGNALED(status) || WIFSTOPPED(status))
    {
      status = WIFSIGNALED(status)?WTERMSIG(status):WSTOPSIG(status);

      if( childPid > 0 )
      {
        RunningTestCases::iterator iter = children.find(childPid);
        if( iter != children.end() )
        {
          printf("Test case %s exited with signal %s\n", iter->second.testCaseName, strsignal(status));
          failedTestCases.push_back(iter->second.testCase);
        }
        else
        {
          printf("Unknown child process: %d signaled %s\n", childPid, strsignal(status));
        }

        numFailures++;
        numRunningChildren--;
      }
    }
  }

  OutputStatistics( numPasses, numFailures );

  if( reRunFailed )
  {
    for( unsigned int i=0; i<failedTestCases.size(); i++)
    {
      char* testCaseStrapline;
      int numChars = asprintf(&testCaseStrapline, "Test case %s", tc_array[failedTestCases[i]].name );
      printf("\n%s\n", testCaseStrapline);
      for(int j=0; j<numChars; j++)
      {
        printf("=");
      }
      printf("\n");
      RunTestCaseInChildProcess( tc_array[failedTestCases[i] ], false );
    }
  }

  return numFailures;
}

int FindAndRunTestCase(::testcase tc_array[], const char* testCaseName)
{
  int result = EXIT_STATUS_TESTCASE_NOT_FOUND;

  for( int i = 0; tc_array[i].name; i++ )
  {
    if( !strcmp(testCaseName, tc_array[i].name) )
    {
      return RunTestCase( tc_array[i] );
    }
  }

  printf("Unknown testcase name: \"%s\"\n", testCaseName);
  return result;
}

void Usage(const char* program)
{
  printf("Usage: \n"
         "   %s <testcase name>\t\t Execute a test case\n"
         "   %s \t\t Execute all test cases in parallel\n"
         "   %s -r\t\t Execute all test cases in parallel, rerunning failed test cases\n",
         program, program, program);
}

} // namespace
<commit_msg>Harmonize test failures<commit_after>/*
 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "test-harness.h"
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>
#include <map>
#include <cstring>
#include <testcase.h>

namespace TestHarness
{

typedef std::map<int, TestCase> RunningTestCases;

namespace
{
const char* RED_COLOR="\e[1;31m";
const char* GREEN_COLOR="\e[1;32m";
const char* ASCII_RESET="\e[0m";
const char* ASCII_BOLD="\e[1m";
}

int RunTestCase( struct ::testcase_s& testCase )
{
  int result = EXIT_STATUS_TESTCASE_FAILED;

// dont want to catch exception as we want to be able to get
// gdb stack trace from the first error
// by default tests should all always pass with no exceptions
  if( testCase.startup )
  {
    testCase.startup();
  }
  result = testCase.function();
  if( testCase.cleanup )
  {
    testCase.cleanup();
  }

  return result;
}

int RunTestCaseInChildProcess( struct ::testcase_s& testCase, bool suppressOutput )
{
  int testResult = EXIT_STATUS_TESTCASE_FAILED;

  int pid = fork();
  if( pid == 0 ) // Child process
  {
    if( suppressOutput )
    {
      close(STDOUT_FILENO);
      close(STDERR_FILENO);
    }
    exit( RunTestCase( testCase ) );
  }
  else if(pid == -1)
  {
    perror("fork");
    exit(EXIT_STATUS_FORK_FAILED);
  }
  else // Parent process
  {
    int status = 0;
    int childPid = waitpid(-1, &status, 0);
    if( childPid == -1 )
    {
      perror("waitpid");
      exit(EXIT_STATUS_WAITPID_FAILED);
    }
    if( WIFEXITED(status) )
    {
      if( childPid > 0 )
      {
        testResult = WEXITSTATUS(status);
        if( testResult )
        {
          printf("Test case %s failed: %d\n", testCase.name, testResult);
        }
      }
    }
    else if(WIFSIGNALED(status) )
    {
      testResult = EXIT_STATUS_TESTCASE_ABORTED;

#ifdef WCOREDUMP
      if(WCOREDUMP(status))
      {
        printf("Test case %s failed: due to a crash\n", testCase.name);
      }
#endif
      printf("Test case %s failed: exit with signal %s\n", testCase.name, strsignal(WTERMSIG(status)));
    }
    else if(WIFSTOPPED(status))
    {
      printf("Test case %s failed: stopped with signal %s\n", testCase.name, strsignal(WSTOPSIG(status)));
    }
  }
  return testResult;
}

void OutputStatistics( int numPasses, int numFailures )
{
  const char* failureColor = GREEN_COLOR;
  if( numFailures > 0 )
  {
    failureColor = RED_COLOR;
  }
  printf("\rNumber of test passes:   %s%4d (%5.2f%%)%s\n", ASCII_BOLD, numPasses, 100.0f * (float)numPasses / (numPasses+numFailures),  ASCII_RESET);
  printf("%sNumber of test failures:%s %s%4d%s\n", failureColor, ASCII_RESET, ASCII_BOLD, numFailures, ASCII_RESET);

}

int RunAll(const char* processName, ::testcase tc_array[], bool reRunFailed)
{
  int numFailures = 0;
  int numPasses = 0;

  // Run test cases in child process( to kill output/handle signals ), but run serially.
  for( unsigned int i=0; tc_array[i].name; i++)
  {
    int result = RunTestCaseInChildProcess( tc_array[i], true );
    if( result == 0 )
    {
      numPasses++;
    }
    else
    {
      numFailures++;
    }
  }

  OutputStatistics(numPasses, numFailures);

  return numFailures;
}

// Constantly runs up to MAX_NUM_CHILDREN processes
int RunAllInParallel(  const char* processName, ::testcase tc_array[], bool reRunFailed)
{
  int numFailures = 0;
  int numPasses = 0;

  RunningTestCases children;
  std::vector<int> failedTestCases;

  // Fork up to MAX_NUM_CHILDREN processes, then
  // wait. As soon as a proc completes, fork the next.

  int nextTestCase = 0;
  int numRunningChildren = 0;

  while( tc_array[nextTestCase].name || numRunningChildren > 0)
  {
    // Create more children (up to the max number or til the end of the array)
    while( numRunningChildren < MAX_NUM_CHILDREN && tc_array[nextTestCase].name )
    {
      int pid = fork();
      if( pid == 0 ) // Child process
      {
        close(STDOUT_FILENO);
        close(STDERR_FILENO);
        exit( RunTestCase( tc_array[nextTestCase] ) );
      }
      else if(pid == -1)
      {
        perror("fork");
        exit(EXIT_STATUS_FORK_FAILED);
      }
      else // Parent process
      {
        TestCase tc(nextTestCase, tc_array[nextTestCase].name);
        children[pid] = tc;
        nextTestCase++;
        numRunningChildren++;
      }
    }

    // Wait for the next child to finish

    int status=0;
    int childPid = waitpid(-1, &status, 0);
    if( childPid == -1 )
    {
      perror("waitpid");
      exit(EXIT_STATUS_WAITPID_FAILED);
    }

    if( WIFEXITED(status) )
    {
      if( childPid > 0 )
      {
        int testResult = WEXITSTATUS(status);
        if( testResult )
        {
          printf("Test case %s failed: %d\n", children[childPid].testCaseName, testResult);
          failedTestCases.push_back(children[childPid].testCase);
          numFailures++;
        }
        else
        {
          numPasses++;
        }
        numRunningChildren--;
      }
    }

    else if( WIFSIGNALED(status) || WIFSTOPPED(status))
    {
      status = WIFSIGNALED(status)?WTERMSIG(status):WSTOPSIG(status);

      if( childPid > 0 )
      {
        RunningTestCases::iterator iter = children.find(childPid);
        if( iter != children.end() )
        {
          printf("Test case %s exited with signal %s\n", iter->second.testCaseName, strsignal(status));
          failedTestCases.push_back(iter->second.testCase);
        }
        else
        {
          printf("Unknown child process: %d signaled %s\n", childPid, strsignal(status));
        }

        numFailures++;
        numRunningChildren--;
      }
    }
  }

  OutputStatistics( numPasses, numFailures );

  if( reRunFailed )
  {
    for( unsigned int i=0; i<failedTestCases.size(); i++)
    {
      char* testCaseStrapline;
      int numChars = asprintf(&testCaseStrapline, "Test case %s", tc_array[failedTestCases[i]].name );
      printf("\n%s\n", testCaseStrapline);
      for(int j=0; j<numChars; j++)
      {
        printf("=");
      }
      printf("\n");
      RunTestCaseInChildProcess( tc_array[failedTestCases[i] ], false );
    }
  }

  return numFailures;
}

int FindAndRunTestCase(::testcase tc_array[], const char* testCaseName)
{
  int result = EXIT_STATUS_TESTCASE_NOT_FOUND;

  for( int i = 0; tc_array[i].name; i++ )
  {
    if( !strcmp(testCaseName, tc_array[i].name) )
    {
      return RunTestCase( tc_array[i] );
    }
  }

  printf("Unknown testcase name: \"%s\"\n", testCaseName);
  return result;
}

void Usage(const char* program)
{
  printf("Usage: \n"
         "   %s <testcase name>\t\t Execute a test case\n"
         "   %s \t\t Execute all test cases in parallel\n"
         "   %s -r\t\t Execute all test cases in parallel, rerunning failed test cases\n",
         program, program, program);
}

} // namespace
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "app/resource_bundle.h"
#include "base/string_util.h"
#include "chrome/browser/gtk/status_icons/status_icon_gtk.h"
#include "chrome/browser/gtk/status_icons/status_tray_gtk.h"
#include "grit/browser_resources.h"
#include "grit/theme_resources.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

class MockStatusIconObserver : public StatusIcon::Observer {
 public:
  MOCK_METHOD0(OnClicked, void());
};

TEST(StatusTrayGtkTest, CreateTray) {
  // Just tests creation/destruction.
  StatusTrayGtk tray;
}

TEST(StatusTrayGtkTest, CreateIcon) {
  // Create an icon, set the images and tooltip, then shut it down.
  StatusTrayGtk tray;
  StatusIcon* icon = tray.GetStatusIcon(ASCIIToUTF16("test"));
  SkBitmap* bitmap = ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_STATUS_TRAY_ICON);
  icon->SetImage(*bitmap);
  icon->SetPressedImage(*bitmap);
  icon->SetToolTip(ASCIIToUTF16("tool tip"));
}

TEST(StatusTrayGtkTest, ClickOnIcon) {
  // Create an icon, send a fake click event, make sure observer is called.
  StatusTrayGtk tray;
  StatusIconGtk* icon = static_cast<StatusIconGtk*>(
      tray.GetStatusIcon(ASCIIToUTF16("test")));
  MockStatusIconObserver observer;
  icon->AddObserver(&observer);
  EXPECT_CALL(observer, OnClicked());
  // Mimic a click.
  icon->OnClick(NULL, icon);
  icon->RemoveObserver(&observer);
}

}  // namespace
<commit_msg>linux: build fix<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "app/resource_bundle.h"
#include "base/string_util.h"
#include "chrome/browser/gtk/status_icons/status_icon_gtk.h"
#include "chrome/browser/gtk/status_icons/status_tray_gtk.h"
#include "grit/browser_resources.h"
#include "grit/theme_resources.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

class MockStatusIconObserver : public StatusIcon::Observer {
 public:
  MOCK_METHOD0(OnClicked, void());
};

TEST(StatusTrayGtkTest, CreateTray) {
  // Just tests creation/destruction.
  StatusTrayGtk tray;
}

TEST(StatusTrayGtkTest, CreateIcon) {
  // Create an icon, set the images and tooltip, then shut it down.
  StatusTrayGtk tray;
  StatusIcon* icon = tray.GetStatusIcon(ASCIIToUTF16("test"));
  SkBitmap* bitmap = ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_STATUS_TRAY_ICON);
  icon->SetImage(*bitmap);
  icon->SetPressedImage(*bitmap);
  icon->SetToolTip(ASCIIToUTF16("tool tip"));
}

TEST(StatusTrayGtkTest, ClickOnIcon) {
  // Create an icon, send a fake click event, make sure observer is called.
  StatusTrayGtk tray;
  StatusIconGtk* icon = static_cast<StatusIconGtk*>(
      tray.GetStatusIcon(ASCIIToUTF16("test")));
  MockStatusIconObserver observer;
  icon->AddObserver(&observer);
  EXPECT_CALL(observer, OnClicked());
  // Mimic a click.
  icon->OnClick(NULL);
  icon->RemoveObserver(&observer);
}

}  // namespace
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/renderer_host/render_widget_host_view_gtk.h"

#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <cairo/cairo.h>

#include "base/logging.h"
#include "base/string_util.h"
#include "chrome/common/native_web_keyboard_event.h"
#include "chrome/common/x11_util.h"
#include "chrome/browser/renderer_host/backing_store.h"
#include "chrome/browser/renderer_host/render_widget_host.h"
#include "third_party/WebKit/WebKit/chromium/public/gtk/WebInputEventFactory.h"

using WebKit::WebInputEventFactory;

namespace {

#include "webkit/glue/webcursor_gtk_data.h"

// This class is a simple convenience wrapper for Gtk functions. It has only
// static methods.
class RenderWidgetHostViewGtkWidget {
 public:
  static GtkWidget* CreateNewWidget(RenderWidgetHostViewGtk* host_view) {
    GtkWidget* widget = gtk_drawing_area_new();
    gtk_widget_set_double_buffered(widget, FALSE);

    gtk_widget_add_events(widget, GDK_EXPOSURE_MASK |
                                  GDK_POINTER_MOTION_MASK |
                                  GDK_BUTTON_PRESS_MASK |
                                  GDK_BUTTON_RELEASE_MASK |
                                  GDK_KEY_PRESS_MASK |
                                  GDK_KEY_RELEASE_MASK);
    GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_FOCUS);

    g_signal_connect(widget, "configure-event",
                     G_CALLBACK(ConfigureEvent), host_view);
    g_signal_connect(widget, "expose-event",
                     G_CALLBACK(ExposeEvent), host_view);
    g_signal_connect(widget, "key-press-event",
                     G_CALLBACK(KeyPressReleaseEvent), host_view);
    g_signal_connect(widget, "key-release-event",
                     G_CALLBACK(KeyPressReleaseEvent), host_view);
    g_signal_connect(widget, "focus-in-event",
                     G_CALLBACK(FocusIn), host_view);
    g_signal_connect(widget, "focus-out-event",
                     G_CALLBACK(FocusOut), host_view);
    g_signal_connect(widget, "button-press-event",
                     G_CALLBACK(ButtonPressReleaseEvent), host_view);
    g_signal_connect(widget, "button-release-event",
                     G_CALLBACK(ButtonPressReleaseEvent), host_view);
    g_signal_connect(widget, "motion-notify-event",
                     G_CALLBACK(MouseMoveEvent), host_view);
    g_signal_connect(widget, "scroll-event",
                     G_CALLBACK(MouseScrollEvent), host_view);

    return widget;
  }

 private:
  static gboolean ConfigureEvent(GtkWidget* widget, GdkEventConfigure* config,
                                 RenderWidgetHostViewGtk* host_view) {
    host_view->GetRenderWidgetHost()->WasResized();
    return FALSE;
  }

  static gboolean ExposeEvent(GtkWidget* widget, GdkEventExpose* expose,
                              RenderWidgetHostViewGtk* host_view) {
    const gfx::Rect damage_rect(expose->area);
    host_view->Paint(damage_rect);
    return FALSE;
  }

  static gboolean KeyPressReleaseEvent(GtkWidget* widget, GdkEventKey* event,
                                       RenderWidgetHostViewGtk* host_view) {
    NativeWebKeyboardEvent wke(event);
    host_view->GetRenderWidgetHost()->ForwardKeyboardEvent(wke);
    // We return TRUE because we did handle the event. If it turns out webkit
    // can't handle the event, we'll deal with it in
    // RenderView::UnhandledKeyboardEvent().
    return TRUE;
  }

  static gboolean FocusIn(GtkWidget* widget, GdkEventFocus* focus,
                          RenderWidgetHostViewGtk* host_view) {
    host_view->GetRenderWidgetHost()->Focus();
    return FALSE;
  }

  static gboolean FocusOut(GtkWidget* widget, GdkEventFocus* focus,
                           RenderWidgetHostViewGtk* host_view) {
    // Whenever we lose focus, set the cursor back to that of our parent window,
    // which should be the default arrow.
    gdk_window_set_cursor(widget->window, NULL);
    host_view->GetRenderWidgetHost()->Blur();
    return FALSE;
  }

  static gboolean ButtonPressReleaseEvent(
      GtkWidget* widget, GdkEventButton* event,
      RenderWidgetHostViewGtk* host_view) {
    host_view->GetRenderWidgetHost()->ForwardMouseEvent(
        WebInputEventFactory::mouseEvent(event));

    // TODO(evanm): why is this necessary here but not in test shell?
    // This logic is the same as GtkButton.
    if (event->type == GDK_BUTTON_PRESS && !GTK_WIDGET_HAS_FOCUS(widget))
      gtk_widget_grab_focus(widget);

    return FALSE;
  }

  static gboolean MouseMoveEvent(GtkWidget* widget, GdkEventMotion* event,
                                 RenderWidgetHostViewGtk* host_view) {
    host_view->GetRenderWidgetHost()->ForwardMouseEvent(
        WebInputEventFactory::mouseEvent(event));
    return FALSE;
  }

  static gboolean MouseScrollEvent(GtkWidget* widget, GdkEventScroll* event,
                                   RenderWidgetHostViewGtk* host_view) {
    host_view->GetRenderWidgetHost()->ForwardWheelEvent(
        WebInputEventFactory::mouseWheelEvent(event));
    return FALSE;
  }

  DISALLOW_IMPLICIT_CONSTRUCTORS(RenderWidgetHostViewGtkWidget);
};

gboolean OnPopupParentFocusOut(GtkWidget* parent, GdkEventFocus* focus,
                               RenderWidgetHost* host) {
  host->Shutdown();
  return FALSE;
}

}  // namespace

// static
RenderWidgetHostView* RenderWidgetHostView::CreateViewForWidget(
    RenderWidgetHost* widget) {
  return new RenderWidgetHostViewGtk(widget);
}

RenderWidgetHostViewGtk::RenderWidgetHostViewGtk(RenderWidgetHost* widget_host)
    : host_(widget_host),
      parent_host_view_(NULL),
      parent_(NULL),
      popup_signal_id_(0),
      activatable_(true),
      is_loading_(false) {
  host_->set_view(this);
}

RenderWidgetHostViewGtk::~RenderWidgetHostViewGtk() {
}

void RenderWidgetHostViewGtk::InitAsChild() {
  view_.Own(RenderWidgetHostViewGtkWidget::CreateNewWidget(this));
  gtk_widget_show(view_.get());
}

void RenderWidgetHostViewGtk::InitAsPopup(
    RenderWidgetHostView* parent_host_view, const gfx::Rect& pos) {
  parent_host_view_ = parent_host_view;
  parent_ = parent_host_view->GetPluginNativeView();
  GtkWidget* popup = gtk_window_new(GTK_WINDOW_POPUP);
  view_.Own(RenderWidgetHostViewGtkWidget::CreateNewWidget(this));
  gtk_container_add(GTK_CONTAINER(popup), view_.get());

  // If we are not activatable, we don't want to grab keyboard input,
  // and webkit will manage our destruction.
  if (activatable_) {
    // Grab all input for the app. If a click lands outside the bounds of the
    // popup, WebKit will notice and destroy us.
    gtk_grab_add(view_.get());
    // We also destroy ourselves if our parent loses focus.
    popup_signal_id_ = g_signal_connect(parent_, "focus-out-event",
        G_CALLBACK(OnPopupParentFocusOut), host_);
    // Our parent widget actually keeps GTK focus within its window, but we have
    // to make the webkit selection box disappear to maintain appearances.
    parent_host_view->Blur();
  }

  gtk_window_set_default_size(GTK_WINDOW(popup),
                              pos.width(), pos.height());
  gtk_widget_show_all(popup);
  gtk_window_move(GTK_WINDOW(popup), pos.x(), pos.y());
}

void RenderWidgetHostViewGtk::DidBecomeSelected() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::WasHidden() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::SetSize(const gfx::Size& size) {
  // We rely on our parent GTK container to size us.
}

gfx::NativeView RenderWidgetHostViewGtk::GetPluginNativeView() {
  // TODO(port): We need to pass some widget pointer out here because the
  // renderer echos it back to us when it asks for GetScreenInfo. However, we
  // should probably be passing the top-level window or some such instead.
  return view_.get();
}

void RenderWidgetHostViewGtk::MovePluginWindows(
    const std::vector<WebPluginGeometry>& plugin_window_moves) {
  if (plugin_window_moves.empty())
    return;

  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::Focus() {
  host_->Focus();
}

void RenderWidgetHostViewGtk::Blur() {
  host_->Blur();
}

bool RenderWidgetHostViewGtk::HasFocus() {
  NOTIMPLEMENTED();
  return false;
}

void RenderWidgetHostViewGtk::Show() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::Hide() {
  NOTIMPLEMENTED();
}

gfx::Rect RenderWidgetHostViewGtk::GetViewBounds() const {
  GtkAllocation* alloc = &view_.get()->allocation;
  return gfx::Rect(alloc->x, alloc->y, alloc->width, alloc->height);
}

void RenderWidgetHostViewGtk::UpdateCursor(const WebCursor& cursor) {
  // Optimize the common case, where the cursor hasn't changed.
  // However, we can switch between different pixmaps, so only on the
  // non-pixmap branch.
  if (current_cursor_.GetCursorType() != GDK_CURSOR_IS_PIXMAP &&
      current_cursor_.GetCursorType() == cursor.GetCursorType())
    return;

  current_cursor_ = cursor;
  ShowCurrentCursor();
}

void RenderWidgetHostViewGtk::SetIsLoading(bool is_loading) {
  is_loading_ = is_loading;
  // Only call ShowCurrentCursor() when it will actually change the cursor.
  if (current_cursor_.GetCursorType() == GDK_LAST_CURSOR)
    ShowCurrentCursor();
}

void RenderWidgetHostViewGtk::IMEUpdateStatus(int control,
                                              const gfx::Rect& caret_rect) {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::DidPaintRect(const gfx::Rect& rect) {
  Paint(rect);
}

void RenderWidgetHostViewGtk::DidScrollRect(const gfx::Rect& rect, int dx,
                                            int dy) {
  Paint(rect);
}

void RenderWidgetHostViewGtk::RenderViewGone() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::Destroy() {
  // If |parent_| is non-null, we are a popup and we must disconnect from our
  // parent and destroy the popup window.
  if (parent_) {
    if (activatable_) {
      g_signal_handler_disconnect(parent_, popup_signal_id_);
      parent_host_view_->Focus();
    }
    gtk_widget_destroy(gtk_widget_get_parent(view_.get()));
  }

  // We need to disconnect ourselves from our parent widget at this time; this
  // does the right thing, automatically removing ourselves from our parent
  // container.
  view_.Destroy();
}

void RenderWidgetHostViewGtk::SetTooltipText(const std::wstring& tooltip_text) {
  if (tooltip_text.empty()) {
    gtk_widget_set_has_tooltip(view_.get(), FALSE);
  } else {
    gtk_widget_set_tooltip_text(view_.get(), WideToUTF8(tooltip_text).c_str());
  }
}

BackingStore* RenderWidgetHostViewGtk::AllocBackingStore(
    const gfx::Size& size) {
  Display* display = x11_util::GetXDisplay();
  void* visual = x11_util::GetVisualFromGtkWidget(view_.get());
  XID root_window = x11_util::GetX11RootWindow();
  bool use_render = x11_util::QueryRenderSupport(display);
  bool use_shared_memory = x11_util::QuerySharedMemorySupport(display);
  int depth = gtk_widget_get_visual(view_.get())->depth;

  return new BackingStore(size, display, depth, visual, root_window,
                          use_render, use_shared_memory);
}

void RenderWidgetHostViewGtk::Paint(const gfx::Rect& damage_rect) {
  BackingStore* backing_store = host_->GetBackingStore();

  GdkWindow* window = view_.get()->window;
  if (backing_store) {
    // Only render the widget if it is attached to a window; there's a short
    // period where this object isn't attached to a window but hasn't been
    // Destroy()ed yet and it receives paint messages...
    if (window) {
      backing_store->ShowRect(
          damage_rect, x11_util::GetX11WindowFromGtkWidget(view_.get()));
    }
  } else {
    if (window)
      gdk_window_clear(window);
    NOTIMPLEMENTED();
  }
}

void RenderWidgetHostViewGtk::ShowCurrentCursor() {
  GdkCursor* gdk_cursor;
  switch(current_cursor_.GetCursorType()) {
    case GDK_CURSOR_IS_PIXMAP:
      // TODO(port): WebKit bug https://bugs.webkit.org/show_bug.cgi?id=16388 is
      // that calling gdk_window_set_cursor repeatedly is expensive.  We should
      // avoid it here where possible.
      gdk_cursor = current_cursor_.GetCustomCursor();
      break;

    case GDK_LAST_CURSOR:
      if (is_loading_) {
        // Use MOZ_CURSOR_SPINNING if we are showing the default cursor and
        // the page is loading.
        static const GdkColor fg = { 0, 0, 0, 0 };
        static const GdkColor bg = { 65535, 65535, 65535, 65535 };
        GdkPixmap* source =
            gdk_bitmap_create_from_data(NULL, moz_spinning_bits, 32, 32);
        GdkPixmap* mask =
            gdk_bitmap_create_from_data(NULL, moz_spinning_mask_bits, 32, 32);
        gdk_cursor = gdk_cursor_new_from_pixmap(source, mask, &fg, &bg, 2, 2);
        g_object_unref(source);
        g_object_unref(mask);
      } else {
        gdk_cursor = NULL;
      }
      break;

    default:
      gdk_cursor = gdk_cursor_new(current_cursor_.GetCursorType());
  }
  gdk_window_set_cursor(view_.get()->window, gdk_cursor);
  // The window now owns the cursor.
  if (gdk_cursor)
    gdk_cursor_unref(gdk_cursor);
}
<commit_msg>Don't try to set the cursor on null windows.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/renderer_host/render_widget_host_view_gtk.h"

#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <cairo/cairo.h>

#include "base/logging.h"
#include "base/string_util.h"
#include "chrome/common/native_web_keyboard_event.h"
#include "chrome/common/x11_util.h"
#include "chrome/browser/renderer_host/backing_store.h"
#include "chrome/browser/renderer_host/render_widget_host.h"
#include "third_party/WebKit/WebKit/chromium/public/gtk/WebInputEventFactory.h"

using WebKit::WebInputEventFactory;

namespace {

#include "webkit/glue/webcursor_gtk_data.h"

// This class is a simple convenience wrapper for Gtk functions. It has only
// static methods.
class RenderWidgetHostViewGtkWidget {
 public:
  static GtkWidget* CreateNewWidget(RenderWidgetHostViewGtk* host_view) {
    GtkWidget* widget = gtk_drawing_area_new();
    gtk_widget_set_double_buffered(widget, FALSE);

    gtk_widget_add_events(widget, GDK_EXPOSURE_MASK |
                                  GDK_POINTER_MOTION_MASK |
                                  GDK_BUTTON_PRESS_MASK |
                                  GDK_BUTTON_RELEASE_MASK |
                                  GDK_KEY_PRESS_MASK |
                                  GDK_KEY_RELEASE_MASK);
    GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_FOCUS);

    g_signal_connect(widget, "configure-event",
                     G_CALLBACK(ConfigureEvent), host_view);
    g_signal_connect(widget, "expose-event",
                     G_CALLBACK(ExposeEvent), host_view);
    g_signal_connect(widget, "key-press-event",
                     G_CALLBACK(KeyPressReleaseEvent), host_view);
    g_signal_connect(widget, "key-release-event",
                     G_CALLBACK(KeyPressReleaseEvent), host_view);
    g_signal_connect(widget, "focus-in-event",
                     G_CALLBACK(FocusIn), host_view);
    g_signal_connect(widget, "focus-out-event",
                     G_CALLBACK(FocusOut), host_view);
    g_signal_connect(widget, "button-press-event",
                     G_CALLBACK(ButtonPressReleaseEvent), host_view);
    g_signal_connect(widget, "button-release-event",
                     G_CALLBACK(ButtonPressReleaseEvent), host_view);
    g_signal_connect(widget, "motion-notify-event",
                     G_CALLBACK(MouseMoveEvent), host_view);
    g_signal_connect(widget, "scroll-event",
                     G_CALLBACK(MouseScrollEvent), host_view);

    return widget;
  }

 private:
  static gboolean ConfigureEvent(GtkWidget* widget, GdkEventConfigure* config,
                                 RenderWidgetHostViewGtk* host_view) {
    host_view->GetRenderWidgetHost()->WasResized();
    return FALSE;
  }

  static gboolean ExposeEvent(GtkWidget* widget, GdkEventExpose* expose,
                              RenderWidgetHostViewGtk* host_view) {
    const gfx::Rect damage_rect(expose->area);
    host_view->Paint(damage_rect);
    return FALSE;
  }

  static gboolean KeyPressReleaseEvent(GtkWidget* widget, GdkEventKey* event,
                                       RenderWidgetHostViewGtk* host_view) {
    NativeWebKeyboardEvent wke(event);
    host_view->GetRenderWidgetHost()->ForwardKeyboardEvent(wke);
    // We return TRUE because we did handle the event. If it turns out webkit
    // can't handle the event, we'll deal with it in
    // RenderView::UnhandledKeyboardEvent().
    return TRUE;
  }

  static gboolean FocusIn(GtkWidget* widget, GdkEventFocus* focus,
                          RenderWidgetHostViewGtk* host_view) {
    host_view->GetRenderWidgetHost()->Focus();
    return FALSE;
  }

  static gboolean FocusOut(GtkWidget* widget, GdkEventFocus* focus,
                           RenderWidgetHostViewGtk* host_view) {
    // Whenever we lose focus, set the cursor back to that of our parent window,
    // which should be the default arrow.
    gdk_window_set_cursor(widget->window, NULL);
    host_view->GetRenderWidgetHost()->Blur();
    return FALSE;
  }

  static gboolean ButtonPressReleaseEvent(
      GtkWidget* widget, GdkEventButton* event,
      RenderWidgetHostViewGtk* host_view) {
    host_view->GetRenderWidgetHost()->ForwardMouseEvent(
        WebInputEventFactory::mouseEvent(event));

    // TODO(evanm): why is this necessary here but not in test shell?
    // This logic is the same as GtkButton.
    if (event->type == GDK_BUTTON_PRESS && !GTK_WIDGET_HAS_FOCUS(widget))
      gtk_widget_grab_focus(widget);

    return FALSE;
  }

  static gboolean MouseMoveEvent(GtkWidget* widget, GdkEventMotion* event,
                                 RenderWidgetHostViewGtk* host_view) {
    host_view->GetRenderWidgetHost()->ForwardMouseEvent(
        WebInputEventFactory::mouseEvent(event));
    return FALSE;
  }

  static gboolean MouseScrollEvent(GtkWidget* widget, GdkEventScroll* event,
                                   RenderWidgetHostViewGtk* host_view) {
    host_view->GetRenderWidgetHost()->ForwardWheelEvent(
        WebInputEventFactory::mouseWheelEvent(event));
    return FALSE;
  }

  DISALLOW_IMPLICIT_CONSTRUCTORS(RenderWidgetHostViewGtkWidget);
};

gboolean OnPopupParentFocusOut(GtkWidget* parent, GdkEventFocus* focus,
                               RenderWidgetHost* host) {
  host->Shutdown();
  return FALSE;
}

}  // namespace

// static
RenderWidgetHostView* RenderWidgetHostView::CreateViewForWidget(
    RenderWidgetHost* widget) {
  return new RenderWidgetHostViewGtk(widget);
}

RenderWidgetHostViewGtk::RenderWidgetHostViewGtk(RenderWidgetHost* widget_host)
    : host_(widget_host),
      parent_host_view_(NULL),
      parent_(NULL),
      popup_signal_id_(0),
      activatable_(true),
      is_loading_(false) {
  host_->set_view(this);
}

RenderWidgetHostViewGtk::~RenderWidgetHostViewGtk() {
}

void RenderWidgetHostViewGtk::InitAsChild() {
  view_.Own(RenderWidgetHostViewGtkWidget::CreateNewWidget(this));
  gtk_widget_show(view_.get());
}

void RenderWidgetHostViewGtk::InitAsPopup(
    RenderWidgetHostView* parent_host_view, const gfx::Rect& pos) {
  parent_host_view_ = parent_host_view;
  parent_ = parent_host_view->GetPluginNativeView();
  GtkWidget* popup = gtk_window_new(GTK_WINDOW_POPUP);
  view_.Own(RenderWidgetHostViewGtkWidget::CreateNewWidget(this));
  gtk_container_add(GTK_CONTAINER(popup), view_.get());

  // If we are not activatable, we don't want to grab keyboard input,
  // and webkit will manage our destruction.
  if (activatable_) {
    // Grab all input for the app. If a click lands outside the bounds of the
    // popup, WebKit will notice and destroy us.
    gtk_grab_add(view_.get());
    // We also destroy ourselves if our parent loses focus.
    popup_signal_id_ = g_signal_connect(parent_, "focus-out-event",
        G_CALLBACK(OnPopupParentFocusOut), host_);
    // Our parent widget actually keeps GTK focus within its window, but we have
    // to make the webkit selection box disappear to maintain appearances.
    parent_host_view->Blur();
  }

  gtk_window_set_default_size(GTK_WINDOW(popup),
                              pos.width(), pos.height());
  gtk_widget_show_all(popup);
  gtk_window_move(GTK_WINDOW(popup), pos.x(), pos.y());
}

void RenderWidgetHostViewGtk::DidBecomeSelected() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::WasHidden() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::SetSize(const gfx::Size& size) {
  // We rely on our parent GTK container to size us.
}

gfx::NativeView RenderWidgetHostViewGtk::GetPluginNativeView() {
  // TODO(port): We need to pass some widget pointer out here because the
  // renderer echos it back to us when it asks for GetScreenInfo. However, we
  // should probably be passing the top-level window or some such instead.
  return view_.get();
}

void RenderWidgetHostViewGtk::MovePluginWindows(
    const std::vector<WebPluginGeometry>& plugin_window_moves) {
  if (plugin_window_moves.empty())
    return;

  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::Focus() {
  host_->Focus();
}

void RenderWidgetHostViewGtk::Blur() {
  host_->Blur();
}

bool RenderWidgetHostViewGtk::HasFocus() {
  NOTIMPLEMENTED();
  return false;
}

void RenderWidgetHostViewGtk::Show() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::Hide() {
  NOTIMPLEMENTED();
}

gfx::Rect RenderWidgetHostViewGtk::GetViewBounds() const {
  GtkAllocation* alloc = &view_.get()->allocation;
  return gfx::Rect(alloc->x, alloc->y, alloc->width, alloc->height);
}

void RenderWidgetHostViewGtk::UpdateCursor(const WebCursor& cursor) {
  // Optimize the common case, where the cursor hasn't changed.
  // However, we can switch between different pixmaps, so only on the
  // non-pixmap branch.
  if (current_cursor_.GetCursorType() != GDK_CURSOR_IS_PIXMAP &&
      current_cursor_.GetCursorType() == cursor.GetCursorType())
    return;

  current_cursor_ = cursor;
  ShowCurrentCursor();
}

void RenderWidgetHostViewGtk::SetIsLoading(bool is_loading) {
  is_loading_ = is_loading;
  // Only call ShowCurrentCursor() when it will actually change the cursor.
  if (current_cursor_.GetCursorType() == GDK_LAST_CURSOR)
    ShowCurrentCursor();
}

void RenderWidgetHostViewGtk::IMEUpdateStatus(int control,
                                              const gfx::Rect& caret_rect) {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::DidPaintRect(const gfx::Rect& rect) {
  Paint(rect);
}

void RenderWidgetHostViewGtk::DidScrollRect(const gfx::Rect& rect, int dx,
                                            int dy) {
  Paint(rect);
}

void RenderWidgetHostViewGtk::RenderViewGone() {
  NOTIMPLEMENTED();
}

void RenderWidgetHostViewGtk::Destroy() {
  // If |parent_| is non-null, we are a popup and we must disconnect from our
  // parent and destroy the popup window.
  if (parent_) {
    if (activatable_) {
      g_signal_handler_disconnect(parent_, popup_signal_id_);
      parent_host_view_->Focus();
    }
    gtk_widget_destroy(gtk_widget_get_parent(view_.get()));
  }

  // We need to disconnect ourselves from our parent widget at this time; this
  // does the right thing, automatically removing ourselves from our parent
  // container.
  view_.Destroy();
}

void RenderWidgetHostViewGtk::SetTooltipText(const std::wstring& tooltip_text) {
  if (tooltip_text.empty()) {
    gtk_widget_set_has_tooltip(view_.get(), FALSE);
  } else {
    gtk_widget_set_tooltip_text(view_.get(), WideToUTF8(tooltip_text).c_str());
  }
}

BackingStore* RenderWidgetHostViewGtk::AllocBackingStore(
    const gfx::Size& size) {
  Display* display = x11_util::GetXDisplay();
  void* visual = x11_util::GetVisualFromGtkWidget(view_.get());
  XID root_window = x11_util::GetX11RootWindow();
  bool use_render = x11_util::QueryRenderSupport(display);
  bool use_shared_memory = x11_util::QuerySharedMemorySupport(display);
  int depth = gtk_widget_get_visual(view_.get())->depth;

  return new BackingStore(size, display, depth, visual, root_window,
                          use_render, use_shared_memory);
}

void RenderWidgetHostViewGtk::Paint(const gfx::Rect& damage_rect) {
  BackingStore* backing_store = host_->GetBackingStore();

  GdkWindow* window = view_.get()->window;
  if (backing_store) {
    // Only render the widget if it is attached to a window; there's a short
    // period where this object isn't attached to a window but hasn't been
    // Destroy()ed yet and it receives paint messages...
    if (window) {
      backing_store->ShowRect(
          damage_rect, x11_util::GetX11WindowFromGtkWidget(view_.get()));
    }
  } else {
    if (window)
      gdk_window_clear(window);
    NOTIMPLEMENTED();
  }
}

void RenderWidgetHostViewGtk::ShowCurrentCursor() {
  // The widget may not have a window. If that's the case, abort mission. This
  // is the same issue as that explained above in Paint().
  if (!view_.get()->window)
    return;

  GdkCursor* gdk_cursor;
  switch(current_cursor_.GetCursorType()) {
    case GDK_CURSOR_IS_PIXMAP:
      // TODO(port): WebKit bug https://bugs.webkit.org/show_bug.cgi?id=16388 is
      // that calling gdk_window_set_cursor repeatedly is expensive.  We should
      // avoid it here where possible.
      gdk_cursor = current_cursor_.GetCustomCursor();
      break;

    case GDK_LAST_CURSOR:
      if (is_loading_) {
        // Use MOZ_CURSOR_SPINNING if we are showing the default cursor and
        // the page is loading.
        static const GdkColor fg = { 0, 0, 0, 0 };
        static const GdkColor bg = { 65535, 65535, 65535, 65535 };
        GdkPixmap* source =
            gdk_bitmap_create_from_data(NULL, moz_spinning_bits, 32, 32);
        GdkPixmap* mask =
            gdk_bitmap_create_from_data(NULL, moz_spinning_mask_bits, 32, 32);
        gdk_cursor = gdk_cursor_new_from_pixmap(source, mask, &fg, &bg, 2, 2);
        g_object_unref(source);
        g_object_unref(mask);
      } else {
        gdk_cursor = NULL;
      }
      break;

    default:
      gdk_cursor = gdk_cursor_new(current_cursor_.GetCursorType());
  }
  gdk_window_set_cursor(view_.get()->window, gdk_cursor);
  // The window now owns the cursor.
  if (gdk_cursor)
    gdk_cursor_unref(gdk_cursor);
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2010 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

// boost
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

// mapnik
#include <mapnik/raster_colorizer.hpp>

using mapnik::raster_colorizer;
using mapnik::raster_colorizer_ptr;
using mapnik::colorizer_stop;
using mapnik::colorizer_stops;
using mapnik::colorizer_mode_enum;
using mapnik::color;
using mapnik::COLORIZER_INHERIT;
using mapnik::COLORIZER_LINEAR;
using mapnik::COLORIZER_DISCRETE;
using mapnik::COLORIZER_EXACT;

namespace {
void add_stop(raster_colorizer_ptr & rc, colorizer_stop & stop)
{
    rc->add_stop(stop);
}
void add_stop2(raster_colorizer_ptr & rc, float v) {
    colorizer_stop stop(v, rc->get_default_mode(), rc->get_default_color());
    rc->add_stop(stop);
}
void add_stop3(raster_colorizer_ptr &rc, float v, color c) {
    colorizer_stop stop(v, rc->get_default_mode(), c);
    rc->add_stop(stop);
}
void add_stop4(raster_colorizer_ptr &rc, float v, colorizer_mode_enum m) {
    colorizer_stop stop(v, m, rc->get_default_color());
    rc->add_stop(stop);
}
void add_stop5(raster_colorizer_ptr &rc, float v, colorizer_mode_enum m, color c) {
    colorizer_stop stop(v, m, c);
    rc->add_stop(stop);
}
colorizer_stops const& get_stops(raster_colorizer_ptr & rc)
{
    return rc->get_stops();
}
}

void export_raster_colorizer()
{
    using namespace boost::python;

    class_<raster_colorizer,raster_colorizer_ptr>("RasterColorizer",
                                                  "A Raster Colorizer object.",
                                                  init<colorizer_mode_enum, color>(args("default_mode","default_color"))
        )
        .def(init<>())
        .add_property("default_color",
                      make_function(&raster_colorizer::get_default_color, return_value_policy<reference_existing_object>()),
                      &raster_colorizer::set_default_color,
                      "The default color for stops added without a color (mapnik.Color).\n")
        .add_property("default_mode",
                      &raster_colorizer::get_default_mode_enum,
                      &raster_colorizer::set_default_mode_enum,
                      "The default mode (mapnik.ColorizerMode).\n"
                      "\n"
                      "If a stop is added without a mode, then it will inherit this default mode\n")
        .add_property("stops",
                      make_function(get_stops,return_value_policy<reference_existing_object>()),
                      "The list of stops this RasterColorizer contains\n")
        .add_property("epsilon",
                      &raster_colorizer::get_epsilon,
                      &raster_colorizer::set_epsilon,
                      "Comparison epsilon value for exact mode\n"
                      "\n"
                      "When comparing values in exact mode, values need only be within epsilon to match.\n")

        .def("add_stop", add_stop,
             (arg("ColorizerStop")),
             "Add a colorizer stop to the raster colorizer.\n"
             "\n"
             "Usage:\n"
             ">>> colorizer = mapnik.RasterColorizer()\n"
             ">>> color = mapnik.Color(\"#0044cc\")\n"
             ">>> stop = mapnik.ColorizerStop(3, mapnik.COLORIZER_INHERIT, color)\n"
             ">>> colorizer.add_stop(stop)\n"
            )
        .def("add_stop", add_stop2,
             (arg("value")),
             "Add a colorizer stop to the raster colorizer, using the default mode and color.\n"
             "\n"
             "Usage:\n"
             ">>> default_color = mapnik.Color(\"#0044cc\")\n"
             ">>> colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, default_color)\n"
             ">>> colorizer.add_stop(100)\n"
            )
        .def("add_stop", add_stop3,
             (arg("value")),
             "Add a colorizer stop to the raster colorizer, using the default mode.\n"
             "\n"
             "Usage:\n"
             ">>> default_color = mapnik.Color(\"#0044cc\")\n"
             ">>> colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, default_color)\n"
             ">>> colorizer.add_stop(100, mapnik.Color(\"#123456\"))\n"
            )
        .def("add_stop", add_stop4,
             (arg("value")),
             "Add a colorizer stop to the raster colorizer, using the default color.\n"
             "\n"
             "Usage:\n"
             ">>> default_color = mapnik.Color(\"#0044cc\")\n"
             ">>> colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, default_color)\n"
             ">>> colorizer.add_stop(100, mapnik.COLORIZER_EXACT)\n"
            )
        .def("add_stop", add_stop5,
             (arg("value")),
             "Add a colorizer stop to the raster colorizer.\n"
             "\n"
             "Usage:\n"
             ">>> default_color = mapnik.Color(\"#0044cc\")\n"
             ">>> colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, default_color)\n"
             ">>> colorizer.add_stop(100, mapnik.COLORIZER_DISCRETE, mapnik.Color(\"#112233\"))\n"
            )
        .def("get_color", &raster_colorizer::get_color,
             "Get the color assigned to a certain value in raster data.\n"
             "\n"
             "Usage:\n"
             ">>> colorizer = mapnik.RasterColorizer()\n"
             ">>> color = mapnik.Color(\"#0044cc\")\n"
             ">>> colorizer.add_stop(0, mapnik.COLORIZER_DISCRETE, mapnik.Color(\"#000000\"))\n"
             ">>> colorizer.add_stop(100, mapnik.COLORIZER_DISCRETE, mapnik.Color(\"#0E0A06\"))\n"
             ">>> colorizer.get_color(50)\n"
             "Color('#070503')\n"
            )
        ;

    class_<colorizer_stops>("ColorizerStops",
                            "A RasterColorizer's collection of ordered color stops.\n"
                            "This class is not meant to be instantiated from python. However, "
                            "it can be accessed at a RasterColorizer's \"stops\" attribute for "
                            "introspection purposes",
                            no_init)
        .def(vector_indexing_suite<colorizer_stops>())
        ;

    enum_<colorizer_mode_enum>("ColorizerMode")
        .value("COLORIZER_INHERIT", COLORIZER_INHERIT)
        .value("COLORIZER_LINEAR", COLORIZER_LINEAR)
        .value("COLORIZER_DISCRETE", COLORIZER_DISCRETE)
        .value("COLORIZER_EXACT", COLORIZER_EXACT)
        .export_values()
        ;

    class_<colorizer_stop>("ColorizerStop",init<float, colorizer_mode_enum, color const&>(
                               "A Colorizer Stop object.\n"
                               "Create with a value, ColorizerMode, and Color\n"
                               "\n"
                               "Usage:"
                               ">>> color = mapnik.Color(\"#fff000\")\n"
                               ">>> stop= mapnik.ColorizerStop(42.42, mapnik.COLORIZER_LINEAR, color)\n"
                               ))
        .add_property("color",
                      make_function(&colorizer_stop::get_color, return_value_policy<reference_existing_object>()),
                      &colorizer_stop::set_color,
                      "The stop color (mapnik.Color).\n")
        .add_property("value",
                      &colorizer_stop::get_value,
                      &colorizer_stop::set_value,
                      "The stop value.\n")
        .add_property("label",
                      make_function(&colorizer_stop::get_label, return_value_policy<copy_const_reference>()),
                      &colorizer_stop::set_label,
                      "The stop label.\n")
        .add_property("mode",
                      &colorizer_stop::get_mode_enum,
                      &colorizer_stop::set_mode_enum,
                      "The stop mode (mapnik.ColorizerMode).\n"
                      "\n"
                      "If this is COLORIZER_INHERIT then it will inherit the default mode\n"
                      " from the RasterColorizer it is added to.\n")
        .def(self == self)
        .def("__str__",&colorizer_stop::to_string)
        ;
}
<commit_msg>fix raster colorizer via python<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2010 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

// boost
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

// mapnik
#include <mapnik/raster_colorizer.hpp>

using mapnik::raster_colorizer;
using mapnik::raster_colorizer_ptr;
using mapnik::colorizer_stop;
using mapnik::colorizer_stops;
using mapnik::colorizer_mode_enum;
using mapnik::color;
using mapnik::COLORIZER_INHERIT;
using mapnik::COLORIZER_LINEAR;
using mapnik::COLORIZER_DISCRETE;
using mapnik::COLORIZER_EXACT;

namespace {
void add_stop(raster_colorizer_ptr & rc, colorizer_stop & stop)
{
    rc->add_stop(stop);
}
void add_stop2(raster_colorizer_ptr & rc, float v) {
    colorizer_stop stop(v, rc->get_default_mode(), rc->get_default_color());
    rc->add_stop(stop);
}
void add_stop3(raster_colorizer_ptr &rc, float v, color c) {
    colorizer_stop stop(v, rc->get_default_mode(), c);
    rc->add_stop(stop);
}
void add_stop4(raster_colorizer_ptr &rc, float v, colorizer_mode_enum m) {
    colorizer_stop stop(v, m, rc->get_default_color());
    rc->add_stop(stop);
}
void add_stop5(raster_colorizer_ptr &rc, float v, colorizer_mode_enum m, color c) {
    colorizer_stop stop(v, m, c);
    rc->add_stop(stop);
}
mapnik::color get_color(raster_colorizer_ptr &rc, float value) {
    unsigned rgba = rc->get_color(value);
    unsigned r = (rgba & 0xff);
    unsigned g = (rgba >> 8 ) & 0xff;
    unsigned b = (rgba >> 16) & 0xff;
    unsigned a = (rgba >> 24) & 0xff;
    return mapnik::color(r,g,b,a);
}

colorizer_stops const& get_stops(raster_colorizer_ptr & rc)
{
    return rc->get_stops();
}
}

void export_raster_colorizer()
{
    using namespace boost::python;

    class_<raster_colorizer,raster_colorizer_ptr>("RasterColorizer",
                                                  "A Raster Colorizer object.",
                                                  init<colorizer_mode_enum, color>(args("default_mode","default_color"))
        )
        .def(init<>())
        .add_property("default_color",
                      make_function(&raster_colorizer::get_default_color, return_value_policy<reference_existing_object>()),
                      &raster_colorizer::set_default_color,
                      "The default color for stops added without a color (mapnik.Color).\n")
        .add_property("default_mode",
                      &raster_colorizer::get_default_mode_enum,
                      &raster_colorizer::set_default_mode_enum,
                      "The default mode (mapnik.ColorizerMode).\n"
                      "\n"
                      "If a stop is added without a mode, then it will inherit this default mode\n")
        .add_property("stops",
                      make_function(get_stops,return_value_policy<reference_existing_object>()),
                      "The list of stops this RasterColorizer contains\n")
        .add_property("epsilon",
                      &raster_colorizer::get_epsilon,
                      &raster_colorizer::set_epsilon,
                      "Comparison epsilon value for exact mode\n"
                      "\n"
                      "When comparing values in exact mode, values need only be within epsilon to match.\n")

        .def("add_stop", add_stop,
             (arg("ColorizerStop")),
             "Add a colorizer stop to the raster colorizer.\n"
             "\n"
             "Usage:\n"
             ">>> colorizer = mapnik.RasterColorizer()\n"
             ">>> color = mapnik.Color(\"#0044cc\")\n"
             ">>> stop = mapnik.ColorizerStop(3, mapnik.COLORIZER_INHERIT, color)\n"
             ">>> colorizer.add_stop(stop)\n"
            )
        .def("add_stop", add_stop2,
             (arg("value")),
             "Add a colorizer stop to the raster colorizer, using the default mode and color.\n"
             "\n"
             "Usage:\n"
             ">>> default_color = mapnik.Color(\"#0044cc\")\n"
             ">>> colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, default_color)\n"
             ">>> colorizer.add_stop(100)\n"
            )
        .def("add_stop", add_stop3,
             (arg("value")),
             "Add a colorizer stop to the raster colorizer, using the default mode.\n"
             "\n"
             "Usage:\n"
             ">>> default_color = mapnik.Color(\"#0044cc\")\n"
             ">>> colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, default_color)\n"
             ">>> colorizer.add_stop(100, mapnik.Color(\"#123456\"))\n"
            )
        .def("add_stop", add_stop4,
             (arg("value")),
             "Add a colorizer stop to the raster colorizer, using the default color.\n"
             "\n"
             "Usage:\n"
             ">>> default_color = mapnik.Color(\"#0044cc\")\n"
             ">>> colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, default_color)\n"
             ">>> colorizer.add_stop(100, mapnik.COLORIZER_EXACT)\n"
            )
        .def("add_stop", add_stop5,
             (arg("value")),
             "Add a colorizer stop to the raster colorizer.\n"
             "\n"
             "Usage:\n"
             ">>> default_color = mapnik.Color(\"#0044cc\")\n"
             ">>> colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, default_color)\n"
             ">>> colorizer.add_stop(100, mapnik.COLORIZER_DISCRETE, mapnik.Color(\"#112233\"))\n"
            )
        .def("get_color", get_color,
             "Get the color assigned to a certain value in raster data.\n"
             "\n"
             "Usage:\n"
             ">>> colorizer = mapnik.RasterColorizer()\n"
             ">>> color = mapnik.Color(\"#0044cc\")\n"
             ">>> colorizer.add_stop(0, mapnik.COLORIZER_DISCRETE, mapnik.Color(\"#000000\"))\n"
             ">>> colorizer.add_stop(100, mapnik.COLORIZER_DISCRETE, mapnik.Color(\"#0E0A06\"))\n"
             ">>> colorizer.get_color(50)\n"
             "Color('#070503')\n"
            )
        ;

    class_<colorizer_stops>("ColorizerStops",
                            "A RasterColorizer's collection of ordered color stops.\n"
                            "This class is not meant to be instantiated from python. However, "
                            "it can be accessed at a RasterColorizer's \"stops\" attribute for "
                            "introspection purposes",
                            no_init)
        .def(vector_indexing_suite<colorizer_stops>())
        ;

    enum_<colorizer_mode_enum>("ColorizerMode")
        .value("COLORIZER_INHERIT", COLORIZER_INHERIT)
        .value("COLORIZER_LINEAR", COLORIZER_LINEAR)
        .value("COLORIZER_DISCRETE", COLORIZER_DISCRETE)
        .value("COLORIZER_EXACT", COLORIZER_EXACT)
        .export_values()
        ;

    class_<colorizer_stop>("ColorizerStop",init<float, colorizer_mode_enum, color const&>(
                               "A Colorizer Stop object.\n"
                               "Create with a value, ColorizerMode, and Color\n"
                               "\n"
                               "Usage:"
                               ">>> color = mapnik.Color(\"#fff000\")\n"
                               ">>> stop= mapnik.ColorizerStop(42.42, mapnik.COLORIZER_LINEAR, color)\n"
                               ))
        .add_property("color",
                      make_function(&colorizer_stop::get_color, return_value_policy<reference_existing_object>()),
                      &colorizer_stop::set_color,
                      "The stop color (mapnik.Color).\n")
        .add_property("value",
                      &colorizer_stop::get_value,
                      &colorizer_stop::set_value,
                      "The stop value.\n")
        .add_property("label",
                      make_function(&colorizer_stop::get_label, return_value_policy<copy_const_reference>()),
                      &colorizer_stop::set_label,
                      "The stop label.\n")
        .add_property("mode",
                      &colorizer_stop::get_mode_enum,
                      &colorizer_stop::set_mode_enum,
                      "The stop mode (mapnik.ColorizerMode).\n"
                      "\n"
                      "If this is COLORIZER_INHERIT then it will inherit the default mode\n"
                      " from the RasterColorizer it is added to.\n")
        .def(self == self)
        .def("__str__",&colorizer_stop::to_string)
        ;
}
<|endoftext|>


<commit_before>/* Copyright 2009 Thomas McGuire <mcguire@kde.org>

   This library is free software; you can redistribute it and/or modify
   it under the terms of the GNU Library General Public License as published
   by the Free Software Foundation; either version 2 of the License or
   ( at your option ) version 3 or, at the discretion of KDE e.V.
   ( which shall act as a proxy as in section 14 of the GPLv3 ), any later version.

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

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/
#include "htmlquotecolorer.h"

#include "csshelper.h"

#include <dom/html_document.h>
#include <dom/dom_element.h>

namespace KMail {

HTMLQuoteColorer::HTMLQuoteColorer( KPIM::CSSHelper *cssHelper )
  : mCSSHelper( cssHelper )
{
}

QString HTMLQuoteColorer::process( const QString &htmlSource )
{
  // Create a DOM Document from the HTML source
  DOM::HTMLDocument doc;
  doc.open();
  doc.write( htmlSource );
  doc.close();

  mIsQuotedLine = false;
  mIsFirstTextNodeInLine = true;
  processNode( doc.documentElement() );
  return doc.toString().string();
}

DOM::Node HTMLQuoteColorer::processNode( DOM::Node node )
{
  // Below, we determine if the current text node should be quote colored by keeping track of
  // linebreaks and wether this text node is the first one.
  const QString textContent = node.textContent().string();
  const bool isTextNode = !textContent.isEmpty() && !node.hasChildNodes();
  if ( isTextNode ) {
    if ( mIsFirstTextNodeInLine ) {
      if ( textContent.simplified().startsWith( '>' ) ||
          textContent.simplified().startsWith( '|' ) ) {
        mIsQuotedLine = true;
        currentQuoteLength = quoteLength( textContent ) - 1;
      }
      else {
        mIsQuotedLine = false;
      }
    }

    // All subsequent text nodes are not the first ones anymore
    mIsFirstTextNodeInLine = false;
  }

  const QString nodeName = node.nodeName().string().toLower();
  QStringList lineBreakNodes;
  lineBreakNodes << "br" << "p" << "div" << "ul" << "ol" << "li";
  if ( lineBreakNodes.contains( nodeName ) ) {
    mIsFirstTextNodeInLine = true;
  }

  DOM::Node returnNode = node;
  bool fontTagAdded = false;
  if ( mIsQuotedLine && isTextNode ) {

    // Ok, we are in a line that should be quoted, so create a font node for the color and replace
    // the current node with it.
    DOM::Element font = node.ownerDocument().createElement( QString( "font" ) );
    font.setAttribute( QString( "color" ), mCSSHelper->quoteColor( currentQuoteLength ).name() );
    node.parentNode().replaceChild( font, node );
    font.appendChild( node );
    returnNode = font;
    fontTagAdded = true;
  }

  // Process all child nodes, but only if we are didn't add those child nodes itself, as otherwise
  // we'll go into an infinite recursion.
  if ( !fontTagAdded ) {
    DOM::Node childNode = node.firstChild();
    while ( !childNode.isNull() ) {
      childNode = processNode( childNode );
      childNode = childNode.nextSibling();
    }
  }
  return returnNode;
}

int HTMLQuoteColorer::quoteLength( const QString &line ) const
{
  QString simplified = line.simplified();
  simplified = simplified.replace( QRegExp( QLatin1String( "\\s" ) ), QString() )
                         .replace( QLatin1Char( '|' ), QLatin1Char( '>' ) );
  if ( simplified.startsWith( ">>>" ) ) return 3;
  if ( simplified.startsWith( ">>" ) ) return 2;
  if ( simplified.startsWith( ">" ) ) return 1;
  return 0;
}

}
<commit_msg>Catch DOM exceptions. This should at fix Dmitry's crash, although I couldn't reproduce it.<commit_after>/* Copyright 2009 Thomas McGuire <mcguire@kde.org>

   This library is free software; you can redistribute it and/or modify
   it under the terms of the GNU Library General Public License as published
   by the Free Software Foundation; either version 2 of the License or
   ( at your option ) version 3 or, at the discretion of KDE e.V.
   ( which shall act as a proxy as in section 14 of the GPLv3 ), any later version.

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

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/
#include "htmlquotecolorer.h"

#include "csshelper.h"

#include <dom/html_document.h>
#include <dom/dom_element.h>
#include <dom/dom_exception.h>

namespace KMail {

HTMLQuoteColorer::HTMLQuoteColorer( KPIM::CSSHelper *cssHelper )
  : mCSSHelper( cssHelper )
{
}

QString HTMLQuoteColorer::process( const QString &htmlSource )
{
  try {
    // Create a DOM Document from the HTML source
    DOM::HTMLDocument doc;
    doc.open();
    doc.write( htmlSource );
    doc.close();

    mIsQuotedLine = false;
    mIsFirstTextNodeInLine = true;
    processNode( doc.documentElement() );
    return doc.toString().string();
  }
  catch( const DOM::DOMException &exception ) {
    kWarning() << "Got a DOM exception with code" << exception.code;
    kWarning() << "No quote coloring for you, then.";
    return htmlSource;
  }
}

DOM::Node HTMLQuoteColorer::processNode( DOM::Node node )
{
  // Below, we determine if the current text node should be quote colored by keeping track of
  // linebreaks and wether this text node is the first one.
  const QString textContent = node.textContent().string();
  const bool isTextNode = !textContent.isEmpty() && !node.hasChildNodes();
  if ( isTextNode ) {
    if ( mIsFirstTextNodeInLine ) {
      if ( textContent.simplified().startsWith( '>' ) ||
          textContent.simplified().startsWith( '|' ) ) {
        mIsQuotedLine = true;
        currentQuoteLength = quoteLength( textContent ) - 1;
      }
      else {
        mIsQuotedLine = false;
      }
    }

    // All subsequent text nodes are not the first ones anymore
    mIsFirstTextNodeInLine = false;
  }

  const QString nodeName = node.nodeName().string().toLower();
  QStringList lineBreakNodes;
  lineBreakNodes << "br" << "p" << "div" << "ul" << "ol" << "li";
  if ( lineBreakNodes.contains( nodeName ) ) {
    mIsFirstTextNodeInLine = true;
  }

  DOM::Node returnNode = node;
  bool fontTagAdded = false;
  if ( mIsQuotedLine && isTextNode ) {

    // Ok, we are in a line that should be quoted, so create a font node for the color and replace
    // the current node with it.
    DOM::Element font = node.ownerDocument().createElement( QString( "font" ) );
    font.setAttribute( QString( "color" ), mCSSHelper->quoteColor( currentQuoteLength ).name() );
    node.parentNode().replaceChild( font, node );
    font.appendChild( node );
    returnNode = font;
    fontTagAdded = true;
  }

  // Process all child nodes, but only if we are didn't add those child nodes itself, as otherwise
  // we'll go into an infinite recursion.
  if ( !fontTagAdded ) {
    DOM::Node childNode = node.firstChild();
    while ( !childNode.isNull() ) {
      childNode = processNode( childNode );
      childNode = childNode.nextSibling();
    }
  }
  return returnNode;
}

int HTMLQuoteColorer::quoteLength( const QString &line ) const
{
  QString simplified = line.simplified();
  simplified = simplified.replace( QRegExp( QLatin1String( "\\s" ) ), QString() )
                         .replace( QLatin1Char( '|' ), QLatin1Char( '>' ) );
  if ( simplified.startsWith( ">>>" ) ) return 3;
  if ( simplified.startsWith( ">>" ) ) return 2;
  if ( simplified.startsWith( ">" ) ) return 1;
  return 0;
}

}
<|endoftext|>


<commit_before>
#include "Globals.h"  // NOTE: MSVC stupidness requires this to be the same across all modules

#include "BeaconEntity.h"
#include "../BlockArea.h"
#include "../Entities/Player.h"
#include "../UI/BeaconWindow.h"
#include "../ClientHandle.h"

cBeaconEntity::cBeaconEntity(BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World):
	Super(a_BlockType, a_BlockMeta, a_BlockX, a_BlockY, a_BlockZ, 1, 1, a_World),
	m_IsActive(false),
	m_BeaconLevel(0),
	m_PrimaryEffect(cEntityEffect::effNoEffect),
	m_SecondaryEffect(cEntityEffect::effNoEffect)
{
	ASSERT(a_BlockType == E_BLOCK_BEACON);
	UpdateBeacon();
}

char cBeaconEntity::CalculatePyramidLevel(void)
{
	cBlockArea Area;
	int MinY = std::max(GetPosY() - 4, 0);
	int MaxY = std::max(GetPosY() - 1, 0);

	Area.Read(
		*m_World,
		GetPosX() - 4, GetPosX() + 4,
		MinY, MaxY,
		GetPosZ() - 4, GetPosZ() + 4,
		cBlockArea::baTypes
	);

	int Layer = 1;
	int MiddleXZ = 4;

	for (int Y = (Area.GetSizeY() - 1); Y >= 0; Y--)
	{
		for (int X = MiddleXZ - Layer; X <= (MiddleXZ + Layer); X++)
		{
			for (int Z = MiddleXZ - Layer; Z <= (MiddleXZ + Layer); Z++)
			{
				if (!IsMineralBlock(Area.GetRelBlockType(X, Y, Z)))
				{
					return static_cast<char>(Layer - 1);
				}
			}
		}
		Layer++;
	}

	return static_cast<char>(Layer - 1);
}

bool cBeaconEntity::IsValidEffect(cEntityEffect::eType a_Effect, char a_BeaconLevel)
{
	switch (a_Effect)
	{
		case cEntityEffect::effRegeneration: return (a_BeaconLevel >= 4);
		case cEntityEffect::effStrength:     return (a_BeaconLevel >= 3);
		case cEntityEffect::effResistance:   return (a_BeaconLevel >= 2);
		case cEntityEffect::effJumpBoost:    return (a_BeaconLevel >= 2);
		case cEntityEffect::effSpeed:        return (a_BeaconLevel >= 1);
		case cEntityEffect::effHaste:        return (a_BeaconLevel >= 1);
		case cEntityEffect::effNoEffect:     return true;

		default:
		{
			LOGD("%s: Invalid beacon effect: %d", __FUNCTION__, static_cast<int>(a_Effect));
			return false;
		}
	}
}

bool cBeaconEntity::SetPrimaryEffect(cEntityEffect::eType a_Effect)
{
	if (!IsValidEffect(a_Effect, m_BeaconLevel))
	{
		m_PrimaryEffect = cEntityEffect::effNoEffect;
		return false;
	}

	m_PrimaryEffect = a_Effect;

	// Send window update:
	if (GetWindow() != nullptr)
	{
		GetWindow()->SetProperty(1, m_PrimaryEffect);
	}
	return true;
}

bool cBeaconEntity::SetSecondaryEffect(cEntityEffect::eType a_Effect)
{
	if (!IsValidEffect(a_Effect, m_BeaconLevel))
	{
		m_SecondaryEffect = cEntityEffect::effNoEffect;
		return false;
	}

	m_SecondaryEffect = a_Effect;

	// Send window update:
	if (GetWindow() != nullptr)
	{
		GetWindow()->SetProperty(2, m_SecondaryEffect);
	}
	return true;
}

bool cBeaconEntity::IsBeaconBlocked(void)
{
	for (int Y = m_PosY; Y < cChunkDef::Height; ++Y)
	{
		BLOCKTYPE Block = m_World->GetBlock(m_PosX, Y, m_PosZ);
		if (!cBlockInfo::IsTransparent(Block))
		{
			return true;
		}
	}
	return false;
}

bool cBeaconEntity::IsMineralBlock(BLOCKTYPE a_BlockType)
{
	switch (a_BlockType)
	{
		case E_BLOCK_DIAMOND_BLOCK:
		case E_BLOCK_GOLD_BLOCK:
		case E_BLOCK_IRON_BLOCK:
		case E_BLOCK_EMERALD_BLOCK:
		{
			return true;
		}
	}
	return false;
}

void cBeaconEntity::UpdateBeacon(void)
{
	int OldBeaconLevel = m_BeaconLevel;

	if (IsBeaconBlocked())
	{
		m_IsActive = false;
		m_BeaconLevel = 0;
	}
	else
	{
		m_BeaconLevel = CalculatePyramidLevel();
		m_IsActive = (m_BeaconLevel > 0);
	}

	if (m_BeaconLevel != OldBeaconLevel)
	{
		// Send window update:
		if (GetWindow() != nullptr)
		{
			GetWindow()->SetProperty(0, m_BeaconLevel);
		}
	}

	// TODO: Add achievement
}

void cBeaconEntity::GiveEffects(void)
{
	if (!m_IsActive || (m_BeaconLevel < 0))
	{
		return;
	}

	int Radius = m_BeaconLevel * 10 + 10;
	short EffectLevel = 0;
	if ((m_BeaconLevel >= 4) && (m_PrimaryEffect == m_SecondaryEffect))
	{
		EffectLevel = 1;
	}

	cEntityEffect::eType SecondaryEffect = cEntityEffect::effNoEffect;
	if ((m_BeaconLevel >= 4) && (m_PrimaryEffect != m_SecondaryEffect) && (m_SecondaryEffect > 0))
	{
		SecondaryEffect = m_SecondaryEffect;
	}

	class cPlayerCallback : public cPlayerListCallback
	{
		int m_Radius;
		int m_PosX, m_PosY, m_PosZ;
		cEntityEffect::eType m_PrimaryEffect, m_SecondaryEffect;
		short m_EffectLevel;

		virtual bool Item(cPlayer * a_Player)
		{
			Vector3d PlayerPosition = Vector3d(a_Player->GetPosition());
			if (PlayerPosition.y > static_cast<double>(m_PosY))
			{
				PlayerPosition.y = static_cast<double>(m_PosY);
			}

			// TODO: Vanilla minecraft uses an AABB check instead of a radius one
			Vector3d BeaconPosition = Vector3d(m_PosX, m_PosY, m_PosZ);
			if ((PlayerPosition - BeaconPosition).Length() <= m_Radius)
			{
				a_Player->AddEntityEffect(m_PrimaryEffect, 180, m_EffectLevel);

				if (m_SecondaryEffect != cEntityEffect::effNoEffect)
				{
					a_Player->AddEntityEffect(m_SecondaryEffect, 180, 0);
				}
			}
			return false;
		}

	public:
		cPlayerCallback(int a_Radius, int a_PosX, int a_PosY, int a_PosZ, cEntityEffect::eType a_PrimaryEffect, cEntityEffect::eType a_SecondaryEffect, short a_EffectLevel):
			m_Radius(a_Radius),
			m_PosX(a_PosX),
			m_PosY(a_PosY),
			m_PosZ(a_PosZ),
			m_PrimaryEffect(a_PrimaryEffect),
			m_SecondaryEffect(a_SecondaryEffect),
			m_EffectLevel(a_EffectLevel)
		{
		}

	} PlayerCallback(Radius, m_PosX, m_PosY, m_PosZ, m_PrimaryEffect, SecondaryEffect, EffectLevel);
	GetWorld()->ForEachPlayer(PlayerCallback);
}

void cBeaconEntity::CopyFrom(const cBlockEntity & a_Src)
{
	Super::CopyFrom(a_Src);
	auto & src = reinterpret_cast<const cBeaconEntity &>(a_Src);
	m_BeaconLevel = src.m_BeaconLevel;
	m_Contents.CopyFrom(src.m_Contents);
	m_IsActive = src.m_IsActive;
	m_PrimaryEffect = src.m_PrimaryEffect;
	m_SecondaryEffect = src.m_SecondaryEffect;
}

void cBeaconEntity::SendTo(cClientHandle & a_Client)
{
	a_Client.SendUpdateBlockEntity(*this);
}

bool cBeaconEntity::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
{
	// Update the beacon every 4 seconds
	if ((GetWorld()->GetWorldAge() % 80) == 0)
	{
		UpdateBeacon();
		GiveEffects();
	}
	return false;
}

bool cBeaconEntity::UsedBy(cPlayer * a_Player)
{
	cWindow * Window = GetWindow();
	if (Window == nullptr)
	{
		OpenWindow(new cBeaconWindow(m_PosX, m_PosY, m_PosZ, this));
		Window = GetWindow();
	}

	if (Window != nullptr)
	{
		// if (a_Player->GetWindow() != Window)
		// -> Because mojang doesn't send a 'close window' packet when you click the cancel button in the beacon inventory ...
		{
			a_Player->OpenWindow(*Window);
		}
	}
	return true;
}

<commit_msg>cBeaconEntity fix no world crash<commit_after>
#include "Globals.h"  // NOTE: MSVC stupidness requires this to be the same across all modules

#include "BeaconEntity.h"
#include "../BlockArea.h"
#include "../Entities/Player.h"
#include "../UI/BeaconWindow.h"
#include "../ClientHandle.h"

cBeaconEntity::cBeaconEntity(BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World):
	Super(a_BlockType, a_BlockMeta, a_BlockX, a_BlockY, a_BlockZ, 1, 1, a_World),
	m_IsActive(false),
	m_BeaconLevel(0),
	m_PrimaryEffect(cEntityEffect::effNoEffect),
	m_SecondaryEffect(cEntityEffect::effNoEffect)
{
	ASSERT(a_BlockType == E_BLOCK_BEACON);
	if (m_World != nullptr)
	{
		UpdateBeacon();
	}
}

char cBeaconEntity::CalculatePyramidLevel(void)
{
	cBlockArea Area;
	int MinY = std::max(GetPosY() - 4, 0);
	int MaxY = std::max(GetPosY() - 1, 0);

	Area.Read(
		*m_World,
		GetPosX() - 4, GetPosX() + 4,
		MinY, MaxY,
		GetPosZ() - 4, GetPosZ() + 4,
		cBlockArea::baTypes
	);

	int Layer = 1;
	int MiddleXZ = 4;

	for (int Y = (Area.GetSizeY() - 1); Y >= 0; Y--)
	{
		for (int X = MiddleXZ - Layer; X <= (MiddleXZ + Layer); X++)
		{
			for (int Z = MiddleXZ - Layer; Z <= (MiddleXZ + Layer); Z++)
			{
				if (!IsMineralBlock(Area.GetRelBlockType(X, Y, Z)))
				{
					return static_cast<char>(Layer - 1);
				}
			}
		}
		Layer++;
	}

	return static_cast<char>(Layer - 1);
}

bool cBeaconEntity::IsValidEffect(cEntityEffect::eType a_Effect, char a_BeaconLevel)
{
	switch (a_Effect)
	{
		case cEntityEffect::effRegeneration: return (a_BeaconLevel >= 4);
		case cEntityEffect::effStrength:     return (a_BeaconLevel >= 3);
		case cEntityEffect::effResistance:   return (a_BeaconLevel >= 2);
		case cEntityEffect::effJumpBoost:    return (a_BeaconLevel >= 2);
		case cEntityEffect::effSpeed:        return (a_BeaconLevel >= 1);
		case cEntityEffect::effHaste:        return (a_BeaconLevel >= 1);
		case cEntityEffect::effNoEffect:     return true;

		default:
		{
			LOGD("%s: Invalid beacon effect: %d", __FUNCTION__, static_cast<int>(a_Effect));
			return false;
		}
	}
}

bool cBeaconEntity::SetPrimaryEffect(cEntityEffect::eType a_Effect)
{
	if (!IsValidEffect(a_Effect, m_BeaconLevel))
	{
		m_PrimaryEffect = cEntityEffect::effNoEffect;
		return false;
	}

	m_PrimaryEffect = a_Effect;

	// Send window update:
	if (GetWindow() != nullptr)
	{
		GetWindow()->SetProperty(1, m_PrimaryEffect);
	}
	return true;
}

bool cBeaconEntity::SetSecondaryEffect(cEntityEffect::eType a_Effect)
{
	if (!IsValidEffect(a_Effect, m_BeaconLevel))
	{
		m_SecondaryEffect = cEntityEffect::effNoEffect;
		return false;
	}

	m_SecondaryEffect = a_Effect;

	// Send window update:
	if (GetWindow() != nullptr)
	{
		GetWindow()->SetProperty(2, m_SecondaryEffect);
	}
	return true;
}

bool cBeaconEntity::IsBeaconBlocked(void)
{
	for (int Y = m_PosY; Y < cChunkDef::Height; ++Y)
	{
		BLOCKTYPE Block = m_World->GetBlock(m_PosX, Y, m_PosZ);
		if (!cBlockInfo::IsTransparent(Block))
		{
			return true;
		}
	}
	return false;
}

bool cBeaconEntity::IsMineralBlock(BLOCKTYPE a_BlockType)
{
	switch (a_BlockType)
	{
		case E_BLOCK_DIAMOND_BLOCK:
		case E_BLOCK_GOLD_BLOCK:
		case E_BLOCK_IRON_BLOCK:
		case E_BLOCK_EMERALD_BLOCK:
		{
			return true;
		}
	}
	return false;
}

void cBeaconEntity::UpdateBeacon(void)
{
	int OldBeaconLevel = m_BeaconLevel;

	if (IsBeaconBlocked())
	{
		m_IsActive = false;
		m_BeaconLevel = 0;
	}
	else
	{
		m_BeaconLevel = CalculatePyramidLevel();
		m_IsActive = (m_BeaconLevel > 0);
	}

	if (m_BeaconLevel != OldBeaconLevel)
	{
		// Send window update:
		if (GetWindow() != nullptr)
		{
			GetWindow()->SetProperty(0, m_BeaconLevel);
		}
	}

	// TODO: Add achievement
}

void cBeaconEntity::GiveEffects(void)
{
	if (!m_IsActive || (m_BeaconLevel < 0))
	{
		return;
	}

	int Radius = m_BeaconLevel * 10 + 10;
	short EffectLevel = 0;
	if ((m_BeaconLevel >= 4) && (m_PrimaryEffect == m_SecondaryEffect))
	{
		EffectLevel = 1;
	}

	cEntityEffect::eType SecondaryEffect = cEntityEffect::effNoEffect;
	if ((m_BeaconLevel >= 4) && (m_PrimaryEffect != m_SecondaryEffect) && (m_SecondaryEffect > 0))
	{
		SecondaryEffect = m_SecondaryEffect;
	}

	class cPlayerCallback : public cPlayerListCallback
	{
		int m_Radius;
		int m_PosX, m_PosY, m_PosZ;
		cEntityEffect::eType m_PrimaryEffect, m_SecondaryEffect;
		short m_EffectLevel;

		virtual bool Item(cPlayer * a_Player)
		{
			Vector3d PlayerPosition = Vector3d(a_Player->GetPosition());
			if (PlayerPosition.y > static_cast<double>(m_PosY))
			{
				PlayerPosition.y = static_cast<double>(m_PosY);
			}

			// TODO: Vanilla minecraft uses an AABB check instead of a radius one
			Vector3d BeaconPosition = Vector3d(m_PosX, m_PosY, m_PosZ);
			if ((PlayerPosition - BeaconPosition).Length() <= m_Radius)
			{
				a_Player->AddEntityEffect(m_PrimaryEffect, 180, m_EffectLevel);

				if (m_SecondaryEffect != cEntityEffect::effNoEffect)
				{
					a_Player->AddEntityEffect(m_SecondaryEffect, 180, 0);
				}
			}
			return false;
		}

	public:
		cPlayerCallback(int a_Radius, int a_PosX, int a_PosY, int a_PosZ, cEntityEffect::eType a_PrimaryEffect, cEntityEffect::eType a_SecondaryEffect, short a_EffectLevel):
			m_Radius(a_Radius),
			m_PosX(a_PosX),
			m_PosY(a_PosY),
			m_PosZ(a_PosZ),
			m_PrimaryEffect(a_PrimaryEffect),
			m_SecondaryEffect(a_SecondaryEffect),
			m_EffectLevel(a_EffectLevel)
		{
		}

	} PlayerCallback(Radius, m_PosX, m_PosY, m_PosZ, m_PrimaryEffect, SecondaryEffect, EffectLevel);
	GetWorld()->ForEachPlayer(PlayerCallback);
}

void cBeaconEntity::CopyFrom(const cBlockEntity & a_Src)
{
	Super::CopyFrom(a_Src);
	auto & src = reinterpret_cast<const cBeaconEntity &>(a_Src);
	m_BeaconLevel = src.m_BeaconLevel;
	m_Contents.CopyFrom(src.m_Contents);
	m_IsActive = src.m_IsActive;
	m_PrimaryEffect = src.m_PrimaryEffect;
	m_SecondaryEffect = src.m_SecondaryEffect;
}

void cBeaconEntity::SendTo(cClientHandle & a_Client)
{
	a_Client.SendUpdateBlockEntity(*this);
}

bool cBeaconEntity::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
{
	// Update the beacon every 4 seconds
	if ((GetWorld()->GetWorldAge() % 80) == 0)
	{
		UpdateBeacon();
		GiveEffects();
	}
	return false;
}

bool cBeaconEntity::UsedBy(cPlayer * a_Player)
{
	cWindow * Window = GetWindow();
	if (Window == nullptr)
	{
		OpenWindow(new cBeaconWindow(m_PosX, m_PosY, m_PosZ, this));
		Window = GetWindow();
	}

	if (Window != nullptr)
	{
		// if (a_Player->GetWindow() != Window)
		// -> Because mojang doesn't send a 'close window' packet when you click the cancel button in the beacon inventory ...
		{
			a_Player->OpenWindow(*Window);
		}
	}
	return true;
}

<|endoftext|>


<commit_before><commit_msg>use p for momentum threshold of protons<commit_after><|endoftext|>


<commit_before>#include "Definitions.h"
#include "Simulator.h"

#include "cpplog/cpplog.hpp"

#include <boost/filesystem.hpp>
#include <boost/make_shared.hpp>

int main(int argc, char **argv)
{
    auto logger = boost::make_shared<cpplog::StdErrLogger>();
    state state0;
    state0.V = -70;
    state0.h = 1.0;
    state0.n = 0.0;
    state0.z = 0.0;
    state0.s_AMPA = 0.0;
    state0.s_NMDA = 0.0;
    state0.x_NMDA = 0.0;
    state0.s_GABAA = 0.0;
    state0.I_app = 1.0;

    auto path = boost::filesystem3::path(CL_SOURCE_DIR);
    path /= "/kernels.cl";

    Simulator sim = Simulator(
        800,
        5000,
        0.1f,
        state0,
        false,
        true,
        path,
        logger);

    sim.simulate();

    exit(0);
}<commit_msg>program options<commit_after>#include "Definitions.h"
#include "Simulator.h"
#include "util.h"

#include "cpplog/cpplog.hpp"

#include <numeric>

#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

namespace po = boost::program_options;

void measureTimes(Logger const& logger, state const& state0, boost::filesystem3::path const& path)
{
    const unsigned int start = 0;
    const unsigned int powers = 10;

    std::vector<const unsigned int> numNeurons;
    std::vector<const double> avgTimesCalculations;
    std::vector<const double> avgTimesFFTW;
    std::vector<const double> avgTimesClFFT;

    for(int i = start; i < powers; ++i)
    {
        auto neurons = static_cast<const unsigned int>(pow(2.f, i));
        numNeurons.push_back(neurons);

        Simulator sim = Simulator(
            neurons,
            500,
            0.1f,
            state0,
            Simulator::NO_PLOT,
            Simulator::MEASURE,
            Simulator::FFTW,
            Simulator::CLFFT,
            path,
            logger);

        sim.simulate();

        auto timesCalculations = sim.getTimesCalculations();
        auto timesFFTW = sim.getTimesFFTW();
        auto timesClFFT = sim.getTimesClFFT();

        avgTimesCalculations.push_back(
            std::accumulate(
                timesCalculations.begin(),
                timesCalculations.end(), 0.0)
            / timesCalculations.size());

        avgTimesFFTW.push_back(
            std::accumulate(
            timesFFTW.begin(),
            timesFFTW.end(), 0.0)
            / timesFFTW.size());

        avgTimesClFFT.push_back(
            std::accumulate(
            timesClFFT.begin(),
            timesClFFT.end(), 0.0)
            / timesClFFT.size());
    }

    for(int i = 0; i < powers - start; ++i)
    {
        std::cout << static_cast<const unsigned int>(pow(2.f, (int)(i + start))) << "\t" << avgTimesCalculations[i] << "\t" << avgTimesFFTW[i] << "\t" << avgTimesClFFT[i] << std::endl;
    }
}

int main(int ac, char **av)
{
    float V0, h0, n0, z0, sAMPA0, sNMDA0, xNMDA0, sGABAA0, IApp0, dt;
    unsigned int numNeurons, timesteps;
    std::string plot, measure, fftw, clfft;

    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "produce help message")
        ("V", po::value<float>(&V0)->default_value(-70.0), "initial value for membrane potential")
        ("h", po::value<float>(&h0)->default_value(1.0), "initial value for h")
        ("n", po::value<float>(&n0)->default_value(0.0), "initial value for n")
        ("z", po::value<float>(&z0)->default_value(0.0), "initial value for z")
        ("sAMPA", po::value<float>(&sAMPA0)->default_value(0.0), "initial value for sAMPA")
        ("sNMDA", po::value<float>(&sNMDA0)->default_value(0.0), "initial value for sNMDA")
        ("xNMDA", po::value<float>(&xNMDA0)->default_value(0.0), "initial value for xNMDA")
        ("sGABAA", po::value<float>(&sGABAA0)->default_value(0.0), "initial value for xNMDA")
        ("IApp", po::value<float>(&IApp0)->default_value(1.0), "initial value for IApp")
        ("dt", po::value<float>(&dt)->default_value(0.1f), "length of one timestep")
        ("timesteps", po::value<unsigned int>(&timesteps)->default_value(500), "number of timesteps")
        ("neurons", po::value<unsigned int>(&numNeurons)->default_value(1024), "number of neurons in network")
        ("plot", po::value<std::string>(&plot)->default_value("true"), "plot results")
        ("measure", po::value<std::string>(&measure)->default_value("true"), "measure execution time")
        ("fftw", po::value<std::string>(&fftw)->default_value("false"), "compute synaptic fields using fftw")
        ("clfft", po::value<std::string>(&clfft)->default_value("true"), "compute synaptic fields using clFFT")
    ;

    po::variables_map vm;
    po::store(po::parse_command_line(ac, av, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        cout << desc << "\n";
        exit(1);
    }

    auto logger = make_shared<cpplog::StdErrLogger>();
    state state0;
    state0.V = V0;
    state0.h = h0;
    state0.n = n0;
    state0.z = z0;
    state0.s_AMPA = sAMPA0;
    state0.s_NMDA = sNMDA0;
    state0.x_NMDA = xNMDA0;
    state0.s_GABAA = sGABAA0;
    state0.I_app = IApp0;

    auto path = boost::filesystem3::path(CL_SOURCE_DIR);
    path /= "/kernels.cl";

    Simulator sim = Simulator(
        numNeurons,
        timesteps,
        dt,
        state0,
        stringToBool(plot) ? Simulator::PLOT : Simulator::NO_PLOT,
        stringToBool(measure) ? Simulator::MEASURE : Simulator::NO_MEASURE,
        stringToBool(fftw) ? Simulator::FFTW : Simulator::NO_FFTW,
        stringToBool(clfft) ? Simulator::CLFFT : Simulator::NO_CLFFT,
        path,
        logger);

    sim.simulate();

    ////measureTimes(logger, state0, path);

    exit(0);
}<|endoftext|>


<commit_before>template <class T> struct F {};
template <class T> class I {
  F<T> m;
};
struct C {
  typedef short char_type;
  typedef F<char_type> f;       // commenting this line out fixes it!
  typedef I<char_type> i;
};
<commit_msg>minor change<commit_after>template <class T> struct F {};
template <class T> struct I {
  F<T> m;
};
struct C {
  typedef short char_type;
  typedef F<char_type> f;       // commenting this line out fixes it!
  typedef I<char_type> i;
};
<|endoftext|>