<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/google/google_update.h"

#include <atlbase.h>
#include <atlcom.h>

#include "base/file_path.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/scoped_comptr_win.h"
#include "base/string_util.h"
#include "base/task.h"
#include "base/thread.h"
#include "base/win/windows_version.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/helper.h"
#include "chrome/installer/util/install_util.h"
#include "views/window/window.h"
#include "google_update_idl_i.c"

using views::Window;

namespace {
// Check if the currently running instance can be updated by Google Update.
// Returns true only if the instance running is a Google Chrome
// distribution installed in a standard location.
bool CanUpdateCurrentChrome(const std::wstring& chrome_exe_path) {
#if !defined(GOOGLE_CHROME_BUILD)
  return false;
#else
  std::wstring user_exe_path = installer::GetChromeInstallPath(false);
  std::wstring machine_exe_path = installer::GetChromeInstallPath(true);
  std::transform(user_exe_path.begin(), user_exe_path.end(),
                 user_exe_path.begin(), tolower);
  std::transform(machine_exe_path.begin(), machine_exe_path.end(),
                 machine_exe_path.begin(), tolower);
  if (chrome_exe_path != user_exe_path &&
      chrome_exe_path != machine_exe_path ) {
    LOG(ERROR) << L"Google Update cannot update Chrome installed in a "
               << L"non-standard location: " << chrome_exe_path.c_str()
               << L". The standard location is: " << user_exe_path.c_str()
               << L" or " << machine_exe_path.c_str() << L".";
    return false;
  }

  return true;
#endif
}

// Creates an instance of a COM Local Server class using either plain vanilla
// CoCreateInstance, or using the Elevation moniker if running on Vista.
// hwnd must refer to a foregound window in order to get the UAC prompt
// showing up in the foreground if running on Vista. It can also be NULL if
// background UAC prompts are desired.
HRESULT CoCreateInstanceAsAdmin(REFCLSID class_id, REFIID interface_id,
                                HWND hwnd, void** interface_ptr) {
  if (!interface_ptr)
    return E_POINTER;

  // For Vista we need to instantiate the COM server via the elevation
  // moniker. This ensures that the UAC dialog shows up.
  if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
    wchar_t class_id_as_string[MAX_PATH] = {0};
    StringFromGUID2(class_id, class_id_as_string,
                    arraysize(class_id_as_string));

    std::wstring elevation_moniker_name =
        StringPrintf(L"Elevation:Administrator!new:%ls", class_id_as_string);

    BIND_OPTS3 bind_opts;
    memset(&bind_opts, 0, sizeof(bind_opts));
    bind_opts.cbStruct = sizeof(bind_opts);
    bind_opts.dwClassContext = CLSCTX_LOCAL_SERVER;
    bind_opts.hwnd = hwnd;

    return CoGetObject(elevation_moniker_name.c_str(), &bind_opts,
                       interface_id, reinterpret_cast<void**>(interface_ptr));
  }

  return CoCreateInstance(class_id, NULL, CLSCTX_LOCAL_SERVER,
                          interface_id,
                          reinterpret_cast<void**>(interface_ptr));
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
//
// The GoogleUpdateJobObserver COM class is responsible for receiving status
// reports from google Update. It keeps track of the progress as Google Update
// notifies us and ends the message loop we are spinning in once Google Update
// reports that it is done.
//
////////////////////////////////////////////////////////////////////////////////
class GoogleUpdateJobObserver
  : public CComObjectRootEx<CComSingleThreadModel>,
    public IJobObserver {
 public:
  BEGIN_COM_MAP(GoogleUpdateJobObserver)
    COM_INTERFACE_ENTRY(IJobObserver)
  END_COM_MAP()

  GoogleUpdateJobObserver()
    : result_(UPGRADE_ERROR) {
  }
  virtual ~GoogleUpdateJobObserver() {}

  // Notifications from Google Update:
  STDMETHOD(OnShow)() {
    return S_OK;
  }
  STDMETHOD(OnCheckingForUpdate)() {
    result_ = UPGRADE_CHECK_STARTED;
    return S_OK;
  }
  STDMETHOD(OnUpdateAvailable)(const TCHAR* version_string) {
    result_ = UPGRADE_IS_AVAILABLE;
    new_version_ = version_string;
    return S_OK;
  }
  STDMETHOD(OnWaitingToDownload)() {
    return S_OK;
  }
  STDMETHOD(OnDownloading)(int time_remaining_ms, int pos) {
    return S_OK;
  }
  STDMETHOD(OnWaitingToInstall)() {
    return S_OK;
  }
  STDMETHOD(OnInstalling)() {
    result_ = UPGRADE_STARTED;
    return S_OK;
  }
  STDMETHOD(OnPause)() {
    return S_OK;
  }
  STDMETHOD(OnComplete)(CompletionCodes code, const TCHAR* text) {
    switch (code) {
      case COMPLETION_CODE_SUCCESS_CLOSE_UI:
      case COMPLETION_CODE_SUCCESS: {
        if (result_ == UPGRADE_STARTED)
          result_ = UPGRADE_SUCCESSFUL;
        else if (result_ == UPGRADE_CHECK_STARTED)
          result_ = UPGRADE_ALREADY_UP_TO_DATE;
        break;
      }
      default: {
        NOTREACHED();
        result_ = UPGRADE_ERROR;
        break;
      }
    }

    event_sink_ = NULL;

    // We no longer need to spin the message loop that we started spinning in
    // InitiateGoogleUpdateCheck.
    MessageLoop::current()->Quit();
    return S_OK;
  }
  STDMETHOD(SetEventSink)(IProgressWndEvents* event_sink) {
    event_sink_ = event_sink;
    return S_OK;
  }

  // Returns the results of the update operation.
  STDMETHOD(GetResult)(GoogleUpdateUpgradeResult* result) {
    // Intermediary steps should never be reported to the client.
    DCHECK(result_ != UPGRADE_STARTED && result_ != UPGRADE_CHECK_STARTED);

    *result = result_;
    return S_OK;
  }

  // Returns which version Google Update found on the server (if a more
  // recent version was found). Otherwise, this will be blank.
  STDMETHOD(GetVersionInfo)(std::wstring* version_string) {
    *version_string = new_version_;
    return S_OK;
  }

 private:
  // The status/result of the Google Update operation.
  GoogleUpdateUpgradeResult result_;

  // The version string Google Update found.
  std::wstring new_version_;

  // Allows us control the upgrade process to a small degree. After OnComplete
  // has been called, this object can not be used.
  ScopedComPtr<IProgressWndEvents> event_sink_;
};

////////////////////////////////////////////////////////////////////////////////
// GoogleUpdate, public:

GoogleUpdate::GoogleUpdate()
    : listener_(NULL) {
}

GoogleUpdate::~GoogleUpdate() {
}

////////////////////////////////////////////////////////////////////////////////
// GoogleUpdate, views::DialogDelegate implementation:

void GoogleUpdate::CheckForUpdate(bool install_if_newer, Window* window) {
  // We need to shunt this request over to InitiateGoogleUpdateCheck and have
  // it run in the file thread.
  BrowserThread::PostTask(
      BrowserThread::FILE, FROM_HERE,
      NewRunnableMethod(
          this, &GoogleUpdate::InitiateGoogleUpdateCheck, install_if_newer,
          window, MessageLoop::current()));
}

////////////////////////////////////////////////////////////////////////////////
// GoogleUpdate, private:

bool GoogleUpdate::InitiateGoogleUpdateCheck(bool install_if_newer,
                                             Window* window,
                                             MessageLoop* main_loop) {

  FilePath chrome_exe_path;
  if (!PathService::Get(base::DIR_EXE, &chrome_exe_path)) {
    NOTREACHED();
    return false;
  }
  std::wstring chrome_exe = chrome_exe_path.value();

  std::transform(chrome_exe.begin(), chrome_exe.end(),
                 chrome_exe.begin(), tolower);

  if (!CanUpdateCurrentChrome(chrome_exe)) {
    main_loop->PostTask(FROM_HERE, NewRunnableMethod(this,
        &GoogleUpdate::ReportResults, UPGRADE_ERROR,
        CANNOT_UPGRADE_CHROME_IN_THIS_DIRECTORY));
    return false;
  }

  CComObject<GoogleUpdateJobObserver>* job_observer;
  HRESULT hr =
      CComObject<GoogleUpdateJobObserver>::CreateInstance(&job_observer);
  if (hr != S_OK) {
    return ReportFailure(hr, GOOGLE_UPDATE_JOB_SERVER_CREATION_FAILED,
                         main_loop);
  }

  ScopedComPtr<IJobObserver> job_holder(job_observer);

  ScopedComPtr<IGoogleUpdate> on_demand;

  if (InstallUtil::IsPerUserInstall(chrome_exe.c_str())) {
    hr = on_demand.CreateInstance(CLSID_OnDemandUserAppsClass);
  } else {
    // The Update operation needs Admin privileges for writing
    // to %ProgramFiles%. On Vista we need to elevate before instantiating
    // the updater instance.
    if (!install_if_newer) {
      hr = on_demand.CreateInstance(CLSID_OnDemandMachineAppsClass);
    } else {
      HWND foreground_hwnd = NULL;
      if (window != NULL) {
        foreground_hwnd = window->GetNativeWindow();
      }

      hr = CoCreateInstanceAsAdmin(CLSID_OnDemandMachineAppsClass,
          IID_IGoogleUpdate, foreground_hwnd,
          reinterpret_cast<void**>(on_demand.Receive()));
    }
  }

  if (hr != S_OK)
    return ReportFailure(hr, GOOGLE_UPDATE_ONDEMAND_CLASS_NOT_FOUND, main_loop);

  BrowserDistribution* dist = BrowserDistribution::GetDistribution();
  if (!install_if_newer)
    hr = on_demand->CheckForUpdate(dist->GetAppGuid().c_str(), job_observer);
  else
    hr = on_demand->Update(dist->GetAppGuid().c_str(), job_observer);

  if (hr != S_OK)
    return ReportFailure(hr, GOOGLE_UPDATE_ONDEMAND_CLASS_REPORTED_ERROR,
                         main_loop);

  // We need to spin the message loop while Google Update is running so that it
  // can report back to us through GoogleUpdateJobObserver. This message loop
  // will terminate once Google Update sends us the completion status
  // (success/error). See OnComplete().
  MessageLoop::current()->Run();

  GoogleUpdateUpgradeResult results;
  hr = job_observer->GetResult(&results);
  if (hr != S_OK)
    return ReportFailure(hr, GOOGLE_UPDATE_GET_RESULT_CALL_FAILED, main_loop);

  if (results == UPGRADE_ERROR)
    return ReportFailure(hr, GOOGLE_UPDATE_ERROR_UPDATING, main_loop);

  hr = job_observer->GetVersionInfo(&version_available_);
  if (hr != S_OK)
    return ReportFailure(hr, GOOGLE_UPDATE_GET_VERSION_INFO_FAILED, main_loop);

  main_loop->PostTask(FROM_HERE, NewRunnableMethod(this,
      &GoogleUpdate::ReportResults, results, GOOGLE_UPDATE_NO_ERROR));
  job_holder = NULL;
  on_demand = NULL;
  return true;
}

void GoogleUpdate::ReportResults(GoogleUpdateUpgradeResult results,
                                 GoogleUpdateErrorCode error_code) {
  // If we get an error, then error code must not be blank, and vice versa.
  DCHECK(results == UPGRADE_ERROR ? error_code != GOOGLE_UPDATE_NO_ERROR :
                                    error_code == GOOGLE_UPDATE_NO_ERROR);
  if (listener_)
    listener_->OnReportResults(results, error_code, version_available_);
}

bool GoogleUpdate::ReportFailure(HRESULT hr, GoogleUpdateErrorCode error_code,
                                 MessageLoop* main_loop) {
  NOTREACHED() << "Communication with Google Update failed: " << hr
               << " error: " << error_code;
  main_loop->PostTask(FROM_HERE, NewRunnableMethod(this,
      &GoogleUpdate::ReportResults, UPGRADE_ERROR, error_code));
  return false;
}
<commit_msg>A build fix for our official bot. This just adds a pointer to BrowserDistribution as the second parameter for installer::GetChromeInstallPath() to fix the build breaks on the "Google Chrome Win" bot.<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/google/google_update.h"

#include <atlbase.h>
#include <atlcom.h>

#include "base/file_path.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/scoped_comptr_win.h"
#include "base/string_util.h"
#include "base/task.h"
#include "base/thread.h"
#include "base/win/windows_version.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/helper.h"
#include "chrome/installer/util/install_util.h"
#include "views/window/window.h"
#include "google_update_idl_i.c"

using views::Window;

namespace {
// Check if the currently running instance can be updated by Google Update.
// Returns true only if the instance running is a Google Chrome
// distribution installed in a standard location.
bool CanUpdateCurrentChrome(const std::wstring& chrome_exe_path) {
#if !defined(GOOGLE_CHROME_BUILD)
  return false;
#else
  // TODO(tommi): Check if using the default distribution is always the right
  // thing to do.
  BrowserDistribution* dist = BrowserDistribution::GetDistribution()
  std::wstring user_exe_path = installer::GetChromeInstallPath(false, dist);
  std::wstring machine_exe_path = installer::GetChromeInstallPath(true, dist);
  std::transform(user_exe_path.begin(), user_exe_path.end(),
                 user_exe_path.begin(), tolower);
  std::transform(machine_exe_path.begin(), machine_exe_path.end(),
                 machine_exe_path.begin(), tolower);
  if (chrome_exe_path != user_exe_path &&
      chrome_exe_path != machine_exe_path ) {
    LOG(ERROR) << L"Google Update cannot update Chrome installed in a "
               << L"non-standard location: " << chrome_exe_path.c_str()
               << L". The standard location is: " << user_exe_path.c_str()
               << L" or " << machine_exe_path.c_str() << L".";
    return false;
  }

  return true;
#endif
}

// Creates an instance of a COM Local Server class using either plain vanilla
// CoCreateInstance, or using the Elevation moniker if running on Vista.
// hwnd must refer to a foregound window in order to get the UAC prompt
// showing up in the foreground if running on Vista. It can also be NULL if
// background UAC prompts are desired.
HRESULT CoCreateInstanceAsAdmin(REFCLSID class_id, REFIID interface_id,
                                HWND hwnd, void** interface_ptr) {
  if (!interface_ptr)
    return E_POINTER;

  // For Vista we need to instantiate the COM server via the elevation
  // moniker. This ensures that the UAC dialog shows up.
  if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
    wchar_t class_id_as_string[MAX_PATH] = {0};
    StringFromGUID2(class_id, class_id_as_string,
                    arraysize(class_id_as_string));

    std::wstring elevation_moniker_name =
        StringPrintf(L"Elevation:Administrator!new:%ls", class_id_as_string);

    BIND_OPTS3 bind_opts;
    memset(&bind_opts, 0, sizeof(bind_opts));
    bind_opts.cbStruct = sizeof(bind_opts);
    bind_opts.dwClassContext = CLSCTX_LOCAL_SERVER;
    bind_opts.hwnd = hwnd;

    return CoGetObject(elevation_moniker_name.c_str(), &bind_opts,
                       interface_id, reinterpret_cast<void**>(interface_ptr));
  }

  return CoCreateInstance(class_id, NULL, CLSCTX_LOCAL_SERVER,
                          interface_id,
                          reinterpret_cast<void**>(interface_ptr));
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
//
// The GoogleUpdateJobObserver COM class is responsible for receiving status
// reports from google Update. It keeps track of the progress as Google Update
// notifies us and ends the message loop we are spinning in once Google Update
// reports that it is done.
//
////////////////////////////////////////////////////////////////////////////////
class GoogleUpdateJobObserver
  : public CComObjectRootEx<CComSingleThreadModel>,
    public IJobObserver {
 public:
  BEGIN_COM_MAP(GoogleUpdateJobObserver)
    COM_INTERFACE_ENTRY(IJobObserver)
  END_COM_MAP()

  GoogleUpdateJobObserver()
    : result_(UPGRADE_ERROR) {
  }
  virtual ~GoogleUpdateJobObserver() {}

  // Notifications from Google Update:
  STDMETHOD(OnShow)() {
    return S_OK;
  }
  STDMETHOD(OnCheckingForUpdate)() {
    result_ = UPGRADE_CHECK_STARTED;
    return S_OK;
  }
  STDMETHOD(OnUpdateAvailable)(const TCHAR* version_string) {
    result_ = UPGRADE_IS_AVAILABLE;
    new_version_ = version_string;
    return S_OK;
  }
  STDMETHOD(OnWaitingToDownload)() {
    return S_OK;
  }
  STDMETHOD(OnDownloading)(int time_remaining_ms, int pos) {
    return S_OK;
  }
  STDMETHOD(OnWaitingToInstall)() {
    return S_OK;
  }
  STDMETHOD(OnInstalling)() {
    result_ = UPGRADE_STARTED;
    return S_OK;
  }
  STDMETHOD(OnPause)() {
    return S_OK;
  }
  STDMETHOD(OnComplete)(CompletionCodes code, const TCHAR* text) {
    switch (code) {
      case COMPLETION_CODE_SUCCESS_CLOSE_UI:
      case COMPLETION_CODE_SUCCESS: {
        if (result_ == UPGRADE_STARTED)
          result_ = UPGRADE_SUCCESSFUL;
        else if (result_ == UPGRADE_CHECK_STARTED)
          result_ = UPGRADE_ALREADY_UP_TO_DATE;
        break;
      }
      default: {
        NOTREACHED();
        result_ = UPGRADE_ERROR;
        break;
      }
    }

    event_sink_ = NULL;

    // We no longer need to spin the message loop that we started spinning in
    // InitiateGoogleUpdateCheck.
    MessageLoop::current()->Quit();
    return S_OK;
  }
  STDMETHOD(SetEventSink)(IProgressWndEvents* event_sink) {
    event_sink_ = event_sink;
    return S_OK;
  }

  // Returns the results of the update operation.
  STDMETHOD(GetResult)(GoogleUpdateUpgradeResult* result) {
    // Intermediary steps should never be reported to the client.
    DCHECK(result_ != UPGRADE_STARTED && result_ != UPGRADE_CHECK_STARTED);

    *result = result_;
    return S_OK;
  }

  // Returns which version Google Update found on the server (if a more
  // recent version was found). Otherwise, this will be blank.
  STDMETHOD(GetVersionInfo)(std::wstring* version_string) {
    *version_string = new_version_;
    return S_OK;
  }

 private:
  // The status/result of the Google Update operation.
  GoogleUpdateUpgradeResult result_;

  // The version string Google Update found.
  std::wstring new_version_;

  // Allows us control the upgrade process to a small degree. After OnComplete
  // has been called, this object can not be used.
  ScopedComPtr<IProgressWndEvents> event_sink_;
};

////////////////////////////////////////////////////////////////////////////////
// GoogleUpdate, public:

GoogleUpdate::GoogleUpdate()
    : listener_(NULL) {
}

GoogleUpdate::~GoogleUpdate() {
}

////////////////////////////////////////////////////////////////////////////////
// GoogleUpdate, views::DialogDelegate implementation:

void GoogleUpdate::CheckForUpdate(bool install_if_newer, Window* window) {
  // We need to shunt this request over to InitiateGoogleUpdateCheck and have
  // it run in the file thread.
  BrowserThread::PostTask(
      BrowserThread::FILE, FROM_HERE,
      NewRunnableMethod(
          this, &GoogleUpdate::InitiateGoogleUpdateCheck, install_if_newer,
          window, MessageLoop::current()));
}

////////////////////////////////////////////////////////////////////////////////
// GoogleUpdate, private:

bool GoogleUpdate::InitiateGoogleUpdateCheck(bool install_if_newer,
                                             Window* window,
                                             MessageLoop* main_loop) {

  FilePath chrome_exe_path;
  if (!PathService::Get(base::DIR_EXE, &chrome_exe_path)) {
    NOTREACHED();
    return false;
  }
  std::wstring chrome_exe = chrome_exe_path.value();

  std::transform(chrome_exe.begin(), chrome_exe.end(),
                 chrome_exe.begin(), tolower);

  if (!CanUpdateCurrentChrome(chrome_exe)) {
    main_loop->PostTask(FROM_HERE, NewRunnableMethod(this,
        &GoogleUpdate::ReportResults, UPGRADE_ERROR,
        CANNOT_UPGRADE_CHROME_IN_THIS_DIRECTORY));
    return false;
  }

  CComObject<GoogleUpdateJobObserver>* job_observer;
  HRESULT hr =
      CComObject<GoogleUpdateJobObserver>::CreateInstance(&job_observer);
  if (hr != S_OK) {
    return ReportFailure(hr, GOOGLE_UPDATE_JOB_SERVER_CREATION_FAILED,
                         main_loop);
  }

  ScopedComPtr<IJobObserver> job_holder(job_observer);

  ScopedComPtr<IGoogleUpdate> on_demand;

  if (InstallUtil::IsPerUserInstall(chrome_exe.c_str())) {
    hr = on_demand.CreateInstance(CLSID_OnDemandUserAppsClass);
  } else {
    // The Update operation needs Admin privileges for writing
    // to %ProgramFiles%. On Vista we need to elevate before instantiating
    // the updater instance.
    if (!install_if_newer) {
      hr = on_demand.CreateInstance(CLSID_OnDemandMachineAppsClass);
    } else {
      HWND foreground_hwnd = NULL;
      if (window != NULL) {
        foreground_hwnd = window->GetNativeWindow();
      }

      hr = CoCreateInstanceAsAdmin(CLSID_OnDemandMachineAppsClass,
          IID_IGoogleUpdate, foreground_hwnd,
          reinterpret_cast<void**>(on_demand.Receive()));
    }
  }

  if (hr != S_OK)
    return ReportFailure(hr, GOOGLE_UPDATE_ONDEMAND_CLASS_NOT_FOUND, main_loop);

  BrowserDistribution* dist = BrowserDistribution::GetDistribution();
  if (!install_if_newer)
    hr = on_demand->CheckForUpdate(dist->GetAppGuid().c_str(), job_observer);
  else
    hr = on_demand->Update(dist->GetAppGuid().c_str(), job_observer);

  if (hr != S_OK)
    return ReportFailure(hr, GOOGLE_UPDATE_ONDEMAND_CLASS_REPORTED_ERROR,
                         main_loop);

  // We need to spin the message loop while Google Update is running so that it
  // can report back to us through GoogleUpdateJobObserver. This message loop
  // will terminate once Google Update sends us the completion status
  // (success/error). See OnComplete().
  MessageLoop::current()->Run();

  GoogleUpdateUpgradeResult results;
  hr = job_observer->GetResult(&results);
  if (hr != S_OK)
    return ReportFailure(hr, GOOGLE_UPDATE_GET_RESULT_CALL_FAILED, main_loop);

  if (results == UPGRADE_ERROR)
    return ReportFailure(hr, GOOGLE_UPDATE_ERROR_UPDATING, main_loop);

  hr = job_observer->GetVersionInfo(&version_available_);
  if (hr != S_OK)
    return ReportFailure(hr, GOOGLE_UPDATE_GET_VERSION_INFO_FAILED, main_loop);

  main_loop->PostTask(FROM_HERE, NewRunnableMethod(this,
      &GoogleUpdate::ReportResults, results, GOOGLE_UPDATE_NO_ERROR));
  job_holder = NULL;
  on_demand = NULL;
  return true;
}

void GoogleUpdate::ReportResults(GoogleUpdateUpgradeResult results,
                                 GoogleUpdateErrorCode error_code) {
  // If we get an error, then error code must not be blank, and vice versa.
  DCHECK(results == UPGRADE_ERROR ? error_code != GOOGLE_UPDATE_NO_ERROR :
                                    error_code == GOOGLE_UPDATE_NO_ERROR);
  if (listener_)
    listener_->OnReportResults(results, error_code, version_available_);
}

bool GoogleUpdate::ReportFailure(HRESULT hr, GoogleUpdateErrorCode error_code,
                                 MessageLoop* main_loop) {
  NOTREACHED() << "Communication with Google Update failed: " << hr
               << " error: " << error_code;
  main_loop->PostTask(FROM_HERE, NewRunnableMethod(this,
      &GoogleUpdate::ReportResults, UPGRADE_ERROR, error_code));
  return false;
}
<|endoftext|>


<commit_before>// Copyright (c) 2015 Stojan Dimitrovski
// Distributed under the MIT license.
// See LICENSE.txt for full text or http://opensource.org/licenses/MIT.

#pragma once

#include <cstddef>
#include <cassert>

using namespace std;

namespace galois {
namespace Field {

/*
 * Implements the Rijndael Galois field, i.e.
 * GF(2^8) with P(x) = x8 + x4 + x3 + x + 1 as the reducing polynomial.
 */
class Rijndael {
private:
  static const unsigned char CARRY_SUBTRACT[];

public:
  Rijndael() {
    assert (CARRY_SUBTRACT[0] == 0);
    assert (CARRY_SUBTRACT[1] == IRREDUCIBLE);
  }

  ~Rijndael() {
    // No-op.
  }

  static const size_t ORDER;
  static const size_t WIDTH;

  static const unsigned char IRREDUCIBLE;

  // output generated by tools/rijndael-inverses.rb
  static const unsigned char INVERSES[];

  inline char* Value(unsigned char value, char* const out) const {
    *out = (char) value;

    return out;
  }

  inline int Compare(const char* const a, const char* const b) const {
    return ((int) *a) - ((int) *b);
  }

  inline char* Add(const char* const a, const char* const b, char* const out) const {
    *out = *a ^ *b;

    return out;
  }

  inline char* Sub(const char* const a, const char* const b, char* const out) const {
    return Add(a, b, out);
  }

  inline char* Mul(const char* const ia, const char* const ib, char* const out) const {
    unsigned char a = *ia;
    unsigned char b = *ib;
    unsigned char p = 0;
    unsigned char carry = 0;

    for (int i = 0; i < 8; i++) {
      p ^= (b & 1) * a; //if (b & 1) { p ^= a; }
      b >>= 1;
      carry = a >> 7; // carry = a & 0x80;
      a <<= 1;
      a ^= CARRY_SUBTRACT[carry]; // if (carry) { a ^= 0x1B; }
    }

    *out = (char) p;

    return out;
  }

  inline char* Div(const char* const a, const char* const b, char* const out) const {
    assert (*b != 0);

    char binv = INVERSES[(unsigned char) *b];

    return Mul(a, (char*) &binv, out);
  }
};

const size_t Rijndael::ORDER = 256;
const size_t Rijndael::WIDTH = 1;

const unsigned char Rijndael::IRREDUCIBLE = 0x11B;

const unsigned char Rijndael::CARRY_SUBTRACT[] = { 0, Rijndael::IRREDUCIBLE };

const unsigned char Rijndael::INVERSES[] = {
    0x00, 0x01, 0x8D, 0xF6, 0xCB, 0x52, 0x7B, 0xD1,
    0xE8, 0x4F, 0x29, 0xC0, 0xB0, 0xE1, 0xE5, 0xC7,
    0x74, 0xB4, 0xAA, 0x4B, 0x99, 0x2B, 0x60, 0x5F,
    0x58, 0x3F, 0xFD, 0xCC, 0xFF, 0x40, 0xEE, 0xB2,
    0x3A, 0x6E, 0x5A, 0xF1, 0x55, 0x4D, 0xA8, 0xC9,
    0xC1, 0x0A, 0x98, 0x15, 0x30, 0x44, 0xA2, 0xC2,
    0x2C, 0x45, 0x92, 0x6C, 0xF3, 0x39, 0x66, 0x42,
    0xF2, 0x35, 0x20, 0x6F, 0x77, 0xBB, 0x59, 0x19,
    0x1D, 0xFE, 0x37, 0x67, 0x2D, 0x31, 0xF5, 0x69,
    0xA7, 0x64, 0xAB, 0x13, 0x54, 0x25, 0xE9, 0x09,
    0xED, 0x5C, 0x05, 0xCA, 0x4C, 0x24, 0x87, 0xBF,
    0x18, 0x3E, 0x22, 0xF0, 0x51, 0xEC, 0x61, 0x17,
    0x16, 0x5E, 0xAF, 0xD3, 0x49, 0xA6, 0x36, 0x43,
    0xF4, 0x47, 0x91, 0xDF, 0x33, 0x93, 0x21, 0x3B,
    0x79, 0xB7, 0x97, 0x85, 0x10, 0xB5, 0xBA, 0x3C,
    0xB6, 0x70, 0xD0, 0x06, 0xA1, 0xFA, 0x81, 0x82,
    0x83, 0x7E, 0x7F, 0x80, 0x96, 0x73, 0xBE, 0x56,
    0x9B, 0x9E, 0x95, 0xD9, 0xF7, 0x02, 0xB9, 0xA4,
    0xDE, 0x6A, 0x32, 0x6D, 0xD8, 0x8A, 0x84, 0x72,
    0x2A, 0x14, 0x9F, 0x88, 0xF9, 0xDC, 0x89, 0x9A,
    0xFB, 0x7C, 0x2E, 0xC3, 0x8F, 0xB8, 0x65, 0x48,
    0x26, 0xC8, 0x12, 0x4A, 0xCE, 0xE7, 0xD2, 0x62,
    0x0C, 0xE0, 0x1F, 0xEF, 0x11, 0x75, 0x78, 0x71,
    0xA5, 0x8E, 0x76, 0x3D, 0xBD, 0xBC, 0x86, 0x57,
    0x0B, 0x28, 0x2F, 0xA3, 0xDA, 0xD4, 0xE4, 0x0F,
    0xA9, 0x27, 0x53, 0x04, 0x1B, 0xFC, 0xAC, 0xE6,
    0x7A, 0x07, 0xAE, 0x63, 0xC5, 0xDB, 0xE2, 0xEA,
    0x94, 0x8B, 0xC4, 0xD5, 0x9D, 0xF8, 0x90, 0x6B,
    0xB1, 0x0D, 0xD6, 0xEB, 0xC6, 0x0E, 0xCF, 0xAD,
    0x08, 0x4E, 0xD7, 0xE3, 0x5D, 0x50, 0x1E, 0xB3,
    0x5B, 0x23, 0x38, 0x34, 0x68, 0x46, 0x03, 0x8C,
    0xDD, 0x9C, 0x7D, 0xA0, 0xCD, 0x1A, 0x41, 0x1C };

} // Field
} // galois
<commit_msg>I don't know why I did what I did in the commit before.<commit_after>// Copyright (c) 2015 Stojan Dimitrovski
// Distributed under the MIT license.
// See LICENSE.txt for full text or http://opensource.org/licenses/MIT.

#pragma once

#include <cstddef>
#include <cassert>

using namespace std;

namespace galois {
namespace Field {

/*
 * Implements the Rijndael Galois field, i.e.
 * GF(2^8) with P(x) = x8 + x4 + x3 + x + 1 as the reducing polynomial.
 */
class Rijndael {
private:
  static const unsigned char CARRY_SUBTRACT[];

public:
  Rijndael() {
    assert (CARRY_SUBTRACT[0] == 0);
    assert (CARRY_SUBTRACT[1] == IRREDUCIBLE);
  }

  ~Rijndael() {
    // No-op.
  }

  static const size_t ORDER;
  static const size_t WIDTH;

  static const unsigned char IRREDUCIBLE;

  // output generated by tools/rijndael-inverses.rb
  static const unsigned char INVERSES[];

  inline char* Value(unsigned char value, char* const out) const {
    *out = (char) value;

    return out;
  }

  inline int Compare(const char* const a, const char* const b) const {
    return ((int) *a) - ((int) *b);
  }

  inline char* Add(const char* const a, const char* const b, char* const out) const {
    *out = *a ^ *b;

    return out;
  }

  inline char* Sub(const char* const a, const char* const b, char* const out) const {
    return Add(a, b, out);
  }

  inline char* Mul(const char* const ia, const char* const ib, char* const out) const {
    unsigned char a = *ia;
    unsigned char b = *ib;
    unsigned char p = 0;
    unsigned char carry = 0;

    for (int i = 0; i < 8; i++) {
      p ^= (b & 1) * a; //if (b & 1) { p ^= a; }
      b >>= 1;
      carry = a >> 7; // carry = a & 0x80;
      a <<= 1;
      a ^= CARRY_SUBTRACT[carry]; // if (carry) { a ^= 0x1B; }
    }

    *out = (char) p;

    return out;
  }

  inline char* Div(const char* const a, const char* const b, char* const out) const {
    assert (*b != 0);

    char binv = INVERSES[(unsigned char) *b];

    return Mul(a, (char*) &binv, out);
  }
};

const size_t Rijndael::ORDER = 256;
const size_t Rijndael::WIDTH = 1;

const unsigned char Rijndael::IRREDUCIBLE = 0x1B;

const unsigned char Rijndael::CARRY_SUBTRACT[] = { 0, Rijndael::IRREDUCIBLE };

const unsigned char Rijndael::INVERSES[] = {
    0x00, 0x01, 0x8D, 0xF6, 0xCB, 0x52, 0x7B, 0xD1,
    0xE8, 0x4F, 0x29, 0xC0, 0xB0, 0xE1, 0xE5, 0xC7,
    0x74, 0xB4, 0xAA, 0x4B, 0x99, 0x2B, 0x60, 0x5F,
    0x58, 0x3F, 0xFD, 0xCC, 0xFF, 0x40, 0xEE, 0xB2,
    0x3A, 0x6E, 0x5A, 0xF1, 0x55, 0x4D, 0xA8, 0xC9,
    0xC1, 0x0A, 0x98, 0x15, 0x30, 0x44, 0xA2, 0xC2,
    0x2C, 0x45, 0x92, 0x6C, 0xF3, 0x39, 0x66, 0x42,
    0xF2, 0x35, 0x20, 0x6F, 0x77, 0xBB, 0x59, 0x19,
    0x1D, 0xFE, 0x37, 0x67, 0x2D, 0x31, 0xF5, 0x69,
    0xA7, 0x64, 0xAB, 0x13, 0x54, 0x25, 0xE9, 0x09,
    0xED, 0x5C, 0x05, 0xCA, 0x4C, 0x24, 0x87, 0xBF,
    0x18, 0x3E, 0x22, 0xF0, 0x51, 0xEC, 0x61, 0x17,
    0x16, 0x5E, 0xAF, 0xD3, 0x49, 0xA6, 0x36, 0x43,
    0xF4, 0x47, 0x91, 0xDF, 0x33, 0x93, 0x21, 0x3B,
    0x79, 0xB7, 0x97, 0x85, 0x10, 0xB5, 0xBA, 0x3C,
    0xB6, 0x70, 0xD0, 0x06, 0xA1, 0xFA, 0x81, 0x82,
    0x83, 0x7E, 0x7F, 0x80, 0x96, 0x73, 0xBE, 0x56,
    0x9B, 0x9E, 0x95, 0xD9, 0xF7, 0x02, 0xB9, 0xA4,
    0xDE, 0x6A, 0x32, 0x6D, 0xD8, 0x8A, 0x84, 0x72,
    0x2A, 0x14, 0x9F, 0x88, 0xF9, 0xDC, 0x89, 0x9A,
    0xFB, 0x7C, 0x2E, 0xC3, 0x8F, 0xB8, 0x65, 0x48,
    0x26, 0xC8, 0x12, 0x4A, 0xCE, 0xE7, 0xD2, 0x62,
    0x0C, 0xE0, 0x1F, 0xEF, 0x11, 0x75, 0x78, 0x71,
    0xA5, 0x8E, 0x76, 0x3D, 0xBD, 0xBC, 0x86, 0x57,
    0x0B, 0x28, 0x2F, 0xA3, 0xDA, 0xD4, 0xE4, 0x0F,
    0xA9, 0x27, 0x53, 0x04, 0x1B, 0xFC, 0xAC, 0xE6,
    0x7A, 0x07, 0xAE, 0x63, 0xC5, 0xDB, 0xE2, 0xEA,
    0x94, 0x8B, 0xC4, 0xD5, 0x9D, 0xF8, 0x90, 0x6B,
    0xB1, 0x0D, 0xD6, 0xEB, 0xC6, 0x0E, 0xCF, 0xAD,
    0x08, 0x4E, 0xD7, 0xE3, 0x5D, 0x50, 0x1E, 0xB3,
    0x5B, 0x23, 0x38, 0x34, 0x68, 0x46, 0x03, 0x8C,
    0xDD, 0x9C, 0x7D, 0xA0, 0xCD, 0x1A, 0x41, 0x1C };

} // Field
} // galois
<|endoftext|>


<commit_before>/*******************************
Copyright (c) 2016-2021 Grégoire Angerand

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**********************************/

#include "ui.h"
#include "assets.h"

#include <editor/ThumbmailRenderer.h>
#include <editor/widgets/AssetSelector.h>
#include <editor/widgets/FileBrowser.h>

#include <yave/assets/AssetStore.h>
#include <yave/utils/FileSystemModel.h>

#include <external/imgui/yave_imgui.h>

namespace editor {
namespace imgui {

bool should_open_context_menu() {
    return ImGui::IsWindowHovered() && ImGui::IsMouseReleased(1);
}

math::Vec2 client_window_pos() {
    if(ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_ViewportsEnable) {
        return ImGui::GetWindowPos();
    }
    return math::Vec2(0.0f);
}

math::Vec2 from_client_pos(const math::Vec2& pos) {
    return client_window_pos() + pos;
}

bool asset_selector(AssetId id, AssetType type, std::string_view text, bool* clear) {
    static constexpr math::Vec2 button_size = math::Vec2(64.0f, 64.0f);

    ImGui::PushID(fmt_c_str("%_%_%", id.id(), uenum(type), text));
    ImGui::BeginGroup();

    const auto name = asset_store().name(id);
    const bool is_valid = name.is_ok();

    if(clear) {
        *clear = false;
    }

    bool ret = false;
    if(is_valid) {
        if(const TextureView* img = thumbmail_renderer().thumbmail(id)) {
            ret = ImGui::ImageButton(const_cast<TextureView*>(img), button_size);
        } else {
            ret = ImGui::Button(ICON_FA_QUESTION, button_size + math::Vec2(ImGui::GetStyle().FramePadding) * 2.0f);
        }
    } else {
        ret = ImGui::Button(ICON_FA_FOLDER_OPEN, button_size + math::Vec2(ImGui::GetStyle().FramePadding) * 2.0f);
    }

    ImGui::SameLine();
    if(ImGui::GetContentRegionAvail().x > button_size.x() * 0.5f) {
        const auto clean_name = [=](auto&& n) { return asset_store().filesystem()->filename(n); };
        const core::String clean = name.map(clean_name).unwrap_or(core::String());

        const bool is_empty = clean.is_empty();
        const char* item_name = is_empty ? "empty" : clean.data();

        ImGui::BeginGroup();
        ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x - ImGui::GetStyle().FramePadding.x * 2.0f);

        if(is_empty) {
            ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyle().Colors[ImGuiCol_TextDisabled]);
        }

        const bool combo = ImGui::BeginCombo("##combo", item_name);

        if(is_empty) {
            ImGui::PopStyleColor();
        }

        if(combo) {
            ImGui::Selectable(item_name, false, ImGuiSelectableFlags_Disabled);

            ImGui::Separator();
            if(ImGui::Selectable(ICON_FA_FOLDER_OPEN " Browse")) {
                ret = true;
            }

            if(!is_empty && clear) {
                ImGui::Separator();
                if(ImGui::Selectable(ICON_FA_TRASH " Clear")) {
                    *clear = true;
                }
            }

            ImGui::EndCombo();
        }
        ImGui::EndGroup();
    }

    ImGui::EndGroup();
    ImGui::PopID();
    return ret;
}

bool path_selector(const char* text, const core::String& path) {
    static constexpr usize buffer_capacity = 1024;

    ImGui::PushID(text);
    ImGui::BeginGroup();

    ImGui::TextUnformatted(text);

    std::array<char, buffer_capacity> buffer;
    {
        const bool end_with_slash = path.ends_with("/");
        const usize len = std::min(buffer.size() - (end_with_slash ? 1 : 2), path.size());
        std::copy_n(path.begin(), len, buffer.begin());
        buffer[len] = '/';
        buffer[len + !end_with_slash] = 0;
    }

    ImGui::InputText("", buffer.data(), buffer.size(), ImGuiInputTextFlags_ReadOnly);
    ImGui::SameLine();
    const bool ret = ImGui::Button(ICON_FA_FOLDER_OPEN);

    ImGui::EndGroup();
    ImGui::PopID();
    return ret;
}

// from https://github.com/ocornut/imgui/issues/2668
void alternating_rows_background(float line_height, const math::Vec4& color) {
    const u32 im_color = ImGui::GetColorU32(color);

    auto* draw_list = ImGui::GetWindowDrawList();
    const auto& style = ImGui::GetStyle();

    if(line_height < 0) {
        line_height = ImGui::GetTextLineHeight();
    }

    line_height += style.ItemSpacing.y;

    float scroll_offset_h = ImGui::GetScrollX();
    float scroll_offset_v = ImGui::GetScrollY();
    float scrolled_out_lines = std::floor(scroll_offset_v / line_height);
    scroll_offset_v -= line_height * scrolled_out_lines;

    ImVec2 clip_rect_min(ImGui::GetWindowPos().x, ImGui::GetWindowPos().y);
    ImVec2 clip_rect_max(clip_rect_min.x + ImGui::GetWindowWidth(), clip_rect_min.y + ImGui::GetWindowHeight());

    if(ImGui::GetScrollMaxX() > 0) {
        clip_rect_max.y -= style.ScrollbarSize;
    }

    draw_list->PushClipRect(clip_rect_min, clip_rect_max);

    const float y_min = clip_rect_min.y - scroll_offset_v + ImGui::GetCursorPosY();
    const float y_max = clip_rect_max.y - scroll_offset_v + line_height;
    const float x_min = clip_rect_min.x + scroll_offset_h + ImGui::GetWindowContentRegionMin().x;
    const float x_max = clip_rect_min.x + scroll_offset_h + ImGui::GetWindowContentRegionMax().x;

    bool is_odd = (static_cast<int>(scrolled_out_lines) % 2) == 0;
    for(float y = y_min; y < y_max; y += line_height, is_odd = !is_odd) {
        if(is_odd) {
            draw_list->AddRectFilled({ x_min, y - style.ItemSpacing.y }, { x_max, y + line_height }, im_color);
        }
    }

    draw_list->PopClipRect();
}

bool begin_suggestion_popup(const char* name, bool* open) {
    const ImGuiWindowFlags popup_flags =
            ImGuiWindowFlags_NoFocusOnAppearing     |
            ImGuiWindowFlags_NoTitleBar             |
            ImGuiWindowFlags_AlwaysAutoResize       |
            ImGuiWindowFlags_NoResize               |
            ImGuiWindowFlags_NoMove                 |
            ImGuiWindowFlags_NoSavedSettings;

    ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
    ImGui::PushStyleColor(ImGuiCol_WindowBg, math::Vec4(40.0f, 40.0f, 40.0f, 220.0f) / 255.0f);

    ImGui::SetNextWindowPos(imgui::from_client_pos(ImGui::GetCursorPos()));

    const bool visible = ImGui::Begin(name, open, popup_flags);

    if(!visible) {
        end_suggestion_popup();
    }

    return visible;
}

void end_suggestion_popup() {
    ImGui::End();

    ImGui::PopStyleColor(1);
    ImGui::PopStyleVar(1);
}

}

}

<commit_msg>Fixed popup placement when viewports are desactivated<commit_after>/*******************************
Copyright (c) 2016-2021 Grégoire Angerand

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**********************************/

#include "ui.h"
#include "assets.h"

#include <editor/ThumbmailRenderer.h>
#include <editor/widgets/AssetSelector.h>
#include <editor/widgets/FileBrowser.h>

#include <yave/assets/AssetStore.h>
#include <yave/utils/FileSystemModel.h>

#include <external/imgui/yave_imgui.h>

namespace editor {
namespace imgui {

bool should_open_context_menu() {
    return ImGui::IsWindowHovered() && ImGui::IsMouseReleased(1);
}

math::Vec2 client_window_pos() {
    if(ImGui::GetIO().ConfigFlags & ImGuiConfigFlags_ViewportsEnable) {
        return ImGui::GetWindowPos();
    }
    return math::Vec2(0.0f);
}

math::Vec2 from_client_pos(const math::Vec2& pos) {
    return client_window_pos() + pos;
}

bool asset_selector(AssetId id, AssetType type, std::string_view text, bool* clear) {
    static constexpr math::Vec2 button_size = math::Vec2(64.0f, 64.0f);

    ImGui::PushID(fmt_c_str("%_%_%", id.id(), uenum(type), text));
    ImGui::BeginGroup();

    const auto name = asset_store().name(id);
    const bool is_valid = name.is_ok();

    if(clear) {
        *clear = false;
    }

    bool ret = false;
    if(is_valid) {
        if(const TextureView* img = thumbmail_renderer().thumbmail(id)) {
            ret = ImGui::ImageButton(const_cast<TextureView*>(img), button_size);
        } else {
            ret = ImGui::Button(ICON_FA_QUESTION, button_size + math::Vec2(ImGui::GetStyle().FramePadding) * 2.0f);
        }
    } else {
        ret = ImGui::Button(ICON_FA_FOLDER_OPEN, button_size + math::Vec2(ImGui::GetStyle().FramePadding) * 2.0f);
    }

    ImGui::SameLine();
    if(ImGui::GetContentRegionAvail().x > button_size.x() * 0.5f) {
        const auto clean_name = [=](auto&& n) { return asset_store().filesystem()->filename(n); };
        const core::String clean = name.map(clean_name).unwrap_or(core::String());

        const bool is_empty = clean.is_empty();
        const char* item_name = is_empty ? "empty" : clean.data();

        ImGui::BeginGroup();
        ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x - ImGui::GetStyle().FramePadding.x * 2.0f);

        if(is_empty) {
            ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyle().Colors[ImGuiCol_TextDisabled]);
        }

        const bool combo = ImGui::BeginCombo("##combo", item_name);

        if(is_empty) {
            ImGui::PopStyleColor();
        }

        if(combo) {
            ImGui::Selectable(item_name, false, ImGuiSelectableFlags_Disabled);

            ImGui::Separator();
            if(ImGui::Selectable(ICON_FA_FOLDER_OPEN " Browse")) {
                ret = true;
            }

            if(!is_empty && clear) {
                ImGui::Separator();
                if(ImGui::Selectable(ICON_FA_TRASH " Clear")) {
                    *clear = true;
                }
            }

            ImGui::EndCombo();
        }
        ImGui::EndGroup();
    }

    ImGui::EndGroup();
    ImGui::PopID();
    return ret;
}

bool path_selector(const char* text, const core::String& path) {
    static constexpr usize buffer_capacity = 1024;

    ImGui::PushID(text);
    ImGui::BeginGroup();

    ImGui::TextUnformatted(text);

    std::array<char, buffer_capacity> buffer;
    {
        const bool end_with_slash = path.ends_with("/");
        const usize len = std::min(buffer.size() - (end_with_slash ? 1 : 2), path.size());
        std::copy_n(path.begin(), len, buffer.begin());
        buffer[len] = '/';
        buffer[len + !end_with_slash] = 0;
    }

    ImGui::InputText("", buffer.data(), buffer.size(), ImGuiInputTextFlags_ReadOnly);
    ImGui::SameLine();
    const bool ret = ImGui::Button(ICON_FA_FOLDER_OPEN);

    ImGui::EndGroup();
    ImGui::PopID();
    return ret;
}

// from https://github.com/ocornut/imgui/issues/2668
void alternating_rows_background(float line_height, const math::Vec4& color) {
    const u32 im_color = ImGui::GetColorU32(color);

    auto* draw_list = ImGui::GetWindowDrawList();
    const auto& style = ImGui::GetStyle();

    if(line_height < 0) {
        line_height = ImGui::GetTextLineHeight();
    }

    line_height += style.ItemSpacing.y;

    float scroll_offset_h = ImGui::GetScrollX();
    float scroll_offset_v = ImGui::GetScrollY();
    float scrolled_out_lines = std::floor(scroll_offset_v / line_height);
    scroll_offset_v -= line_height * scrolled_out_lines;

    ImVec2 clip_rect_min(ImGui::GetWindowPos().x, ImGui::GetWindowPos().y);
    ImVec2 clip_rect_max(clip_rect_min.x + ImGui::GetWindowWidth(), clip_rect_min.y + ImGui::GetWindowHeight());

    if(ImGui::GetScrollMaxX() > 0) {
        clip_rect_max.y -= style.ScrollbarSize;
    }

    draw_list->PushClipRect(clip_rect_min, clip_rect_max);

    const float y_min = clip_rect_min.y - scroll_offset_v + ImGui::GetCursorPosY();
    const float y_max = clip_rect_max.y - scroll_offset_v + line_height;
    const float x_min = clip_rect_min.x + scroll_offset_h + ImGui::GetWindowContentRegionMin().x;
    const float x_max = clip_rect_min.x + scroll_offset_h + ImGui::GetWindowContentRegionMax().x;

    bool is_odd = (static_cast<int>(scrolled_out_lines) % 2) == 0;
    for(float y = y_min; y < y_max; y += line_height, is_odd = !is_odd) {
        if(is_odd) {
            draw_list->AddRectFilled({ x_min, y - style.ItemSpacing.y }, { x_max, y + line_height }, im_color);
        }
    }

    draw_list->PopClipRect();
}

bool begin_suggestion_popup(const char* name, bool* open) {
    const ImGuiWindowFlags popup_flags =
            ImGuiWindowFlags_NoFocusOnAppearing     |
            ImGuiWindowFlags_NoTitleBar             |
            ImGuiWindowFlags_AlwaysAutoResize       |
            ImGuiWindowFlags_NoResize               |
            ImGuiWindowFlags_NoMove                 |
            ImGuiWindowFlags_NoSavedSettings;

    ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
    ImGui::PushStyleColor(ImGuiCol_WindowBg, math::Vec4(40.0f, 40.0f, 40.0f, 220.0f) / 255.0f);

    ImGui::SetNextWindowPos(math::Vec2(ImGui::GetWindowPos()) + math::Vec2(ImGui::GetCursorPos()));

    const bool visible = ImGui::Begin(name, open, popup_flags);

    if(!visible) {
        end_suggestion_popup();
    }

    return visible;
}

void end_suggestion_popup() {
    ImGui::End();

    ImGui::PopStyleColor(1);
    ImGui::PopStyleVar(1);
}

}

}

<|endoftext|>


<commit_before>/*******************************************************************************
 * Copyright (c) 2009-2014, MAV'RIC Development Team
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors
 * may be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
 ******************************************************************************/

/*******************************************************************************
 * \file central_data.c
 *
 * \author MAV'RIC Team
 *
 * \brief Place where the central data is stored and initialized
 *
 ******************************************************************************/

#include "central_data.hpp"
#include "stabilisation_copter_default_config.hpp"
#include "data_logging_default_config.hpp"
#include "mavlink_communication_default_config.hpp"

#include "position_estimation_default_config.hpp"
#include "remote_default_config.hpp"
#include "state_default_config.hpp"
#include "manual_control_default_config.hpp"

extern "C"
{
	#include "time_keeper.h"
	#include "navigation_default_config.h"
	#include "qfilter_default_config.h"
	#include "scheduler_default_config.h"
	#include "servos_mix_quadcopter_diag_default_config.h"

	#include "print_util.h"
}

Central_data::Central_data(Imu& imu, Barometer& barometer, Gps& gps, Sonar& sonar, Serial& serial_mavlink, Satellite& satellite, File& file_flash, Battery& battery, servos_t& servos):
	imu( imu ),
	barometer( barometer ),
	gps( gps ),
	sonar( sonar ),
	serial_mavlink( serial_mavlink ),
	satellite( satellite ),
	file_flash( file_flash ),
	battery( battery ),
	servos( servos )
{}

bool Central_data::init(void)
{
	bool init_success = true;
	bool ret;

	print_util_dbg_sep('%');
	time_keeper_delay_ms(100);
	print_util_dbg_sep('-');
	time_keeper_delay_ms(100);
	print_util_dbg_print("[CENTRAL_DATA] ...\r\n");
	time_keeper_delay_ms(100);
	print_util_dbg_sep('-');

	// -------------------------------------------------------------------------
	// Init main sheduler
	// -------------------------------------------------------------------------
	ret = scheduler_init(&scheduler, scheduler_default_config());
	print_util_dbg_init_msg("[SCHEDULER]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init mavlink communication
	// -------------------------------------------------------------------------
	mavlink_communication_conf_t mavlink_communication_config = mavlink_communication_default_config();
	mavlink_communication_config.mavlink_stream_config.sysid = 1;
	mavlink_communication_config.message_handler_config.debug = true;
	mavlink_communication_config.onboard_parameters_config.debug = true;
	mavlink_communication_config.mavlink_stream_config.debug = true;
	ret = mavlink_communication_init(	&mavlink_communication,
										mavlink_communication_config,
										&serial_mavlink,
										&state,
										&file_flash );
	print_util_dbg_init_msg("[MAVLINK]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init state structure
	// -------------------------------------------------------------------------
	ret = state_init(	&state,
						state_default_config(),
						&battery);
	print_util_dbg_init_msg("[STATE]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	//Init state_machine
	// -------------------------------------------------------------------------
	ret = state_machine_init( 	&state_machine,
								&state,
								&gps,
								&manual_control);
	print_util_dbg_init_msg("[STATE MACHINE]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init ahrs
	// -------------------------------------------------------------------------
	ret = ahrs_init(&ahrs);
	print_util_dbg_init_msg("[AHRS]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init qfilter
	// -------------------------------------------------------------------------
	ret = qfilter_init( &attitude_filter,
						qfilter_default_config(),
						&imu,
						&ahrs);
	print_util_dbg_init_msg("[QFILTER]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init position_estimation_init
	// -------------------------------------------------------------------------
	ret = position_estimation_init( &position_estimation,
									position_estimation_default_config(),
									&state,
									&barometer,
									&sonar,
									&gps,
									&ahrs);
	print_util_dbg_init_msg("[POS EST]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init navigation
	// -------------------------------------------------------------------------
	ret = navigation_init(	&navigation,
							navigation_default_config(),
							&controls_nav,
							&ahrs.qe,
							&position_estimation,
							&state,
							&manual_control,
							&mavlink_communication);/*,
							&sonar_i2cxl);*/
	print_util_dbg_init_msg("[NAV]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init waypoint handler
	// -------------------------------------------------------------------------
	ret = waypoint_handler_init(	&waypoint_handler,
									&position_estimation,
									&navigation,
									&ahrs,
									&state,
									&manual_control,
									&mavlink_communication,
									&mavlink_communication.mavlink_stream);
	waypoint_handler_init_homing_waypoint(&waypoint_handler);
	waypoint_handler_nav_plan_init(&waypoint_handler);
	print_util_dbg_init_msg("[WAYPOINT]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init stabilisers
	// -------------------------------------------------------------------------
	ret = stabilisation_copter_init(	&stabilisation_copter,
										stabilisation_copter_default_config(),
										&controls,
										&ahrs,
										&position_estimation,
										&command.torque,
										&command.thrust);
	print_util_dbg_init_msg("[STABILISATION COPTER]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init controls
	// -------------------------------------------------------------------------
	ret = stabilisation_init( &controls);
	print_util_dbg_init_msg("[CONTROLS]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init hud
	// -------------------------------------------------------------------------
	ret = hud_telemetry_init(	&hud_structure,
								&position_estimation,
								&controls,
								&ahrs);
	print_util_dbg_init_msg("[HUD]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init servo mixing
	// -------------------------------------------------------------------------
	ret = servos_mix_quadcotper_diag_init( 	&servo_mix,
											servos_mix_quadcopter_diag_default_config(),
											&command.torque,
											&command.thrust,
											&servos);
	print_util_dbg_init_msg("[SERVOS MIX]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init manual control
	// -------------------------------------------------------------------------
	ret = manual_control_init(	&manual_control,
								&satellite,
								manual_control_default_config(),
								remote_default_config());
	print_util_dbg_init_msg("[MANUAL CTRL]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	print_util_dbg_sep('-');
	time_keeper_delay_ms(100);
	print_util_dbg_init_msg("[CENTRAL_DATA]", init_success);
	time_keeper_delay_ms(100);
	print_util_dbg_sep('-');
	time_keeper_delay_ms(100);

	return init_success;
}
<commit_msg>Fix second compilation error<commit_after>/*******************************************************************************
 * Copyright (c) 2009-2014, MAV'RIC Development Team
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors
 * may be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
 ******************************************************************************/

/*******************************************************************************
 * \file central_data.c
 *
 * \author MAV'RIC Team
 *
 * \brief Place where the central data is stored and initialized
 *
 ******************************************************************************/

#include "central_data.hpp"
#include "stabilisation_copter_default_config.hpp"
#include "data_logging_default_config.hpp"
#include "mavlink_communication_default_config.hpp"

#include "position_estimation_default_config.hpp"
#include "remote_default_config.hpp"
#include "state_default_config.hpp"
#include "manual_control_default_config.hpp"

extern "C"
{
	#include "time_keeper.h"
	#include "navigation_default_config.h"
	#include "qfilter_default_config.h"
	#include "scheduler_default_config.h"
	#include "servos_mix_quadcopter_diag_default_config.h"

	#include "print_util.h"
}

Central_data::Central_data(Imu& imu, Barometer& barometer, Gps& gps, Sonar& sonar, Serial& serial_mavlink, Satellite& satellite, File& file_flash, Battery& battery, servos_t& servos):
	imu( imu ),
	barometer( barometer ),
	gps( gps ),
	sonar( sonar ),
	serial_mavlink( serial_mavlink ),
	satellite( satellite ),
	file_flash( file_flash ),
	battery( battery ),
	servos( servos )
{}

bool Central_data::init(void)
{
	bool init_success = true;
	bool ret;

	print_util_dbg_sep('%');
	time_keeper_delay_ms(100);
	print_util_dbg_sep('-');
	time_keeper_delay_ms(100);
	print_util_dbg_print("[CENTRAL_DATA] ...\r\n");
	time_keeper_delay_ms(100);
	print_util_dbg_sep('-');

	// -------------------------------------------------------------------------
	// Init main sheduler
	// -------------------------------------------------------------------------
	ret = scheduler_init(&scheduler, scheduler_default_config());
	print_util_dbg_init_msg("[SCHEDULER]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init mavlink communication
	// -------------------------------------------------------------------------
	mavlink_communication_conf_t mavlink_communication_config = mavlink_communication_default_config();
	mavlink_communication_config.mavlink_stream_config.sysid = 1;
	mavlink_communication_config.message_handler_config.debug = true;
	mavlink_communication_config.onboard_parameters_config.debug = true;
	mavlink_communication_config.mavlink_stream_config.debug = true;
	ret = mavlink_communication_init(	&mavlink_communication,
										mavlink_communication_config,
										&serial_mavlink,
										&state,
										&file_flash );
	print_util_dbg_init_msg("[MAVLINK]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init state structure
	// -------------------------------------------------------------------------
	ret = state_init(	&state,
						state_default_config(),
						&battery);
	print_util_dbg_init_msg("[STATE]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	//Init state_machine
	// -------------------------------------------------------------------------
	ret = state_machine_init( 	&state_machine,
								&state,
								&gps,
								&manual_control);
	print_util_dbg_init_msg("[STATE MACHINE]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init ahrs
	// -------------------------------------------------------------------------
	ret = ahrs_init(&ahrs);
	print_util_dbg_init_msg("[AHRS]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init qfilter
	// -------------------------------------------------------------------------
	ret = qfilter_init( &attitude_filter,
						qfilter_default_config(),
						&imu,
						&ahrs);
	print_util_dbg_init_msg("[QFILTER]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init position_estimation_init
	// -------------------------------------------------------------------------
	ret = position_estimation_init( &position_estimation,
									position_estimation_default_config(),
									&state,
									&barometer,
									&sonar,
									&gps,
									&ahrs);
	print_util_dbg_init_msg("[POS EST]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init navigation
	// -------------------------------------------------------------------------
	ret = navigation_init(	&navigation,
							navigation_default_config(),
							&controls_nav,
							&ahrs.qe,
							&position_estimation,
							&state,
							&mavlink_communication);/*,
							&sonar_i2cxl);*/
	print_util_dbg_init_msg("[NAV]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init waypoint handler
	// -------------------------------------------------------------------------
	ret = waypoint_handler_init(	&waypoint_handler,
									&position_estimation,
									&navigation,
									&ahrs,
									&state,
									&manual_control,
									&mavlink_communication,
									&mavlink_communication.mavlink_stream);
	waypoint_handler_init_homing_waypoint(&waypoint_handler);
	waypoint_handler_nav_plan_init(&waypoint_handler);
	print_util_dbg_init_msg("[WAYPOINT]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init stabilisers
	// -------------------------------------------------------------------------
	ret = stabilisation_copter_init(	&stabilisation_copter,
										stabilisation_copter_default_config(),
										&controls,
										&ahrs,
										&position_estimation,
										&command.torque,
										&command.thrust);
	print_util_dbg_init_msg("[STABILISATION COPTER]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init controls
	// -------------------------------------------------------------------------
	ret = stabilisation_init( &controls);
	print_util_dbg_init_msg("[CONTROLS]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init hud
	// -------------------------------------------------------------------------
	ret = hud_telemetry_init(	&hud_structure,
								&position_estimation,
								&controls,
								&ahrs);
	print_util_dbg_init_msg("[HUD]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init servo mixing
	// -------------------------------------------------------------------------
	ret = servos_mix_quadcotper_diag_init( 	&servo_mix,
											servos_mix_quadcopter_diag_default_config(),
											&command.torque,
											&command.thrust,
											&servos);
	print_util_dbg_init_msg("[SERVOS MIX]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	// -------------------------------------------------------------------------
	// Init manual control
	// -------------------------------------------------------------------------
	ret = manual_control_init(	&manual_control,
								&satellite,
								manual_control_default_config(),
								remote_default_config());
	print_util_dbg_init_msg("[MANUAL CTRL]", ret);
	init_success &= ret;
	time_keeper_delay_ms(100);

	print_util_dbg_sep('-');
	time_keeper_delay_ms(100);
	print_util_dbg_init_msg("[CENTRAL_DATA]", init_success);
	time_keeper_delay_ms(100);
	print_util_dbg_sep('-');
	time_keeper_delay_ms(100);

	return init_success;
}
<|endoftext|>


<commit_before>#include <babylon/layer/layer.h>

#include <babylon/babylon_stl_util.h>
#include <babylon/engine/engine.h>
#include <babylon/materials/effect.h>
#include <babylon/materials/effect_creation_options.h>
#include <babylon/materials/effect_fallbacks.h>
#include <babylon/materials/textures/texture.h>
#include <babylon/math/matrix.h>
#include <babylon/mesh/vertex_buffer.h>

namespace BABYLON {

Layer::Layer(const string_t& name, const string_t& imgUrl, Scene* scene,
             bool iIsBackground, const Color4& iColor)
    : isBackground{iIsBackground}
    , color{iColor}
    , scale{Vector2(1.f, 1.f)}
    , offset{Vector2(0.f, 0.f)}
    , alphaBlendingMode{EngineConstants::ALPHA_COMBINE}
    , layerMask{0x0FFFFFFF}
    , _onDisposeObserver{nullptr}
    , _onBeforeRenderObserver{nullptr}
    , _onAfterRenderObserver{nullptr}
    , _name{name}
{
  texture = !imgUrl.empty() ? Texture::New(imgUrl, scene, true) : nullptr;

  _scene = scene ? scene : Engine::LastCreatedScene();
  _scene->layers.emplace_back(this);

  auto engine = scene->getEngine();

  // VBO
  Float32Array vertices{
    1.f,  1.f,  //
    -1.f, 1.f,  //
    -1.f, -1.f, //
    1.f,  -1.f  //
  };

  _vertexBuffers[VertexBuffer::PositionKindChars]
    = ::std::make_unique<VertexBuffer>(
      engine, vertices, VertexBuffer::PositionKind, false, false, 2);

  _createIndexBuffer();

  // Effects
  {
    EffectCreationOptions options;
    options.attributes    = {VertexBuffer::PositionKindChars};
    options.uniformsNames = {"textureMatrix", "color", "scale", "offset"};
    options.samplers      = {"textureSampler"};
    options.defines       = "";

    _effect = engine->createEffect("layer", options, _scene->getEngine());
  }

  {
    EffectCreationOptions options;
    options.attributes    = {VertexBuffer::PositionKindChars};
    options.uniformsNames = {"textureMatrix", "color", "scale", "offset"};
    options.samplers      = {"textureSampler"};
    options.defines       = "#define ALPHATEST";

    _alphaTestEffect
      = engine->createEffect("layer", options, _scene->getEngine());
  }
}

Layer::~Layer()
{
}

// Events
void Layer::setOnDispose(
  const ::std::function<void(Layer*, EventState&)>& callback)
{
  if (_onDisposeObserver) {
    onDisposeObservable.remove(_onDisposeObserver);
  }
  _onDisposeObserver = onDisposeObservable.add(callback);
}

void Layer::setOnBeforeRender(
  const ::std::function<void(Layer*, EventState&)>& callback)
{
  if (_onBeforeRenderObserver) {
    onBeforeRenderObservable.remove(_onBeforeRenderObserver);
  }
  _onBeforeRenderObserver = onBeforeRenderObservable.add(callback);
}

void Layer::setOnAfterRender(
  const ::std::function<void(Layer*, EventState&)>& callback)
{
  if (_onAfterRenderObserver) {
    onAfterRenderObservable.remove(_onAfterRenderObserver);
  }
  _onAfterRenderObserver = onAfterRenderObservable.add(callback);
}

void Layer::_createIndexBuffer()
{
  auto engine = _scene->getEngine();

  // Indices
  Uint32Array indices{
    0, //
    1, //
    2, //
    0, //
    2, //
    3  //
  };
  _indexBuffer = engine->createIndexBuffer(indices);
}

void Layer::_rebuild()
{
  auto& vb = _vertexBuffers[VertexBuffer::PositionKindChars];

  if (vb) {
    vb->_rebuild();
  }

  _createIndexBuffer();
}

void Layer::render()
{
  auto currentEffect = alphaTest ? _alphaTestEffect : _effect;

  // Check
  if (!currentEffect->isReady() || !texture || !texture->isReady()) {
    return;
  }

  auto engine = _scene->getEngine();

  onBeforeRenderObservable.notifyObservers(this);

  // Render
  engine->enableEffect(currentEffect);
  engine->setState(false);

  // Texture
  currentEffect->setTexture("textureSampler", texture);
  currentEffect->setMatrix("textureMatrix", *texture->getTextureMatrix());

  // Color
  currentEffect->setFloat4("color", color.r, color.g, color.b, color.a);

  // Scale / offset
  currentEffect->setVector2("offset", offset);
  currentEffect->setVector2("scale", scale);

  // VBOs
  engine->bindBuffers(stl_util::to_raw_ptr_map(_vertexBuffers),
                      _indexBuffer.get(), currentEffect);

  // Draw order
  if (!_alphaTestEffect) {
    engine->setAlphaMode(alphaBlendingMode);
    engine->draw(true, 0, 6);
    engine->setAlphaMode(EngineConstants::ALPHA_DISABLE);
  }
  else {
    engine->draw(true, 0, 6);
  }

  onAfterRenderObservable.notifyObservers(this);
}

void Layer::dispose(bool /*doNotRecurse*/)
{
  if (stl_util::contains(_vertexBuffers, VertexBuffer::PositionKindChars)) {
    auto& vertexBuffer = _vertexBuffers[VertexBuffer::PositionKindChars];
    if (vertexBuffer) {
      vertexBuffer->dispose();
      _vertexBuffers.erase(VertexBuffer::PositionKindChars);
    }
  }

  if (_indexBuffer) {
    _scene->getEngine()->_releaseBuffer(_indexBuffer.get());
    _indexBuffer = nullptr;
  }

  if (texture) {
    texture->dispose();
    texture = nullptr;
  }

  // Remove from scene
  auto& layers = _scene->layers;
  layers.erase(std::remove(layers.begin(), layers.end(), this), layers.end());

  // Callback
  onDisposeObservable.notifyObservers(this);

  onDisposeObservable.clear();
  onAfterRenderObservable.clear();
  onBeforeRenderObservable.clear();
}

} // end of namespace BABYLON
<commit_msg>Updated Layer class to latest version 3.2.0-alpha7<commit_after>#include <babylon/layer/layer.h>

#include <babylon/babylon_stl_util.h>
#include <babylon/engine/engine.h>
#include <babylon/materials/effect.h>
#include <babylon/materials/effect_creation_options.h>
#include <babylon/materials/effect_fallbacks.h>
#include <babylon/materials/material.h>
#include <babylon/materials/textures/texture.h>
#include <babylon/math/matrix.h>
#include <babylon/mesh/vertex_buffer.h>

namespace BABYLON {

Layer::Layer(const string_t& name, const string_t& imgUrl, Scene* scene,
             bool iIsBackground, const Color4& iColor)
    : isBackground{iIsBackground}
    , color{iColor}
    , scale{Vector2(1.f, 1.f)}
    , offset{Vector2(0.f, 0.f)}
    , alphaBlendingMode{EngineConstants::ALPHA_COMBINE}
    , layerMask{0x0FFFFFFF}
    , _onDisposeObserver{nullptr}
    , _onBeforeRenderObserver{nullptr}
    , _onAfterRenderObserver{nullptr}
    , _name{name}
{
  texture = !imgUrl.empty() ? Texture::New(imgUrl, scene, true) : nullptr;

  _scene = scene ? scene : Engine::LastCreatedScene();
  _scene->layers.emplace_back(this);

  auto engine = scene->getEngine();

  // VBO
  Float32Array vertices{
    1.f,  1.f,  //
    -1.f, 1.f,  //
    -1.f, -1.f, //
    1.f,  -1.f  //
  };

  _vertexBuffers[VertexBuffer::PositionKindChars]
    = ::std::make_unique<VertexBuffer>(
      engine, vertices, VertexBuffer::PositionKind, false, false, 2);

  _createIndexBuffer();

  // Effects
  {
    EffectCreationOptions options;
    options.attributes    = {VertexBuffer::PositionKindChars};
    options.uniformsNames = {"textureMatrix", "color", "scale", "offset"};
    options.samplers      = {"textureSampler"};
    options.defines       = "";

    _effect = engine->createEffect("layer", options, _scene->getEngine());
  }

  {
    EffectCreationOptions options;
    options.attributes    = {VertexBuffer::PositionKindChars};
    options.uniformsNames = {"textureMatrix", "color", "scale", "offset"};
    options.samplers      = {"textureSampler"};
    options.defines       = "#define ALPHATEST";

    _alphaTestEffect
      = engine->createEffect("layer", options, _scene->getEngine());
  }
}

Layer::~Layer()
{
}

// Events
void Layer::setOnDispose(
  const ::std::function<void(Layer*, EventState&)>& callback)
{
  if (_onDisposeObserver) {
    onDisposeObservable.remove(_onDisposeObserver);
  }
  _onDisposeObserver = onDisposeObservable.add(callback);
}

void Layer::setOnBeforeRender(
  const ::std::function<void(Layer*, EventState&)>& callback)
{
  if (_onBeforeRenderObserver) {
    onBeforeRenderObservable.remove(_onBeforeRenderObserver);
  }
  _onBeforeRenderObserver = onBeforeRenderObservable.add(callback);
}

void Layer::setOnAfterRender(
  const ::std::function<void(Layer*, EventState&)>& callback)
{
  if (_onAfterRenderObserver) {
    onAfterRenderObservable.remove(_onAfterRenderObserver);
  }
  _onAfterRenderObserver = onAfterRenderObservable.add(callback);
}

void Layer::_createIndexBuffer()
{
  auto engine = _scene->getEngine();

  // Indices
  Uint32Array indices{
    0, //
    1, //
    2, //
    0, //
    2, //
    3  //
  };
  _indexBuffer = engine->createIndexBuffer(indices);
}

void Layer::_rebuild()
{
  auto& vb = _vertexBuffers[VertexBuffer::PositionKindChars];

  if (vb) {
    vb->_rebuild();
  }

  _createIndexBuffer();
}

void Layer::render()
{
  auto currentEffect = alphaTest ? _alphaTestEffect : _effect;

  // Check
  if (!currentEffect->isReady() || !texture || !texture->isReady()) {
    return;
  }

  auto engine = _scene->getEngine();

  onBeforeRenderObservable.notifyObservers(this);

  // Render
  engine->enableEffect(currentEffect);
  engine->setState(false);

  // Texture
  currentEffect->setTexture("textureSampler", texture);
  currentEffect->setMatrix("textureMatrix", *texture->getTextureMatrix());

  // Color
  currentEffect->setFloat4("color", color.r, color.g, color.b, color.a);

  // Scale / offset
  currentEffect->setVector2("offset", offset);
  currentEffect->setVector2("scale", scale);

  // VBOs
  engine->bindBuffers(stl_util::to_raw_ptr_map(_vertexBuffers),
                      _indexBuffer.get(), currentEffect);

  // Draw order
  if (!alphaTest) {
    engine->setAlphaMode(alphaBlendingMode);
    engine->drawElementsType(Material::TriangleFillMode, 0, 6);
    engine->setAlphaMode(EngineConstants::ALPHA_DISABLE);
  }
  else {
    engine->drawElementsType(Material::TriangleFillMode, 0, 6);
  }

  onAfterRenderObservable.notifyObservers(this);
}

void Layer::dispose(bool /*doNotRecurse*/)
{
  if (stl_util::contains(_vertexBuffers, VertexBuffer::PositionKindChars)) {
    auto& vertexBuffer = _vertexBuffers[VertexBuffer::PositionKindChars];
    if (vertexBuffer) {
      vertexBuffer->dispose();
      _vertexBuffers.erase(VertexBuffer::PositionKindChars);
    }
  }

  if (_indexBuffer) {
    _scene->getEngine()->_releaseBuffer(_indexBuffer.get());
    _indexBuffer = nullptr;
  }

  if (texture) {
    texture->dispose();
    texture = nullptr;
  }

  // Remove from scene
  auto& layers = _scene->layers;
  layers.erase(std::remove(layers.begin(), layers.end(), this), layers.end());

  // Callback
  onDisposeObservable.notifyObservers(this);

  onDisposeObservable.clear();
  onAfterRenderObservable.clear();
  onBeforeRenderObservable.clear();
}

} // end of namespace BABYLON
<|endoftext|>


<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)

#include <TROOT.h>
#include <TStyle.h>
#include <Riostream.h>
#include "TClassTable.h"
#include <TStopwatch.h>
#include <TDatime.h>
#include <TClassTable.h>
#include <TH1.h>
#include <TH2.h>
#include <TF1.h>
#include <TProfile.h>
#include <TFunction.h>
#include <TCanvas.h>
#include <TFile.h>

#endif

void CheckPedestal( Int_t optPlot = 1, const char * histoFName = "ZDCPedHisto.root")
{

  int const kNChannels = 24;
  //
  TFile * file = new TFile(histoFName, "READ");
  file->cd();
  TH1F::AddDirectory(0);
  //
  TH1F *hPedhg[kNChannels], *hPedOutOfTimehg[kNChannels];
  TH2F *hPedCorrhg[kNChannels];
  TH1F *hPedlg[kNChannels], *hPedOutOfTimelg[kNChannels];
  TH2F *hPedCorrlg[kNChannels];
  //
  char namhist1hg[50], namhist2hg[50], namhist3hg[50];
  char namhist1lg[50], namhist2lg[50], namhist3lg[50];
  for(Int_t j=0; j<kNChannels; j++){
     if(j<=4){ // ZNC
       sprintf(namhist1hg,"PedZNChg_%d",j);
       sprintf(namhist2hg,"PedZNChgOutOfTime_%d",j);
       sprintf(namhist3hg,"PedCorrZNChg_%d",j);
       //
       sprintf(namhist1lg,"PedZNClg_%d",j);
       sprintf(namhist2lg,"PedZNClgOutOfTime_%d",j);
       sprintf(namhist3lg,"PedCorrZNClg_%d",j);
     }
     else if(j>=5 && j<=9){ // ZPC
       sprintf(namhist1hg,"PedZPChg_%d",j-5);
       sprintf(namhist2hg,"PedZPChgOutOfTime_%d",j-5);
       sprintf(namhist3hg,"PedCorrZPChg_%d",j-5);
       //
       sprintf(namhist1lg,"PedZPClg_%d",j-5);
       sprintf(namhist2lg,"PedZPClgOutOfTime_%d",j-5);
       sprintf(namhist3lg,"PedCorrZPClg_%d",j-5);
     }
     else if(j==10 || j==11){ // ZEM
       sprintf(namhist1hg,"PedZEMhg_%d",j-10);
       sprintf(namhist2hg,"PedZEMhgOutOfTime_%d",j-10);
       sprintf(namhist3hg,"PedCorrZEMhg_%d",j-10);
       //
       sprintf(namhist1lg,"PedZEMlg_%d",j-10);
       sprintf(namhist2lg,"PedZEMlgOutOfTime_%d",j-10);
       sprintf(namhist3lg,"PedCorrZEMlg_%d",j-10);
     }
     else if(j>=12 && j<=16){ // ZNA
       sprintf(namhist1hg,"PedZNAhg_%d",j-12);
       sprintf(namhist2hg,"PedZNAhgOutOfTime_%d",j-12);
       sprintf(namhist3hg,"PedCorrZNAhg_%d",j-12);
       //
       sprintf(namhist1lg,"PedZNAlg_%d",j-12);
       sprintf(namhist2lg,"PedZNAlgOutOfTime_%d",j-12);
       sprintf(namhist3lg,"PedCorrZNAlg_%d",j-12);
     }
     else if(j>=17 && j<=21){ // ZPA
       sprintf(namhist1hg,"PedZPAhg_%d",j-17);
       sprintf(namhist2hg,"PedZPAhgOutOfTime_%d",j-17);
       sprintf(namhist3hg,"PedCorrZPAhg_%d",j-17);
       //
       sprintf(namhist1lg,"PedZPAlg_%d",j-17);
       sprintf(namhist2lg,"PedZPAlgOutOfTime_%d",j-17);
       sprintf(namhist3lg,"PedCorrZPAlg_%d",j-17);
     }
     else if(j==22 || j==24){ //Reference PMs
       sprintf(namhist1hg,"PedRefhg_%d",j-22);
       sprintf(namhist2hg,"PedRefhgOutOfTime_%d",j-22);
       sprintf(namhist3hg,"PedCorrRefhg_%d",j-22);
       //
       sprintf(namhist1lg,"PedReflg_%d",j-22);
       sprintf(namhist2lg,"PedReflgOutOfTime_%d",j-22);
       sprintf(namhist3lg,"PedCorrReflg_%d",j-22);
     }
     // --- High gain chain histos
     hPedhg[j] = (TH1F*) file->Get(namhist1hg);
     hPedOutOfTimehg[j] = (TH1F*) file->Get(namhist2hg);
     hPedCorrhg[j] =  (TH2F*) file->Get(namhist3hg);
     // --- Low gain chain histos
     hPedlg[j] = (TH1F*) file->Get(namhist1lg);
     hPedOutOfTimelg[j] =(TH1F*) file->Get(namhist2lg);
     hPedCorrlg[j] = (TH2F*) file->Get(namhist3lg);
  }

 if(optPlot==1){
  // Plot the retrieved histos
  //***********************************************************
  // #### ROOT initialization
  gROOT->Reset();
  gStyle->SetCanvasColor(10);
  gStyle->SetFrameFillColor(10);
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(1111);
  gStyle->SetOptFit(111);
  gStyle->SetTitleTextColor(9);
  gStyle->SetStatTextColor(4);
  gStyle->SetLineColor(1);
  gStyle->SetPalette(1);
  //***********************************************************
  TCanvas *c6 = new TCanvas("c6","Side C correlations",0,200,1000,800);
  c6->Divide(5,4);
  for(Int_t t=0; t<10; t++){
    c6->cd(t+1);
    hPedCorrhg[t]->Draw();
    c6->cd(t+11);
    hPedCorrlg[t]->Draw();
  }
  c6->Print("CorrSideC.ps");
  //
  TCanvas *c7 = new TCanvas("c7","Side A correlations",300,200,1000,800);
  c7->Divide(5,4);
  for(Int_t t=0; t<10; t++){
    c7->cd(t+1);
    hPedCorrhg[t+12]->Draw();
    c7->cd(t+11);
    hPedCorrlg[t+12]->Draw();
  }
  c7->Print("CorrSideA.ps");
  //
  TCanvas *c8 = new TCanvas("c8","ZEM correlations",400,200,400,400);
  c8->Divide(2,2);
  for(Int_t t=0; t<2; t++){
    c8->cd(t+1);
    hPedCorrhg[t+10]->Draw();
    c8->cd(t+3);
    hPedCorrlg[t+10]->Draw();
  }
  c8->Print("CorrZEM.ps");
  //***********************************************************
  TCanvas *c1 = new TCanvas("c1","ZNC pedestals",0,0,1000,400);
  c1->Divide(5,2);
  for(Int_t y=0; y<5; y++){
    c1->cd(y+1);
    hPedhg[y]->Draw();
    c1->cd(y+6);
    hPedlg[y]->Draw();
  }
  c1->Print("ZNCPed.ps");
  //
  TCanvas *c2 = new TCanvas("c2","ZPC pedestals",300,0,1000,400);
  c2->Divide(5,2);
  for(Int_t y=0; y<5; y++){
    c2->cd(y+1);
    hPedhg[y+5]->Draw();
    c2->cd(y+6);
    hPedlg[y+5]->Draw();
  }
  c2->Print("ZPCPed.ps");
  //
  TCanvas *c3 = new TCanvas("c3","ZEM pedestals",400,0,400,400);
  c3->Divide(2,2);
  for(Int_t y=0; y<2; y++){
    c3->cd(y+1);
    hPedhg[y+10]->Draw();
    c3->cd(y+3);
    hPedlg[y+10]->Draw();
  }
  c3->Print("ZEMPed.ps");
  //
  TCanvas *c4 = new TCanvas("c4","ZNA pedestals",0,400,1000,400);
  c4->Divide(5,2);
  for(Int_t y=0; y<5; y++){
    c4->cd(y+1);
    hPedhg[y+12]->Draw();
    c4->cd(y+6);
    hPedlg[y+12]->Draw();
  }
  c4->Print("ZNAPed.ps");
  //
  TCanvas *c5 = new TCanvas("c5","ZPA pedestals",300,400,1000,400);
  c5->Divide(5,2);
  for(Int_t y=0; y<5; y++){
    c5->cd(y+1);
    hPedhg[y+17]->Draw();
    c5->cd(y+6);
    hPedlg[y+17]->Draw();
  }
  c5->Print("ZPAPed.ps");
 }
}
<commit_msg>Updated macro<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)

#include <TROOT.h>
#include <TStyle.h>
#include <Riostream.h>
#include "TClassTable.h"
#include <TStopwatch.h>
#include <TDatime.h>
#include <TClassTable.h>
#include <TH1.h>
#include <TH2.h>
#include <TF1.h>
#include <TProfile.h>
#include <TFunction.h>
#include <TCanvas.h>
#include <TFile.h>

#endif

void CheckPedestal(const char * histoFName = "ZDCPedHisto.root", Int_t optPlot = 1)
{

  int const kNChannels = 24;
  //
  TFile * file = new TFile(histoFName, "READ");
  file->cd();
  TH1F::AddDirectory(0);
  //
  TH1F *hPedhg[kNChannels], *hPedOutOfTimehg[kNChannels];
  TH2F *hPedCorrhg[kNChannels];
  TH1F *hPedlg[kNChannels], *hPedOutOfTimelg[kNChannels];
  TH2F *hPedCorrlg[kNChannels];
  //
  char namhist1hg[50], namhist2hg[50], namhist3hg[50];
  char namhist1lg[50], namhist2lg[50], namhist3lg[50];
  for(Int_t j=0; j<kNChannels; j++){
     if(j<=4){ // ZNC
       sprintf(namhist1hg,"PedZNChg_%d",j);
       sprintf(namhist2hg,"PedZNChgOutOfTime_%d",j);
       sprintf(namhist3hg,"PedCorrZNChg_%d",j);
       //
       sprintf(namhist1lg,"PedZNClg_%d",j);
       sprintf(namhist2lg,"PedZNClgOutOfTime_%d",j);
       sprintf(namhist3lg,"PedCorrZNClg_%d",j);
     }
     else if(j>=5 && j<=9){ // ZPC
       sprintf(namhist1hg,"PedZPChg_%d",j-5);
       sprintf(namhist2hg,"PedZPChgOutOfTime_%d",j-5);
       sprintf(namhist3hg,"PedCorrZPChg_%d",j-5);
       //
       sprintf(namhist1lg,"PedZPClg_%d",j-5);
       sprintf(namhist2lg,"PedZPClgOutOfTime_%d",j-5);
       sprintf(namhist3lg,"PedCorrZPClg_%d",j-5);
     }
     else if(j==10 || j==11){ // ZEM
       sprintf(namhist1hg,"PedZEMhg_%d",j-9);
       sprintf(namhist2hg,"PedZEMhgOutOfTime_%d",j-9);
       sprintf(namhist3hg,"PedCorrZEMhg_%d",j-9);
       //
       sprintf(namhist1lg,"PedZEMlg_%d",j-9);
       sprintf(namhist2lg,"PedZEMlgOutOfTime_%d",j-9);
       sprintf(namhist3lg,"PedCorrZEMlg_%d",j-9);
     }
     else if(j>=12 && j<=16){ // ZNA
       sprintf(namhist1hg,"PedZNAhg_%d",j-12);
       sprintf(namhist2hg,"PedZNAhgOutOfTime_%d",j-12);
       sprintf(namhist3hg,"PedCorrZNAhg_%d",j-12);
       //
       sprintf(namhist1lg,"PedZNAlg_%d",j-12);
       sprintf(namhist2lg,"PedZNAlgOutOfTime_%d",j-12);
       sprintf(namhist3lg,"PedCorrZNAlg_%d",j-12);
     }
     else if(j>=17 && j<=21){ // ZPA
       sprintf(namhist1hg,"PedZPAhg_%d",j-17);
       sprintf(namhist2hg,"PedZPAhgOutOfTime_%d",j-17);
       sprintf(namhist3hg,"PedCorrZPAhg_%d",j-17);
       //
       sprintf(namhist1lg,"PedZPAlg_%d",j-17);
       sprintf(namhist2lg,"PedZPAlgOutOfTime_%d",j-17);
       sprintf(namhist3lg,"PedCorrZPAlg_%d",j-17);
     }
     else if(j==22 || j==23){ //Reference PMs
       sprintf(namhist1hg,"PedRefhg_%d",j-22);
       sprintf(namhist2hg,"PedRefhgOutOfTime_%d",j-22);
       sprintf(namhist3hg,"PedCorrRefhg_%d",j-22);
       //
       sprintf(namhist1lg,"PedReflg_%d",j-22);
       sprintf(namhist2lg,"PedReflgOutOfTime_%d",j-22);
       sprintf(namhist3lg,"PedCorrReflg_%d",j-22);
     }
     // --- High gain chain histos
     hPedhg[j] = (TH1F*) file->Get(namhist1hg);
     hPedOutOfTimehg[j] = (TH1F*) file->Get(namhist2hg);
     hPedCorrhg[j] =  (TH2F*) file->Get(namhist3hg);
     // --- Low gain chain histos
     hPedlg[j] = (TH1F*) file->Get(namhist1lg);
     hPedOutOfTimelg[j] =(TH1F*) file->Get(namhist2lg);
     hPedCorrlg[j] = (TH2F*) file->Get(namhist3lg);
  }

 if(optPlot==1){
  // Plot the retrieved histos
  //***********************************************************
  // #### ROOT initialization
  gROOT->Reset();
  gStyle->SetCanvasColor(10);
  gStyle->SetFrameFillColor(10);
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(1111);
  gStyle->SetOptFit(111);
  gStyle->SetTitleTextColor(9);
  gStyle->SetStatTextColor(4);
  gStyle->SetLineColor(1);
  gStyle->SetPalette(1);
  //***********************************************************
  TCanvas *c6 = new TCanvas("c6","Side C correlations",0,200,1000,800);
  c6->Divide(5,4);
  for(Int_t t=0; t<10; t++){
    c6->cd(t+1);
    hPedCorrhg[t]->Draw();
    c6->cd(t+11);
    hPedCorrlg[t]->Draw();
  }
  c6->Print("CorrSideC.ps");
  //
  TCanvas *c7 = new TCanvas("c7","Side A correlations",300,200,1000,800);
  c7->Divide(5,4);
  for(Int_t t=0; t<10; t++){
    c7->cd(t+1);
    hPedCorrhg[t+12]->Draw();
    c7->cd(t+11);
    hPedCorrlg[t+12]->Draw();
  }
  c7->Print("CorrSideA.ps");
  //
  TCanvas *c8 = new TCanvas("c8","ZEM correlations",400,200,400,400);
  c8->Divide(2,2);
  for(Int_t t=0; t<2; t++){
    c8->cd(t+1);
    hPedCorrhg[t+10]->Draw();
    c8->cd(t+3);
    hPedCorrlg[t+10]->Draw();
  }
  c8->Print("CorrZEM.ps");
  //***********************************************************
  TCanvas *c1 = new TCanvas("c1","ZNC pedestals",0,0,1000,400);
  c1->Divide(5,2);
  for(Int_t y=0; y<5; y++){
    c1->cd(y+1);
    hPedhg[y]->Draw();
    c1->cd(y+6);
    hPedlg[y]->Draw();
  }
  c1->Print("ZNCPed.ps");
  //
  TCanvas *c2 = new TCanvas("c2","ZPC pedestals",300,0,1000,400);
  c2->Divide(5,2);
  for(Int_t y=0; y<5; y++){
    c2->cd(y+1);
    hPedhg[y+5]->Draw();
    c2->cd(y+6);
    hPedlg[y+5]->Draw();
  }
  c2->Print("ZPCPed.ps");
  //
  TCanvas *c3 = new TCanvas("c3","ZEM pedestals",400,0,400,400);
  c3->Divide(2,2);
  for(Int_t y=0; y<2; y++){
    c3->cd(y+1);
    hPedhg[y+10]->Draw();
    c3->cd(y+3);
    hPedlg[y+10]->Draw();
  }
  c3->Print("ZEMPed.ps");
  //
  TCanvas *c4 = new TCanvas("c4","ZNA pedestals",0,400,1000,400);
  c4->Divide(5,2);
  for(Int_t y=0; y<5; y++){
    c4->cd(y+1);
    hPedhg[y+12]->Draw();
    c4->cd(y+6);
    hPedlg[y+12]->Draw();
  }
  c4->Print("ZNAPed.ps");
  //
  TCanvas *c5 = new TCanvas("c5","ZPA pedestals",300,400,1000,400);
  c5->Divide(5,2);
  for(Int_t y=0; y<5; y++){
    c5->cd(y+1);
    hPedhg[y+17]->Draw();
    c5->cd(y+6);
    hPedlg[y+17]->Draw();
  }
  c5->Print("ZPAPed.ps");
 }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dlgegif.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 15:40:55 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_goodies.hxx"
#ifndef GCC
#endif
#include <tools/ref.hxx>
#include <svtools/FilterConfigItem.hxx>
#include <vcl/msgbox.hxx>
#include "dlgegif.hxx"
#include "dlgegif.hrc"
#include "strings.hrc"

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/

DlgExportEGIF::DlgExportEGIF( FltCallDialogParameter& rPara ) :
                ModalDialog         ( rPara.pWindow, ResId( DLG_EXPORT_GIF, rPara.pResMgr ) ),
                rFltCallPara        ( rPara ),
                aCbxInterlaced      ( this, ResId( CBX_INTERLACED ) ),
                aCbxTranslucent     ( this, ResId( CBX_TRANSLUCENT ) ),
                aGrpMode            ( this, ResId( GRP_MODE ) ),
                aGrpDraw            ( this, ResId( GRP_DRAW ) ),
                aBtnOK              ( this, ResId( BTN_OK ) ),
                aBtnCancel          ( this, ResId( BTN_CANCEL ) ),
                aBtnHelp            ( this, ResId( BTN_HELP ) ),
                pMgr                ( rPara.pResMgr )
{
    FreeResource();

    String  aFilterConfigPath( RTL_CONSTASCII_USTRINGPARAM( "Office.Common/Filter/Graphic/Export/GIF" ) );
    pConfigItem = new FilterConfigItem( aFilterConfigPath, &rPara.aFilterData );

    String aInterlaceStr( ResId( KEY_INTER, pMgr ) );
    String aTranslucentStr( ResId( KEY_TRANS, pMgr ) );
    // Config-Parameter lesen
    sal_Bool bInterlaced = pConfigItem->ReadInt32( aInterlaceStr, 1 ) != 0;
    sal_Bool bTranslucent = pConfigItem->ReadInt32( aTranslucentStr, 1 ) != 0;

    aCbxInterlaced.Check( bInterlaced );
    aCbxTranslucent.Check( bTranslucent );

    aBtnOK.SetClickHdl( LINK( this, DlgExportEGIF, OK ) );
}

DlgExportEGIF::~DlgExportEGIF()
{
    delete pConfigItem;
}

/*************************************************************************
|*
|* Speichert eingestellte Werte in ini-Datei
|*
\************************************************************************/

IMPL_LINK( DlgExportEGIF, OK, void *, EMPTYARG )
{

    // Config-Parameter schreiben
    String aInterlaceStr( ResId( KEY_INTER, pMgr ) );
    String aTranslucentStr( ResId( KEY_TRANS, pMgr ) );

    sal_Int32 nValue = 0;
    if ( aCbxInterlaced.IsChecked() )
        nValue++;
    pConfigItem->WriteInt32( aInterlaceStr, nValue );

    nValue = 0;
    if ( aCbxTranslucent.IsChecked() )
        nValue++;
    pConfigItem->WriteInt32( aTranslucentStr, nValue );
    rFltCallPara.aFilterData = pConfigItem->GetFilterData();
    EndDialog( RET_OK );

    return 0;
}

<commit_msg>INTEGRATION: CWS residcleanup (1.7.72); FILE MERGED 2007/02/18 19:58:09 pl 1.7.72.1: #i74635# get rid of implicit global ResMgr<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dlgegif.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-26 09:59:31 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_goodies.hxx"
#ifndef GCC
#endif
#include <tools/ref.hxx>
#include <svtools/FilterConfigItem.hxx>
#include <vcl/msgbox.hxx>
#include "dlgegif.hxx"
#include "dlgegif.hrc"
#include "strings.hrc"

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/

DlgExportEGIF::DlgExportEGIF( FltCallDialogParameter& rPara ) :
                ModalDialog         ( rPara.pWindow, ResId( DLG_EXPORT_GIF, *rPara.pResMgr ) ),
                rFltCallPara        ( rPara ),
                aCbxInterlaced      ( this, ResId( CBX_INTERLACED, *rPara.pResMgr ) ),
                aCbxTranslucent     ( this, ResId( CBX_TRANSLUCENT, *rPara.pResMgr ) ),
                aGrpMode            ( this, ResId( GRP_MODE, *rPara.pResMgr ) ),
                aGrpDraw            ( this, ResId( GRP_DRAW, *rPara.pResMgr ) ),
                aBtnOK              ( this, ResId( BTN_OK, *rPara.pResMgr ) ),
                aBtnCancel          ( this, ResId( BTN_CANCEL, *rPara.pResMgr ) ),
                aBtnHelp            ( this, ResId( BTN_HELP, *rPara.pResMgr ) ),
                pMgr                ( rPara.pResMgr )
{
    FreeResource();

    String  aFilterConfigPath( RTL_CONSTASCII_USTRINGPARAM( "Office.Common/Filter/Graphic/Export/GIF" ) );
    pConfigItem = new FilterConfigItem( aFilterConfigPath, &rPara.aFilterData );

    String aInterlaceStr( ResId( KEY_INTER, *pMgr ) );
    String aTranslucentStr( ResId( KEY_TRANS, *pMgr ) );
    // Config-Parameter lesen
    sal_Bool bInterlaced = pConfigItem->ReadInt32( aInterlaceStr, 1 ) != 0;
    sal_Bool bTranslucent = pConfigItem->ReadInt32( aTranslucentStr, 1 ) != 0;

    aCbxInterlaced.Check( bInterlaced );
    aCbxTranslucent.Check( bTranslucent );

    aBtnOK.SetClickHdl( LINK( this, DlgExportEGIF, OK ) );
}

DlgExportEGIF::~DlgExportEGIF()
{
    delete pConfigItem;
}

/*************************************************************************
|*
|* Speichert eingestellte Werte in ini-Datei
|*
\************************************************************************/

IMPL_LINK( DlgExportEGIF, OK, void *, EMPTYARG )
{

    // Config-Parameter schreiben
    String aInterlaceStr( ResId( KEY_INTER, *pMgr ) );
    String aTranslucentStr( ResId( KEY_TRANS, *pMgr ) );

    sal_Int32 nValue = 0;
    if ( aCbxInterlaced.IsChecked() )
        nValue++;
    pConfigItem->WriteInt32( aInterlaceStr, nValue );

    nValue = 0;
    if ( aCbxTranslucent.IsChecked() )
        nValue++;
    pConfigItem->WriteInt32( aTranslucentStr, nValue );
    rFltCallPara.aFilterData = pConfigItem->GetFilterData();
    EndDialog( RET_OK );

    return 0;
}

<|endoftext|>