<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hfi_module.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 16:36: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
 *
 ************************************************************************/

#include <precomp.h>
#include "hfi_module.hxx"

// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_ce.hxx>
#include <ary/idl/i_module.hxx>
#include <ary/idl/ik_module.hxx>
#include <ary/doc/d_oldidldocu.hxx>
#include <ary/getncast.hxx>
#include <toolkit/hf_docentry.hxx>
#include <toolkit/hf_linachain.hxx>
#include <toolkit/hf_navi_sub.hxx>
#include <toolkit/hf_title.hxx>
#include "hfi_doc.hxx"
#include "hfi_navibar.hxx"
#include "hfi_tag.hxx"
#include "hfi_typetext.hxx"
#include "hi_linkhelper.hxx"

extern const String
    C_sCePrefix_Module("module");

namespace
{

const String
    C_sList_NestedModules("Nested Modules");
const String
    C_sList_NestedModules_Label("NestedModules");
const String
    C_sList_Services("Services");
const String
    C_sList_Singletons("Singletons");
const String
    C_sList_Interfaces("Interfaces");
const String
    C_sList_Structs("Structs");
const String
    C_sList_Exceptions("Exceptions");
const String
    C_sList_Enums("Enums");
const String
    C_sList_Typedefs("Typedefs");
const String
    C_sList_ConstGroups("Constant Groups");
const String
    C_sList_ConstGroups_Label("ConstantGroups");

enum E_SubListIndices
{   // In case of changes, also adapt make_Navibar() !!
    sli_NestedModules = 0,
    sli_Services = 1,
    sli_Singletons = 2,
    sli_Interfaces = 3,
    sli_Structs = 4,
    sli_Exceptions = 5,
    sli_Enums = 6,
    sli_Typedefs = 7,
    sli_ConstGroups = 8
};

} //anonymous namespace

HF_IdlModule::HF_IdlModule( Environment &         io_rEnv,
                            Xml::Element &        o_rOut )
    :   HtmlFactory_Idl(io_rEnv, &o_rOut)
{
}

HF_IdlModule::~HF_IdlModule()
{
}

typedef ary::idl::ifc_module::attr  ModuleAttr;

void
HF_IdlModule::Produce_byData( const client & i_ce ) const
{
    Dyn<HF_NaviSubRow>
        pNaviSubRow( &make_Navibar(i_ce) );

    HF_TitleTable
        aTitle(CurOut());
    HF_LinkedNameChain
        aNameChain(aTitle.Add_Row());

    if ( Env().CurPosition().Depth() > 0 )
    {
        aNameChain.Produce_CompleteChain_forModule(Env().CurPosition(), nameChainLinker);

        StreamLock
            sl(200);
        aTitle.Produce_Title( sl()
                                << C_sCePrefix_Module
                                  << " "
                                << i_ce.LocalName()
                                << c_str );
    }
    else
    {
        aTitle.Produce_Title( "Global Module" );
    }

    write_Docu(aTitle.Add_Row(), i_ce);
    CurOut() << new Html::HorizontalLine();

    // Write children lists:
    ce_ptr_list aNestedModules;
    ce_ptr_list aServices;
    ce_ptr_list aInterfaces;
    ce_ptr_list aStructs;
    ce_ptr_list aExceptions;
    ce_ptr_list aEnums;
    ce_ptr_list aTypedefs;
    ce_ptr_list aConstantGroups;
    ce_ptr_list aSingletons;

    ModuleAttr::Get_AllChildrenSeparated(
                                aNestedModules,
                                aServices,
                                aInterfaces,
                                aStructs,
                                aExceptions,
                                aEnums,
                                aTypedefs,
                                aConstantGroups,
                                aSingletons,
                                Env().Data().Ces(),
                                i_ce );

    // Has this to be in the order of enum E_SubListIndices ???
    if (produce_ChildList(C_sList_NestedModules, C_sList_NestedModules_Label, aNestedModules ))
        pNaviSubRow->SwitchOn(sli_NestedModules);
    if (produce_ChildList(C_sList_Services, C_sList_Services, aServices))
        pNaviSubRow->SwitchOn(sli_Services);
    if (produce_ChildList(C_sList_Singletons, C_sList_Singletons, aSingletons))
        pNaviSubRow->SwitchOn(sli_Singletons);
    if (produce_ChildList(C_sList_Interfaces, C_sList_Interfaces, aInterfaces))
        pNaviSubRow->SwitchOn(sli_Interfaces);
    if (produce_ChildList(C_sList_Structs, C_sList_Structs, aStructs))
        pNaviSubRow->SwitchOn(sli_Structs);
    if (produce_ChildList(C_sList_Exceptions, C_sList_Exceptions, aExceptions))
        pNaviSubRow->SwitchOn(sli_Exceptions);
    if (produce_ChildList(C_sList_Enums, C_sList_Enums, aEnums))
        pNaviSubRow->SwitchOn(sli_Enums);
    if (produce_ChildList(C_sList_Typedefs, C_sList_Typedefs, aTypedefs))
        pNaviSubRow->SwitchOn(sli_Typedefs);
    if (produce_ChildList(C_sList_ConstGroups, C_sList_ConstGroups_Label, aConstantGroups))
        pNaviSubRow->SwitchOn(sli_ConstGroups);
    pNaviSubRow->Produce_Row();
}

DYN HF_NaviSubRow &
HF_IdlModule::make_Navibar( const client & i_ce ) const
{
    HF_IdlNavigationBar
        aNaviBar(Env(), CurOut());
    aNaviBar.Produce_ModuleMainRow(i_ce);

    DYN HF_NaviSubRow &
        ret = aNaviBar.Add_SubRow();

    // Has to be in the order of E_SubListIndices:
    ret.AddItem(C_sList_NestedModules, C_sList_NestedModules_Label, false);
    ret.AddItem(C_sList_Services, C_sList_Services, false);
    ret.AddItem(C_sList_Singletons, C_sList_Singletons, false);
    ret.AddItem(C_sList_Interfaces, C_sList_Interfaces, false);
    ret.AddItem(C_sList_Structs, C_sList_Structs, false);
    ret.AddItem(C_sList_Exceptions, C_sList_Exceptions, false);
    ret.AddItem(C_sList_Enums, C_sList_Enums, false);
    ret.AddItem(C_sList_Typedefs, C_sList_Typedefs, false);
    ret.AddItem(C_sList_ConstGroups, C_sList_ConstGroups_Label, false);

    CurOut() << new Html::HorizontalLine();
    return ret;
}

bool
HF_IdlModule::produce_ChildList( const String &      i_sName,
                                 const String &      i_sLabel,
                                 const ce_ptr_list & i_list ) const
{
    if ( i_list.size() == 0 )
        return false;

    HF_SubTitleTable
        aTable( CurOut(),
                i_sLabel,
                i_sName,
                2 );

    ce_ptr_list::const_iterator
        itEnd = i_list.end();
    for ( ce_ptr_list::const_iterator it = i_list.begin();
          it != itEnd;
          ++it )
    {
        Xml::Element &
            rRow = aTable.Add_Row();
        produce_Link(rRow, *it);
        produce_LinkDoc(rRow, *it);
    }   // end for

    return true;
}

void
HF_IdlModule::produce_Link( Xml::Element &      o_row,
                            const client *      i_ce ) const
{
    csv_assert(i_ce != 0);
    Xml::Element &
        rCell = o_row
                >> *new Html::TableCell
                    << new Html::ClassAttr(C_sCellStyle_SummaryLeft);

    if ( NOT ary::is_type<ary::idl::Module>(*i_ce) )
    {
        HF_IdlTypeText
            aText(Env(), rCell, true);
        aText.Produce_byData(i_ce->CeId());
    }
    else
    {
        StreamLock slBuf(100);
         rCell
            >> *new Html::Link( slBuf() << i_ce->LocalName()
                                        << "/module-ix.html"
                                        << c_str )
                << i_ce->LocalName();
    }
}

void
HF_IdlModule::produce_LinkDoc( Xml::Element &      o_row,
                               const client *      i_ce ) const
{
    csv_assert(i_ce != 0);

    // We need the cell in any case, because, the rendering may be hurt else.
    Xml::Element &
        rCell = o_row
                    >> *new Html::TableCell
                        << new Html::ClassAttr(C_sCellStyle_SummaryRight);

    const client &
        rCe = *i_ce;
    const ce_info *
        pShort = Get_IdlDocu(rCe.Docu());
    if ( pShort == 0 )
        return;

    if (pShort->IsDeprecated())
    {
        rCell << "[ DEPRECATED ]" << new Html::LineBreak;
    }
    if (pShort->IsOptional())
    {
        rCell << "[ OPTIONAL ]" << new Html::LineBreak;
    }

    HF_IdlDocuTextDisplay
        aShortDisplay(Env(), &rCell, *i_ce);
    pShort->Short().DisplayAt(aShortDisplay);
}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.22); FILE MERGED 2008/03/28 16:02:04 rt 1.7.22.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: hfi_module.cxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <precomp.h>
#include "hfi_module.hxx"

// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_ce.hxx>
#include <ary/idl/i_module.hxx>
#include <ary/idl/ik_module.hxx>
#include <ary/doc/d_oldidldocu.hxx>
#include <ary/getncast.hxx>
#include <toolkit/hf_docentry.hxx>
#include <toolkit/hf_linachain.hxx>
#include <toolkit/hf_navi_sub.hxx>
#include <toolkit/hf_title.hxx>
#include "hfi_doc.hxx"
#include "hfi_navibar.hxx"
#include "hfi_tag.hxx"
#include "hfi_typetext.hxx"
#include "hi_linkhelper.hxx"

extern const String
    C_sCePrefix_Module("module");

namespace
{

const String
    C_sList_NestedModules("Nested Modules");
const String
    C_sList_NestedModules_Label("NestedModules");
const String
    C_sList_Services("Services");
const String
    C_sList_Singletons("Singletons");
const String
    C_sList_Interfaces("Interfaces");
const String
    C_sList_Structs("Structs");
const String
    C_sList_Exceptions("Exceptions");
const String
    C_sList_Enums("Enums");
const String
    C_sList_Typedefs("Typedefs");
const String
    C_sList_ConstGroups("Constant Groups");
const String
    C_sList_ConstGroups_Label("ConstantGroups");

enum E_SubListIndices
{   // In case of changes, also adapt make_Navibar() !!
    sli_NestedModules = 0,
    sli_Services = 1,
    sli_Singletons = 2,
    sli_Interfaces = 3,
    sli_Structs = 4,
    sli_Exceptions = 5,
    sli_Enums = 6,
    sli_Typedefs = 7,
    sli_ConstGroups = 8
};

} //anonymous namespace

HF_IdlModule::HF_IdlModule( Environment &         io_rEnv,
                            Xml::Element &        o_rOut )
    :   HtmlFactory_Idl(io_rEnv, &o_rOut)
{
}

HF_IdlModule::~HF_IdlModule()
{
}

typedef ary::idl::ifc_module::attr  ModuleAttr;

void
HF_IdlModule::Produce_byData( const client & i_ce ) const
{
    Dyn<HF_NaviSubRow>
        pNaviSubRow( &make_Navibar(i_ce) );

    HF_TitleTable
        aTitle(CurOut());
    HF_LinkedNameChain
        aNameChain(aTitle.Add_Row());

    if ( Env().CurPosition().Depth() > 0 )
    {
        aNameChain.Produce_CompleteChain_forModule(Env().CurPosition(), nameChainLinker);

        StreamLock
            sl(200);
        aTitle.Produce_Title( sl()
                                << C_sCePrefix_Module
                                  << " "
                                << i_ce.LocalName()
                                << c_str );
    }
    else
    {
        aTitle.Produce_Title( "Global Module" );
    }

    write_Docu(aTitle.Add_Row(), i_ce);
    CurOut() << new Html::HorizontalLine();

    // Write children lists:
    ce_ptr_list aNestedModules;
    ce_ptr_list aServices;
    ce_ptr_list aInterfaces;
    ce_ptr_list aStructs;
    ce_ptr_list aExceptions;
    ce_ptr_list aEnums;
    ce_ptr_list aTypedefs;
    ce_ptr_list aConstantGroups;
    ce_ptr_list aSingletons;

    ModuleAttr::Get_AllChildrenSeparated(
                                aNestedModules,
                                aServices,
                                aInterfaces,
                                aStructs,
                                aExceptions,
                                aEnums,
                                aTypedefs,
                                aConstantGroups,
                                aSingletons,
                                Env().Data().Ces(),
                                i_ce );

    // Has this to be in the order of enum E_SubListIndices ???
    if (produce_ChildList(C_sList_NestedModules, C_sList_NestedModules_Label, aNestedModules ))
        pNaviSubRow->SwitchOn(sli_NestedModules);
    if (produce_ChildList(C_sList_Services, C_sList_Services, aServices))
        pNaviSubRow->SwitchOn(sli_Services);
    if (produce_ChildList(C_sList_Singletons, C_sList_Singletons, aSingletons))
        pNaviSubRow->SwitchOn(sli_Singletons);
    if (produce_ChildList(C_sList_Interfaces, C_sList_Interfaces, aInterfaces))
        pNaviSubRow->SwitchOn(sli_Interfaces);
    if (produce_ChildList(C_sList_Structs, C_sList_Structs, aStructs))
        pNaviSubRow->SwitchOn(sli_Structs);
    if (produce_ChildList(C_sList_Exceptions, C_sList_Exceptions, aExceptions))
        pNaviSubRow->SwitchOn(sli_Exceptions);
    if (produce_ChildList(C_sList_Enums, C_sList_Enums, aEnums))
        pNaviSubRow->SwitchOn(sli_Enums);
    if (produce_ChildList(C_sList_Typedefs, C_sList_Typedefs, aTypedefs))
        pNaviSubRow->SwitchOn(sli_Typedefs);
    if (produce_ChildList(C_sList_ConstGroups, C_sList_ConstGroups_Label, aConstantGroups))
        pNaviSubRow->SwitchOn(sli_ConstGroups);
    pNaviSubRow->Produce_Row();
}

DYN HF_NaviSubRow &
HF_IdlModule::make_Navibar( const client & i_ce ) const
{
    HF_IdlNavigationBar
        aNaviBar(Env(), CurOut());
    aNaviBar.Produce_ModuleMainRow(i_ce);

    DYN HF_NaviSubRow &
        ret = aNaviBar.Add_SubRow();

    // Has to be in the order of E_SubListIndices:
    ret.AddItem(C_sList_NestedModules, C_sList_NestedModules_Label, false);
    ret.AddItem(C_sList_Services, C_sList_Services, false);
    ret.AddItem(C_sList_Singletons, C_sList_Singletons, false);
    ret.AddItem(C_sList_Interfaces, C_sList_Interfaces, false);
    ret.AddItem(C_sList_Structs, C_sList_Structs, false);
    ret.AddItem(C_sList_Exceptions, C_sList_Exceptions, false);
    ret.AddItem(C_sList_Enums, C_sList_Enums, false);
    ret.AddItem(C_sList_Typedefs, C_sList_Typedefs, false);
    ret.AddItem(C_sList_ConstGroups, C_sList_ConstGroups_Label, false);

    CurOut() << new Html::HorizontalLine();
    return ret;
}

bool
HF_IdlModule::produce_ChildList( const String &      i_sName,
                                 const String &      i_sLabel,
                                 const ce_ptr_list & i_list ) const
{
    if ( i_list.size() == 0 )
        return false;

    HF_SubTitleTable
        aTable( CurOut(),
                i_sLabel,
                i_sName,
                2 );

    ce_ptr_list::const_iterator
        itEnd = i_list.end();
    for ( ce_ptr_list::const_iterator it = i_list.begin();
          it != itEnd;
          ++it )
    {
        Xml::Element &
            rRow = aTable.Add_Row();
        produce_Link(rRow, *it);
        produce_LinkDoc(rRow, *it);
    }   // end for

    return true;
}

void
HF_IdlModule::produce_Link( Xml::Element &      o_row,
                            const client *      i_ce ) const
{
    csv_assert(i_ce != 0);
    Xml::Element &
        rCell = o_row
                >> *new Html::TableCell
                    << new Html::ClassAttr(C_sCellStyle_SummaryLeft);

    if ( NOT ary::is_type<ary::idl::Module>(*i_ce) )
    {
        HF_IdlTypeText
            aText(Env(), rCell, true);
        aText.Produce_byData(i_ce->CeId());
    }
    else
    {
        StreamLock slBuf(100);
         rCell
            >> *new Html::Link( slBuf() << i_ce->LocalName()
                                        << "/module-ix.html"
                                        << c_str )
                << i_ce->LocalName();
    }
}

void
HF_IdlModule::produce_LinkDoc( Xml::Element &      o_row,
                               const client *      i_ce ) const
{
    csv_assert(i_ce != 0);

    // We need the cell in any case, because, the rendering may be hurt else.
    Xml::Element &
        rCell = o_row
                    >> *new Html::TableCell
                        << new Html::ClassAttr(C_sCellStyle_SummaryRight);

    const client &
        rCe = *i_ce;
    const ce_info *
        pShort = Get_IdlDocu(rCe.Docu());
    if ( pShort == 0 )
        return;

    if (pShort->IsDeprecated())
    {
        rCell << "[ DEPRECATED ]" << new Html::LineBreak;
    }
    if (pShort->IsOptional())
    {
        rCell << "[ OPTIONAL ]" << new Html::LineBreak;
    }

    HF_IdlDocuTextDisplay
        aShortDisplay(Env(), &rCell, *i_ce);
    pShort->Short().DisplayAt(aShortDisplay);
}
<|endoftext|>


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

#include "chrome/browser/hung_renderer_dialog.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/i18n/rtl.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/common/result_codes.h"
#include "gfx/canvas.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/grid_layout.h"
#include "views/controls/button/native_button.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/table/group_table_view.h"
#include "views/standard_layout.h"
#include "views/window/client_view.h"
#include "views/window/dialog_delegate.h"
#include "views/window/window.h"

class HungRendererDialogView;

namespace {
// We only support showing one of these at a time per app.
HungRendererDialogView* g_instance = NULL;
}

///////////////////////////////////////////////////////////////////////////////
// HungPagesTableModel

class HungPagesTableModel : public views::GroupTableModel {
 public:
  HungPagesTableModel();
  virtual ~HungPagesTableModel();

  void InitForTabContents(TabContents* hung_contents);

  // Overridden from views::GroupTableModel:
  virtual int RowCount();
  virtual std::wstring GetText(int row, int column_id);
  virtual SkBitmap GetIcon(int row);
  virtual void SetObserver(TableModelObserver* observer);
  virtual void GetGroupRangeForItem(int item, views::GroupRange* range);

 private:
  typedef std::vector<TabContents*> TabContentsVector;
  TabContentsVector tab_contentses_;

  TableModelObserver* observer_;

  DISALLOW_COPY_AND_ASSIGN(HungPagesTableModel);
};

///////////////////////////////////////////////////////////////////////////////
// HungPagesTableModel, public:

HungPagesTableModel::HungPagesTableModel() : observer_(NULL) {
}

HungPagesTableModel::~HungPagesTableModel() {
}

void HungPagesTableModel::InitForTabContents(TabContents* hung_contents) {
  tab_contentses_.clear();
  for (TabContentsIterator it; !it.done(); ++it) {
    if (it->GetRenderProcessHost() == hung_contents->GetRenderProcessHost())
      tab_contentses_.push_back(*it);
  }
  // The world is different.
  if (observer_)
    observer_->OnModelChanged();
}

///////////////////////////////////////////////////////////////////////////////
// HungPagesTableModel, views::GroupTableModel implementation:

int HungPagesTableModel::RowCount() {
  return static_cast<int>(tab_contentses_.size());
}

std::wstring HungPagesTableModel::GetText(int row, int column_id) {
  DCHECK(row >= 0 && row < RowCount());
  std::wstring title = UTF16ToWideHack(tab_contentses_[row]->GetTitle());
  if (title.empty())
    title = UTF16ToWideHack(TabContents::GetDefaultTitle());
  // TODO(xji): Consider adding a special case if the title text is a URL,
  // since those should always have LTR directionality. Please refer to
  // http://crbug.com/6726 for more information.
  base::i18n::AdjustStringForLocaleDirection(title, &title);
  return title;
}

SkBitmap HungPagesTableModel::GetIcon(int row) {
  DCHECK(row >= 0 && row < RowCount());
  return tab_contentses_.at(row)->GetFavIcon();
}

void HungPagesTableModel::SetObserver(TableModelObserver* observer) {
  observer_ = observer;
}

void HungPagesTableModel::GetGroupRangeForItem(int item,
                                               views::GroupRange* range) {
  DCHECK(range);
  range->start = 0;
  range->length = RowCount();
}

///////////////////////////////////////////////////////////////////////////////
// HungRendererDialogView

class HungRendererDialogView : public views::View,
                               public views::DialogDelegate,
                               public views::ButtonListener {
 public:
  HungRendererDialogView();
  ~HungRendererDialogView();

  void ShowForTabContents(TabContents* contents);
  void EndForTabContents(TabContents* contents);

  // views::WindowDelegate overrides:
  virtual std::wstring GetWindowTitle() const;
  virtual void WindowClosing();
  virtual int GetDialogButtons() const;
  virtual std::wstring GetDialogButtonLabel(
      MessageBoxFlags::DialogButton button) const;
  virtual views::View* GetExtraView();
  virtual bool Accept(bool window_closing);
  virtual views::View* GetContentsView();

  // views::ButtonListener overrides:
  virtual void ButtonPressed(views::Button* sender, const views::Event& event);

 protected:
  // views::View overrides:
  virtual void ViewHierarchyChanged(bool is_add,
                                    views::View* parent,
                                    views::View* child);

 private:
  // Initialize the controls in this dialog.
  void Init();
  void CreateKillButtonView();

  // Returns the bounds the dialog should be displayed at to be meaningfully
  // associated with the specified TabContents.
  gfx::Rect GetDisplayBounds(TabContents* contents);

  static void InitClass();

  // Controls within the dialog box.
  views::ImageView* frozen_icon_view_;
  views::Label* info_label_;
  views::GroupTableView* hung_pages_table_;

  // The button we insert into the ClientView to kill the errant process. This
  // is parented to a container view that uses a grid layout to align it
  // properly.
  views::NativeButton* kill_button_;
  class ButtonContainer : public views::View {
   public:
    ButtonContainer() {}
    virtual ~ButtonContainer() {}
   private:
    DISALLOW_COPY_AND_ASSIGN(ButtonContainer);
  };
  ButtonContainer* kill_button_container_;

  // The model that provides the contents of the table that shows a list of
  // pages affected by the hang.
  scoped_ptr<HungPagesTableModel> hung_pages_table_model_;

  // The TabContents that we detected had hung in the first place resulting in
  // the display of this view.
  TabContents* contents_;

  // Whether or not we've created controls for ourself.
  bool initialized_;

  // An amusing icon image.
  static SkBitmap* frozen_icon_;

  DISALLOW_COPY_AND_ASSIGN(HungRendererDialogView);
};

// static
SkBitmap* HungRendererDialogView::frozen_icon_ = NULL;

// The distance in pixels from the top of the relevant contents to place the
// warning window.
static const int kOverlayContentsOffsetY = 50;

// The dimensions of the hung pages list table view, in pixels.
static const int kTableViewWidth = 300;
static const int kTableViewHeight = 100;

///////////////////////////////////////////////////////////////////////////////
// HungRendererDialogView, public:

HungRendererDialogView::HungRendererDialogView()
    : frozen_icon_view_(NULL),
      info_label_(NULL),
      hung_pages_table_(NULL),
      kill_button_(NULL),
      kill_button_container_(NULL),
      contents_(NULL),
      initialized_(false) {
  InitClass();
}

HungRendererDialogView::~HungRendererDialogView() {
  hung_pages_table_->SetModel(NULL);
}

void HungRendererDialogView::ShowForTabContents(TabContents* contents) {
  DCHECK(contents && window());
  contents_ = contents;

  // Don't show the warning unless the foreground window is the frame, or this
  // window (but still invisible). If the user has another window or
  // application selected, activating ourselves is rude.
  HWND frame_hwnd = GetAncestor(contents->GetNativeView(), GA_ROOT);
  HWND foreground_window = GetForegroundWindow();
  if (foreground_window != frame_hwnd &&
      foreground_window != window()->GetNativeWindow()) {
    return;
  }

  if (!window()->IsActive()) {
    gfx::Rect bounds = GetDisplayBounds(contents);
    window()->SetBounds(bounds, frame_hwnd);

    // We only do this if the window isn't active (i.e. hasn't been shown yet,
    // or is currently shown but deactivated for another TabContents). This is
    // because this window is a singleton, and it's possible another active
    // renderer may hang while this one is showing, and we don't want to reset
    // the list of hung pages for a potentially unrelated renderer while this
    // one is showing.
    hung_pages_table_model_->InitForTabContents(contents);
    window()->Show();
  }
}

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

///////////////////////////////////////////////////////////////////////////////
// HungRendererDialogView, views::DialogDelegate implementation:

std::wstring HungRendererDialogView::GetWindowTitle() const {
  return l10n_util::GetString(IDS_PRODUCT_NAME);
}

void HungRendererDialogView::WindowClosing() {
  // We are going to be deleted soon, so make sure our instance is destroyed.
  g_instance = NULL;
}

int HungRendererDialogView::GetDialogButtons() const {
  // We specifically don't want a CANCEL button here because that code path is
  // also called when the window is closed by the user clicking the X button in
  // the window's titlebar, and also if we call Window::Close. Rather, we want
  // the OK button to wait for responsiveness (and close the dialog) and our
  // additional button (which we create) to kill the process (which will result
  // in the dialog being destroyed).
  return MessageBoxFlags::DIALOGBUTTON_OK;
}

std::wstring HungRendererDialogView::GetDialogButtonLabel(
    MessageBoxFlags::DialogButton button) const {
  if (button == MessageBoxFlags::DIALOGBUTTON_OK)
    return l10n_util::GetString(IDS_BROWSER_HANGMONITOR_RENDERER_WAIT);
  return std::wstring();
}

views::View* HungRendererDialogView::GetExtraView() {
  return kill_button_container_;
}

bool HungRendererDialogView::Accept(bool window_closing) {
  // Don't do anything if we're being called only because the dialog is being
  // destroyed and we don't supply a Cancel function...
  if (window_closing)
    return true;

  // Start waiting again for responsiveness.
  if (contents_ && contents_->render_view_host())
    contents_->render_view_host()->RestartHangMonitorTimeout();
  return true;
}

views::View* HungRendererDialogView::GetContentsView() {
  return this;
}

///////////////////////////////////////////////////////////////////////////////
// HungRendererDialogView, views::ButtonListener implementation:

void HungRendererDialogView::ButtonPressed(
    views::Button* sender, const views::Event& event) {
  if (sender == kill_button_) {
    if (!contents_) {
      // Kill the process.
      TerminateProcess(contents_->GetRenderProcessHost()->GetHandle(),
                       ResultCodes::HUNG);
    }
  }
}

///////////////////////////////////////////////////////////////////////////////
// HungRendererDialogView, views::View overrides:

void HungRendererDialogView::ViewHierarchyChanged(bool is_add,
                                                  views::View* parent,
                                                  views::View* child) {
  if (!initialized_ && is_add && child == this && GetWidget())
    Init();
}

///////////////////////////////////////////////////////////////////////////////
// HungRendererDialogView, private:

void HungRendererDialogView::Init() {
  frozen_icon_view_ = new views::ImageView;
  frozen_icon_view_->SetImage(frozen_icon_);

  info_label_ = new views::Label(
      l10n_util::GetString(IDS_BROWSER_HANGMONITOR_RENDERER));
  info_label_->SetMultiLine(true);
  info_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);

  hung_pages_table_model_.reset(new HungPagesTableModel);
  std::vector<TableColumn> columns;
  columns.push_back(TableColumn());
  hung_pages_table_ = new views::GroupTableView(
      hung_pages_table_model_.get(), columns, views::ICON_AND_TEXT, true,
      false, true);
  hung_pages_table_->SetPreferredSize(
    gfx::Size(kTableViewWidth, kTableViewHeight));

  CreateKillButtonView();

  using views::GridLayout;
  using views::ColumnSet;

  GridLayout* layout = CreatePanelGridLayout(this);
  SetLayoutManager(layout);

  const int double_column_set_id = 0;
  ColumnSet* column_set = layout->AddColumnSet(double_column_set_id);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, 0,
                        GridLayout::FIXED, frozen_icon_->width(), 0);
  column_set->AddPaddingColumn(0, kUnrelatedControlLargeHorizontalSpacing);
  column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
                        GridLayout::USE_PREF, 0, 0);

  layout->StartRow(0, double_column_set_id);
  layout->AddView(frozen_icon_view_, 1, 3);
  layout->AddView(info_label_);

  layout->AddPaddingRow(0, kUnrelatedControlVerticalSpacing);

  layout->StartRow(0, double_column_set_id);
  layout->SkipColumns(1);
  layout->AddView(hung_pages_table_);

  initialized_ = true;
}

void HungRendererDialogView::CreateKillButtonView() {
  kill_button_ = new views::NativeButton(
      this, l10n_util::GetString(IDS_BROWSER_HANGMONITOR_RENDERER_END));

  kill_button_container_ = new ButtonContainer;

  using views::GridLayout;
  using views::ColumnSet;

  GridLayout* layout = new GridLayout(kill_button_container_);
  kill_button_container_->SetLayoutManager(layout);

  const int single_column_set_id = 0;
  ColumnSet* column_set = layout->AddColumnSet(single_column_set_id);
  column_set->AddPaddingColumn(0, frozen_icon_->width() +
      kPanelHorizMargin + kUnrelatedControlHorizontalSpacing);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, 0,
                        GridLayout::USE_PREF, 0, 0);

  layout->StartRow(0, single_column_set_id);
  layout->AddView(kill_button_);
}

gfx::Rect HungRendererDialogView::GetDisplayBounds(
    TabContents* contents) {
  HWND contents_hwnd = contents->GetNativeView();
  RECT contents_bounds_rect;
  GetWindowRect(contents_hwnd, &contents_bounds_rect);
  gfx::Rect contents_bounds(contents_bounds_rect);
  gfx::Rect window_bounds = window()->GetBounds();

  int window_x = contents_bounds.x() +
      (contents_bounds.width() - window_bounds.width()) / 2;
  int window_y = contents_bounds.y() + kOverlayContentsOffsetY;
  return gfx::Rect(window_x, window_y, window_bounds.width(),
                   window_bounds.height());
}

// static
void HungRendererDialogView::InitClass() {
  static bool initialized = false;
  if (!initialized) {
    ResourceBundle& rb = ResourceBundle::GetSharedInstance();
    frozen_icon_ = rb.GetBitmapNamed(IDR_FROZEN_TAB_ICON);
    initialized = true;
  }
}

///////////////////////////////////////////////////////////////////////////////
// HungRendererDialog

static HungRendererDialogView* CreateHungRendererDialogView() {
  HungRendererDialogView* cv = new HungRendererDialogView;
  views::Window::CreateChromeWindow(NULL, gfx::Rect(), cv);
  return cv;
}

namespace hung_renderer_dialog {

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

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

}  // namespace hung_renderer_dialog

<commit_msg>views: Use IDS_BROWSER_HANGMONITOR_RENDERER_TITLE as the hung renderer dialog title.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/hung_renderer_dialog.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/i18n/rtl.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/common/result_codes.h"
#include "gfx/canvas.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/grid_layout.h"
#include "views/controls/button/native_button.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/table/group_table_view.h"
#include "views/standard_layout.h"
#include "views/window/client_view.h"
#include "views/window/dialog_delegate.h"
#include "views/window/window.h"

class HungRendererDialogView;

namespace {
// We only support showing one of these at a time per app.
HungRendererDialogView* g_instance = NULL;
}

///////////////////////////////////////////////////////////////////////////////
// HungPagesTableModel

class HungPagesTableModel : public views::GroupTableModel {
 public:
  HungPagesTableModel();
  virtual ~HungPagesTableModel();

  void InitForTabContents(TabContents* hung_contents);

  // Overridden from views::GroupTableModel:
  virtual int RowCount();
  virtual std::wstring GetText(int row, int column_id);
  virtual SkBitmap GetIcon(int row);
  virtual void SetObserver(TableModelObserver* observer);
  virtual void GetGroupRangeForItem(int item, views::GroupRange* range);

 private:
  typedef std::vector<TabContents*> TabContentsVector;
  TabContentsVector tab_contentses_;

  TableModelObserver* observer_;

  DISALLOW_COPY_AND_ASSIGN(HungPagesTableModel);
};

///////////////////////////////////////////////////////////////////////////////
// HungPagesTableModel, public:

HungPagesTableModel::HungPagesTableModel() : observer_(NULL) {
}

HungPagesTableModel::~HungPagesTableModel() {
}

void HungPagesTableModel::InitForTabContents(TabContents* hung_contents) {
  tab_contentses_.clear();
  for (TabContentsIterator it; !it.done(); ++it) {
    if (it->GetRenderProcessHost() == hung_contents->GetRenderProcessHost())
      tab_contentses_.push_back(*it);
  }
  // The world is different.
  if (observer_)
    observer_->OnModelChanged();
}

///////////////////////////////////////////////////////////////////////////////
// HungPagesTableModel, views::GroupTableModel implementation:

int HungPagesTableModel::RowCount() {
  return static_cast<int>(tab_contentses_.size());
}

std::wstring HungPagesTableModel::GetText(int row, int column_id) {
  DCHECK(row >= 0 && row < RowCount());
  std::wstring title = UTF16ToWideHack(tab_contentses_[row]->GetTitle());
  if (title.empty())
    title = UTF16ToWideHack(TabContents::GetDefaultTitle());
  // TODO(xji): Consider adding a special case if the title text is a URL,
  // since those should always have LTR directionality. Please refer to
  // http://crbug.com/6726 for more information.
  base::i18n::AdjustStringForLocaleDirection(title, &title);
  return title;
}

SkBitmap HungPagesTableModel::GetIcon(int row) {
  DCHECK(row >= 0 && row < RowCount());
  return tab_contentses_.at(row)->GetFavIcon();
}

void HungPagesTableModel::SetObserver(TableModelObserver* observer) {
  observer_ = observer;
}

void HungPagesTableModel::GetGroupRangeForItem(int item,
                                               views::GroupRange* range) {
  DCHECK(range);
  range->start = 0;
  range->length = RowCount();
}

///////////////////////////////////////////////////////////////////////////////
// HungRendererDialogView

class HungRendererDialogView : public views::View,
                               public views::DialogDelegate,
                               public views::ButtonListener {
 public:
  HungRendererDialogView();
  ~HungRendererDialogView();

  void ShowForTabContents(TabContents* contents);
  void EndForTabContents(TabContents* contents);

  // views::WindowDelegate overrides:
  virtual std::wstring GetWindowTitle() const;
  virtual void WindowClosing();
  virtual int GetDialogButtons() const;
  virtual std::wstring GetDialogButtonLabel(
      MessageBoxFlags::DialogButton button) const;
  virtual views::View* GetExtraView();
  virtual bool Accept(bool window_closing);
  virtual views::View* GetContentsView();

  // views::ButtonListener overrides:
  virtual void ButtonPressed(views::Button* sender, const views::Event& event);

 protected:
  // views::View overrides:
  virtual void ViewHierarchyChanged(bool is_add,
                                    views::View* parent,
                                    views::View* child);

 private:
  // Initialize the controls in this dialog.
  void Init();
  void CreateKillButtonView();

  // Returns the bounds the dialog should be displayed at to be meaningfully
  // associated with the specified TabContents.
  gfx::Rect GetDisplayBounds(TabContents* contents);

  static void InitClass();

  // Controls within the dialog box.
  views::ImageView* frozen_icon_view_;
  views::Label* info_label_;
  views::GroupTableView* hung_pages_table_;

  // The button we insert into the ClientView to kill the errant process. This
  // is parented to a container view that uses a grid layout to align it
  // properly.
  views::NativeButton* kill_button_;
  class ButtonContainer : public views::View {
   public:
    ButtonContainer() {}
    virtual ~ButtonContainer() {}
   private:
    DISALLOW_COPY_AND_ASSIGN(ButtonContainer);
  };
  ButtonContainer* kill_button_container_;

  // The model that provides the contents of the table that shows a list of
  // pages affected by the hang.
  scoped_ptr<HungPagesTableModel> hung_pages_table_model_;

  // The TabContents that we detected had hung in the first place resulting in
  // the display of this view.
  TabContents* contents_;

  // Whether or not we've created controls for ourself.
  bool initialized_;

  // An amusing icon image.
  static SkBitmap* frozen_icon_;

  DISALLOW_COPY_AND_ASSIGN(HungRendererDialogView);
};

// static
SkBitmap* HungRendererDialogView::frozen_icon_ = NULL;

// The distance in pixels from the top of the relevant contents to place the
// warning window.
static const int kOverlayContentsOffsetY = 50;

// The dimensions of the hung pages list table view, in pixels.
static const int kTableViewWidth = 300;
static const int kTableViewHeight = 100;

///////////////////////////////////////////////////////////////////////////////
// HungRendererDialogView, public:

HungRendererDialogView::HungRendererDialogView()
    : frozen_icon_view_(NULL),
      info_label_(NULL),
      hung_pages_table_(NULL),
      kill_button_(NULL),
      kill_button_container_(NULL),
      contents_(NULL),
      initialized_(false) {
  InitClass();
}

HungRendererDialogView::~HungRendererDialogView() {
  hung_pages_table_->SetModel(NULL);
}

void HungRendererDialogView::ShowForTabContents(TabContents* contents) {
  DCHECK(contents && window());
  contents_ = contents;

  // Don't show the warning unless the foreground window is the frame, or this
  // window (but still invisible). If the user has another window or
  // application selected, activating ourselves is rude.
  HWND frame_hwnd = GetAncestor(contents->GetNativeView(), GA_ROOT);
  HWND foreground_window = GetForegroundWindow();
  if (foreground_window != frame_hwnd &&
      foreground_window != window()->GetNativeWindow()) {
    return;
  }

  if (!window()->IsActive()) {
    gfx::Rect bounds = GetDisplayBounds(contents);
    window()->SetBounds(bounds, frame_hwnd);

    // We only do this if the window isn't active (i.e. hasn't been shown yet,
    // or is currently shown but deactivated for another TabContents). This is
    // because this window is a singleton, and it's possible another active
    // renderer may hang while this one is showing, and we don't want to reset
    // the list of hung pages for a potentially unrelated renderer while this
    // one is showing.
    hung_pages_table_model_->InitForTabContents(contents);
    window()->Show();
  }
}

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

///////////////////////////////////////////////////////////////////////////////
// HungRendererDialogView, views::DialogDelegate implementation:

std::wstring HungRendererDialogView::GetWindowTitle() const {
  return l10n_util::GetString(IDS_BROWSER_HANGMONITOR_RENDERER_TITLE);
}

void HungRendererDialogView::WindowClosing() {
  // We are going to be deleted soon, so make sure our instance is destroyed.
  g_instance = NULL;
}

int HungRendererDialogView::GetDialogButtons() const {
  // We specifically don't want a CANCEL button here because that code path is
  // also called when the window is closed by the user clicking the X button in
  // the window's titlebar, and also if we call Window::Close. Rather, we want
  // the OK button to wait for responsiveness (and close the dialog) and our
  // additional button (which we create) to kill the process (which will result
  // in the dialog being destroyed).
  return MessageBoxFlags::DIALOGBUTTON_OK;
}

std::wstring HungRendererDialogView::GetDialogButtonLabel(
    MessageBoxFlags::DialogButton button) const {
  if (button == MessageBoxFlags::DIALOGBUTTON_OK)
    return l10n_util::GetString(IDS_BROWSER_HANGMONITOR_RENDERER_WAIT);
  return std::wstring();
}

views::View* HungRendererDialogView::GetExtraView() {
  return kill_button_container_;
}

bool HungRendererDialogView::Accept(bool window_closing) {
  // Don't do anything if we're being called only because the dialog is being
  // destroyed and we don't supply a Cancel function...
  if (window_closing)
    return true;

  // Start waiting again for responsiveness.
  if (contents_ && contents_->render_view_host())
    contents_->render_view_host()->RestartHangMonitorTimeout();
  return true;
}

views::View* HungRendererDialogView::GetContentsView() {
  return this;
}

///////////////////////////////////////////////////////////////////////////////
// HungRendererDialogView, views::ButtonListener implementation:

void HungRendererDialogView::ButtonPressed(
    views::Button* sender, const views::Event& event) {
  if (sender == kill_button_) {
    if (!contents_) {
      // Kill the process.
      TerminateProcess(contents_->GetRenderProcessHost()->GetHandle(),
                       ResultCodes::HUNG);
    }
  }
}

///////////////////////////////////////////////////////////////////////////////
// HungRendererDialogView, views::View overrides:

void HungRendererDialogView::ViewHierarchyChanged(bool is_add,
                                                  views::View* parent,
                                                  views::View* child) {
  if (!initialized_ && is_add && child == this && GetWidget())
    Init();
}

///////////////////////////////////////////////////////////////////////////////
// HungRendererDialogView, private:

void HungRendererDialogView::Init() {
  frozen_icon_view_ = new views::ImageView;
  frozen_icon_view_->SetImage(frozen_icon_);

  info_label_ = new views::Label(
      l10n_util::GetString(IDS_BROWSER_HANGMONITOR_RENDERER));
  info_label_->SetMultiLine(true);
  info_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);

  hung_pages_table_model_.reset(new HungPagesTableModel);
  std::vector<TableColumn> columns;
  columns.push_back(TableColumn());
  hung_pages_table_ = new views::GroupTableView(
      hung_pages_table_model_.get(), columns, views::ICON_AND_TEXT, true,
      false, true);
  hung_pages_table_->SetPreferredSize(
    gfx::Size(kTableViewWidth, kTableViewHeight));

  CreateKillButtonView();

  using views::GridLayout;
  using views::ColumnSet;

  GridLayout* layout = CreatePanelGridLayout(this);
  SetLayoutManager(layout);

  const int double_column_set_id = 0;
  ColumnSet* column_set = layout->AddColumnSet(double_column_set_id);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, 0,
                        GridLayout::FIXED, frozen_icon_->width(), 0);
  column_set->AddPaddingColumn(0, kUnrelatedControlLargeHorizontalSpacing);
  column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
                        GridLayout::USE_PREF, 0, 0);

  layout->StartRow(0, double_column_set_id);
  layout->AddView(frozen_icon_view_, 1, 3);
  layout->AddView(info_label_);

  layout->AddPaddingRow(0, kUnrelatedControlVerticalSpacing);

  layout->StartRow(0, double_column_set_id);
  layout->SkipColumns(1);
  layout->AddView(hung_pages_table_);

  initialized_ = true;
}

void HungRendererDialogView::CreateKillButtonView() {
  kill_button_ = new views::NativeButton(
      this, l10n_util::GetString(IDS_BROWSER_HANGMONITOR_RENDERER_END));

  kill_button_container_ = new ButtonContainer;

  using views::GridLayout;
  using views::ColumnSet;

  GridLayout* layout = new GridLayout(kill_button_container_);
  kill_button_container_->SetLayoutManager(layout);

  const int single_column_set_id = 0;
  ColumnSet* column_set = layout->AddColumnSet(single_column_set_id);
  column_set->AddPaddingColumn(0, frozen_icon_->width() +
      kPanelHorizMargin + kUnrelatedControlHorizontalSpacing);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, 0,
                        GridLayout::USE_PREF, 0, 0);

  layout->StartRow(0, single_column_set_id);
  layout->AddView(kill_button_);
}

gfx::Rect HungRendererDialogView::GetDisplayBounds(
    TabContents* contents) {
  HWND contents_hwnd = contents->GetNativeView();
  RECT contents_bounds_rect;
  GetWindowRect(contents_hwnd, &contents_bounds_rect);
  gfx::Rect contents_bounds(contents_bounds_rect);
  gfx::Rect window_bounds = window()->GetBounds();

  int window_x = contents_bounds.x() +
      (contents_bounds.width() - window_bounds.width()) / 2;
  int window_y = contents_bounds.y() + kOverlayContentsOffsetY;
  return gfx::Rect(window_x, window_y, window_bounds.width(),
                   window_bounds.height());
}

// static
void HungRendererDialogView::InitClass() {
  static bool initialized = false;
  if (!initialized) {
    ResourceBundle& rb = ResourceBundle::GetSharedInstance();
    frozen_icon_ = rb.GetBitmapNamed(IDR_FROZEN_TAB_ICON);
    initialized = true;
  }
}

///////////////////////////////////////////////////////////////////////////////
// HungRendererDialog

static HungRendererDialogView* CreateHungRendererDialogView() {
  HungRendererDialogView* cv = new HungRendererDialogView;
  views::Window::CreateChromeWindow(NULL, gfx::Rect(), cv);
  return cv;
}

namespace hung_renderer_dialog {

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

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

}  // namespace hung_renderer_dialog

<|endoftext|>


<commit_before>#include <glm/gtc/matrix_transform.hpp>
#include "Core/Engine.hh"
#include "Core/Renderer.hh"
#include "DemoScene.hh"

#include <Components/RotationForce.hh>
#include <Components/CameraComponent.hh>
#include <Components/RigidBody.hpp>
#include <Components/FPController.hpp>
#include <Components/FirstPersonView.hpp>

#include <OpenGL/ComputeShader.hh>
#include <OpenGL/Attribute.hh>
#include <OpenGL/include/SDL/SDL_opengl.h>

#include <Systems/RotationForceSystem.hpp>
#include <Systems/GraphNodeSystem.hpp>
#include <Systems/CameraSystem.hpp>
#include <Systems/MeshRenderSystem.h>
#include <Systems/BulletDynamicSystem.hpp>
#include <Systems/FPControllerSystem.hpp>
#include <Systems/FirstPersonViewSystem.hpp>
#include <Systems/CollisionAdderSystem.hpp>
#include <Systems/CollisionCleanerSystem.hpp>

#include <Core/Engine.hh>

#include <SDL\SDL.h>

DemoScene::DemoScene(Engine &engine) : AScene(engine)
{
}

DemoScene::~DemoScene(void)
{
}

Entity  DemoScene::createSphere(glm::vec3 &pos, glm::vec3 &scale, std::string const &tex, float mass)
{
	auto e = createEntity();
	e->setLocalTransform() = glm::translate(e->getLocalTransform(), pos);
	e->setLocalTransform() = glm::scale(e->getLocalTransform(), scale);
	auto rigidBody = e->addComponent<Component::RigidBody>(mass);
	rigidBody->setCollisionShape(Component::RigidBody::SPHERE);

	auto mesh = e->addComponent<Component::MeshRenderer>(AMediaFile::get<ObjFile>("obj__ball"));
	e->addComponent<Component::GraphNode>();
	mesh->setShader("MaterialBasic");
	return e;
}

Entity  DemoScene::createCube(glm::vec3 &pos, glm::vec3 &scale, std::string const &tex, float mass)
{
	auto e = createEntity();
	e->setLocalTransform() = glm::translate(e->getLocalTransform(), pos);
	e->setLocalTransform() = glm::rotate(e->getLocalTransform(), 0.0f, glm::vec3(1, 0, 0));
	e->setLocalTransform() = glm::rotate(e->getLocalTransform(), 0.0f, glm::vec3(0, 1, 0));
	e->setLocalTransform() = glm::scale(e->getLocalTransform(), scale);
	auto rigidBody = e->addComponent<Component::RigidBody>(mass);
	rigidBody->setCollisionShape(Component::RigidBody::BOX);
	auto mesh = e->addComponent<Component::MeshRenderer>(AMediaFile::get<ObjFile>("obj__cube"));
	e->addComponent<Component::GraphNode>();
	mesh->setShader("MaterialBasic");
	return e;
}

Entity  DemoScene::createMonkey(glm::vec3 &pos, glm::vec3 &scale, std::string const &tex, float mass)
{
	auto e = createEntity();
	e->setLocalTransform() = glm::translate(e->getLocalTransform(), pos);
	e->setLocalTransform() = glm::scale(e->getLocalTransform(), scale);
	auto rigidBody = e->addComponent<Component::RigidBody>(mass);
	rigidBody->setCollisionShape(Component::RigidBody::MESH, "collision_sphere_galileo");
	//auto mesh = e->addComponent<Component::MeshRenderer>(AMediaFile::get<ObjFile>("obj__galileo"));
	//mesh->setShader("MaterialBasic");
	e->addComponent<Component::GraphNode>();
	return e;
}

bool 			DemoScene::userStart()
{
	std::srand(0);

	// System Tests
	//
	//
	addSystem<MeshRendererSystem>(0);
	addSystem<GraphNodeSystem>(0); // UPDATE ENTITIES TRANSFORMATION
	addSystem<BulletDynamicSystem>(10); // UPDATE PHYSIC WORLD
	addSystem<CollisionAdder>(20); // ADD COLLISION COMPONENT TO COLLIDING ENTITIES
	addSystem<FPControllerSystem>(50); // UPDATE FIRST PERSON CONTROLLER
	addSystem<FirstPersonViewSystem>(150); // UPDATE FIRST PERSON CAMERA
	addSystem<CameraSystem>(200); // UPDATE CAMERA AND RENDER TO SCREEN
	addSystem<CollisionCleaner>(300); // REMOVE COLLISION COMPONENTS FROM COLLIDING ENTITIES
	//
	//
	// end System Test

		std::string		perModelVars[] =
		{
			"model"
		};

		std::string		perFrameVars[] =
		{
			"projection",
			"view",
			"light",
			"time"
		};

		std::string		materialBasic[] =
		{
			"ambient",
			"diffuse",
			"specular",
			"transmittance",
			"emission",
			"shininess"
		};

	OpenGLTools::Shader &s = _engine.getInstance<Renderer>().addShader("MaterialBasic",
		"./Shaders/MaterialBasic.vp",
		"./Shaders/MaterialBasic.fp");

		_engine.getInstance<Renderer>().addUniform("MaterialBasic")
			.init(&s, "MaterialBasic", materialBasic);
		_engine.getInstance<Renderer>().addUniform("PerFrame")
			.init(&s, "PerFrame", perFrameVars);
		_engine.getInstance<Renderer>().addUniform("PerModel")
			.init(&s, "PerModel", perModelVars);

	_engine.getInstance<Renderer>().addShader("basic", "Shaders/basic.vp", "Shaders/basic.fp", "Shaders/basic.gp");
	_engine.getInstance<Renderer>().addShader("basicLight", "Shaders/light.vp", "Shaders/light.fp");
	_engine.getInstance<Renderer>().addShader("bump", "Shaders/bump.vp", "Shaders/bump.fp");
	_engine.getInstance<Renderer>().addShader("earth", "Shaders/earth.vp", "Shaders/earth.fp");
	_engine.getInstance<Renderer>().addShader("fboToScreen", "Shaders/fboToScreen.vp", "Shaders/fboToScreen.fp");
	_engine.getInstance<Renderer>().addShader("brightnessFilter", "Shaders/brightnessFilter.vp", "Shaders/brightnessFilter.fp");
	_engine.getInstance<Renderer>().addShader("blurY", "Shaders/brightnessFilter.vp", "Shaders/blur1.fp");

	_engine.getInstance<Renderer>().getShader("basic")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();
	_engine.getInstance<Renderer>().getShader("basicLight")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();
	_engine.getInstance<Renderer>().getShader("bump")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(2).build();
	_engine.getInstance<Renderer>().getShader("fboToScreen")->addTarget(GL_COLOR_ATTACHMENT0)
		.addLayer(GL_COLOR_ATTACHMENT0).build();
	_engine.getInstance<Renderer>().getShader("MaterialBasic")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(4).build();
	_engine.getInstance<Renderer>().getShader("earth")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(4).build();
	_engine.getInstance<Renderer>().getShader("brightnessFilter")->addTarget(GL_COLOR_ATTACHMENT1)
		.addLayer(GL_COLOR_ATTACHMENT0).build();
	_engine.getInstance<Renderer>().getShader("blurY")->addTarget(GL_COLOR_ATTACHMENT2)
		.addLayer(GL_COLOR_ATTACHMENT0).addLayer(GL_COLOR_ATTACHMENT1).build();

	_engine.getInstance<Renderer>().getUniform("PerFrame")->setUniform("light", glm::vec4(0, 0, 0, 1));

	_engine.getInstance<Renderer>().bindShaderToUniform("basicLight", "PerFrame", "PerFrame");
	_engine.getInstance<Renderer>().bindShaderToUniform("basicLight", "PerModel", "PerModel");
	_engine.getInstance<Renderer>().bindShaderToUniform("basicLight", "MaterialBasic", "MaterialBasic");
	_engine.getInstance<Renderer>().bindShaderToUniform("basic", "PerFrame", "PerFrame");
	_engine.getInstance<Renderer>().bindShaderToUniform("basic", "PerModel", "PerModel");
	_engine.getInstance<Renderer>().bindShaderToUniform("basic", "MaterialBasic", "MaterialBasic");
	_engine.getInstance<Renderer>().bindShaderToUniform("earth", "PerFrame", "PerFrame");
	_engine.getInstance<Renderer>().bindShaderToUniform("earth", "PerModel", "PerModel");
	_engine.getInstance<Renderer>().bindShaderToUniform("earth", "MaterialBasic", "MaterialBasic");
	_engine.getInstance<Renderer>().bindShaderToUniform("bump", "PerFrame", "PerFrame");
	_engine.getInstance<Renderer>().bindShaderToUniform("bump", "PerModel", "PerModel");
	_engine.getInstance<Renderer>().bindShaderToUniform("bump", "MaterialBasic", "MaterialBasic");
	_engine.getInstance<Renderer>().bindShaderToUniform("MaterialBasic", "PerFrame", "PerFrame");
	_engine.getInstance<Renderer>().bindShaderToUniform("MaterialBasic", "PerModel", "PerModel");
	_engine.getInstance<Renderer>().bindShaderToUniform("MaterialBasic", "MaterialBasic", "MaterialBasic");

	AMediaFile::loadFromList("./Assets/Serialized/export__cube.cpd");
	AMediaFile::loadFromList("./Assets/Serialized/export__ball.cpd");
	AMediaFile::loadFromList("./Assets/Serialized/export__Space.cpd");
//	AMediaFile::loadFromList("./Assets/Serialized/export__sponza.cpd");
	AMediaFile::loadFromList("./Assets/Serialized/export__galileo.cpd");

	// EXAMPLE LOAD FROM SAVE
	AMediaFile::loadFromFile<cereal::BinaryInputArchive>(File("./Assets/Serialized/my_planet.cpd"));

	// EXAMPLE: HOW TO CREATE A MEDIA FILE DYNAMICALY
	//auto defaultBallMesh = AMediaFile::get<ObjFile>("obj__ball");
	//auto planetMesh = AMediaFile::create<ObjFile>("my_planet", defaultBallMesh);
	//planetMesh->material = AMediaFile::create<MaterialFile>("my_planet_material", defaultBallMesh->material);
	//auto testsss = planetMesh->material->materials[0];
	//planetMesh->material->materials[0].ambientTex = AMediaFile::get<TextureFile>("texture__EarthTexture");
	//planetMesh->material->materials[0].diffuseTex = AMediaFile::get<TextureFile>("texture__EarthNightTexture");
	//planetMesh->material->materials[0].specularTex = AMediaFile::get<TextureFile>("texture__EarthClouds");
	//planetMesh->material->materials[0].normalTex = AMediaFile::get<TextureFile>("texture__EarthTextureBump");

	// EXAMPLE: HOW TO SAVE TO FILE A MEDIA FILE CREATED DYNAMICALY
	//AMediaFile::saveToFile("my_planet_material", "./Assets/Serialized/");
	//AMediaFile::saveToFile("my_planet", "./Assets/Serialized/");

	auto p1 = createCube(glm::vec3(0, 0, 0), glm::vec3(100, 1, 100), "texture__MoonTexture", 0.0f);
	//p1->getComponent<Component::RigidBody>()->setTransformConstraint(false, false, false);
	//p1->getComponent<Component::RigidBody>()->setRotationConstraint(false, false, false);

	{
		auto e = createEntity();
		e->setLocalTransform() = glm::rotate(e->getLocalTransform(), 45.0f, glm::vec3(0, 1, 0));
		e->setLocalTransform() = glm::translate(e->getLocalTransform(), glm::vec3(10,10,10));
		e->setLocalTransform() = glm::scale(e->getLocalTransform(), glm::vec3(10,10,10));

		auto rigidBody = e->addComponent<Component::RigidBody>(1.0f);
		rigidBody->setCollisionShape(Component::RigidBody::BOX);
		auto mesh = e->addComponent<Component::MeshRenderer>(AMediaFile::get<ObjFile>("obj__cube"));
		mesh->setShader("MaterialBasic");
		e->addComponent<Component::GraphNode>();
		e->getComponent<Component::RigidBody>()->setTransformConstraint(false, false, false);
		e->getComponent<Component::RigidBody>()->setRotationConstraint(true, true, true);
	}

	{
		auto e = createEntity();
		e->setLocalTransform() = glm::translate(e->getLocalTransform(), glm::vec3(-5,0,0));
		e->setLocalTransform() = glm::scale(e->getLocalTransform(), glm::vec3(6));

		auto rigidBody = e->addComponent<Component::RigidBody>(0);
		rigidBody->setCollisionShape(Component::RigidBody::SPHERE);
		auto mesh = e->addComponent<Component::MeshRenderer>(AMediaFile::get<ObjFile>("my_planet"));
		e->addComponent<Component::GraphNode>();
		mesh->setShader("earth");
	}

	Entity character;
	{
		auto e = createEntity();
		e->setLocalTransform() = glm::translate(e->getLocalTransform(), glm::vec3(0,20,0));
		e->addComponent<Component::FPController>();
		e->addComponent<Component::GraphNode>();
		character = e;
	}

	Entity c1;
	auto lolol = 0;
	for (unsigned int i = 0; i < 20; ++i)
	{
		//if (i % 3)
		//{
		//	c1 = createCube(glm::vec3(-3 + 0.2 * (float)i, 3 * i + 16, 0), glm::vec3(2, 1, 3), "texture__SunTexture", 1.f);
		//}
		//else if (i % 2)
		//{
		//	c1 = createSphere(glm::vec3(-3 + 0.2 * (float)i, 3 * i + 16, 0), glm::vec3(1, 1, 1), "texture__SunTexture", 1.0f);
		//	c1->getComponent<Component::MeshRenderer>()->mesh = AMediaFile::get<ObjFile>("my_planet");
		//}
		//else
		//{
		for (size_t j = 0; j < 20 - i; j++)
		{
			c1 = createMonkey(glm::vec3(5 - i + j * 10, i * 10, 0), glm::vec3(rand() % 3 + 1), "texture__SunTexture", 1.0f);
			++lolol;
		}
		//}
	}

	// --
	// Setting camera with skybox
	// --

	//setCamera(new TrackBall(_engine, follow, 30.0f, 1.0f, 1.0f));
	auto cameraComponent = character->addComponent<Component::CameraComponent>();
	character->addComponent<Component::FirstPersonView>();

	std::string		vars[] =
	{
		"projection",
		"view"
	};

	OpenGLTools::Shader &sky = _engine.getInstance<Renderer>().addShader("cubemapShader", "Shaders/cubemap.vp", "Shaders/cubemap.fp");

	_engine.getInstance<Renderer>().getShader("cubemapShader")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();

	_engine.getInstance<Renderer>().addUniform("cameraUniform").
		init(&sky, "cameraUniform", vars);

	_engine.getInstance<Renderer>().bindShaderToUniform("cubemapShader", "cameraUniform", "cameraUniform");

	cameraComponent->attachSkybox("skybox__space", "cubemapShader");
	return (true);
}

bool 			DemoScene::userUpdate(double time)
{
	if (_engine.getInstance<Input>().getInput(SDLK_ESCAPE) ||
		_engine.getInstance<Input>().getInput(SDL_QUIT))
		return (false);
	return (true);
}
<commit_msg>Some tests<commit_after>#include <glm/gtc/matrix_transform.hpp>
#include "Core/Engine.hh"
#include "Core/Renderer.hh"
#include "DemoScene.hh"

#include <Components/RotationForce.hh>
#include <Components/CameraComponent.hh>
#include <Components/RigidBody.hpp>
#include <Components/FPController.hpp>
#include <Components/FirstPersonView.hpp>

#include <OpenGL/ComputeShader.hh>
#include <OpenGL/Attribute.hh>
#include <OpenGL/include/SDL/SDL_opengl.h>

#include <Systems/RotationForceSystem.hpp>
#include <Systems/GraphNodeSystem.hpp>
#include <Systems/CameraSystem.hpp>
#include <Systems/MeshRenderSystem.h>
#include <Systems/BulletDynamicSystem.hpp>
#include <Systems/FPControllerSystem.hpp>
#include <Systems/FirstPersonViewSystem.hpp>
#include <Systems/CollisionAdderSystem.hpp>
#include <Systems/CollisionCleanerSystem.hpp>

#include <Core/Engine.hh>

#include <SDL\SDL.h>

DemoScene::DemoScene(Engine &engine) : AScene(engine)
{
}

DemoScene::~DemoScene(void)
{
}

Entity  DemoScene::createSphere(glm::vec3 &pos, glm::vec3 &scale, std::string const &tex, float mass)
{
	auto e = createEntity();
	e->setLocalTransform() = glm::translate(e->getLocalTransform(), pos);
	e->setLocalTransform() = glm::scale(e->getLocalTransform(), scale);
	auto rigidBody = e->addComponent<Component::RigidBody>(mass);
	rigidBody->setCollisionShape(Component::RigidBody::SPHERE);

	auto mesh = e->addComponent<Component::MeshRenderer>(AMediaFile::get<ObjFile>("obj__ball"));
	e->addComponent<Component::GraphNode>();
	mesh->setShader("MaterialBasic");
	return e;
}

Entity  DemoScene::createCube(glm::vec3 &pos, glm::vec3 &scale, std::string const &tex, float mass)
{
	auto e = createEntity();
	e->setLocalTransform() = glm::translate(e->getLocalTransform(), pos);
	e->setLocalTransform() = glm::rotate(e->getLocalTransform(), 0.0f, glm::vec3(1, 0, 0));
	e->setLocalTransform() = glm::rotate(e->getLocalTransform(), 0.0f, glm::vec3(0, 1, 0));
	e->setLocalTransform() = glm::scale(e->getLocalTransform(), scale);
	auto rigidBody = e->addComponent<Component::RigidBody>(mass);
	rigidBody->setCollisionShape(Component::RigidBody::BOX);
	auto mesh = e->addComponent<Component::MeshRenderer>(AMediaFile::get<ObjFile>("obj__cube"));
	e->addComponent<Component::GraphNode>();
	mesh->setShader("MaterialBasic");
	return e;
}

Entity  DemoScene::createMonkey(glm::vec3 &pos, glm::vec3 &scale, std::string const &tex, float mass)
{
	auto e = createEntity();
	e->setLocalTransform() = glm::translate(e->getLocalTransform(), pos);
	e->setLocalTransform() = glm::scale(e->getLocalTransform(), scale);
	auto rigidBody = e->addComponent<Component::RigidBody>(mass);
	rigidBody->setCollisionShape(Component::RigidBody::MESH, "collision_sphere_galileo");
	auto mesh = e->addComponent<Component::MeshRenderer>(AMediaFile::get<ObjFile>("obj__galileo"));
	mesh->setShader("MaterialBasic");
	e->addComponent<Component::GraphNode>();
	return e;
}

bool 			DemoScene::userStart()
{
	std::srand(0);

	// System Tests
	//
	//
	addSystem<MeshRendererSystem>(0);
	addSystem<GraphNodeSystem>(0); // UPDATE ENTITIES TRANSFORMATION
	addSystem<BulletDynamicSystem>(10); // UPDATE PHYSIC WORLD
	addSystem<CollisionAdder>(20); // ADD COLLISION COMPONENT TO COLLIDING ENTITIES
	addSystem<FPControllerSystem>(50); // UPDATE FIRST PERSON CONTROLLER
	addSystem<FirstPersonViewSystem>(150); // UPDATE FIRST PERSON CAMERA
	addSystem<CameraSystem>(200); // UPDATE CAMERA AND RENDER TO SCREEN
	addSystem<CollisionCleaner>(300); // REMOVE COLLISION COMPONENTS FROM COLLIDING ENTITIES
	//
	//
	// end System Test

		std::string		perModelVars[] =
		{
			"model"
		};

		std::string		perFrameVars[] =
		{
			"projection",
			"view",
			"light",
			"time"
		};

		std::string		materialBasic[] =
		{
			"ambient",
			"diffuse",
			"specular",
			"transmittance",
			"emission",
			"shininess"
		};

	OpenGLTools::Shader &s = _engine.getInstance<Renderer>().addShader("MaterialBasic",
		"./Shaders/MaterialBasic.vp",
		"./Shaders/MaterialBasic.fp");

		_engine.getInstance<Renderer>().addUniform("MaterialBasic")
			.init(&s, "MaterialBasic", materialBasic);
		_engine.getInstance<Renderer>().addUniform("PerFrame")
			.init(&s, "PerFrame", perFrameVars);
		_engine.getInstance<Renderer>().addUniform("PerModel")
			.init(&s, "PerModel", perModelVars);

	_engine.getInstance<Renderer>().addShader("basic", "Shaders/basic.vp", "Shaders/basic.fp", "Shaders/basic.gp");
	_engine.getInstance<Renderer>().addShader("basicLight", "Shaders/light.vp", "Shaders/light.fp");
	_engine.getInstance<Renderer>().addShader("bump", "Shaders/bump.vp", "Shaders/bump.fp");
	_engine.getInstance<Renderer>().addShader("earth", "Shaders/earth.vp", "Shaders/earth.fp");
	_engine.getInstance<Renderer>().addShader("fboToScreen", "Shaders/fboToScreen.vp", "Shaders/fboToScreen.fp");
	_engine.getInstance<Renderer>().addShader("brightnessFilter", "Shaders/brightnessFilter.vp", "Shaders/brightnessFilter.fp");
	_engine.getInstance<Renderer>().addShader("blurY", "Shaders/brightnessFilter.vp", "Shaders/blur1.fp");

	_engine.getInstance<Renderer>().getShader("basic")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();
	_engine.getInstance<Renderer>().getShader("basicLight")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();
	_engine.getInstance<Renderer>().getShader("bump")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(2).build();
	_engine.getInstance<Renderer>().getShader("fboToScreen")->addTarget(GL_COLOR_ATTACHMENT0)
		.addLayer(GL_COLOR_ATTACHMENT0).build();
	_engine.getInstance<Renderer>().getShader("MaterialBasic")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(4).build();
	_engine.getInstance<Renderer>().getShader("earth")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(4).build();
	_engine.getInstance<Renderer>().getShader("brightnessFilter")->addTarget(GL_COLOR_ATTACHMENT1)
		.addLayer(GL_COLOR_ATTACHMENT0).build();
	_engine.getInstance<Renderer>().getShader("blurY")->addTarget(GL_COLOR_ATTACHMENT2)
		.addLayer(GL_COLOR_ATTACHMENT0).addLayer(GL_COLOR_ATTACHMENT1).build();

	_engine.getInstance<Renderer>().getUniform("PerFrame")->setUniform("light", glm::vec4(0, 0, 0, 1));

	_engine.getInstance<Renderer>().bindShaderToUniform("basicLight", "PerFrame", "PerFrame");
	_engine.getInstance<Renderer>().bindShaderToUniform("basicLight", "PerModel", "PerModel");
	_engine.getInstance<Renderer>().bindShaderToUniform("basicLight", "MaterialBasic", "MaterialBasic");
	_engine.getInstance<Renderer>().bindShaderToUniform("basic", "PerFrame", "PerFrame");
	_engine.getInstance<Renderer>().bindShaderToUniform("basic", "PerModel", "PerModel");
	_engine.getInstance<Renderer>().bindShaderToUniform("basic", "MaterialBasic", "MaterialBasic");
	_engine.getInstance<Renderer>().bindShaderToUniform("earth", "PerFrame", "PerFrame");
	_engine.getInstance<Renderer>().bindShaderToUniform("earth", "PerModel", "PerModel");
	_engine.getInstance<Renderer>().bindShaderToUniform("earth", "MaterialBasic", "MaterialBasic");
	_engine.getInstance<Renderer>().bindShaderToUniform("bump", "PerFrame", "PerFrame");
	_engine.getInstance<Renderer>().bindShaderToUniform("bump", "PerModel", "PerModel");
	_engine.getInstance<Renderer>().bindShaderToUniform("bump", "MaterialBasic", "MaterialBasic");
	_engine.getInstance<Renderer>().bindShaderToUniform("MaterialBasic", "PerFrame", "PerFrame");
	_engine.getInstance<Renderer>().bindShaderToUniform("MaterialBasic", "PerModel", "PerModel");
	_engine.getInstance<Renderer>().bindShaderToUniform("MaterialBasic", "MaterialBasic", "MaterialBasic");

	AMediaFile::loadFromList("./Assets/Serialized/export__cube.cpd");
	AMediaFile::loadFromList("./Assets/Serialized/export__ball.cpd");
	AMediaFile::loadFromList("./Assets/Serialized/export__Space.cpd");
//	AMediaFile::loadFromList("./Assets/Serialized/export__sponza.cpd");
	AMediaFile::loadFromList("./Assets/Serialized/export__galileo.cpd");

	// EXAMPLE LOAD FROM SAVE
	AMediaFile::loadFromFile<cereal::BinaryInputArchive>(File("./Assets/Serialized/my_planet.cpd"));

	// EXAMPLE: HOW TO CREATE A MEDIA FILE DYNAMICALY
	//auto defaultBallMesh = AMediaFile::get<ObjFile>("obj__ball");
	//auto planetMesh = AMediaFile::create<ObjFile>("my_planet", defaultBallMesh);
	//planetMesh->material = AMediaFile::create<MaterialFile>("my_planet_material", defaultBallMesh->material);
	//auto testsss = planetMesh->material->materials[0];
	//planetMesh->material->materials[0].ambientTex = AMediaFile::get<TextureFile>("texture__EarthTexture");
	//planetMesh->material->materials[0].diffuseTex = AMediaFile::get<TextureFile>("texture__EarthNightTexture");
	//planetMesh->material->materials[0].specularTex = AMediaFile::get<TextureFile>("texture__EarthClouds");
	//planetMesh->material->materials[0].normalTex = AMediaFile::get<TextureFile>("texture__EarthTextureBump");

	// EXAMPLE: HOW TO SAVE TO FILE A MEDIA FILE CREATED DYNAMICALY
	//AMediaFile::saveToFile("my_planet_material", "./Assets/Serialized/");
	//AMediaFile::saveToFile("my_planet", "./Assets/Serialized/");

	auto p1 = createCube(glm::vec3(0, 0, 0), glm::vec3(100, 1, 100), "texture__MoonTexture", 0.0f);
	//p1->getComponent<Component::RigidBody>()->setTransformConstraint(false, false, false);
	//p1->getComponent<Component::RigidBody>()->setRotationConstraint(false, false, false);

	{
		auto e = createEntity();
		e->setLocalTransform() = glm::rotate(e->getLocalTransform(), 45.0f, glm::vec3(0, 1, 0));
		e->setLocalTransform() = glm::translate(e->getLocalTransform(), glm::vec3(10,10,10));
		e->setLocalTransform() = glm::scale(e->getLocalTransform(), glm::vec3(10,10,10));

		auto rigidBody = e->addComponent<Component::RigidBody>(1.0f);
		rigidBody->setCollisionShape(Component::RigidBody::BOX);
		auto mesh = e->addComponent<Component::MeshRenderer>(AMediaFile::get<ObjFile>("obj__cube"));
		mesh->setShader("MaterialBasic");
		e->addComponent<Component::GraphNode>();
		e->getComponent<Component::RigidBody>()->setTransformConstraint(false, false, false);
		e->getComponent<Component::RigidBody>()->setRotationConstraint(true, true, true);
	}

	{
		auto e = createEntity();
		e->setLocalTransform() = glm::translate(e->getLocalTransform(), glm::vec3(-5,0,0));
		e->setLocalTransform() = glm::scale(e->getLocalTransform(), glm::vec3(6));

		auto rigidBody = e->addComponent<Component::RigidBody>(0);
		rigidBody->setCollisionShape(Component::RigidBody::SPHERE);
		auto mesh = e->addComponent<Component::MeshRenderer>(AMediaFile::get<ObjFile>("my_planet"));
		e->addComponent<Component::GraphNode>();
		mesh->setShader("earth");
	}

	Entity character;
	{
		auto e = createEntity();
		e->setLocalTransform() = glm::translate(e->getLocalTransform(), glm::vec3(0,20,0));
		e->addComponent<Component::FPController>();
		e->addComponent<Component::GraphNode>();
		character = e;
	}

	Entity c1;
	auto lolol = 0;
	for (unsigned int i = 0; i < 20; ++i)
	{
		//if (i % 3)
		//{
		//	c1 = createCube(glm::vec3(-3 + 0.2 * (float)i, 3 * i + 16, 0), glm::vec3(2, 1, 3), "texture__SunTexture", 1.f);
		//}
		//else if (i % 2)
		//{
		//	c1 = createSphere(glm::vec3(-3 + 0.2 * (float)i, 3 * i + 16, 0), glm::vec3(1, 1, 1), "texture__SunTexture", 1.0f);
		//	c1->getComponent<Component::MeshRenderer>()->mesh = AMediaFile::get<ObjFile>("my_planet");
		//}
		//else
		//{
		for (size_t j = 0; j < 20 - i; j++)
		{
			c1 = createMonkey(glm::vec3(5 - i + j * 10, i * 10, 0), glm::vec3(rand() % 3 + 1), "texture__SunTexture", 1.0f);
			++lolol;
		}
		//}
	}

	// --
	// Setting camera with skybox
	// --

	//setCamera(new TrackBall(_engine, follow, 30.0f, 1.0f, 1.0f));
	auto cameraComponent = character->addComponent<Component::CameraComponent>();
	character->addComponent<Component::FirstPersonView>();

	std::string		vars[] =
	{
		"projection",
		"view"
	};

	OpenGLTools::Shader &sky = _engine.getInstance<Renderer>().addShader("cubemapShader", "Shaders/cubemap.vp", "Shaders/cubemap.fp");

	_engine.getInstance<Renderer>().getShader("cubemapShader")->addTarget(GL_COLOR_ATTACHMENT0).setTextureNumber(1).build();

	_engine.getInstance<Renderer>().addUniform("cameraUniform").
		init(&sky, "cameraUniform", vars);

	_engine.getInstance<Renderer>().bindShaderToUniform("cubemapShader", "cameraUniform", "cameraUniform");

	cameraComponent->attachSkybox("skybox__space", "cubemapShader");
	return (true);
}

bool 			DemoScene::userUpdate(double time)
{
	if (_engine.getInstance<Input>().getInput(SDLK_ESCAPE) ||
		_engine.getInstance<Input>().getInput(SDL_QUIT))
		return (false);
	return (true);
}
<|endoftext|>


<commit_before>#ifndef TELEGRAMQT_PENDING_OPERATION
#define TELEGRAMQT_PENDING_OPERATION

#include "telegramqt_global.h"

#include <QObject>
#include <QVariantHash>

#include "telegramqt_global.h"

namespace Telegram {

class PendingOperationPrivate;
class TELEGRAMQT_EXPORT PendingOperation : public QObject
{
    Q_OBJECT
    Q_DISABLE_COPY(PendingOperation)
public:
    explicit PendingOperation(QObject *parent = nullptr);
    ~PendingOperation() override;
    bool isFinished() const;
    bool isSucceeded() const;
    bool isFailed() const;

    static QString c_text();

    QVariantHash errorDetails() const;

    template <typename OperationType>
    static OperationType *failOperation(const QVariantHash &failDetails, QObject *parent = nullptr)
    {
        OperationType *op = new OperationType();
        op->setParent(parent);
        op->setDelayedFinishedWithError(failDetails);
        return op;
    }

    template <typename OperationType>
    static OperationType *failOperation(const QString &failDescription, QObject *parent = nullptr)
    {
        return failOperation<OperationType>({{ c_text(), failDescription}}, parent);
    }

    template<typename T, typename M>
    static void callMember(T *obj, M method)
    {
        (obj->*method)();
    }

    static PendingOperation *failOperation(const QVariantHash &failDetails, QObject *parent = nullptr)
    {
        return failOperation<PendingOperation>(failDetails, parent);
    }

    static PendingOperation *failOperation(const QString &failDescription, QObject *parent = nullptr)
    {
        return failOperation<PendingOperation>({{ c_text(), failDescription}}, parent);
    }

Q_SIGNALS:
    void finished(PendingOperation *operation);
    void succeeded(PendingOperation *operation);
    void failed(PendingOperation *operation, const QVariantHash &details);

public Q_SLOTS:
    virtual void start() { }
    void startLater();
    void runAfter(PendingOperation *operation);

    void setFinished();
    void setFinishedWithError(const QVariantHash &details);
    void setDelayedFinishedWithError(const QVariantHash &details);
    virtual void clearResult();

protected:
    void onPreviousFailed(PendingOperation *operation, const QVariantHash &details);

protected:
    Q_DECLARE_PRIVATE_D(d, PendingOperation)
    PendingOperationPrivate *d = nullptr;
    QVariantHash m_errorDetails;
    bool m_finished;
    bool m_succeeded;
};

class SucceededPendingOperation : public PendingOperation
{
    Q_OBJECT
public:
    explicit SucceededPendingOperation(QObject *parent = nullptr);

    void start() override;
};

inline bool PendingOperation::isFinished() const
{
    return m_finished;
}

inline bool PendingOperation::isSucceeded() const
{
    return m_finished && m_succeeded;
}

inline bool PendingOperation::isFailed() const
{
    return m_finished && !m_succeeded;
}

inline QVariantHash PendingOperation::errorDetails() const
{
    return m_errorDetails;
}

}

#endif // TELEGRAMQT_PENDING_OPERATION
<commit_msg>PendingOperation: Add connectToFinished() template with arguments<commit_after>#ifndef TELEGRAMQT_PENDING_OPERATION
#define TELEGRAMQT_PENDING_OPERATION

#include "telegramqt_global.h"

#include <QObject>
#include <QVariantHash>

#include "telegramqt_global.h"

namespace Telegram {

class PendingOperationPrivate;
class TELEGRAMQT_EXPORT PendingOperation : public QObject
{
    Q_OBJECT
    Q_DISABLE_COPY(PendingOperation)
public:
    explicit PendingOperation(QObject *parent = nullptr);
    ~PendingOperation() override;
    bool isFinished() const;
    bool isSucceeded() const;
    bool isFailed() const;

    static QString c_text();

    QVariantHash errorDetails() const;

    template <typename OperationType>
    static OperationType *failOperation(const QVariantHash &failDetails, QObject *parent = nullptr)
    {
        OperationType *op = new OperationType();
        op->setParent(parent);
        op->setDelayedFinishedWithError(failDetails);
        return op;
    }

    template <typename OperationType>
    static OperationType *failOperation(const QString &failDescription, QObject *parent = nullptr)
    {
        return failOperation<OperationType>({{ c_text(), failDescription}}, parent);
    }

    template<typename T, typename M, typename... Arg>
    static void callMember(T *obj, M method, Arg... arg)
    {
        (obj->*method)(arg...);
    }

    static PendingOperation *failOperation(const QVariantHash &failDetails, QObject *parent = nullptr)
    {
        return failOperation<PendingOperation>(failDetails, parent);
    }

    static PendingOperation *failOperation(const QString &failDescription, QObject *parent = nullptr)
    {
        return failOperation<PendingOperation>({{ c_text(), failDescription}}, parent);
    }

#if Q_CC_GNU && (Q_CC_GNU < 409)
    // Workaround https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55914
    // Remove this once we require GCC 4.9+
    template<typename Receiver, typename ReceiverMethod>
    void connectToFinished(Receiver *obj, ReceiverMethod method)
    {
        connect(this, &PendingOperation::finished, obj, [obj, method] () {
            callMember(obj, method);
        });
    }
    template<typename Receiver, typename ReceiverMethod, typename Arg1>
    void connectToFinished(Receiver *obj, ReceiverMethod method, Arg1 arg1)
    {
        connect(this, &PendingOperation::finished, obj, [obj, method, arg1] () {
            callMember(obj, method, arg1);
        });
    }
    template<typename Receiver, typename ReceiverMethod, typename Arg1, typename Arg2>
    void connectToFinished(Receiver *obj, ReceiverMethod method, Arg1 arg1, Arg2 arg2)
    {
        connect(this, &PendingOperation::finished, obj, [obj, method, arg1, arg2] () {
            callMember(obj, method, arg1, arg2);
        });
    }
#else
    template<typename Receiver, typename ReceiverMethod, typename ...Args>
    void connectToFinished(Receiver *obj, ReceiverMethod method, Args ...args)
    {
        connect(this, &PendingOperation::finished, obj, [obj, method, args...] () {
            callMember(obj, method, args...);
        });
    }
#endif

Q_SIGNALS:
    void finished(PendingOperation *operation);
    void succeeded(PendingOperation *operation);
    void failed(PendingOperation *operation, const QVariantHash &details);

public Q_SLOTS:
    virtual void start() { }
    void startLater();
    void runAfter(PendingOperation *operation);

    void setFinished();
    void setFinishedWithError(const QVariantHash &details);
    void setDelayedFinishedWithError(const QVariantHash &details);
    virtual void clearResult();

protected:
    void onPreviousFailed(PendingOperation *operation, const QVariantHash &details);

protected:
    Q_DECLARE_PRIVATE_D(d, PendingOperation)
    PendingOperationPrivate *d = nullptr;
    QVariantHash m_errorDetails;
    bool m_finished;
    bool m_succeeded;
};

class SucceededPendingOperation : public PendingOperation
{
    Q_OBJECT
public:
    explicit SucceededPendingOperation(QObject *parent = nullptr);

    void start() override;
};

inline bool PendingOperation::isFinished() const
{
    return m_finished;
}

inline bool PendingOperation::isSucceeded() const
{
    return m_finished && m_succeeded;
}

inline bool PendingOperation::isFailed() const
{
    return m_finished && !m_succeeded;
}

inline QVariantHash PendingOperation::errorDetails() const
{
    return m_errorDetails;
}

}

#endif // TELEGRAMQT_PENDING_OPERATION
<|endoftext|>


<commit_before>#ifndef __AND_CPP__
#define __AND_CPP__

#include "Connector.h"
#include "AND.h"

//constructors
AND::AND(Base* lhs, Base* rhs): Connector(lhs,rhs) {}
AND::AND(): Connector() {}

//executes its right child if its left child has executed
//returns true if both children execute successfully
//otherwise returns false
bool AND::execute(int in, int out) {
    if(lhs->execute(in,1)){
       if(rhs->execute(0,out)){
           return true;
       }
       else {
           return false;
       }
    }
    else {
        return false;
     }
}
#endif
<commit_msg>commit<commit_after>#ifndef __AND_CPP__
#define __AND_CPP__

#include "Connector.h"
#include "AND.h"

//constructors
AND::AND(Base* lhs, Base* rhs): Connector(lhs,rhs) {}
AND::AND(): Connector() {}

//executes its right child if its left child has executed
//returns true if both children execute successfully
//otherwise returns false
bool AND::execute(int in, int out) {
    if(lhs->execute(in,out)){
       if(rhs->execute(in,out)){
           return true;
       }
       else {
           return false;
       }
    }
    else {
        return false;
     }
}
#endif
<|endoftext|>


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

/** typedefs for functions from vendorplugin.h
 */
typedef javaPluginError (*jfw_plugin_getAllJavaInfos_ptr)(
    rtl_uString * sVendor,
    rtl_uString * sMinVersion,
    rtl_uString * sMaxVersion,
    rtl_uString * * arExcludeList,
    sal_Int32  nLenList,
    JavaInfo*** parJavaInfo,
    sal_Int32 *nLenInfoList);

typedef javaPluginError (*jfw_plugin_getJavaInfoByPath_ptr)(
    rtl_uString * sPath,
    rtl_uString * sMinVersion,
    rtl_uString * sMaxVersion,
    rtl_uString * * arExcludeList,
    sal_Int32  nLenList,
    JavaInfo** ppInfo);

/** starts a Java Virtual Machine.

    The function shall ensure, that the VM does not abort the process
    during instantiation.

 */
typedef javaPluginError (*jfw_plugin_startJavaVirtualMachine_ptr)(
    const JavaInfo *info,
    const JavaVMOption* options,
    sal_Int32 cOptions,
    JavaVM ** ppVM,
    JNIEnv ** ppEnv);

namespace jfw
{

class CJavaInfo
{
    static JavaInfo * copyJavaInfo(const JavaInfo * pInfo);

    enum _transfer_ownership {TRANSFER};
    /*Attaching the pointer to this class. The argument pInfo must not
    be freed afterwards.
    */
    CJavaInfo(::JavaInfo * info, _transfer_ownership);

public:
    ::JavaInfo * pInfo;

    CJavaInfo();
    explicit CJavaInfo(const ::JavaInfo* pInfo);
    CJavaInfo(const CJavaInfo &);
    ~CJavaInfo();
    CJavaInfo& operator =(const ::JavaInfo* info);
    CJavaInfo & operator = (const CJavaInfo& info);

    /* The returned class takes ownership of the argument info. info
    must not been freed afterwards.
    */
    static CJavaInfo createWrapper(::JavaInfo* info);
    /*Attaching the pointer to this class. The argument pInfo must not
    be freed afterwards.
    */
    void attach(::JavaInfo* pInfo);
    ::JavaInfo * detach();
    const ::JavaInfo* operator ->() const;
//    ::JavaInfo** operator & ();
    operator ::JavaInfo* ();
    operator ::JavaInfo const * () const;
    ::JavaInfo* cloneJavaInfo() const;

    rtl::OUString getVendor() const;
    rtl::OUString getLocation() const;
    rtl::OUString getVersion() const;
    sal_uInt64 getFeatures() const;
    sal_uInt64 getRequirements() const;
    rtl::ByteSequence getVendorData() const;
};

class FrameworkException
{
public:

    FrameworkException(javaFrameworkError err, const rtl::OString& msg):
        errorCode(err), message(msg)
        {
        }
    javaFrameworkError errorCode;
    rtl::OString message;
};
}
#endif
<commit_msg>INTEGRATION: CWS jl15 (1.5.2); FILE MERGED 2004/11/24 12:46:18 jl 1.5.2.1: #i37225#<commit_after>/*************************************************************************
 *
 *  $RCSfile: framework.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2004-12-16 11:47:37 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#if !defined INCLUDED_JVMFWK_LOCAL_FRAMEWORK_HXX
#define INCLUDED_JVMFWK_LOCAL_FRAMEWORK_HXX
#include "rtl/ustring.hxx"
#include "rtl/byteseq.hxx"
#include "jvmfwk/framework.h"
#include "jvmfwk/vendorplugin.h"

/** typedefs for functions from vendorplugin.h
 */
typedef javaPluginError (*jfw_plugin_getAllJavaInfos_ptr)(
    rtl_uString * sVendor,
    rtl_uString * sMinVersion,
    rtl_uString * sMaxVersion,
    rtl_uString * * arExcludeList,
    sal_Int32  nLenList,
    JavaInfo*** parJavaInfo,
    sal_Int32 *nLenInfoList);

typedef javaPluginError (*jfw_plugin_getJavaInfoByPath_ptr)(
    rtl_uString * sPath,
    rtl_uString * sVendor,
    rtl_uString * sMinVersion,
    rtl_uString * sMaxVersion,
    rtl_uString * * arExcludeList,
    sal_Int32  nLenList,
    JavaInfo** ppInfo);

/** starts a Java Virtual Machine.

    The function shall ensure, that the VM does not abort the process
    during instantiation.

 */
typedef javaPluginError (*jfw_plugin_startJavaVirtualMachine_ptr)(
    const JavaInfo *info,
    const JavaVMOption* options,
    sal_Int32 cOptions,
    JavaVM ** ppVM,
    JNIEnv ** ppEnv);

namespace jfw
{

class CJavaInfo
{
    static JavaInfo * copyJavaInfo(const JavaInfo * pInfo);

    enum _transfer_ownership {TRANSFER};
    /*Attaching the pointer to this class. The argument pInfo must not
    be freed afterwards.
    */
    CJavaInfo(::JavaInfo * info, _transfer_ownership);

public:
    ::JavaInfo * pInfo;

    CJavaInfo();
    explicit CJavaInfo(const ::JavaInfo* pInfo);
    CJavaInfo(const CJavaInfo &);
    ~CJavaInfo();
    CJavaInfo& operator =(const ::JavaInfo* info);
    CJavaInfo & operator = (const CJavaInfo& info);

    /* The returned class takes ownership of the argument info. info
    must not been freed afterwards.
    */
    static CJavaInfo createWrapper(::JavaInfo* info);
    /*Attaching the pointer to this class. The argument pInfo must not
    be freed afterwards.
    */
    void attach(::JavaInfo* pInfo);
    ::JavaInfo * detach();
    const ::JavaInfo* operator ->() const;
//    ::JavaInfo** operator & ();
    operator ::JavaInfo* ();
    operator ::JavaInfo const * () const;
    ::JavaInfo* cloneJavaInfo() const;

    rtl::OUString getVendor() const;
    rtl::OUString getLocation() const;
    rtl::OUString getVersion() const;
    sal_uInt64 getFeatures() const;
    sal_uInt64 getRequirements() const;
    rtl::ByteSequence getVendorData() const;
};

class FrameworkException
{
public:

    FrameworkException(javaFrameworkError err, const rtl::OString& msg):
        errorCode(err), message(msg)
        {
        }
    javaFrameworkError errorCode;
    rtl::OString message;
};
}
#endif
<|endoftext|>