<commit_before>// @(#)root/gpad:$Id$
// Author: Nenad Buncic   20/02/96

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

/////////////////////////////////////////////////////////////////////////
//                                                                     //
//   ControlBar is fully user configurable tool which provides fast    //
// access to frequently used operations. User can choose between       //
// buttons and drawnbuttons (let's say icons) and assign to them his   //
// own actions (let's say ROOT or C++ commands).                       //
//
// The macro belows shows an example of controlbar.
// To execute an item, click with the left mouse button.
// To see the HELP of a button, click on the right mouse button.
//
// You have access to the last clicked button via the method
// GetClicked(). For example, bar->GetClicked()->GetName()
// will return the name of the last clicked button.
//
//
//{
//   gROOT.Reset("a");
//   TControlBar bar("vertical");
//   bar.AddButton("Help to run demos",".x demoshelp.C",
//                 "Explains how to run the demos");
//   bar.AddButton("framework",        ".x framework.C",
//                 "An Example of Object Oriented User Interface");
//   bar.AddButton("hsimple",          ".x hsimple.C",
//                 "An Example Creating Histograms/Ntuples on File");
//   bar.AddButton("hsum",             ".x hsum.C",
//                 "Filling histograms and some graphics options");
//   bar.AddButton("canvas",           ".x canvas.C",
//                 "Canvas and Pad Management");
//   bar.AddButton("formula1",         ".x formula1.C",
//                 "Simple Formula and Functions");
//   bar.AddButton("fillrandom",       ".x fillrandom.C",
//                 "Histograms with Random Numbers from a Function");
//   bar.AddButton("fit1",             ".x fit1.C",
//                 "A Simple Fitting Example");
//   bar.AddButton("h1draw",           ".x h1draw.C",
//                 "Drawing Options for 1D Histograms");
//   bar.AddButton("graph",            ".x graph.C",
//                 "Examples of a simple graph");
//   bar.AddButton("tornado",          ".x tornado.C",
//                 "Examples of 3-D PolyMarkers");
//   bar.AddButton("shapes",           ".x shapes.C",
//                 "The Geometry Shapes");
//   bar.AddButton("atlasna49",        ".x atlasna49.C",
//                 "Creating and Viewing Geometries");
//   bar.AddButton("file_layout",      ".x file.C",
//                 "The ROOT file format");
//   bar.AddButton("tree_layout",      ".x tree.C",
//                 "The Tree Data Structure");
//   bar.AddButton("ntuple1",          ".x ntuple1.C",
//                 "Ntuples and Selections");
//   bar.AddButton("run benchmarks",   ".x benchmarks.C",
//                 "Runs all the ROOT benchmarks");
//   bar.AddButton("rootmarks",        ".x rootmarks.C",
//                 "Prints an estimated ROOTMARKS for your machine");
//   bar.AddButton("edit_hsimple",     ".!ved hsimple.C &",
//                 "Invokes the text editor on file hsimple.C");
//   bar.AddButton("Close Bar",        "gROOT.Reset(\"a\")",
//                 "Close ControlBar");
//   bar.Show();
//   gROOT.SaveContext();
//}
//
//Begin_Html
/*

*/
//End_Html
//
//                                                                     //
/////////////////////////////////////////////////////////////////////////

#include "TControlBar.h"
#include "TGuiFactory.h"
#include "TList.h"
#include "TStyle.h"

ClassImp(TControlBar)

//_______________________________________________________________________
TControlBar::TControlBar() : TControlBarButton()
{
   // Default constructor.

   fControlBarImp = 0;
   fOrientation   = 0;
   fButtons       = 0;
   fNoroc         = 1;
}

//_______________________________________________________________________
TControlBar::TControlBar(const char *orientation, const char *title)
            : TControlBarButton(title, "", "", "button")

{
   // Normal constructor.

   SetOrientation( orientation );
   Initialize(-999, -999);
}

//_______________________________________________________________________
TControlBar::TControlBar(const char *orientation, const char *title, Int_t x, Int_t y)
            : TControlBarButton(title, "", "", "button")

{
   // Normal constructor.

   Int_t xs = (Int_t)(x*gStyle->GetScreenFactor());
   Int_t ys = (Int_t)(y*gStyle->GetScreenFactor());
   SetOrientation( orientation );
   Initialize(xs, ys);
}

//_______________________________________________________________________
TControlBar::~TControlBar()
{
   // Destructor.

   delete fControlBarImp;

   if( fButtons )
      fButtons->Delete();

   fButtons       = 0;
   fControlBarImp = 0;
}

//_______________________________________________________________________
void TControlBar::AddButton(TControlBarButton &button)
{
   // Add button.

   AddButton( &button );
}

//_______________________________________________________________________
void TControlBar::AddButton(TControlBarButton *button)
{
   // Add button.

   if( fButtons && button )
      fButtons->Add( button );
}

//_______________________________________________________________________
void TControlBar::AddButton(const char *label, const char *action, const char *hint, const char *type)
{
   // Add button.

   TControlBarButton *button = new TControlBarButton( label, action, hint, type );
   AddButton( button );
}

//_______________________________________________________________________
void TControlBar::AddControlBar(TControlBar &controlBar)
{
   // Add controlbar.

   AddControlBar( &controlBar );
}

//_______________________________________________________________________
void TControlBar::AddControlBar(TControlBar *controlBar)
{
   // Add controlbar.

   if( fButtons && controlBar )
      fButtons->Add( controlBar );
}

//_______________________________________________________________________
void TControlBar::AddSeparator()
{
   // Add separator.
}

//_______________________________________________________________________
void TControlBar::Create()
{
   // Create controlbar.

   if( fControlBarImp ) {
      fControlBarImp->Create();
   }
}

//_______________________________________________________________________
void TControlBar::Hide()
{
   // Hide controlbar.

   if( fControlBarImp ) {
      fControlBarImp->Hide();
   }
}

//_______________________________________________________________________
void TControlBar::Initialize(Int_t x, Int_t y)
{
   // Initialize controlbar.

   if (x == -999) {
      fControlBarImp = gGuiFactory->CreateControlBarImp( this, GetName() );
   } else {
      fControlBarImp = gGuiFactory->CreateControlBarImp( this, GetName(), x, y );
   }

   fButtons       = new TList();
   fNoroc         = 1;
}

//_______________________________________________________________________
void TControlBar::SetFont(const char *fontName)
{
   // Sets new font for control bar buttons, e.g.:
   // root > .x tutorials/demos.C
   // root > bar->SetFont("-adobe-helvetica-bold-r-*-*-24-*-*-*-*-*-iso8859-1")

   fControlBarImp->SetFont(fontName);
}

//_______________________________________________________________________
void TControlBar::SetTextColor(const char *colorName)
{
   // Sets text color for control bar buttons, e.g.:
   // root > .x tutorials/demos.C
   // root > bar->SetTextColor("red")

   fControlBarImp->SetTextColor(colorName);
}

//_______________________________________________________________________
void TControlBar::SetButtonState(const char *label, Int_t state)
{
   // Sets a state for control bar button 'label'; possible states are
   // 0-kButtonUp, 1-kButtonDown, 2-kButtonEngaged, 3-kButtonDisabled,
   // e.g.:
   // root > .x tutorials/demos.C
   // to disable the button 'first' do:
   // root > bar->SetButtonState("first", 3)
   // to enable the button 'first' do:
   // root > bar->SetButtonState("first", 0)

   if (state > 3) {
      Error("SetButtonState", "not valid button state (expecting 0, 1, 2 or 3)");
      return;
   }
   fControlBarImp->SetButtonState(label, state);
}

 //_______________________________________________________________________
void TControlBar::SetButtonWidth(UInt_t width)
{
   // Sets the width in pixels for control bar button.

   fControlBarImp->SetButtonWidth(width);
}

//_______________________________________________________________________
void TControlBar::SetOrientation(const char *o)
{
   // Set controlbar orientation.

   fOrientation = kVertical;

   if( *o ) {
      if( !strcasecmp( o, "vertical" ) )
         fOrientation = kVertical;
      else if( !strcasecmp( o, "horizontal" ) )
         fOrientation = kHorizontal;
      else
         Error( "SetOrientation", "Unknown orientation: '%s' !\n\t\t(choice of: %s, %s)",
                 o, "vertical", "horizontal" );
   }
}

//_______________________________________________________________________
void TControlBar::SetOrientation(Int_t o)
{
   // Set controlbar orientation.

   fOrientation = kVertical;

   if( ( o == kVertical ) || ( o == kHorizontal ) )
      fOrientation = o;
   else
      Error( "SetOrientation", "Unknown orientation: %d !\n\t\t(choice of: %d, %d)",
              o, kVertical, kHorizontal );
}

//_______________________________________________________________________
void TControlBar::Show()
{
   // Show controlbar.

   if( fControlBarImp )
      fControlBarImp->Show();
}

//_______________________________________________________________________
TControlBarButton *TControlBar::GetClicked() const
{
   // Returns a pointer to the last clicked controlbar button;
   // null if no button was clicked yet

   if (!fControlBarImp->GetClicked())
      Printf("None of the controlbar buttons is clicked yet");
   return fControlBarImp->GetClicked();
}
<commit_msg>Load and initialize graphics libraries when using TControlBar (needed by demos.C)<commit_after>// @(#)root/gpad:$Id$
// Author: Nenad Buncic   20/02/96

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

/////////////////////////////////////////////////////////////////////////
//                                                                     //
//   ControlBar is fully user configurable tool which provides fast    //
// access to frequently used operations. User can choose between       //
// buttons and drawnbuttons (let's say icons) and assign to them his   //
// own actions (let's say ROOT or C++ commands).                       //
//
// The macro belows shows an example of controlbar.
// To execute an item, click with the left mouse button.
// To see the HELP of a button, click on the right mouse button.
//
// You have access to the last clicked button via the method
// GetClicked(). For example, bar->GetClicked()->GetName()
// will return the name of the last clicked button.
//
//
//{
//   gROOT.Reset("a");
//   TControlBar bar("vertical");
//   bar.AddButton("Help to run demos",".x demoshelp.C",
//                 "Explains how to run the demos");
//   bar.AddButton("framework",        ".x framework.C",
//                 "An Example of Object Oriented User Interface");
//   bar.AddButton("hsimple",          ".x hsimple.C",
//                 "An Example Creating Histograms/Ntuples on File");
//   bar.AddButton("hsum",             ".x hsum.C",
//                 "Filling histograms and some graphics options");
//   bar.AddButton("canvas",           ".x canvas.C",
//                 "Canvas and Pad Management");
//   bar.AddButton("formula1",         ".x formula1.C",
//                 "Simple Formula and Functions");
//   bar.AddButton("fillrandom",       ".x fillrandom.C",
//                 "Histograms with Random Numbers from a Function");
//   bar.AddButton("fit1",             ".x fit1.C",
//                 "A Simple Fitting Example");
//   bar.AddButton("h1draw",           ".x h1draw.C",
//                 "Drawing Options for 1D Histograms");
//   bar.AddButton("graph",            ".x graph.C",
//                 "Examples of a simple graph");
//   bar.AddButton("tornado",          ".x tornado.C",
//                 "Examples of 3-D PolyMarkers");
//   bar.AddButton("shapes",           ".x shapes.C",
//                 "The Geometry Shapes");
//   bar.AddButton("atlasna49",        ".x atlasna49.C",
//                 "Creating and Viewing Geometries");
//   bar.AddButton("file_layout",      ".x file.C",
//                 "The ROOT file format");
//   bar.AddButton("tree_layout",      ".x tree.C",
//                 "The Tree Data Structure");
//   bar.AddButton("ntuple1",          ".x ntuple1.C",
//                 "Ntuples and Selections");
//   bar.AddButton("run benchmarks",   ".x benchmarks.C",
//                 "Runs all the ROOT benchmarks");
//   bar.AddButton("rootmarks",        ".x rootmarks.C",
//                 "Prints an estimated ROOTMARKS for your machine");
//   bar.AddButton("edit_hsimple",     ".!ved hsimple.C &",
//                 "Invokes the text editor on file hsimple.C");
//   bar.AddButton("Close Bar",        "gROOT.Reset(\"a\")",
//                 "Close ControlBar");
//   bar.Show();
//   gROOT.SaveContext();
//}
//
//Begin_Html
/*

*/
//End_Html
//
//                                                                     //
/////////////////////////////////////////////////////////////////////////

#include "TApplication.h"
#include "TControlBar.h"
#include "TGuiFactory.h"
#include "TList.h"
#include "TStyle.h"

ClassImp(TControlBar)

//_______________________________________________________________________
TControlBar::TControlBar() : TControlBarButton()
{
   // Default constructor.

   fControlBarImp = 0;
   fOrientation   = 0;
   fButtons       = 0;
   fNoroc         = 1;
}

//_______________________________________________________________________
TControlBar::TControlBar(const char *orientation, const char *title)
            : TControlBarButton(title, "", "", "button")

{
   // Normal constructor.

   SetOrientation( orientation );
   Initialize(-999, -999);
}

//_______________________________________________________________________
TControlBar::TControlBar(const char *orientation, const char *title, Int_t x, Int_t y)
            : TControlBarButton(title, "", "", "button")

{
   // Normal constructor.

   Int_t xs = (Int_t)(x*gStyle->GetScreenFactor());
   Int_t ys = (Int_t)(y*gStyle->GetScreenFactor());
   SetOrientation( orientation );
   Initialize(xs, ys);
}

//_______________________________________________________________________
TControlBar::~TControlBar()
{
   // Destructor.

   delete fControlBarImp;

   if( fButtons )
      fButtons->Delete();

   fButtons       = 0;
   fControlBarImp = 0;
}

//_______________________________________________________________________
void TControlBar::AddButton(TControlBarButton &button)
{
   // Add button.

   AddButton( &button );
}

//_______________________________________________________________________
void TControlBar::AddButton(TControlBarButton *button)
{
   // Add button.

   if( fButtons && button )
      fButtons->Add( button );
}

//_______________________________________________________________________
void TControlBar::AddButton(const char *label, const char *action, const char *hint, const char *type)
{
   // Add button.

   TControlBarButton *button = new TControlBarButton( label, action, hint, type );
   AddButton( button );
}

//_______________________________________________________________________
void TControlBar::AddControlBar(TControlBar &controlBar)
{
   // Add controlbar.

   AddControlBar( &controlBar );
}

//_______________________________________________________________________
void TControlBar::AddControlBar(TControlBar *controlBar)
{
   // Add controlbar.

   if( fButtons && controlBar )
      fButtons->Add( controlBar );
}

//_______________________________________________________________________
void TControlBar::AddSeparator()
{
   // Add separator.
}

//_______________________________________________________________________
void TControlBar::Create()
{
   // Create controlbar.

   if( fControlBarImp ) {
      fControlBarImp->Create();
   }
}

//_______________________________________________________________________
void TControlBar::Hide()
{
   // Hide controlbar.

   if( fControlBarImp ) {
      fControlBarImp->Hide();
   }
}

//_______________________________________________________________________
void TControlBar::Initialize(Int_t x, Int_t y)
{
   // Initialize controlbar.

   // Load and initialize graphics libraries if
   // TApplication::NeedGraphicsLibs() has been called by a
   // library static initializer.
   if (gApplication)
      gApplication->InitializeGraphics();

   if (x == -999) {
      fControlBarImp = gGuiFactory->CreateControlBarImp( this, GetName() );
   } else {
      fControlBarImp = gGuiFactory->CreateControlBarImp( this, GetName(), x, y );
   }

   fButtons       = new TList();
   fNoroc         = 1;
}

//_______________________________________________________________________
void TControlBar::SetFont(const char *fontName)
{
   // Sets new font for control bar buttons, e.g.:
   // root > .x tutorials/demos.C
   // root > bar->SetFont("-adobe-helvetica-bold-r-*-*-24-*-*-*-*-*-iso8859-1")

   fControlBarImp->SetFont(fontName);
}

//_______________________________________________________________________
void TControlBar::SetTextColor(const char *colorName)
{
   // Sets text color for control bar buttons, e.g.:
   // root > .x tutorials/demos.C
   // root > bar->SetTextColor("red")

   fControlBarImp->SetTextColor(colorName);
}

//_______________________________________________________________________
void TControlBar::SetButtonState(const char *label, Int_t state)
{
   // Sets a state for control bar button 'label'; possible states are
   // 0-kButtonUp, 1-kButtonDown, 2-kButtonEngaged, 3-kButtonDisabled,
   // e.g.:
   // root > .x tutorials/demos.C
   // to disable the button 'first' do:
   // root > bar->SetButtonState("first", 3)
   // to enable the button 'first' do:
   // root > bar->SetButtonState("first", 0)

   if (state > 3) {
      Error("SetButtonState", "not valid button state (expecting 0, 1, 2 or 3)");
      return;
   }
   fControlBarImp->SetButtonState(label, state);
}

 //_______________________________________________________________________
void TControlBar::SetButtonWidth(UInt_t width)
{
   // Sets the width in pixels for control bar button.

   fControlBarImp->SetButtonWidth(width);
}

//_______________________________________________________________________
void TControlBar::SetOrientation(const char *o)
{
   // Set controlbar orientation.

   fOrientation = kVertical;

   if( *o ) {
      if( !strcasecmp( o, "vertical" ) )
         fOrientation = kVertical;
      else if( !strcasecmp( o, "horizontal" ) )
         fOrientation = kHorizontal;
      else
         Error( "SetOrientation", "Unknown orientation: '%s' !\n\t\t(choice of: %s, %s)",
                 o, "vertical", "horizontal" );
   }
}

//_______________________________________________________________________
void TControlBar::SetOrientation(Int_t o)
{
   // Set controlbar orientation.

   fOrientation = kVertical;

   if( ( o == kVertical ) || ( o == kHorizontal ) )
      fOrientation = o;
   else
      Error( "SetOrientation", "Unknown orientation: %d !\n\t\t(choice of: %d, %d)",
              o, kVertical, kHorizontal );
}

//_______________________________________________________________________
void TControlBar::Show()
{
   // Show controlbar.

   if( fControlBarImp )
      fControlBarImp->Show();
}

//_______________________________________________________________________
TControlBarButton *TControlBar::GetClicked() const
{
   // Returns a pointer to the last clicked controlbar button;
   // null if no button was clicked yet

   if (!fControlBarImp->GetClicked())
      Printf("None of the controlbar buttons is clicked yet");
   return fControlBarImp->GetClicked();
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 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/extensions/extension_creator.h"

#include <vector>
#include <string>

#include "base/crypto/rsa_private_key.h"
#include "base/crypto/signature_creator.h"
#include "base/file_util.h"
#include "base/scoped_handle.h"
#include "base/string_util.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/zip.h"
#include "net/base/base64.h"

namespace {
  const int kRSAKeySize = 1024;
};

const char ExtensionCreator::kExtensionHeaderMagic[] = "Cr24";

bool ExtensionCreator::InitializeInput(
    const FilePath& extension_dir,
    const FilePath& private_key_path,
    const FilePath& private_key_output_path) {
  // Validate input |extension_dir|.
  if (extension_dir.value().empty() ||
      !file_util::DirectoryExists(extension_dir)) {
    error_message_ = "Input directory must exist.";
    return false;
  }

  // Validate input |private_key| (if provided).
  if (!private_key_path.value().empty() &&
      !file_util::PathExists(private_key_path)) {
    error_message_ = "Input value for private key must be a valid path.";
    return false;
  }

  // If an |output_private_key| path is given, make sure it doesn't over-write
  // an existing private key.
  if (private_key_path.value().empty() &&
      !private_key_output_path.value().empty() &&
      file_util::PathExists(private_key_output_path)) {
      error_message_ = "Private key exists next to input directory. Try using "
          "--pack-extension-key";
      return false;
  }

  return true;
}

base::RSAPrivateKey* ExtensionCreator::ReadInputKey(const FilePath&
    private_key_path) {
  if (!file_util::PathExists(private_key_path)) {
    error_message_ = "Input value for private key must exist.";
    return false;
  }

  std::string private_key_contents;
  if (!file_util::ReadFileToString(private_key_path,
      &private_key_contents)) {
    error_message_ = "Failed to read private key.";
    return false;
  }

  std::string private_key_bytes;
  if (!Extension::ParsePEMKeyBytes(private_key_contents,
       &private_key_bytes)) {
    error_message_ = "Invalid private key.";
    return false;
  }

  return base::RSAPrivateKey::CreateFromPrivateKeyInfo(
      std::vector<uint8>(private_key_bytes.begin(), private_key_bytes.end()));
}

base::RSAPrivateKey* ExtensionCreator::GenerateKey(const FilePath&
    output_private_key_path) {
  scoped_ptr<base::RSAPrivateKey> key_pair(
      base::RSAPrivateKey::Create(kRSAKeySize));
  if (!key_pair.get()) {
    error_message_ = "Yikes! Failed to generate random RSA private key.";
    return NULL;
  }

  std::vector<uint8> private_key_vector;
  if (!key_pair->ExportPrivateKey(&private_key_vector)) {
    error_message_ = "Failed to export private key.";
    return NULL;
  }
  std::string private_key_bytes(private_key_vector.begin(),
      private_key_vector.end());

  std::string private_key;
  if (!Extension::ProducePEM(private_key_bytes, &private_key)) {
    error_message_ = "Failed to output private key.";
    return NULL;
  }
  std::string pem_output;
  if (!Extension::FormatPEMForFileOutput(private_key, &pem_output,
       false)) {
    error_message_ = "Failed to output private key.";
    return NULL;
  }

  if (!output_private_key_path.empty()) {
    if (-1 == file_util::WriteFile(output_private_key_path,
        pem_output.c_str(), pem_output.size())) {
      error_message_ = "Failed to write private key.";
      return NULL;
    }
  }

  return key_pair.release();
}

bool ExtensionCreator::CreateZip(const FilePath& extension_dir,
                                 FilePath* zip_path) {
  file_util::CreateNewTempDirectory(FILE_PATH_LITERAL("chrome_"), zip_path);
  *zip_path = zip_path->Append(FILE_PATH_LITERAL("extension.zip"));

  if (!Zip(extension_dir, *zip_path)) {
    error_message_ = "Failed to create temporary zip file during packaging.";
    return false;
  }

  return true;
}

bool ExtensionCreator::SignZip(const FilePath& zip_path,
                               base::RSAPrivateKey* private_key,
                               std::vector<uint8>* signature) {
  scoped_ptr<base::SignatureCreator> signature_creator(
      base::SignatureCreator::Create(private_key));
  ScopedStdioHandle zip_handle(file_util::OpenFile(zip_path, "rb"));
  uint8 buffer[1 << 16];
  int bytes_read = -1;
  while ((bytes_read = fread(buffer, 1, sizeof(buffer),
       zip_handle.get())) > 0) {
    if (!signature_creator->Update(buffer, bytes_read)) {
      error_message_ = "Error while signing extension.";
      return false;
    }
  }
  zip_handle.Close();

  signature_creator->Final(signature);
  return true;
}

bool ExtensionCreator::WriteCRX(const FilePath& zip_path,
                                base::RSAPrivateKey* private_key,
                                const std::vector<uint8>& signature,
                                const FilePath& crx_path) {
  if (file_util::PathExists(crx_path))
    file_util::Delete(crx_path, false);
  ScopedStdioHandle crx_handle(file_util::OpenFile(crx_path, "wb"));

  std::vector<uint8> public_key;
  if (!private_key->ExportPublicKey(&public_key)) {
    error_message_ = "Failed to export public key.";
    return false;
  }

  ExtensionCreator::ExtensionHeader header;
  memcpy(&header.magic, ExtensionCreator::kExtensionHeaderMagic,
         ExtensionCreator::kExtensionHeaderMagicSize);
  header.version = kCurrentVersion;
  header.key_size = public_key.size();
  header.signature_size = signature.size();

  fwrite(&header, sizeof(ExtensionCreator::ExtensionHeader), 1,
      crx_handle.get());
  fwrite(&public_key.front(), sizeof(uint8), public_key.size(),
      crx_handle.get());
  fwrite(&signature.front(), sizeof(uint8), signature.size(),
      crx_handle.get());

  uint8 buffer[1 << 16];
  int bytes_read = -1;
  ScopedStdioHandle zip_handle(file_util::OpenFile(zip_path, "rb"));
  while ((bytes_read = fread(buffer, 1, sizeof(buffer),
      zip_handle.get())) > 0) {
    fwrite(buffer, sizeof(char), bytes_read, crx_handle.get());
  }

  return true;
}

bool ExtensionCreator::Run(const FilePath& extension_dir,
                           const FilePath& crx_path,
                           const FilePath& private_key_path,
                           const FilePath& output_private_key_path) {
  // Check input diretory and read manifest.
  if (!InitializeInput(extension_dir, private_key_path,
                       output_private_key_path)) {
    return false;
  }

  // Initialize Key Pair
  scoped_ptr<base::RSAPrivateKey> key_pair;
  if (!private_key_path.value().empty())
    key_pair.reset(ReadInputKey(private_key_path));
  else
    key_pair.reset(GenerateKey(output_private_key_path));
  if (!key_pair.get())
    return false;

  // Zip up the extension.
  FilePath zip_path;
  std::vector<uint8> signature;
  bool result = false;
  if (CreateZip(extension_dir, &zip_path) &&
      SignZip(zip_path, key_pair.get(), &signature) &&
      WriteCRX(zip_path, key_pair.get(), signature, crx_path)) {
    result = true;
  }

  file_util::Delete(zip_path, false);
  return result;
}
<commit_msg>Fix UMR in ExtensionCreator.<commit_after>// Copyright (c) 2009 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/extensions/extension_creator.h"

#include <vector>
#include <string>

#include "base/crypto/rsa_private_key.h"
#include "base/crypto/signature_creator.h"
#include "base/file_util.h"
#include "base/scoped_handle.h"
#include "base/string_util.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/zip.h"
#include "net/base/base64.h"

namespace {
  const int kRSAKeySize = 1024;
};

const char ExtensionCreator::kExtensionHeaderMagic[] = "Cr24";

bool ExtensionCreator::InitializeInput(
    const FilePath& extension_dir,
    const FilePath& private_key_path,
    const FilePath& private_key_output_path) {
  // Validate input |extension_dir|.
  if (extension_dir.value().empty() ||
      !file_util::DirectoryExists(extension_dir)) {
    error_message_ = "Input directory must exist.";
    return false;
  }

  // Validate input |private_key| (if provided).
  if (!private_key_path.value().empty() &&
      !file_util::PathExists(private_key_path)) {
    error_message_ = "Input value for private key must be a valid path.";
    return false;
  }

  // If an |output_private_key| path is given, make sure it doesn't over-write
  // an existing private key.
  if (private_key_path.value().empty() &&
      !private_key_output_path.value().empty() &&
      file_util::PathExists(private_key_output_path)) {
      error_message_ = "Private key exists next to input directory. Try using "
          "--pack-extension-key";
      return false;
  }

  return true;
}

base::RSAPrivateKey* ExtensionCreator::ReadInputKey(const FilePath&
    private_key_path) {
  if (!file_util::PathExists(private_key_path)) {
    error_message_ = "Input value for private key must exist.";
    return false;
  }

  std::string private_key_contents;
  if (!file_util::ReadFileToString(private_key_path,
      &private_key_contents)) {
    error_message_ = "Failed to read private key.";
    return false;
  }

  std::string private_key_bytes;
  if (!Extension::ParsePEMKeyBytes(private_key_contents,
       &private_key_bytes)) {
    error_message_ = "Invalid private key.";
    return false;
  }

  return base::RSAPrivateKey::CreateFromPrivateKeyInfo(
      std::vector<uint8>(private_key_bytes.begin(), private_key_bytes.end()));
}

base::RSAPrivateKey* ExtensionCreator::GenerateKey(const FilePath&
    output_private_key_path) {
  scoped_ptr<base::RSAPrivateKey> key_pair(
      base::RSAPrivateKey::Create(kRSAKeySize));
  if (!key_pair.get()) {
    error_message_ = "Yikes! Failed to generate random RSA private key.";
    return NULL;
  }

  std::vector<uint8> private_key_vector;
  if (!key_pair->ExportPrivateKey(&private_key_vector)) {
    error_message_ = "Failed to export private key.";
    return NULL;
  }
  std::string private_key_bytes(
      reinterpret_cast<char*>(&private_key_vector.front()),
      private_key_vector.size());

  std::string private_key;
  if (!Extension::ProducePEM(private_key_bytes, &private_key)) {
    error_message_ = "Failed to output private key.";
    return NULL;
  }
  std::string pem_output;
  if (!Extension::FormatPEMForFileOutput(private_key, &pem_output,
       false)) {
    error_message_ = "Failed to output private key.";
    return NULL;
  }

  if (!output_private_key_path.empty()) {
    if (-1 == file_util::WriteFile(output_private_key_path,
        pem_output.c_str(), pem_output.size())) {
      error_message_ = "Failed to write private key.";
      return NULL;
    }
  }

  return key_pair.release();
}

bool ExtensionCreator::CreateZip(const FilePath& extension_dir,
                                 FilePath* zip_path) {
  file_util::CreateNewTempDirectory(FILE_PATH_LITERAL("chrome_"), zip_path);
  *zip_path = zip_path->Append(FILE_PATH_LITERAL("extension.zip"));

  if (!Zip(extension_dir, *zip_path)) {
    error_message_ = "Failed to create temporary zip file during packaging.";
    return false;
  }

  return true;
}

bool ExtensionCreator::SignZip(const FilePath& zip_path,
                               base::RSAPrivateKey* private_key,
                               std::vector<uint8>* signature) {
  scoped_ptr<base::SignatureCreator> signature_creator(
      base::SignatureCreator::Create(private_key));
  ScopedStdioHandle zip_handle(file_util::OpenFile(zip_path, "rb"));
  uint8 buffer[1 << 16];
  int bytes_read = -1;
  while ((bytes_read = fread(buffer, 1, sizeof(buffer),
       zip_handle.get())) > 0) {
    if (!signature_creator->Update(buffer, bytes_read)) {
      error_message_ = "Error while signing extension.";
      return false;
    }
  }
  zip_handle.Close();

  signature_creator->Final(signature);
  return true;
}

bool ExtensionCreator::WriteCRX(const FilePath& zip_path,
                                base::RSAPrivateKey* private_key,
                                const std::vector<uint8>& signature,
                                const FilePath& crx_path) {
  if (file_util::PathExists(crx_path))
    file_util::Delete(crx_path, false);
  ScopedStdioHandle crx_handle(file_util::OpenFile(crx_path, "wb"));

  std::vector<uint8> public_key;
  if (!private_key->ExportPublicKey(&public_key)) {
    error_message_ = "Failed to export public key.";
    return false;
  }

  ExtensionCreator::ExtensionHeader header;
  memcpy(&header.magic, ExtensionCreator::kExtensionHeaderMagic,
         ExtensionCreator::kExtensionHeaderMagicSize);
  header.version = kCurrentVersion;
  header.key_size = public_key.size();
  header.signature_size = signature.size();

  fwrite(&header, sizeof(ExtensionCreator::ExtensionHeader), 1,
      crx_handle.get());
  fwrite(&public_key.front(), sizeof(uint8), public_key.size(),
      crx_handle.get());
  fwrite(&signature.front(), sizeof(uint8), signature.size(),
      crx_handle.get());

  uint8 buffer[1 << 16];
  int bytes_read = -1;
  ScopedStdioHandle zip_handle(file_util::OpenFile(zip_path, "rb"));
  while ((bytes_read = fread(buffer, 1, sizeof(buffer),
      zip_handle.get())) > 0) {
    fwrite(buffer, sizeof(char), bytes_read, crx_handle.get());
  }

  return true;
}

bool ExtensionCreator::Run(const FilePath& extension_dir,
                           const FilePath& crx_path,
                           const FilePath& private_key_path,
                           const FilePath& output_private_key_path) {
  // Check input diretory and read manifest.
  if (!InitializeInput(extension_dir, private_key_path,
                       output_private_key_path)) {
    return false;
  }

  // Initialize Key Pair
  scoped_ptr<base::RSAPrivateKey> key_pair;
  if (!private_key_path.value().empty())
    key_pair.reset(ReadInputKey(private_key_path));
  else
    key_pair.reset(GenerateKey(output_private_key_path));
  if (!key_pair.get())
    return false;

  // Zip up the extension.
  FilePath zip_path;
  std::vector<uint8> signature;
  bool result = false;
  if (CreateZip(extension_dir, &zip_path) &&
      SignZip(zip_path, key_pair.get(), &signature) &&
      WriteCRX(zip_path, key_pair.get(), signature, crx_path)) {
    result = true;
  }

  file_util::Delete(zip_path, false);
  return result;
}
<|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 "chrome/browser/hung_renderer_dialog.h"

#include <gtk/gtk.h>

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/process_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/common/result_codes.h"
#include "gfx/gtk_util.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"

namespace {

// A wrapper class that represents the Gtk dialog.
class HungRendererDialogGtk {
 public:
  HungRendererDialogGtk();
  void ShowForTabContents(TabContents* hung_contents);
  void EndForTabContents(TabContents* hung_contents);

 private:
  // The GtkTreeView column ids.
  enum {
    COL_FAVICON,
    COL_TITLE,
    COL_COUNT,
  };

  // Create the gtk dialog and add the widgets.
  void Init();

  static void OnDialogResponseThunk(GtkDialog* dialog, gint response_id,
                                    HungRendererDialogGtk* dialog_gtk) {
    dialog_gtk->OnDialogResponse(response_id);
  }
  void OnDialogResponse(gint response_id);

  GtkDialog* dialog_;
  GtkListStore* model_;
  TabContents* contents_;

  DISALLOW_COPY_AND_ASSIGN(HungRendererDialogGtk);
};

// We only support showing one of these at a time per app.
HungRendererDialogGtk* g_instance = NULL;

// The response ID for the "Kill pages" button.  Anything positive should be
// fine (the built in GtkResponseTypes are negative numbers).
const int kKillPagesButtonResponse = 1;

HungRendererDialogGtk::HungRendererDialogGtk()
    : dialog_(NULL), model_(NULL), contents_(NULL) {
  Init();
}

void HungRendererDialogGtk::Init() {
  dialog_ = GTK_DIALOG(gtk_dialog_new_with_buttons(
      l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_TITLE).c_str(),
      NULL,  // No parent because tabs can span multiple windows.
      GTK_DIALOG_NO_SEPARATOR,
      l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_END).c_str(),
      kKillPagesButtonResponse,
      l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_WAIT).c_str(),
      GTK_RESPONSE_OK,
      NULL));
  gtk_dialog_set_default_response(dialog_, GTK_RESPONSE_OK);
  g_signal_connect(dialog_, "response", G_CALLBACK(OnDialogResponseThunk),
                   this);

  // We have an hbox with the frozen icon on the left.  On the right,
  // we have a vbox with the unresponsive text on top and a table of
  // tabs on bottom.
  // ·-----------------------------------·
  // |·---------------------------------·|
  // ||·----·|·------------------------·||
  // |||icon|||                        |||
  // ||·----·|| The folowing page(s).. |||
  // ||      ||                        |||
  // ||      ||------------------------|||
  // ||      || table of tabs          |||
  // ||      |·------------------------·||
  // |·---------------------------------·|
  // |                                   |
  // |         kill button    wait button|
  // ·-----------------------------------·
  GtkWidget* contents_vbox = dialog_->vbox;
  gtk_box_set_spacing(GTK_BOX(contents_vbox), gtk_util::kContentAreaSpacing);

  GtkWidget* hbox = gtk_hbox_new(FALSE, 12);
  gtk_box_pack_start(GTK_BOX(contents_vbox), hbox, TRUE, TRUE, 0);

  // Wrap the icon in a vbox so it stays top aligned.
  GtkWidget* icon_vbox = gtk_vbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(hbox), icon_vbox, FALSE, FALSE, 0);
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
  GdkPixbuf* icon_pixbuf = rb.GetPixbufNamed(IDR_FROZEN_TAB_ICON);
  GtkWidget* icon = gtk_image_new_from_pixbuf(icon_pixbuf);
  gtk_box_pack_start(GTK_BOX(icon_vbox), icon, FALSE, FALSE, 0);

  GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
  gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);

  GtkWidget* text = gtk_label_new(
      l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER).c_str());
  gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
  gtk_box_pack_start(GTK_BOX(vbox), text, FALSE, FALSE, 0);

  GtkWidget* scroll_list = gtk_scrolled_window_new(NULL, NULL);
  gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll_list),
      GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
  gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll_list),
                                      GTK_SHADOW_ETCHED_IN);
  gtk_box_pack_start(GTK_BOX(vbox), scroll_list, TRUE, TRUE, 0);

  // The list of hung tabs is GtkTreeView with a GtkListStore as the model.
  model_ = gtk_list_store_new(COL_COUNT, GDK_TYPE_PIXBUF, G_TYPE_STRING);
  GtkWidget* tree_view = gtk_tree_view_new_with_model(
      GTK_TREE_MODEL(model_));
  g_object_unref(model_);
  gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree_view), FALSE);
  GtkTreeViewColumn* column = gtk_tree_view_column_new();
  GtkCellRenderer* renderer = gtk_cell_renderer_pixbuf_new();
  gtk_tree_view_column_pack_start(column, renderer, FALSE);
  gtk_tree_view_column_add_attribute(column, renderer, "pixbuf", COL_FAVICON);
  renderer = gtk_cell_renderer_text_new();
  gtk_tree_view_column_pack_start(column, renderer, TRUE);
  gtk_tree_view_column_add_attribute(column, renderer, "text", COL_TITLE);

  gtk_tree_view_append_column(GTK_TREE_VIEW(tree_view), column);
  gtk_container_add(GTK_CONTAINER(scroll_list), tree_view);
}

void HungRendererDialogGtk::ShowForTabContents(TabContents* hung_contents) {
  DCHECK(hung_contents && dialog_);
  contents_ = hung_contents;
  gtk_list_store_clear(model_);

  GtkTreeIter tree_iter;
  for (TabContentsIterator it; !it.done(); ++it) {
    if (it->GetRenderProcessHost() == hung_contents->GetRenderProcessHost()) {
      gtk_list_store_append(model_, &tree_iter);
      std::string title = UTF16ToUTF8(it->GetTitle());
      if (title.empty())
        title = UTF16ToUTF8(TabContents::GetDefaultTitle());
      SkBitmap favicon = it->GetFavIcon();

      GdkPixbuf* pixbuf = NULL;
      if (favicon.width() > 0)
        pixbuf = gfx::GdkPixbufFromSkBitmap(&favicon);
      gtk_list_store_set(model_, &tree_iter,
          COL_FAVICON, pixbuf,
          COL_TITLE, title.c_str(),
          -1);
      if (pixbuf)
        g_object_unref(pixbuf);
    }
  }
  gtk_util::ShowDialog(GTK_WIDGET(dialog_));
}

void HungRendererDialogGtk::EndForTabContents(TabContents* contents) {
  DCHECK(contents);
  if (contents_ && contents_->GetRenderProcessHost() ==
      contents->GetRenderProcessHost()) {
    gtk_widget_hide(GTK_WIDGET(dialog_));
    // Since we're closing, we no longer need this TabContents.
    contents_ = NULL;
  }
}

// When the user clicks a button on the dialog or closes the dialog, this
// callback is called.
void HungRendererDialogGtk::OnDialogResponse(gint response_id) {
  DCHECK(g_instance == this);
  switch (response_id) {
    case kKillPagesButtonResponse:
      // Kill the process.
      if (contents_ && contents_->GetRenderProcessHost()) {
        base::KillProcess(contents_->GetRenderProcessHost()->GetHandle(),
                          ResultCodes::HUNG, false);
      }
      break;

    case GTK_RESPONSE_OK:
    case GTK_RESPONSE_DELETE_EVENT:
      // Start waiting again for responsiveness.
      if (contents_ && contents_->render_view_host())
        contents_->render_view_host()->RestartHangMonitorTimeout();
      break;
    default:
      NOTREACHED();
  }

  gtk_widget_destroy(GTK_WIDGET(dialog_));
  delete g_instance;
  g_instance = NULL;
}

}  // namespace

namespace hung_renderer_dialog {

void ShowForTabContents(TabContents* contents) {
  if (!logging::DialogsAreSuppressed()) {
    if (!g_instance)
      g_instance = new HungRendererDialogGtk();
    g_instance->ShowForTabContents(contents);
  }
}

// static
void HideForTabContents(TabContents* contents) {
  if (!logging::DialogsAreSuppressed() && g_instance)
    g_instance->EndForTabContents(contents);
}

}  // namespace hung_renderer_dialog
<commit_msg>gtk: User CHROMEGTK macro in HungRendererDialogGtk.<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 "chrome/browser/hung_renderer_dialog.h"

#include <gtk/gtk.h>

#include "app/gtk_signal.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/process_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/common/result_codes.h"
#include "gfx/gtk_util.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"

namespace {

// A wrapper class that represents the Gtk dialog.
class HungRendererDialogGtk {
 public:
  HungRendererDialogGtk();
  void ShowForTabContents(TabContents* hung_contents);
  void EndForTabContents(TabContents* hung_contents);

 private:
  // The GtkTreeView column ids.
  enum {
    COL_FAVICON,
    COL_TITLE,
    COL_COUNT,
  };

  // Create the gtk dialog and add the widgets.
  void Init();

  CHROMEGTK_CALLBACK_1(HungRendererDialogGtk, void, OnDialogResponse, gint);

  GtkDialog* dialog_;
  GtkListStore* model_;
  TabContents* contents_;

  DISALLOW_COPY_AND_ASSIGN(HungRendererDialogGtk);
};

// We only support showing one of these at a time per app.
HungRendererDialogGtk* g_instance = NULL;

// The response ID for the "Kill pages" button.  Anything positive should be
// fine (the built in GtkResponseTypes are negative numbers).
const int kKillPagesButtonResponse = 1;

HungRendererDialogGtk::HungRendererDialogGtk()
    : dialog_(NULL), model_(NULL), contents_(NULL) {
  Init();
}

void HungRendererDialogGtk::Init() {
  dialog_ = GTK_DIALOG(gtk_dialog_new_with_buttons(
      l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_TITLE).c_str(),
      NULL,  // No parent because tabs can span multiple windows.
      GTK_DIALOG_NO_SEPARATOR,
      l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_END).c_str(),
      kKillPagesButtonResponse,
      l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_WAIT).c_str(),
      GTK_RESPONSE_OK,
      NULL));
  gtk_dialog_set_default_response(dialog_, GTK_RESPONSE_OK);
  g_signal_connect(dialog_, "response",
                   G_CALLBACK(OnDialogResponseThunk), this);

  // We have an hbox with the frozen icon on the left.  On the right,
  // we have a vbox with the unresponsive text on top and a table of
  // tabs on bottom.
  // ·-----------------------------------·
  // |·---------------------------------·|
  // ||·----·|·------------------------·||
  // |||icon|||                        |||
  // ||·----·|| The folowing page(s).. |||
  // ||      ||                        |||
  // ||      ||------------------------|||
  // ||      || table of tabs          |||
  // ||      |·------------------------·||
  // |·---------------------------------·|
  // |                                   |
  // |         kill button    wait button|
  // ·-----------------------------------·
  GtkWidget* contents_vbox = dialog_->vbox;
  gtk_box_set_spacing(GTK_BOX(contents_vbox), gtk_util::kContentAreaSpacing);

  GtkWidget* hbox = gtk_hbox_new(FALSE, 12);
  gtk_box_pack_start(GTK_BOX(contents_vbox), hbox, TRUE, TRUE, 0);

  // Wrap the icon in a vbox so it stays top aligned.
  GtkWidget* icon_vbox = gtk_vbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(hbox), icon_vbox, FALSE, FALSE, 0);
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
  GdkPixbuf* icon_pixbuf = rb.GetPixbufNamed(IDR_FROZEN_TAB_ICON);
  GtkWidget* icon = gtk_image_new_from_pixbuf(icon_pixbuf);
  gtk_box_pack_start(GTK_BOX(icon_vbox), icon, FALSE, FALSE, 0);

  GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
  gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);

  GtkWidget* text = gtk_label_new(
      l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER).c_str());
  gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
  gtk_box_pack_start(GTK_BOX(vbox), text, FALSE, FALSE, 0);

  GtkWidget* scroll_list = gtk_scrolled_window_new(NULL, NULL);
  gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll_list),
      GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
  gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll_list),
                                      GTK_SHADOW_ETCHED_IN);
  gtk_box_pack_start(GTK_BOX(vbox), scroll_list, TRUE, TRUE, 0);

  // The list of hung tabs is GtkTreeView with a GtkListStore as the model.
  model_ = gtk_list_store_new(COL_COUNT, GDK_TYPE_PIXBUF, G_TYPE_STRING);
  GtkWidget* tree_view = gtk_tree_view_new_with_model(
      GTK_TREE_MODEL(model_));
  g_object_unref(model_);
  gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree_view), FALSE);
  GtkTreeViewColumn* column = gtk_tree_view_column_new();
  GtkCellRenderer* renderer = gtk_cell_renderer_pixbuf_new();
  gtk_tree_view_column_pack_start(column, renderer, FALSE);
  gtk_tree_view_column_add_attribute(column, renderer, "pixbuf", COL_FAVICON);
  renderer = gtk_cell_renderer_text_new();
  gtk_tree_view_column_pack_start(column, renderer, TRUE);
  gtk_tree_view_column_add_attribute(column, renderer, "text", COL_TITLE);

  gtk_tree_view_append_column(GTK_TREE_VIEW(tree_view), column);
  gtk_container_add(GTK_CONTAINER(scroll_list), tree_view);
}

void HungRendererDialogGtk::ShowForTabContents(TabContents* hung_contents) {
  DCHECK(hung_contents && dialog_);
  contents_ = hung_contents;
  gtk_list_store_clear(model_);

  GtkTreeIter tree_iter;
  for (TabContentsIterator it; !it.done(); ++it) {
    if (it->GetRenderProcessHost() == hung_contents->GetRenderProcessHost()) {
      gtk_list_store_append(model_, &tree_iter);
      std::string title = UTF16ToUTF8(it->GetTitle());
      if (title.empty())
        title = UTF16ToUTF8(TabContents::GetDefaultTitle());
      SkBitmap favicon = it->GetFavIcon();

      GdkPixbuf* pixbuf = NULL;
      if (favicon.width() > 0)
        pixbuf = gfx::GdkPixbufFromSkBitmap(&favicon);
      gtk_list_store_set(model_, &tree_iter,
          COL_FAVICON, pixbuf,
          COL_TITLE, title.c_str(),
          -1);
      if (pixbuf)
        g_object_unref(pixbuf);
    }
  }
  gtk_util::ShowDialog(GTK_WIDGET(dialog_));
}

void HungRendererDialogGtk::EndForTabContents(TabContents* contents) {
  DCHECK(contents);
  if (contents_ && contents_->GetRenderProcessHost() ==
      contents->GetRenderProcessHost()) {
    gtk_widget_hide(GTK_WIDGET(dialog_));
    // Since we're closing, we no longer need this TabContents.
    contents_ = NULL;
  }
}

// When the user clicks a button on the dialog or closes the dialog, this
// callback is called.
void HungRendererDialogGtk::OnDialogResponse(GtkWidget* widget,
                                             gint response_id) {
  DCHECK(g_instance == this);
  switch (response_id) {
    case kKillPagesButtonResponse:
      // Kill the process.
      if (contents_ && contents_->GetRenderProcessHost()) {
        base::KillProcess(contents_->GetRenderProcessHost()->GetHandle(),
                          ResultCodes::HUNG, false);
      }
      break;

    case GTK_RESPONSE_OK:
    case GTK_RESPONSE_DELETE_EVENT:
      // Start waiting again for responsiveness.
      if (contents_ && contents_->render_view_host())
        contents_->render_view_host()->RestartHangMonitorTimeout();
      break;
    default:
      NOTREACHED();
  }

  gtk_widget_destroy(GTK_WIDGET(dialog_));
  delete g_instance;
  g_instance = NULL;
}

}  // namespace

namespace hung_renderer_dialog {

void ShowForTabContents(TabContents* contents) {
  if (!logging::DialogsAreSuppressed()) {
    if (!g_instance)
      g_instance = new HungRendererDialogGtk();
    g_instance->ShowForTabContents(contents);
  }
}

// static
void HideForTabContents(TabContents* contents) {
  if (!logging::DialogsAreSuppressed() && g_instance)
    g_instance->EndForTabContents(contents);
}

}  // namespace hung_renderer_dialog
<|endoftext|>


<commit_before>// Copyright (c) 2011 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/ui/panels/panel_browser_view.h"

#include "base/logging.h"
#include "chrome/browser/ui/panels/panel.h"
#include "chrome/browser/ui/panels/panel_browser_frame_view.h"
#include "chrome/browser/ui/panels/panel_manager.h"
#include "chrome/browser/ui/views/frame/browser_frame.h"
#include "grit/chromium_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "views/window/window.h"

BrowserWindow* Panel::CreateNativePanel(Browser* browser, Panel* panel) {
  BrowserView* view = new PanelBrowserView(browser, panel);
  BrowserFrame::Create(view, browser->profile());
  view->GetWindow()->non_client_view()->SetAccessibleName(
      l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));
  return view;
}

PanelBrowserView::PanelBrowserView(Browser* browser, Panel* panel)
  : BrowserView(browser),
    panel_(panel),
    mouse_pressed_(false),
    mouse_dragging_(false) {
}

PanelBrowserView::~PanelBrowserView() {
}

void PanelBrowserView::Close() {
  if (!panel_)
    return;
  ::BrowserView::Close();
  panel_ = NULL;
}

void PanelBrowserView::UpdateTitleBar() {
  ::BrowserView::UpdateTitleBar();
  GetFrameView()->UpdateTitleBar();
}

bool PanelBrowserView::GetSavedWindowBounds(gfx::Rect* bounds) const {
  *bounds = panel_->GetRestoredBounds();
  return true;
}

void PanelBrowserView::OnWindowActivationChanged(bool active) {
  ::BrowserView::OnWindowActivationChanged(active);
  GetFrameView()->OnActivationChanged(active);
}

PanelBrowserFrameView* PanelBrowserView::GetFrameView() const {
  return static_cast<PanelBrowserFrameView*>(frame()->GetFrameView());
}

bool PanelBrowserView::OnTitleBarMousePressed(const views::MouseEvent& event) {
  if (!event.IsOnlyLeftMouseButton())
    return false;
  mouse_pressed_ = true;
  mouse_pressed_point_ = event.location();
  mouse_dragging_ = false;
  panel_->manager()->StartDragging(panel_);
  return true;
}

bool PanelBrowserView::OnTitleBarMouseDragged(const views::MouseEvent& event) {
  if (!mouse_pressed_)
    return false;

  // We do not allow dragging vertically.
  int delta_x = event.location().x() - mouse_pressed_point_.x();
  if (!mouse_dragging_ && ExceededDragThreshold(delta_x, 0))
    mouse_dragging_ = true;
  if (mouse_dragging_)
    panel_->manager()->Drag(delta_x);
  return true;
}

bool PanelBrowserView::OnTitleBarMouseReleased(const views::MouseEvent& event) {
  // Only handle clicks that started in our window.
  if (!mouse_pressed_)
    return false;
  mouse_pressed_ = false;

  if (mouse_dragging_) {
    mouse_dragging_ = false;
    panel_->manager()->EndDragging(false);
  }
  return true;
}
<commit_msg>Make panel topmost on Windows.<commit_after>// Copyright (c) 2011 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/ui/panels/panel_browser_view.h"

#include "base/logging.h"
#include "chrome/browser/ui/panels/panel.h"
#include "chrome/browser/ui/panels/panel_browser_frame_view.h"
#include "chrome/browser/ui/panels/panel_manager.h"
#include "chrome/browser/ui/views/frame/browser_frame.h"
#include "grit/chromium_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "views/window/window.h"

BrowserWindow* Panel::CreateNativePanel(Browser* browser, Panel* panel) {
  BrowserView* view = new PanelBrowserView(browser, panel);
  BrowserFrame::Create(view, browser->profile());
  view->GetWidget()->SetAlwaysOnTop(true);
  view->GetWindow()->non_client_view()->SetAccessibleName(
      l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));
  return view;
}

PanelBrowserView::PanelBrowserView(Browser* browser, Panel* panel)
  : BrowserView(browser),
    panel_(panel),
    mouse_pressed_(false),
    mouse_dragging_(false) {
}

PanelBrowserView::~PanelBrowserView() {
}

void PanelBrowserView::Close() {
  if (!panel_)
    return;
  ::BrowserView::Close();
  panel_ = NULL;
}

void PanelBrowserView::UpdateTitleBar() {
  ::BrowserView::UpdateTitleBar();
  GetFrameView()->UpdateTitleBar();
}

bool PanelBrowserView::GetSavedWindowBounds(gfx::Rect* bounds) const {
  *bounds = panel_->GetRestoredBounds();
  return true;
}

void PanelBrowserView::OnWindowActivationChanged(bool active) {
  ::BrowserView::OnWindowActivationChanged(active);
  GetFrameView()->OnActivationChanged(active);
}

PanelBrowserFrameView* PanelBrowserView::GetFrameView() const {
  return static_cast<PanelBrowserFrameView*>(frame()->GetFrameView());
}

bool PanelBrowserView::OnTitleBarMousePressed(const views::MouseEvent& event) {
  if (!event.IsOnlyLeftMouseButton())
    return false;
  mouse_pressed_ = true;
  mouse_pressed_point_ = event.location();
  mouse_dragging_ = false;
  panel_->manager()->StartDragging(panel_);
  return true;
}

bool PanelBrowserView::OnTitleBarMouseDragged(const views::MouseEvent& event) {
  if (!mouse_pressed_)
    return false;

  // We do not allow dragging vertically.
  int delta_x = event.location().x() - mouse_pressed_point_.x();
  if (!mouse_dragging_ && ExceededDragThreshold(delta_x, 0))
    mouse_dragging_ = true;
  if (mouse_dragging_)
    panel_->manager()->Drag(delta_x);
  return true;
}

bool PanelBrowserView::OnTitleBarMouseReleased(const views::MouseEvent& event) {
  // Only handle clicks that started in our window.
  if (!mouse_pressed_)
    return false;
  mouse_pressed_ = false;

  if (mouse_dragging_) {
    mouse_dragging_ = false;
    panel_->manager()->EndDragging(false);
  }
  return true;
}
<|endoftext|>


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

#include "chrome/browser/ui/views/frame/browser_frame.h"

#include "base/command_line.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/views/frame/browser_non_client_frame_view.h"
#include "chrome/browser/ui/views/frame/browser_root_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/frame/native_browser_frame.h"
#include "chrome/common/chrome_switches.h"
#include "ui/base/theme_provider.h"
#include "ui/gfx/screen.h"
#include "ui/views/widget/native_widget.h"

#if defined(OS_WIN) && !defined(USE_AURA)
#include "chrome/browser/ui/views/frame/glass_browser_frame_view.h"
#elif defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/system/runtime_environment.h"
#endif

#if defined(USE_AURA)
#include "ash/ash_switches.h"
#include "ash/shell.h"
#include "chrome/browser/chromeos/status/status_area_view.h"
#include "chrome/browser/ui/views/aura/chrome_shell_delegate.h"
#endif

////////////////////////////////////////////////////////////////////////////////
// BrowserFrame, public:

BrowserFrame::BrowserFrame(BrowserView* browser_view)
    : native_browser_frame_(NULL),
      root_view_(NULL),
      browser_frame_view_(NULL),
      browser_view_(browser_view) {
  browser_view_->set_frame(this);
  set_is_secondary_widget(false);
  // Don't focus anything on creation, selecting a tab will set the focus.
  set_focus_on_creation(false);
}

BrowserFrame::~BrowserFrame() {
}

void BrowserFrame::InitBrowserFrame() {
  native_browser_frame_ =
      NativeBrowserFrame::CreateNativeBrowserFrame(this, browser_view_);
  views::Widget::InitParams params;
  params.delegate = browser_view_;
  params.native_widget = native_browser_frame_->AsNativeWidget();
  if (browser_view_->browser()->is_type_tabbed()) {
    // Typed panel/popup can only return a size once the widget has been
    // created.
    params.bounds = browser_view_->browser()->GetSavedWindowBounds();
    params.show_state = browser_view_->browser()->GetSavedWindowShowState();
  }
  if (browser_view_->browser()->is_type_panel()) {
    // We need to set the top-most bit when the panel window is created.
    // There is a Windows bug/feature that would very likely prevent the window
    // from being changed to top-most after the window is created without
    // activation.
    params.type = views::Widget::InitParams::TYPE_PANEL;
  }
#if defined(USE_AURA)
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(ash::switches::kAuraTranslucentFrames))
    params.transparent = true;
  // Aura compact mode fills the monitor with with its windows.
  if (ash::Shell::GetInstance()->IsWindowModeCompact() &&
      browser_view_->IsBrowserTypeNormal()) {
    params.bounds = gfx::Screen::GetPrimaryMonitorBounds();
    params.show_state = ui::SHOW_STATE_MAXIMIZED;
  }
#endif
  Init(params);

  // On ChromeOS and Aura compact mode we always want top-level windows
  // to appear active.
  bool disable_inactive_rendering = false;
#if defined(USE_AURA)
  disable_inactive_rendering = ash::Shell::GetInstance()->IsWindowModeCompact();
#elif defined(OS_CHROMEOS)
  disable_inactive_rendering = true;
#endif
  if (disable_inactive_rendering && !browser_view_->IsBrowserTypePopup())
    DisableInactiveRendering();
}

int BrowserFrame::GetMinimizeButtonOffset() const {
  return native_browser_frame_->GetMinimizeButtonOffset();
}

gfx::Rect BrowserFrame::GetBoundsForTabStrip(views::View* tabstrip) const {
  gfx::Rect tab_strip_bounds =
      browser_frame_view_->GetBoundsForTabStrip(tabstrip);
#if defined(USE_AURA)
  // Leave space for status area when maximized under aura compact window mode.
  if (ash::Shell::GetInstance()->IsWindowModeCompact() &&
      IsMaximized() &&
      ChromeShellDelegate::instance()) {
    StatusAreaView* status_area =
        ChromeShellDelegate::instance()->GetStatusArea();
    if (status_area) {
      // Non-client frameview origin of a maximized BrowserFrame is also the
      // origin of the screen. So we can use StatusArea's screen bounds with
      // the |tab_strip_bounds| directly.
      DCHECK(gfx::Point(0, 0) == GetWindowScreenBounds().origin());
      DCHECK(gfx::Point(0, 0) == browser_frame_view_->bounds().origin());

      gfx::Rect status_rect = status_area->GetWidget()->GetWindowScreenBounds();
      if (status_rect.Intersects(tab_strip_bounds)) {
        status_rect.set_y(tab_strip_bounds.y());
        status_rect.set_height(tab_strip_bounds.height());

        tab_strip_bounds = tab_strip_bounds.Subtract(status_rect);
      }
    }
  }
#endif
  return tab_strip_bounds;
}

int BrowserFrame::GetHorizontalTabStripVerticalOffset(bool restored) const {
  return browser_frame_view_->GetHorizontalTabStripVerticalOffset(restored);
}

void BrowserFrame::UpdateThrobber(bool running) {
  browser_frame_view_->UpdateThrobber(running);
}

views::View* BrowserFrame::GetFrameView() const {
  return browser_frame_view_;
}

void BrowserFrame::TabStripDisplayModeChanged() {
  if (GetRootView()->has_children()) {
    // Make sure the child of the root view gets Layout again.
    GetRootView()->child_at(0)->InvalidateLayout();
  }
  GetRootView()->Layout();
  native_browser_frame_->TabStripDisplayModeChanged();
}

bool BrowserFrame::IsSingleWindowMode() const {
  bool single_window_mode = false;
#if defined(USE_AURA)
  single_window_mode = ash::Shell::GetInstance()->IsWindowModeCompact();
#elif defined(OS_CHROMEOS)
  single_window_mode =
      chromeos::system::runtime_environment::IsRunningOnChromeOS();
#endif
  return single_window_mode;
}

///////////////////////////////////////////////////////////////////////////////
// BrowserFrame, views::Widget overrides:

bool BrowserFrame::IsMaximized() const {
#if defined(OS_CHROMEOS) && !defined(USE_AURA)
  if (chromeos::system::runtime_environment::IsRunningOnChromeOS()) {
    return !IsFullscreen() &&
        (!browser_view_->IsBrowserTypePopup() || Widget::IsMaximized());
  }
#endif
  return Widget::IsMaximized();
}

views::internal::RootView* BrowserFrame::CreateRootView() {
  root_view_ = new BrowserRootView(browser_view_, this);
  return root_view_;
}

views::NonClientFrameView* BrowserFrame::CreateNonClientFrameView() {
#if defined(OS_WIN) && !defined(USE_AURA)
  if (ShouldUseNativeFrame()) {
    browser_frame_view_ = new GlassBrowserFrameView(this, browser_view_);
  } else {
#endif
    browser_frame_view_ =
        browser::CreateBrowserNonClientFrameView(this, browser_view_);
#if defined(OS_WIN) && !defined(USE_AURA)
  }
#endif
  return browser_frame_view_;
}

bool BrowserFrame::GetAccelerator(int command_id,
                                  ui::Accelerator* accelerator) {
  return browser_view_->GetAccelerator(command_id, accelerator);
}

ThemeProvider* BrowserFrame::GetThemeProvider() const {
  return ThemeServiceFactory::GetForProfile(
      browser_view_->browser()->profile());
}

void BrowserFrame::OnNativeWidgetActivationChanged(bool active) {
  if (active) {
    // When running under remote desktop, if the remote desktop client is not
    // active on the users desktop, then none of the windows contained in the
    // remote desktop will be activated.  However, NativeWidgetWin::Activate()
    // will still bring this browser window to the foreground.  We explicitly
    // set ourselves as the last active browser window to ensure that we get
    // treated as such by the rest of Chrome.
    BrowserList::SetLastActive(browser_view_->browser());
  }
  Widget::OnNativeWidgetActivationChanged(active);
}

AvatarMenuButton* BrowserFrame::GetAvatarMenuButton() {
  return browser_frame_view_->avatar_button();
}
<commit_msg>[Aura] Convert status area bounds into frame view coordinate for tabstrip bounds check.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/frame/browser_frame.h"

#include "base/command_line.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/views/frame/browser_non_client_frame_view.h"
#include "chrome/browser/ui/views/frame/browser_root_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/frame/native_browser_frame.h"
#include "chrome/common/chrome_switches.h"
#include "ui/base/theme_provider.h"
#include "ui/gfx/screen.h"
#include "ui/views/widget/native_widget.h"

#if defined(OS_WIN) && !defined(USE_AURA)
#include "chrome/browser/ui/views/frame/glass_browser_frame_view.h"
#elif defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/system/runtime_environment.h"
#endif

#if defined(USE_AURA)
#include "ash/ash_switches.h"
#include "ash/shell.h"
#include "chrome/browser/chromeos/status/status_area_view.h"
#include "chrome/browser/ui/views/aura/chrome_shell_delegate.h"
#endif

////////////////////////////////////////////////////////////////////////////////
// BrowserFrame, public:

BrowserFrame::BrowserFrame(BrowserView* browser_view)
    : native_browser_frame_(NULL),
      root_view_(NULL),
      browser_frame_view_(NULL),
      browser_view_(browser_view) {
  browser_view_->set_frame(this);
  set_is_secondary_widget(false);
  // Don't focus anything on creation, selecting a tab will set the focus.
  set_focus_on_creation(false);
}

BrowserFrame::~BrowserFrame() {
}

void BrowserFrame::InitBrowserFrame() {
  native_browser_frame_ =
      NativeBrowserFrame::CreateNativeBrowserFrame(this, browser_view_);
  views::Widget::InitParams params;
  params.delegate = browser_view_;
  params.native_widget = native_browser_frame_->AsNativeWidget();
  if (browser_view_->browser()->is_type_tabbed()) {
    // Typed panel/popup can only return a size once the widget has been
    // created.
    params.bounds = browser_view_->browser()->GetSavedWindowBounds();
    params.show_state = browser_view_->browser()->GetSavedWindowShowState();
  }
  if (browser_view_->browser()->is_type_panel()) {
    // We need to set the top-most bit when the panel window is created.
    // There is a Windows bug/feature that would very likely prevent the window
    // from being changed to top-most after the window is created without
    // activation.
    params.type = views::Widget::InitParams::TYPE_PANEL;
  }
#if defined(USE_AURA)
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(ash::switches::kAuraTranslucentFrames))
    params.transparent = true;
  // Aura compact mode fills the monitor with with its windows.
  if (ash::Shell::GetInstance()->IsWindowModeCompact() &&
      browser_view_->IsBrowserTypeNormal()) {
    params.bounds = gfx::Screen::GetPrimaryMonitorBounds();
    params.show_state = ui::SHOW_STATE_MAXIMIZED;
  }
#endif
  Init(params);

  // On ChromeOS and Aura compact mode we always want top-level windows
  // to appear active.
  bool disable_inactive_rendering = false;
#if defined(USE_AURA)
  disable_inactive_rendering = ash::Shell::GetInstance()->IsWindowModeCompact();
#elif defined(OS_CHROMEOS)
  disable_inactive_rendering = true;
#endif
  if (disable_inactive_rendering && !browser_view_->IsBrowserTypePopup())
    DisableInactiveRendering();
}

int BrowserFrame::GetMinimizeButtonOffset() const {
  return native_browser_frame_->GetMinimizeButtonOffset();
}

gfx::Rect BrowserFrame::GetBoundsForTabStrip(views::View* tabstrip) const {
  gfx::Rect tab_strip_bounds =
      browser_frame_view_->GetBoundsForTabStrip(tabstrip);
#if defined(USE_AURA)
  // Leave space for status area when maximized under aura compact window mode.
  if (ash::Shell::GetInstance()->IsWindowModeCompact() &&
      IsMaximized() &&
      ChromeShellDelegate::instance()) {
    StatusAreaView* status_area =
        ChromeShellDelegate::instance()->GetStatusArea();
    if (status_area) {
      gfx::Rect status_rect = status_area->GetWidget()->GetWindowScreenBounds();

      // Translate status_rect to frame view coordinates.
      gfx::Point frame_origin = GetWindowScreenBounds().origin();
      gfx::Point frame_view_origin = browser_frame_view_->bounds().origin();
      status_rect.Offset(-(frame_origin.x() + frame_view_origin.x()),
                         -(frame_origin.y() + frame_view_origin.y()));

      if (status_rect.Intersects(tab_strip_bounds)) {
        status_rect.set_y(tab_strip_bounds.y());
        status_rect.set_height(tab_strip_bounds.height());

        tab_strip_bounds = tab_strip_bounds.Subtract(status_rect);
      }
    }
  }
#endif
  return tab_strip_bounds;
}

int BrowserFrame::GetHorizontalTabStripVerticalOffset(bool restored) const {
  return browser_frame_view_->GetHorizontalTabStripVerticalOffset(restored);
}

void BrowserFrame::UpdateThrobber(bool running) {
  browser_frame_view_->UpdateThrobber(running);
}

views::View* BrowserFrame::GetFrameView() const {
  return browser_frame_view_;
}

void BrowserFrame::TabStripDisplayModeChanged() {
  if (GetRootView()->has_children()) {
    // Make sure the child of the root view gets Layout again.
    GetRootView()->child_at(0)->InvalidateLayout();
  }
  GetRootView()->Layout();
  native_browser_frame_->TabStripDisplayModeChanged();
}

bool BrowserFrame::IsSingleWindowMode() const {
  bool single_window_mode = false;
#if defined(USE_AURA)
  single_window_mode = ash::Shell::GetInstance()->IsWindowModeCompact();
#elif defined(OS_CHROMEOS)
  single_window_mode =
      chromeos::system::runtime_environment::IsRunningOnChromeOS();
#endif
  return single_window_mode;
}

///////////////////////////////////////////////////////////////////////////////
// BrowserFrame, views::Widget overrides:

bool BrowserFrame::IsMaximized() const {
#if defined(OS_CHROMEOS) && !defined(USE_AURA)
  if (chromeos::system::runtime_environment::IsRunningOnChromeOS()) {
    return !IsFullscreen() &&
        (!browser_view_->IsBrowserTypePopup() || Widget::IsMaximized());
  }
#endif
  return Widget::IsMaximized();
}

views::internal::RootView* BrowserFrame::CreateRootView() {
  root_view_ = new BrowserRootView(browser_view_, this);
  return root_view_;
}

views::NonClientFrameView* BrowserFrame::CreateNonClientFrameView() {
#if defined(OS_WIN) && !defined(USE_AURA)
  if (ShouldUseNativeFrame()) {
    browser_frame_view_ = new GlassBrowserFrameView(this, browser_view_);
  } else {
#endif
    browser_frame_view_ =
        browser::CreateBrowserNonClientFrameView(this, browser_view_);
#if defined(OS_WIN) && !defined(USE_AURA)
  }
#endif
  return browser_frame_view_;
}

bool BrowserFrame::GetAccelerator(int command_id,
                                  ui::Accelerator* accelerator) {
  return browser_view_->GetAccelerator(command_id, accelerator);
}

ThemeProvider* BrowserFrame::GetThemeProvider() const {
  return ThemeServiceFactory::GetForProfile(
      browser_view_->browser()->profile());
}

void BrowserFrame::OnNativeWidgetActivationChanged(bool active) {
  if (active) {
    // When running under remote desktop, if the remote desktop client is not
    // active on the users desktop, then none of the windows contained in the
    // remote desktop will be activated.  However, NativeWidgetWin::Activate()
    // will still bring this browser window to the foreground.  We explicitly
    // set ourselves as the last active browser window to ensure that we get
    // treated as such by the rest of Chrome.
    BrowserList::SetLastActive(browser_view_->browser());
  }
  Widget::OnNativeWidgetActivationChanged(active);
}

AvatarMenuButton* BrowserFrame::GetAvatarMenuButton() {
  return browser_frame_view_->avatar_button();
}
<|endoftext|>


<commit_before>#include "ccharisc.h"
#include "crosepacket.h"
#include "ccharserver.h"
#include "config.h"

using namespace RoseCommon;

CCharISC::CCharISC() : CRoseISC(), login_connection_(false) {

}

CCharISC::CCharISC(tcp::socket _sock)
    : CRoseISC(std::move(_sock)), login_connection_(false) {

}

bool CCharISC::HandlePacket(uint8_t* _buffer) {
  CRosePacket* pak = (CRosePacket*)_buffer;
  switch (pak->Header.Command) {
    case ePacketType::ISC_ALIVE:
      return true;
    case ePacketType::ISC_SERVER_AUTH:
      return true;
    case ePacketType::ISC_SERVER_REGISTER:
      return ServerRegister(pak);
    case ePacketType::ISC_TRANSFER:
      return true;
    case ePacketType::ISC_SHUTDOWN:
      return true;
    default: {
      CRoseISC::HandlePacket(_buffer);
      return false;
    }
  }
  return true;
}

bool CCharISC::ServerRegister(CRosePacket* P) {
  CRosePacket* pak = (CRosePacket*)P;
  uint16_t _insize = pak->Header.Size - 6;

  ServerReg pMapServer;
  if (pMapServer.ParseFromArray(pak->Data, _insize) == false) return false;

  int16_t _type = 0;
  _type = pMapServer.type();

  // 1 == char server
  // 2 == node server
  // 3 == map master server (This is the only type the login server will care
  // about)
  // 4 == map workers/threads

  ServerReg pServerReg;

  if (_type == 2) {
    // This is a node and we need to figure out something to do with this
  } else if (_type == 3) {
    pServerReg.set_name(pMapServer.name());
    pServerReg.set_addr(pMapServer.addr());
    pServerReg.set_port(pMapServer.port());
    pServerReg.set_type(pMapServer.type());
    pServerReg.set_accright(pMapServer.accright());
  }

  std::unique_ptr<CRosePacket> pakToLS(new CRosePacket(ePacketType::ISC_SERVER_REGISTER));
  int _size = pServerReg.ByteSize();
  std::unique_ptr<uint8_t> data( new uint8_t[_size] );
  memset(data.get(), 0, _size);
  if (pServerReg.SerializeToArray(data.get(), _size) == false)
    logger_->error("Couldn't serialize the data");
  pakToLS->AddBytes(data.get(), _size);

  // todo: get the ISC connection to the login server and send the packet to it
  std::lock_guard<std::mutex> lock(CCharServer::GetISCListMutex());
  for (auto& server : CCharServer::GetISCList()) {
    CCharISC* svr = (CCharISC*)server;
    if (svr->IsLogin()) {
      svr->Send((CRosePacket*)pakToLS.release());
//      delete[] data;
      return true;
    }
  }
//  delete[] data;
  return false;
}

void CCharISC::OnConnected() {
  CRosePacket* pak = new CRosePacket(ePacketType::ISC_SERVER_REGISTER);

  Core::Config& config = Core::Config::getInstance();

  ServerReg pServerReg;
  pServerReg.set_name(config.char_server().worldname());
  pServerReg.set_addr(config.serverdata().ip());
  pServerReg.set_port(config.char_server().clientport());
  pServerReg.set_type(ServerReg_ServerType_CHAR);
  pServerReg.set_accright(config.char_server().accesslevel());

  int _size = pServerReg.ByteSize();
  uint8_t* data = new uint8_t[_size];
  memset(data, 0, _size);
  if (pServerReg.SerializeToArray(data, _size) == false)
    logger_->error("Couldn't serialize the data");
  pak->AddBytes(data, _size);

  logger_->trace("Sent a packet on CRoseISC: Header[{0}, 0x{1:x}]",
                 pak->Header.Size, (uint16_t)pak->Header.Command);

  Send((CRosePacket*)pak);
  delete[] data;
}
<commit_msg>Char server now tells us when a map server has been registered.<commit_after>#include "ccharisc.h"
#include "crosepacket.h"
#include "ccharserver.h"
#include "config.h"

using namespace RoseCommon;

CCharISC::CCharISC() : CRoseISC(), login_connection_(false) {

}

CCharISC::CCharISC(tcp::socket _sock)
    : CRoseISC(std::move(_sock)), login_connection_(false) {

}

bool CCharISC::HandlePacket(uint8_t* _buffer) {
  CRosePacket* pak = (CRosePacket*)_buffer;
  switch (pak->Header.Command) {
    case ePacketType::ISC_ALIVE:
      return true;
    case ePacketType::ISC_SERVER_AUTH:
      return true;
    case ePacketType::ISC_SERVER_REGISTER:
      return ServerRegister(pak);
    case ePacketType::ISC_TRANSFER:
      return true;
    case ePacketType::ISC_SHUTDOWN:
      return true;
    default: {
      CRoseISC::HandlePacket(_buffer);
      return false;
    }
  }
  return true;
}

bool CCharISC::ServerRegister(CRosePacket* P) {
  logger_->trace("CCharISC::ServerRegister(CRosePacket* P)");
  CRosePacket* pak = (CRosePacket*)P;
  uint16_t _insize = pak->Header.Size - 6;

  ServerReg pMapServer;
  if (pMapServer.ParseFromArray(pak->Data, _insize) == false){
    logger_->debug("pMapServer.ParseFromArray Failed!");
    return false;
  }

  int16_t _type = 0;
  _type = pMapServer.type();

  // 1 == char server
  // 2 == node server
  // 3 == map master server (This is the only type the login server will care
  // about)
  // 4 == map workers/threads

  ServerReg pServerReg;

  if (_type == 2) {
    // This is a node and we need to figure out something to do with this
  } else if (_type == 3) {
    pServerReg.set_name(pMapServer.name());
    pServerReg.set_addr(pMapServer.addr());
    pServerReg.set_port(pMapServer.port());
    pServerReg.set_type(pMapServer.type());
    pServerReg.set_accright(pMapServer.accright());
  }

  logger_->notice("ISC Server Connected: [{}, {}, {}:{}]\n",
                ServerReg_ServerType_Name(pServerReg.type()).c_str(),
                pServerReg.name().c_str(), pServerReg.addr().c_str(),
                pServerReg.port());

  std::unique_ptr<CRosePacket> pakToLS(new CRosePacket(ePacketType::ISC_SERVER_REGISTER));
  int _size = pServerReg.ByteSize();
  std::unique_ptr<uint8_t> data( new uint8_t[_size] );
  memset(data.get(), 0, _size);
  if (pServerReg.SerializeToArray(data.get(), _size) == false)
    logger_->error("Couldn't serialize the data");
  pakToLS->AddBytes(data.get(), _size);

  // todo: get the ISC connection to the login server and send the packet to it
  std::lock_guard<std::mutex> lock(CCharServer::GetISCListMutex());
  for (auto& server : CCharServer::GetISCList()) {
    CCharISC* svr = (CCharISC*)server;
    if (svr->IsLogin()) {
      svr->Send((CRosePacket*)pakToLS.release());
//      delete[] data;
      return true;
    }
  }
//  delete[] data;
  return false;
}

void CCharISC::OnConnected() {
  logger_->trace("CCharISC::OnConnected()");
  CRosePacket* pak = new CRosePacket(ePacketType::ISC_SERVER_REGISTER);

  Core::Config& config = Core::Config::getInstance();

  ServerReg pServerReg;
  pServerReg.set_name(config.char_server().worldname());
  pServerReg.set_addr(config.serverdata().ip());
  pServerReg.set_port(config.char_server().clientport());
  pServerReg.set_type(ServerReg_ServerType_CHAR);
  pServerReg.set_accright(config.char_server().accesslevel());

  int _size = pServerReg.ByteSize();
  uint8_t* data = new uint8_t[_size];
  memset(data, 0, _size);
  if (pServerReg.SerializeToArray(data, _size) == false)
    logger_->error("Couldn't serialize the data");
  pak->AddBytes(data, _size);

  logger_->trace("Sent a packet on CRoseISC: Header[{0}, 0x{1:x}]",
                 pak->Header.Size, (uint16_t)pak->Header.Command);

  Send((CRosePacket*)pak);
  delete[] data;
}
<|endoftext|>


<commit_before>/*
 Copyright (c) 2013, The Cinder Project (http://libcinder.org)
 All rights reserved.

 Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and
	the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials provided with the distribution.

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

#include "cinder/ConvexHull.h"

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>

namespace cinder {

typedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;

namespace {

template<typename T>
PolyLine<Vec2<T> > toPolyLine( const polygon &p )
{
	PolyLine<Vec2<T> > result;

	for( auto pt = p.outer().begin(); pt != p.outer().end(); ++pt )
		result.push_back( Vec2<T>( (T)boost::geometry::get<0>(*pt), (T)boost::geometry::get<1>(*pt) ) );

	return result;
}

boost::geometry::model::d2::point_xy<double> makePoint( const Vec2f &p )
{
	return boost::geometry::make<boost::geometry::model::d2::point_xy<double> >( p.x, p.y );
}

void includePathExtremeties( const Path2d &p, polygon *output )
{
	size_t firstPoint = 0;
	for( size_t s = 0; s < p.getSegments().size(); ++s ) {
		switch( p.getSegments()[s] ) {
			case Path2d::CUBICTO: {
				float monotoneT[4];
				int monotoneCnt = Path2d::calcCubicBezierMonotoneRegions( &(p.getPoints()[firstPoint]), monotoneT );
				for( int monotoneIdx = 0; monotoneIdx < monotoneCnt; ++monotoneIdx )
					output->outer().push_back( makePoint( Path2d::calcCubicBezierPos( &(p.getPoints()[firstPoint]), monotoneT[monotoneIdx] ) ) );

				output->outer().push_back( makePoint( p.getPoints()[firstPoint+0] ) );
				output->outer().push_back( makePoint( p.getPoints()[firstPoint+1] ) );
				output->outer().push_back( makePoint( p.getPoints()[firstPoint+2] ) );
			}
			break;
			case Path2d::QUADTO: {
				float monotoneT[2];
				int monotoneCnt = Path2d::calcCubicBezierMonotoneRegions( &(p.getPoints()[firstPoint]), monotoneT );
				for( int monotoneIdx = 0; monotoneIdx < monotoneCnt; ++monotoneIdx )
					output->outer().push_back( makePoint( Path2d::calcQuadraticBezierPos( &(p.getPoints()[firstPoint]), monotoneT[monotoneIdx] ) ) );
				output->outer().push_back( makePoint( p.getPoints()[firstPoint+0] ) );
				output->outer().push_back( makePoint( p.getPoints()[firstPoint+1] ) );
			}
			break;
			case Path2d::LINETO:
				output->outer().push_back( makePoint( p.getPoints()[firstPoint+0] ) );
			break;
			case Path2d::CLOSE:
				output->outer().push_back( makePoint( p.getPoints()[firstPoint+0] ) );
			break;
			default:
				throw Path2dExc();
		}

		firstPoint += Path2d::sSegmentTypePointCounts[p.getSegments()[s]];
	}
}

} // anonymous namespace

PolyLine2f calcConvexHull( const std::vector<Vec2f> &points )
{
	if( points.empty() )
		return PolyLine2f();
	else
		return calcConvexHull( points.data(), points.size() );
}

PolyLine2f calcConvexHull( const Vec2f *points, size_t numPoints )
{
	polygon poly;
	for( size_t p = 0; p < numPoints; ++p )
		poly.outer().push_back( boost::geometry::make<boost::geometry::model::d2::point_xy<double> >( points[p].x, points[p].y ) );

	polygon result;
	boost::geometry::convex_hull( poly, result );

	return toPolyLine<float>( result );
}

PolyLine2f calcConvexHull( const Shape2d &shape )
{
	polygon poly;
	for( auto contourIt = shape.getContours().begin(); contourIt != shape.getContours().end(); ++contourIt )
		includePathExtremeties( *contourIt, &poly );

	polygon result;
	boost::geometry::convex_hull( poly, result );

	return toPolyLine<float>( result );
}

PolyLine2f calcConvexHull( const Path2d &path )
{
	polygon poly;
	includePathExtremeties( path, &poly );

	polygon result;
	boost::geometry::convex_hull( poly, result );

	return toPolyLine<float>( result );
}

PolyLine2f calcConvexHull( const PolyLine2f &polyLine )
{
	polygon poly;
	for( auto ptIt = polyLine.begin(); ptIt != polyLine.end(); ++ptIt )
		poly.outer().push_back( boost::geometry::make<boost::geometry::model::d2::point_xy<double> >( ptIt->x, ptIt->y ) );

	polygon result;
	boost::geometry::convex_hull( poly, result );

	return toPolyLine<float>( result );
}

} // namespace cinder<commit_msg>remove templates Vec2 type, it was private and only float is in use (avoids another vlm::detail::tvec2 exposure)<commit_after>/*
 Copyright (c) 2013, The Cinder Project (http://libcinder.org)
 All rights reserved.

 Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and
	the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials provided with the distribution.

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

#include "cinder/ConvexHull.h"

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>

namespace cinder {

typedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;

namespace {

PolyLine2f toPolyLine( const polygon &p )
{
	PolyLine2f result;

	for( auto pt = p.outer().begin(); pt != p.outer().end(); ++pt )
		result.push_back( vec2( boost::geometry::get<0>(*pt), boost::geometry::get<1>(*pt) ) );

	return result;
}

boost::geometry::model::d2::point_xy<double> makePoint( const Vec2f &p )
{
	return boost::geometry::make<boost::geometry::model::d2::point_xy<double> >( p.x, p.y );
}

void includePathExtremeties( const Path2d &p, polygon *output )
{
	size_t firstPoint = 0;
	for( size_t s = 0; s < p.getSegments().size(); ++s ) {
		switch( p.getSegments()[s] ) {
			case Path2d::CUBICTO: {
				float monotoneT[4];
				int monotoneCnt = Path2d::calcCubicBezierMonotoneRegions( &(p.getPoints()[firstPoint]), monotoneT );
				for( int monotoneIdx = 0; monotoneIdx < monotoneCnt; ++monotoneIdx )
					output->outer().push_back( makePoint( Path2d::calcCubicBezierPos( &(p.getPoints()[firstPoint]), monotoneT[monotoneIdx] ) ) );

				output->outer().push_back( makePoint( p.getPoints()[firstPoint+0] ) );
				output->outer().push_back( makePoint( p.getPoints()[firstPoint+1] ) );
				output->outer().push_back( makePoint( p.getPoints()[firstPoint+2] ) );
			}
			break;
			case Path2d::QUADTO: {
				float monotoneT[2];
				int monotoneCnt = Path2d::calcCubicBezierMonotoneRegions( &(p.getPoints()[firstPoint]), monotoneT );
				for( int monotoneIdx = 0; monotoneIdx < monotoneCnt; ++monotoneIdx )
					output->outer().push_back( makePoint( Path2d::calcQuadraticBezierPos( &(p.getPoints()[firstPoint]), monotoneT[monotoneIdx] ) ) );
				output->outer().push_back( makePoint( p.getPoints()[firstPoint+0] ) );
				output->outer().push_back( makePoint( p.getPoints()[firstPoint+1] ) );
			}
			break;
			case Path2d::LINETO:
				output->outer().push_back( makePoint( p.getPoints()[firstPoint+0] ) );
			break;
			case Path2d::CLOSE:
				output->outer().push_back( makePoint( p.getPoints()[firstPoint+0] ) );
			break;
			default:
				throw Path2dExc();
		}

		firstPoint += Path2d::sSegmentTypePointCounts[p.getSegments()[s]];
	}
}

} // anonymous namespace

PolyLine2f calcConvexHull( const std::vector<Vec2f> &points )
{
	if( points.empty() )
		return PolyLine2f();
	else
		return calcConvexHull( points.data(), points.size() );
}

PolyLine2f calcConvexHull( const Vec2f *points, size_t numPoints )
{
	polygon poly;
	for( size_t p = 0; p < numPoints; ++p )
		poly.outer().push_back( boost::geometry::make<boost::geometry::model::d2::point_xy<double> >( points[p].x, points[p].y ) );

	polygon result;
	boost::geometry::convex_hull( poly, result );

	return toPolyLine( result );
}

PolyLine2f calcConvexHull( const Shape2d &shape )
{
	polygon poly;
	for( auto contourIt = shape.getContours().begin(); contourIt != shape.getContours().end(); ++contourIt )
		includePathExtremeties( *contourIt, &poly );

	polygon result;
	boost::geometry::convex_hull( poly, result );

	return toPolyLine( result );
}

PolyLine2f calcConvexHull( const Path2d &path )
{
	polygon poly;
	includePathExtremeties( path, &poly );

	polygon result;
	boost::geometry::convex_hull( poly, result );

	return toPolyLine( result );
}

PolyLine2f calcConvexHull( const PolyLine2f &polyLine )
{
	polygon poly;
	for( auto ptIt = polyLine.begin(); ptIt != polyLine.end(); ++ptIt )
		poly.outer().push_back( boost::geometry::make<boost::geometry::model::d2::point_xy<double> >( ptIt->x, ptIt->y ) );

	polygon result;
	boost::geometry::convex_hull( poly, result );

	return toPolyLine( result );
}

} // namespace cinder<|endoftext|>


<commit_before>#include "effectswidgets.h"
#include <QPainter>
#include <QTimer>
#include <QEvent>
#include <QApplication>
using namespace GUtil::QtControls::EffectsWidgets;

FaderWidget::FaderWidget(QWidget *par, int fade_duration, int start_delay)
    : QWidget(par)
{
    if (par)
        color = par->palette().window().color();
    else
        color = Qt::white;

    _fade_in = false;

    duration = fade_duration;
    delay = start_delay;

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));

    // We want to intercept resize event so we can adjust our size
    par->installEventFilter(this);
}

bool FaderWidget::eventFilter(QObject *obj, QEvent *ev)
{
    bool ret = false;

    if(obj == parent())
    {
        if(ev->type() == QEvent::Resize)
        {
            resize(parentWidget()->size());
            ret = true;
        }
    }

    return ret;
}

QColor FaderWidget::fadeColor() const
{
    return color;
}

void FaderWidget::setFadeColor(const QColor &newColor)
{
    color = newColor;
}

int FaderWidget::fadeDuration() const
{
    return duration;
}

void FaderWidget::setFadeDuration(int milliseconds)
{
    duration = milliseconds;
}

void FaderWidget::start_fading()
{
    if(timer->isActive())
    {
        // don't allow to fade while it's in the middle of fading
        return;
    }

    if(_fade_in)
        currentAlpha = 255;
    else
        currentAlpha = 0;

    show();

    // Check if the parent is in the correct state before we fade it
    if((_fade_in && parentWidget()->isHidden()) ||
       (!_fade_in && !parentWidget()->isHidden()))
    {
        QTimer::singleShot(delay, this, SLOT(_start()));
    }
}

void FaderWidget::_start()
{
    if(_fade_in)
        parentWidget()->show();

    timer->start(30);
}

void FaderWidget::paintEvent(QPaintEvent * /* event */)
{
    QPainter painter(this);
    QColor semiTransparentColor = color;
    semiTransparentColor.setAlpha(currentAlpha);

    painter.fillRect(rect(), semiTransparentColor);

    if(timer->isActive())
    {
        if(_fade_in)
        {
            currentAlpha -= (255 * timer->interval()) / duration;
            if (currentAlpha <= 0)
            {
                timer->stop();
                currentAlpha = 0;

                hide();

                emit doneFading(true);
            }
        }
        else
        {
            currentAlpha += (255 * timer->interval()) / duration;
            if (currentAlpha >= 255)
            {
                timer->stop();
                currentAlpha = 255;

                // Hide the parent once we're faded out
                parentWidget()->hide();

                hide();

                emit doneFading(false);
            }
        }
    }
}

void FaderWidget::fadeIn()
{
    _fade_in = true;
    start_fading();
}

void FaderWidget::fadeOut()
{
    _fade_in = false;
    start_fading();
}

void FaderWidget::toggleFade()
{
    _fade_in = !_fade_in;
    start_fading();
}
<commit_msg>Minor change so it does 'showNormal' instead of show<commit_after>#include "effectswidgets.h"
#include <QPainter>
#include <QTimer>
#include <QEvent>
#include <QApplication>
using namespace GUtil::QtControls::EffectsWidgets;

FaderWidget::FaderWidget(QWidget *par, int fade_duration, int start_delay)
    : QWidget(par)
{
    if (par)
        color = par->palette().window().color();
    else
        color = Qt::white;

    _fade_in = false;

    duration = fade_duration;
    delay = start_delay;

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));

    // We want to intercept resize event so we can adjust our size
    par->installEventFilter(this);
}

bool FaderWidget::eventFilter(QObject *obj, QEvent *ev)
{
    bool ret = false;

    if(obj == parent())
    {
        if(ev->type() == QEvent::Resize)
        {
            resize(parentWidget()->size());
            ret = true;
        }
    }

    return ret;
}

QColor FaderWidget::fadeColor() const
{
    return color;
}

void FaderWidget::setFadeColor(const QColor &newColor)
{
    color = newColor;
}

int FaderWidget::fadeDuration() const
{
    return duration;
}

void FaderWidget::setFadeDuration(int milliseconds)
{
    duration = milliseconds;
}

void FaderWidget::start_fading()
{
    if(timer->isActive())
    {
        // don't allow to fade while it's in the middle of fading
        return;
    }

    if(_fade_in)
        currentAlpha = 255;
    else
        currentAlpha = 0;

    show();

    // Check if the parent is in the correct state before we fade it
    if((_fade_in && parentWidget()->isHidden()) ||
       (!_fade_in && !parentWidget()->isHidden()))
    {
        QTimer::singleShot(delay, this, SLOT(_start()));
    }
}

void FaderWidget::_start()
{
    if(_fade_in)
        parentWidget()->showNormal();

    timer->start(30);
}

void FaderWidget::paintEvent(QPaintEvent * /* event */)
{
    QPainter painter(this);
    QColor semiTransparentColor = color;
    semiTransparentColor.setAlpha(currentAlpha);

    painter.fillRect(rect(), semiTransparentColor);

    if(timer->isActive())
    {
        if(_fade_in)
        {
            currentAlpha -= (255 * timer->interval()) / duration;
            if (currentAlpha <= 0)
            {
                timer->stop();
                currentAlpha = 0;

                hide();

                emit doneFading(true);
            }
        }
        else
        {
            currentAlpha += (255 * timer->interval()) / duration;
            if (currentAlpha >= 255)
            {
                timer->stop();
                currentAlpha = 255;

                // Hide the parent once we're faded out
                parentWidget()->hide();

                hide();

                emit doneFading(false);
            }
        }
    }
}

void FaderWidget::fadeIn()
{
    _fade_in = true;
    start_fading();
}

void FaderWidget::fadeOut()
{
    _fade_in = false;
    start_fading();
}

void FaderWidget::toggleFade()
{
    _fade_in = !_fade_in;
    start_fading();
}
<|endoftext|>


<commit_before>#ifndef _SNARKFRONT_HPP_
#define _SNARKFRONT_HPP_

////////////////////////////////////////////////////////////////////////////////
// this header file includes everything applications need
//

// the basic language
#include "FoundationDSL.hpp"

// progress bar for proof generation and verification
#include "GenericProgressBar.hpp"

// input and printing of hexadecimal text
#include "HexUtil.hpp"

// initialize elliptic curves
#include "MainEC.hpp"

// Merkle tree
#include "MerkleTree.hpp"

// Secure Hash Algorithms
#include "SHA_1.hpp"
#include "SHA_224.hpp"
#include "SHA_256.hpp"
#include "SHA_384.hpp"
#include "SHA_512.hpp"
#include "SHA_512_224.hpp"
#include "SHA_512_256.hpp"

#endif
<commit_msg>refactored header files<commit_after>#ifndef _SNARKFRONT_HPP_
#define _SNARKFRONT_HPP_

////////////////////////////////////////////////////////////////////////////////
// this header file includes everything applications need
//

// the basic language
#include "DSL_base.hpp"
#include "DSL_bless.hpp"
#include "DSL_identity.hpp"
#include "DSL_ppzk.hpp"
#include "DSL_utility.hpp"

// progress bar for proof generation and verification
#include "GenericProgressBar.hpp"

// input and printing of hexadecimal text
#include "HexUtil.hpp"

// initialize elliptic curves
#include "InitPairing.hpp"

// Merkle tree
#include "MerkleTree.hpp"

// Secure Hash Algorithms
#include "SHA_1.hpp"
#include "SHA_224.hpp"
#include "SHA_256.hpp"
#include "SHA_384.hpp"
#include "SHA_512.hpp"
#include "SHA_512_224.hpp"
#include "SHA_512_256.hpp"

#endif
<|endoftext|>