<commit_before>/*
 * Copyright (c) 2012, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Willow Garage, Inc. nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdio.h>

#include <sstream>

#include "rviz/display_context.h"
#include "rviz/failed_view_controller.h"
#include "rviz/properties/enum_property.h"
#include "rviz/properties/property_tree_model.h"
#include "rviz/render_panel.h"
#include "rviz/view_controller.h"

#include "rviz/view_manager.h"

namespace rviz
{

ViewManager::ViewManager( DisplayContext* context )
  : context_( context )
  , root_property_( new ViewControllerContainer )
  , property_model_( new PropertyTreeModel( root_property_ ))
  , factory_( new PluginlibFactory<ViewController>( "rviz", "rviz::ViewController" ))
  , current_( NULL )
  , render_panel_( NULL )
{
  property_model_->setDragDropClass( "view-controller" );
  connect( property_model_, SIGNAL( configChanged() ), this, SIGNAL( configChanged() ));
}

ViewManager::~ViewManager()
{
  delete property_model_;
  delete factory_;
}

void ViewManager::initialize()
{
  setCurrent( create( "rviz/Orbit" ), false );
}

void ViewManager::update( float wall_dt, float ros_dt )
{
  if( getCurrent() )
  {
    getCurrent()->update( wall_dt, ros_dt );
  }
}

ViewController* ViewManager::create( const QString& class_id )
{
  QString error;
  ViewController* view = factory_->make( class_id, &error );
  if( !view )
  {
    view = new FailedViewController( class_id, error );
  }
  view->initialize( context_ );

  return view;
}

ViewController* ViewManager::getCurrent() const
{
  return current_;
}

void ViewManager::setCurrentFrom( ViewController* source_view )
{
  if( source_view == NULL )
  {
    return;
  }

  ViewController* previous = getCurrent();
  if( source_view != previous )
  {
    ViewController* new_current = copy( source_view );

    setCurrent( new_current, false );
    Q_EMIT configChanged();
  }
}

void ViewManager::onCurrentDestroyed( QObject* obj )
{
  if( obj == current_ )
  {
    current_ = NULL;
  }
}

void ViewManager::setCurrent( ViewController* new_current, bool mimic_view )
{
  ViewController* previous = getCurrent();
  if( previous )
  {
    if( mimic_view )
    {
      new_current->mimic( previous );
    }
    else
    {
      new_current->transitionFrom( previous );
    }
    disconnect( previous, SIGNAL( destroyed( QObject* )), this, SLOT( onCurrentDestroyed( QObject* )));
  }
  new_current->setName( "Current View" );
  connect( new_current, SIGNAL( destroyed( QObject* )), this, SLOT( onCurrentDestroyed( QObject* )));
  current_ = new_current;
  root_property_->addChildToFront( new_current );
  delete previous;

  if( render_panel_ )
  {
    // This setViewController() can indirectly call
    // ViewManager::update(), so make sure getCurrent() will return the
    // new one by this point.
    render_panel_->setViewController( new_current );
  }
  Q_EMIT currentChanged();
}

void ViewManager::setCurrentViewControllerType( const QString& new_class_id )
{
  setCurrent( create( new_class_id ), true );
}

void ViewManager::copyCurrentToList()
{
  ViewController* current = getCurrent();
  if( current )
  {
    ViewController* new_copy = copy( current );
    new_copy->setName( factory_->getClassName( new_copy->getClassId() ));
    root_property_->addChild( new_copy );
  }
}

ViewController* ViewManager::getViewAt( int index ) const
{
  if( index < 0 )
  {
    index = 0;
  }
  return qobject_cast<ViewController*>( root_property_->childAt( index + 1 ));
}

int ViewManager::getNumViews() const
{
  int count = root_property_->numChildren();
  if( count <= 0 )
  {
    return 0;
  }
  else
  {
    return count-1;
  }
}

void ViewManager::add( ViewController* view, int index )
{
  if( index < 0 )
  {
    index = root_property_->numChildren();
  }
  else
  {
    index++;
  }
  property_model_->getRoot()->addChild( view, index );
}

ViewController* ViewManager::take( ViewController* view )
{
  for( int i = 0; i < getNumViews(); i++ )
  {
    if( getViewAt( i ) == view )
    {
      return qobject_cast<ViewController*>( root_property_->takeChildAt( i + 1 ));
    }
  }
  return NULL;
}

ViewController* ViewManager::takeAt( int index )
{
  if( index < 0 )
  {
    return NULL;
  }
  return qobject_cast<ViewController*>( root_property_->takeChildAt( index + 1 ));
}

void ViewManager::load( const Config& config )
{
  Config current_config = config.mapGetChild( "Current" );
  QString class_id;
  if( current_config.mapGetString( "Class", &class_id ))
  {
    ViewController* new_current = create( class_id );
    new_current->load( current_config );
    setCurrent( new_current, false );
  }

  Config saved_views_config = config.mapGetChild( "Saved" );
  root_property_->removeChildren( 1 );
  int num_saved = saved_views_config.listLength();
  for( int i = 0; i < num_saved; i++ )
  {
    Config view_config = saved_views_config.listChildAt( i );

    if( view_config.mapGetString( "Class", &class_id ))
    {
      ViewController* view = create( class_id );
      view->load( view_config );
      add( view );
    }
  }
}

void ViewManager::save( Config config ) const
{
  getCurrent()->save( config.mapMakeChild( "Current" ));

  Config saved_views_config = config.mapMakeChild( "Saved" );
  for( int i = 0; i < getNumViews(); i++ )
  {
    getViewAt( i )->save( saved_views_config.listAppendNew() );
  }
}

ViewController* ViewManager::copy( ViewController* source )
{
  Config config;
  source->save( config );

  ViewController* copy_of_source = create( source->getClassId() );
  copy_of_source->load( config );

  return copy_of_source;
}

void ViewManager::setRenderPanel( RenderPanel* render_panel )
{
  render_panel_ = render_panel;
}

Qt::ItemFlags ViewControllerContainer::getViewFlags( int column ) const
{
  return Property::getViewFlags( column ) | Qt::ItemIsDropEnabled;
}

void ViewControllerContainer::addChild( Property* child, int index )
{
  if( index == 0 )
  {
    index = 1;
  }
  Property::addChild( child, index );
}

void ViewControllerContainer::addChildToFront( Property* child )
{
  Property::addChild( child, 0 );
}

} // end namespace rviz
<commit_msg>Correctly save new current view controller<commit_after>/*
 * Copyright (c) 2012, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Willow Garage, Inc. nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdio.h>

#include <sstream>

#include "rviz/display_context.h"
#include "rviz/failed_view_controller.h"
#include "rviz/properties/enum_property.h"
#include "rviz/properties/property_tree_model.h"
#include "rviz/render_panel.h"
#include "rviz/view_controller.h"

#include "rviz/view_manager.h"

namespace rviz
{

ViewManager::ViewManager( DisplayContext* context )
  : context_( context )
  , root_property_( new ViewControllerContainer )
  , property_model_( new PropertyTreeModel( root_property_ ))
  , factory_( new PluginlibFactory<ViewController>( "rviz", "rviz::ViewController" ))
  , current_( NULL )
  , render_panel_( NULL )
{
  property_model_->setDragDropClass( "view-controller" );
  connect( property_model_, SIGNAL( configChanged() ), this, SIGNAL( configChanged() ));
  connect( this, SIGNAL( currentChanged() ), this, SIGNAL( configChanged() ));
}

ViewManager::~ViewManager()
{
  delete property_model_;
  delete factory_;
}

void ViewManager::initialize()
{
  setCurrent( create( "rviz/Orbit" ), false );
}

void ViewManager::update( float wall_dt, float ros_dt )
{
  if( getCurrent() )
  {
    getCurrent()->update( wall_dt, ros_dt );
  }
}

ViewController* ViewManager::create( const QString& class_id )
{
  QString error;
  ViewController* view = factory_->make( class_id, &error );
  if( !view )
  {
    view = new FailedViewController( class_id, error );
  }
  view->initialize( context_ );

  return view;
}

ViewController* ViewManager::getCurrent() const
{
  return current_;
}

void ViewManager::setCurrentFrom( ViewController* source_view )
{
  if( source_view == NULL )
  {
    return;
  }

  ViewController* previous = getCurrent();
  if( source_view != previous )
  {
    ViewController* new_current = copy( source_view );

    setCurrent( new_current, false );
    Q_EMIT configChanged();
  }
}

void ViewManager::onCurrentDestroyed( QObject* obj )
{
  if( obj == current_ )
  {
    current_ = NULL;
  }
}

void ViewManager::setCurrent( ViewController* new_current, bool mimic_view )
{
  ViewController* previous = getCurrent();
  if( previous )
  {
    if( mimic_view )
    {
      new_current->mimic( previous );
    }
    else
    {
      new_current->transitionFrom( previous );
    }
    disconnect( previous, SIGNAL( destroyed( QObject* )), this, SLOT( onCurrentDestroyed( QObject* )));
  }
  new_current->setName( "Current View" );
  connect( new_current, SIGNAL( destroyed( QObject* )), this, SLOT( onCurrentDestroyed( QObject* )));
  current_ = new_current;
  root_property_->addChildToFront( new_current );
  delete previous;

  if( render_panel_ )
  {
    // This setViewController() can indirectly call
    // ViewManager::update(), so make sure getCurrent() will return the
    // new one by this point.
    render_panel_->setViewController( new_current );
  }
  if (current_ != previous)
    Q_EMIT currentChanged();
}

void ViewManager::setCurrentViewControllerType( const QString& new_class_id )
{
  setCurrent( create( new_class_id ), true );
}

void ViewManager::copyCurrentToList()
{
  ViewController* current = getCurrent();
  if( current )
  {
    ViewController* new_copy = copy( current );
    new_copy->setName( factory_->getClassName( new_copy->getClassId() ));
    root_property_->addChild( new_copy );
  }
}

ViewController* ViewManager::getViewAt( int index ) const
{
  if( index < 0 )
  {
    index = 0;
  }
  return qobject_cast<ViewController*>( root_property_->childAt( index + 1 ));
}

int ViewManager::getNumViews() const
{
  int count = root_property_->numChildren();
  if( count <= 0 )
  {
    return 0;
  }
  else
  {
    return count-1;
  }
}

void ViewManager::add( ViewController* view, int index )
{
  if( index < 0 )
  {
    index = root_property_->numChildren();
  }
  else
  {
    index++;
  }
  property_model_->getRoot()->addChild( view, index );
}

ViewController* ViewManager::take( ViewController* view )
{
  for( int i = 0; i < getNumViews(); i++ )
  {
    if( getViewAt( i ) == view )
    {
      return qobject_cast<ViewController*>( root_property_->takeChildAt( i + 1 ));
    }
  }
  return NULL;
}

ViewController* ViewManager::takeAt( int index )
{
  if( index < 0 )
  {
    return NULL;
  }
  return qobject_cast<ViewController*>( root_property_->takeChildAt( index + 1 ));
}

void ViewManager::load( const Config& config )
{
  Config current_config = config.mapGetChild( "Current" );
  QString class_id;
  if( current_config.mapGetString( "Class", &class_id ))
  {
    ViewController* new_current = create( class_id );
    new_current->load( current_config );
    setCurrent( new_current, false );
  }

  Config saved_views_config = config.mapGetChild( "Saved" );
  root_property_->removeChildren( 1 );
  int num_saved = saved_views_config.listLength();
  for( int i = 0; i < num_saved; i++ )
  {
    Config view_config = saved_views_config.listChildAt( i );

    if( view_config.mapGetString( "Class", &class_id ))
    {
      ViewController* view = create( class_id );
      view->load( view_config );
      add( view );
    }
  }
}

void ViewManager::save( Config config ) const
{
  getCurrent()->save( config.mapMakeChild( "Current" ));

  Config saved_views_config = config.mapMakeChild( "Saved" );
  for( int i = 0; i < getNumViews(); i++ )
  {
    getViewAt( i )->save( saved_views_config.listAppendNew() );
  }
}

ViewController* ViewManager::copy( ViewController* source )
{
  Config config;
  source->save( config );

  ViewController* copy_of_source = create( source->getClassId() );
  copy_of_source->load( config );

  return copy_of_source;
}

void ViewManager::setRenderPanel( RenderPanel* render_panel )
{
  render_panel_ = render_panel;
}

Qt::ItemFlags ViewControllerContainer::getViewFlags( int column ) const
{
  return Property::getViewFlags( column ) | Qt::ItemIsDropEnabled;
}

void ViewControllerContainer::addChild( Property* child, int index )
{
  if( index == 0 )
  {
    index = 1;
  }
  Property::addChild( child, index );
}

void ViewControllerContainer::addChildToFront( Property* child )
{
  Property::addChild( child, 0 );
}

} // end namespace rviz
<|endoftext|>


<commit_before>//=====================================================================//
/*! @file
	@brief  img メイン関係
	@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <iostream>
#include "img_main.hpp"
#include "core/glcore.hpp"
#include "widgets/widget_utils.hpp"

namespace app {

	//-----------------------------------------------------------------//
	/*!
		@brief  初期化
	*/
	//-----------------------------------------------------------------//
	void img_main::initialize()
	{
		gl::IGLcore* igl = gl::get_glcore();

		using namespace gui;
		widget_director& wd = director_.at().widget_director_;

		{ // 画像ファイル表示用フレーム
			widget::param wp(vtx::srect(30, 30, 256, 256));
			widget_frame::param wp_;
			frame_ = wd.add_widget<widget_frame>(wp, wp_);
		}
		{ // 画像ファイル表示イメージ
			widget::param wp(vtx::srect(0, 0, 256, 256), frame_);
			widget_image::param wp_;
			image_ = wd.add_widget<widget_image>(wp, wp_);
			image_->set_state(widget::state::CLIP_PARENTS);
		}

		{ // 機能ツールパレット
			widget::param wp(vtx::srect(10, 10, 120, 300));
			widget_frame::param wp_;
			tools_ = wd.add_widget<widget_frame>(wp, wp_);
		}
		{ // ファイラー起動ボタン
			widget::param wp(vtx::srect(5, 5, 100, 40), tools_);
			widget_button::param wp_("file");
			open_ = wd.add_widget<widget_button>(wp, wp_);
		}
		{ // ファイラー本体
			widget::param wp(vtx::srect(10, 30, 300, 200));
			widget_filer::param wp_(igl->get_current_path());
			filer_ = wd.add_widget<widget_filer>(wp, wp_);
			filer_->enable(false);
		}
		{ // ダイアログ
			widget::param wp(vtx::srect(10, 30, 450, 200));
			widget_dialog::param wp_;
			dialog_ = wd.add_widget<widget_dialog>(wp, wp_);
			dialog_->enable(false);
		}

		mobj_.initialize();

		// プリファレンスの取得
		sys::preference& pre = director_.at().preference_;
		if(filer_) {
			filer_->load(pre);
			frame_->load(pre);
			tools_->load(pre);
		}
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  アップデート
	*/
	//-----------------------------------------------------------------//
	void img_main::update()
	{
		gl::IGLcore* igl = gl::get_glcore();
		const vtx::spos& size = igl->get_size();

		gui::widget_director& wd = director_.at().widget_director_;

		if(open_) {
			if(open_->get_selected()) {
				if(filer_) {
					bool f = filer_->get_state(gui::widget::state::ENABLE);
					filer_->enable(!f);
				}
			}
		}

		if(filer_) {
			if(filer_id_ != filer_->get_select_file_id()) {
				filer_id_ = filer_->get_select_file_id();

				img::img_files& imf = wd.at_img_files();
				if(!imf.load(filer_->get_file())) {
					dialog_->set_text("Can't decode image file:\n '"
						+ filer_->get_file() + "'");
					dialog_->enable();
				} else {
					mobj_.destroy();
					mobj_.initialize();
					img_handle_ = mobj_.install(imf.get_image_if());
					image_->at_local_param().mobj_ = mobj_;
					image_->at_local_param().mobj_handle_ = img_handle_;
// imf.set_image_if(imf.get_image_if());
// imf.save("test.tga", "rle");
				}
			}
		}

		// frame 内 image のサイズを設定
		if(frame_ && image_) {
			vtx::spos ofs(frame_->get_local_param().plate_param_.frame_width_);
			image_->at_rect().org = ofs;
			image_->at_rect().size = frame_->get_rect().size - ofs * 2;
		}

		wd.update();
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  レンダリング
	*/
	//-----------------------------------------------------------------//
	void img_main::render()
	{
		director_.at().widget_director_.service();
		director_.at().widget_director_.render();
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  廃棄
	*/
	//-----------------------------------------------------------------//
	void img_main::destroy()
	{
		sys::preference& pre = director_.at().preference_;
		if(filer_) {
			filer_->save(pre);
			frame_->save(pre);
			tools_->save(pre);
		}
	}
}
<commit_msg>画像フレームのリサイズ対応<commit_after>//=====================================================================//
/*! @file
	@brief  img メイン関係
	@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <iostream>
#include "img_main.hpp"
#include "core/glcore.hpp"
#include "widgets/widget_utils.hpp"

namespace app {

	//-----------------------------------------------------------------//
	/*!
		@brief  初期化
	*/
	//-----------------------------------------------------------------//
	void img_main::initialize()
	{
		gl::IGLcore* igl = gl::get_glcore();

		using namespace gui;
		widget_director& wd = director_.at().widget_director_;

		{ // 画像ファイル表示用フレーム
			widget::param wp(vtx::srect(30, 30, 256, 256));
			widget_frame::param wp_;
			frame_ = wd.add_widget<widget_frame>(wp, wp_);
		}
		{ // 画像ファイル表示イメージ
			widget::param wp(vtx::srect(0, 0, 256, 256), frame_);
			widget_image::param wp_;
			image_ = wd.add_widget<widget_image>(wp, wp_);
			image_->set_state(widget::state::CLIP_PARENTS);
			image_->set_state(widget::state::RESIZE_ROOT);
		}

		{ // 機能ツールパレット
			widget::param wp(vtx::srect(10, 10, 120, 300));
			widget_frame::param wp_;
			tools_ = wd.add_widget<widget_frame>(wp, wp_);
		}
		{ // ファイラー起動ボタン
			widget::param wp(vtx::srect(5, 5, 100, 40), tools_);
			widget_button::param wp_("file");
			open_ = wd.add_widget<widget_button>(wp, wp_);
		}
		{ // ファイラー本体
			widget::param wp(vtx::srect(10, 30, 300, 200));
			widget_filer::param wp_(igl->get_current_path());
			filer_ = wd.add_widget<widget_filer>(wp, wp_);
			filer_->enable(false);
		}
		{ // ダイアログ
			widget::param wp(vtx::srect(10, 30, 450, 200));
			widget_dialog::param wp_;
			dialog_ = wd.add_widget<widget_dialog>(wp, wp_);
			dialog_->enable(false);
		}

		mobj_.initialize();

		// プリファレンスの取得
		sys::preference& pre = director_.at().preference_;
		if(filer_) {
			filer_->load(pre);
			frame_->load(pre);
			tools_->load(pre);
		}
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  アップデート
	*/
	//-----------------------------------------------------------------//
	void img_main::update()
	{
		gl::IGLcore* igl = gl::get_glcore();
		const vtx::spos& size = igl->get_size();

		gui::widget_director& wd = director_.at().widget_director_;

		if(open_) {
			if(open_->get_selected()) {
				if(filer_) {
					bool f = filer_->get_state(gui::widget::state::ENABLE);
					filer_->enable(!f);
				}
			}
		}

		if(filer_) {
			if(filer_id_ != filer_->get_select_file_id()) {
				filer_id_ = filer_->get_select_file_id();

				img::img_files& imf = wd.at_img_files();
				if(!imf.load(filer_->get_file())) {
					dialog_->set_text("Can't decode image file:\n '"
						+ filer_->get_file() + "'");
					dialog_->enable();
				} else {
					mobj_.destroy();
					mobj_.initialize();
					img_handle_ = mobj_.install(imf.get_image_if());
					image_->at_local_param().mobj_ = mobj_;
					image_->at_local_param().mobj_handle_ = img_handle_;
// imf.set_image_if(imf.get_image_if());
// imf.save("test.tga", "rle");
				}
			}
		}

		// frame 内 image のサイズを設定
		if(frame_ && image_) {
			vtx::spos ofs(frame_->get_local_param().plate_param_.frame_width_);
			image_->at_rect().org = ofs;
			image_->at_rect().size = frame_->get_rect().size - ofs * 2;
		}

		wd.update();
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  レンダリング
	*/
	//-----------------------------------------------------------------//
	void img_main::render()
	{
		director_.at().widget_director_.service();
		director_.at().widget_director_.render();
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  廃棄
	*/
	//-----------------------------------------------------------------//
	void img_main::destroy()
	{
		sys::preference& pre = director_.at().preference_;
		if(filer_) {
			filer_->save(pre);
			frame_->save(pre);
			tools_->save(pre);
		}
	}
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Mathematics (glm.g-truc.net)
///
/// Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net)
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
///
/// @file glm/gtc/matrix_transform.hpp
/// @date 2009-04-29 / 2011-05-16
/// @author Christophe Riccio
///
/// @ref gtc_matrix_transform
/// @see core (dependence)
/// @see gtc_matrix_transform
/// @see gtx_transform
/// @see gtx_transform2
///////////////////////////////////////////////////////////////////////////////////

#ifndef glm_gtc_matrix_transform
#define glm_gtc_matrix_transform

// Dependency:
#include "../glm.hpp"

#if(defined(GLM_MESSAGES) && !defined(glm_ext))
#	pragma message("GLM: GLM_GTC_matrix_transform extension included")
#endif

namespace glm{
namespace test{
	bool main_gtc_matrix_transform();
}//namespace test

namespace gtc{
/// GLM_GTC_matrix_transform extension: Add transformation matrices
namespace matrix_transform
{
	/// @addtogroup gtc_matrix_transform
	/// @{

	/// Builds a translation 4 * 4 matrix created from a vector of 3 components.
	/// @see - gtc_matrix_transform
	/// @see - gtx_transform:
	/// - @link glm::gtx::transform::translate(T x, T y, T z) translate(T x, T y, T z) @endlink
	/// - @link glm::gtx::transform::translate(detail::tmat4x4<T> const & m, T x, T y, T z) translate(mat4x4<T> const & m, T x, T y, T z) @endlink
	template <typename T>
	detail::tmat4x4<T> translate(
		detail::tmat4x4<T> const & m,
		detail::tvec3<T> const & v);

	/// Builds a rotation 4 * 4 matrix created from an axis vector and an angle expressed in degrees.
	/// @see - gtc_matrix_transform
	/// @see - gtx_transform:
	/// - @link glm::gtx::transform::rotate(T angle, T x, T y, T z) rotate(T const & angle, T const & x, T const & y, T const & z) @endlink
	/// - @link glm::gtx::transform::rotate(detail::tmat4x4<T> const & m, T angle, T x, T y, T z) rotate(mat4x4<T> const & m, T const & angle, T const & x, T const & y, T const & z) @endlink
	template <typename T>
	detail::tmat4x4<T> rotate(
		detail::tmat4x4<T> const & m,
		T const & angle,
		detail::tvec3<T> const & v);

	/// Builds a scale 4 * 4 matrix created from 3 scalars.
	/// @see - gtc_matrix_transform
	/// @see - gtx_transform:
	/// - @link glm::gtx::transform::scale(T x, T y, T z) rotate(T const & angle, T const & x, T const & y, T const & z) @endlink
	/// - @link glm::gtx::transform::scale(detail::tmat4x4<T> const & m, T x, T y, T z) rotate(mat4x4<T> const & m, T const & angle, T const & x, T const & y, T const & z) @endlink
	template <typename T>
	detail::tmat4x4<T> scale(
		detail::tmat4x4<T> const & m,
		detail::tvec3<T> const & v);

	/// Creates a matrix for an orthographic parallel viewing volume.
	/// @see - gtc_matrix_transform:
	/// - @link glm::gtc::matrix_transform::ortho(T const & left, T const & right, T const & bottom, T const & top) ortho(T const & left, T const & right, T const & bottom, T const & top) @endlink
	template <typename T>
	detail::tmat4x4<T> ortho(
		T const & left,
		T const & right,
		T const & bottom,
		T const & top,
		T const & zNear,
		T const & zFar);

	/// Creates a matrix for projecting two-dimensional coordinates onto the screen.
	/// @see - gtc_matrix_transform:
    /// - @link glm::gtc::matrix_transform::ortho(T const & left, T const & right, T const & bottom, T const & top, T const & zNear, T const & zFar) ortho(T const & left, T const & right, T const & bottom, T const & top, T const & zNear, T const & zFar) @endlink
	template <typename T>
	detail::tmat4x4<T> ortho(
		T const & left,
		T const & right,
		T const & bottom,
		T const & top);

	/// Creates a frustum matrix.
	/// @see - gtc_matrix_transform
	template <typename T>
	detail::tmat4x4<T> frustum(
		T const & left,
		T const & right,
		T const & bottom,
		T const & top,
		T const & nearVal,
		T const & farVal);

	/// Creates a matrix for a symetric perspective-view frustum.
	/// @see - gtc_matrix_transform
	template <typename T>
	detail::tmat4x4<T> perspective(
		T const & fovy,
		T const & aspect,
		T const & zNear,
		T const & zFar);

	/// Builds a perspective projection matrix based on a field of view
	/// @see - gtc_matrix_transform
	template <typename valType>
	detail::tmat4x4<valType> perspectiveFov(
		valType const & fov,
		valType const & width,
		valType const & height,
		valType const & zNear,
		valType const & zFar);

	/// Creates a matrix for a symmetric perspective-view frustum with far plane at infinite .
	/// @see - gtc_matrix_transform
    template <typename T>
	detail::tmat4x4<T> infinitePerspective(
		T fovy, T aspect, T zNear);

	/// Creates a matrix for a symmetric perspective-view frustum with far plane at infinite for graphics hardware that doesn't support depth clamping.
	/// @see - gtc_matrix_transform
    template <typename T>
	detail::tmat4x4<T> tweakedInfinitePerspective(
		T fovy, T aspect, T zNear);

	/// Map the specified object coordinates (obj.x, obj.y, obj.z) into window coordinates.
	/// @see - gtc_matrix_transform
	template <typename T, typename U>
	detail::tvec3<T> project(
		detail::tvec3<T> const & obj,
		detail::tmat4x4<T> const & model,
		detail::tmat4x4<T> const & proj,
		detail::tvec4<U> const & viewport);

	/// Map the specified window coordinates (win.x, win.y, win.z) into object coordinates.
	/// @see - gtc_matrix_transform
	template <typename T, typename U>
	detail::tvec3<T> unProject(
		detail::tvec3<T> const & win,
		detail::tmat4x4<T> const & model,
		detail::tmat4x4<T> const & proj,
		detail::tvec4<U> const & viewport);

	/// Define a picking region
	/// @see - gtc_matrix_transform
	template <typename T, typename U>
	detail::tmat4x4<T> pickMatrix(
		detail::tvec2<T> const & center,
		detail::tvec2<T> const & delta,
		detail::tvec4<U> const & viewport);

	/// Build a look at view matrix.
	/// @see - gtc_matrix_transform:
	/// - @link frustum(T const & left, T const & right, T const & bottom, T const & top, T const & nearVal, T const & farVal) frustum(T const & left, T const & right, T const & bottom, T const & top, T const & nearVal, T const & farVal) @endlink
	/// @param eye Position of the camera
	/// @param center Position where the camera is looking at
	/// @param up Normalized up vector, how the camera is oriented. Typically (0, 0, 1)
	template <typename T>
	detail::tmat4x4<T> lookAt(
		detail::tvec3<T> const & eye,
		detail::tvec3<T> const & center,
		detail::tvec3<T> const & up);

	/// @}
}//namespace matrix_transform
}//namespace gtc
}//namespace glm

#include "matrix_transform.inl"

namespace glm{using namespace gtc::matrix_transform;}

#endif//glm_gtc_matrix_transform
<commit_msg>Improved doxygens documentation<commit_after>///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Mathematics (glm.g-truc.net)
///
/// Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net)
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
///
/// @ref gtc_matrix_transform
/// @file glm/gtc/matrix_transform.hpp
/// @date 2009-04-29 / 2011-05-16
/// @author Christophe Riccio
///
/// @see core (dependence)
/// @see gtx_transform
/// @see gtx_transform2
///////////////////////////////////////////////////////////////////////////////////

#ifndef glm_gtc_matrix_transform
#define glm_gtc_matrix_transform

// Dependency:
#include "../glm.hpp"

#if(defined(GLM_MESSAGES) && !defined(glm_ext))
#	pragma message("GLM: GLM_GTC_matrix_transform extension included")
#endif

namespace glm{
namespace test{
	bool main_gtc_matrix_transform();
}//namespace test

namespace gtc{
/// GLM_GTC_matrix_transform extension: Add transformation matrices
namespace matrix_transform
{
	/// @addtogroup gtc_matrix_transform
	/// @{

	/// Builds a translation 4 * 4 matrix created from a vector of 3 components.
	/// @see - gtc_matrix_transform
	/// @see - gtx_transform:
	/// - @link glm::gtx::transform::translate(T x, T y, T z) translate(T x, T y, T z) @endlink
	/// - @link glm::gtx::transform::translate(detail::tmat4x4<T> const & m, T x, T y, T z) translate(mat4x4<T> const & m, T x, T y, T z) @endlink
	/// - @link glm::gtx::transform::translate(detail::tvec3<T> const & v) translate(vec3<T> const & v) @endlink
	template <typename T>
	detail::tmat4x4<T> translate(
		detail::tmat4x4<T> const & m,
		detail::tvec3<T> const & v);

	/// Builds a rotation 4 * 4 matrix created from an axis vector and an angle expressed in degrees.
	/// @see - gtc_matrix_transform
	/// @see - gtx_transform:
	/// - @link glm::gtx::transform::rotate(T angle, T x, T y, T z) rotate(T const & angle, T const & x, T const & y, T const & z) @endlink
	/// - @link glm::gtx::transform::rotate(detail::tmat4x4<T> const & m, T angle, T x, T y, T z) rotate(mat4x4<T> const & m, T const & angle, T const & x, T const & y, T const & z) @endlink
	/// - @link glm::gtx::transform::rotate(T angle, detail::tvec3<T> const & v) rotate(T const & angle, vec3<T> const & v) @endlink
	template <typename T>
	detail::tmat4x4<T> rotate(
		detail::tmat4x4<T> const & m,
		T const & angle,
		detail::tvec3<T> const & v);

	/// Builds a scale 4 * 4 matrix created from 3 scalars.
	/// @see - gtc_matrix_transform
	/// @see - gtx_transform:
	/// - @link glm::gtx::transform::scale(T x, T y, T z) scale(T const & x, T const & y, T const & z) @endlink
	/// - @link glm::gtx::transform::scale(detail::tmat4x4<T> const & m, T x, T y, T z) scale(mat4x4<T> const & m, T const & angle, T const & x, T const & y, T const & z) @endlink
	/// - @link glm::gtx::transform::scale(detail::tvec3<T> const & v) scale(vec3<T> const & v) @endlink
	template <typename T>
	detail::tmat4x4<T> scale(
		detail::tmat4x4<T> const & m,
		detail::tvec3<T> const & v);

	/// Creates a matrix for an orthographic parallel viewing volume.
	/// @see - gtc_matrix_transform:
	/// - @link glm::gtc::matrix_transform::ortho(T const & left, T const & right, T const & bottom, T const & top) ortho(T const & left, T const & right, T const & bottom, T const & top) @endlink
	template <typename T>
	detail::tmat4x4<T> ortho(
		T const & left,
		T const & right,
		T const & bottom,
		T const & top,
		T const & zNear,
		T const & zFar);

	/// Creates a matrix for projecting two-dimensional coordinates onto the screen.
	/// @see - gtc_matrix_transform:
    /// - @link glm::gtc::matrix_transform::ortho(T const & left, T const & right, T const & bottom, T const & top, T const & zNear, T const & zFar) ortho(T const & left, T const & right, T const & bottom, T const & top, T const & zNear, T const & zFar) @endlink
	template <typename T>
	detail::tmat4x4<T> ortho(
		T const & left,
		T const & right,
		T const & bottom,
		T const & top);

	/// Creates a frustum matrix.
	/// @see - gtc_matrix_transform
	template <typename T>
	detail::tmat4x4<T> frustum(
		T const & left,
		T const & right,
		T const & bottom,
		T const & top,
		T const & nearVal,
		T const & farVal);

	/// Creates a matrix for a symetric perspective-view frustum.
	/// @see - gtc_matrix_transform
	template <typename T>
	detail::tmat4x4<T> perspective(
		T const & fovy,
		T const & aspect,
		T const & zNear,
		T const & zFar);

	/// Builds a perspective projection matrix based on a field of view
	/// @see - gtc_matrix_transform
	template <typename valType>
	detail::tmat4x4<valType> perspectiveFov(
		valType const & fov,
		valType const & width,
		valType const & height,
		valType const & zNear,
		valType const & zFar);

	/// Creates a matrix for a symmetric perspective-view frustum with far plane at infinite .
	/// @see - gtc_matrix_transform
    template <typename T>
	detail::tmat4x4<T> infinitePerspective(
		T fovy, T aspect, T zNear);

	/// Creates a matrix for a symmetric perspective-view frustum with far plane at infinite for graphics hardware that doesn't support depth clamping.
	/// @see - gtc_matrix_transform
    template <typename T>
	detail::tmat4x4<T> tweakedInfinitePerspective(
		T fovy, T aspect, T zNear);

	/// Map the specified object coordinates (obj.x, obj.y, obj.z) into window coordinates.
	/// @see - gtc_matrix_transform
	template <typename T, typename U>
	detail::tvec3<T> project(
		detail::tvec3<T> const & obj,
		detail::tmat4x4<T> const & model,
		detail::tmat4x4<T> const & proj,
		detail::tvec4<U> const & viewport);

	/// Map the specified window coordinates (win.x, win.y, win.z) into object coordinates.
	/// @see - gtc_matrix_transform
	template <typename T, typename U>
	detail::tvec3<T> unProject(
		detail::tvec3<T> const & win,
		detail::tmat4x4<T> const & model,
		detail::tmat4x4<T> const & proj,
		detail::tvec4<U> const & viewport);

	/// Define a picking region
	/// @see - gtc_matrix_transform
	template <typename T, typename U>
	detail::tmat4x4<T> pickMatrix(
		detail::tvec2<T> const & center,
		detail::tvec2<T> const & delta,
		detail::tvec4<U> const & viewport);

	/// Build a look at view matrix.
	/// @see - gtc_matrix_transform:
	/// - @link frustum(T const & left, T const & right, T const & bottom, T const & top, T const & nearVal, T const & farVal) frustum(T const & left, T const & right, T const & bottom, T const & top, T const & nearVal, T const & farVal) @endlink
	/// @param eye Position of the camera
	/// @param center Position where the camera is looking at
	/// @param up Normalized up vector, how the camera is oriented. Typically (0, 0, 1)
	template <typename T>
	detail::tmat4x4<T> lookAt(
		detail::tvec3<T> const & eye,
		detail::tvec3<T> const & center,
		detail::tvec3<T> const & up);

	/// @}
}//namespace matrix_transform
}//namespace gtc
}//namespace glm

#include "matrix_transform.inl"

namespace glm{using namespace gtc::matrix_transform;}

#endif//glm_gtc_matrix_transform
<|endoftext|>


<commit_before>/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
 * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
 * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple Inc. All rights reserved.
 * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
 * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
 * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
 * Copyright (C) Research In Motion Limited 2011. All rights reserved.
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include "core/css/resolver/MatchedPropertiesCache.h"

#include "core/css/StylePropertySet.h"
#include "core/css/resolver/StyleResolverState.h"
#include "core/rendering/style/RenderStyle.h"

namespace blink {

#if ENABLE(OILPAN)
bool CachedMatchedPropertiesHashTraits::traceInCollection(Visitor* visitor, Member<CachedMatchedProperties>& cachedProperties, WTF::ShouldWeakPointersBeMarkedStrongly strongify)
{
    // Only honor the cache's weakness semantics if the collection is traced
    // with WeakPointersActWeak. Otherwise just trace the cachedProperties
    // strongly, ie. call trace on it.
    if (cachedProperties && strongify == WTF::WeakPointersActWeak) {
        // A given cache entry is only kept alive if none of the MatchedProperties
        // in the CachedMatchedProperties value contain a dead "properties" field.
        // If there is a dead field the entire cache entry is removed.
        for (const auto& cachedProperties : cachedProperties->matchedProperties) {
            if (!visitor->isAlive(cachedProperties.properties)) {
                // For now report the cache entry as dead. This might not
                // be the final result if in a subsequent call for this entry,
                // the "properties" field has been marked via another path.
                return true;
            }
        }
    }
    // At this point none of the entries in the matchedProperties vector
    // had a dead "properties" field so trace CachedMatchedProperties strongly.
    visitor->trace(cachedProperties);
    return false;
}
#endif

void CachedMatchedProperties::set(const RenderStyle* style, const RenderStyle* parentStyle, const MatchResult& matchResult)
{
    matchedProperties.appendVector(matchResult.matchedProperties);
    ranges = matchResult.ranges;

    // Note that we don't cache the original RenderStyle instance. It may be further modified.
    // The RenderStyle in the cache is really just a holder for the substructures and never used as-is.
    this->renderStyle = RenderStyle::clone(style);
    this->parentRenderStyle = RenderStyle::clone(parentStyle);
}

void CachedMatchedProperties::clear()
{
    matchedProperties.clear();
    renderStyle = nullptr;
    parentRenderStyle = nullptr;
}

MatchedPropertiesCache::MatchedPropertiesCache()
#if !ENABLE(OILPAN)
    : m_additionsSinceLastSweep(0)
    , m_sweepTimer(this, &MatchedPropertiesCache::sweep)
#endif
{
}

const CachedMatchedProperties* MatchedPropertiesCache::find(unsigned hash, const StyleResolverState& styleResolverState, const MatchResult& matchResult)
{
    ASSERT(hash);

    Cache::iterator it = m_cache.find(hash);
    if (it == m_cache.end())
        return 0;
    CachedMatchedProperties* cacheItem = it->value.get();
    ASSERT(cacheItem);

    size_t size = matchResult.matchedProperties.size();
    if (size != cacheItem->matchedProperties.size())
        return 0;
    if (cacheItem->renderStyle->insideLink() != styleResolverState.style()->insideLink())
        return 0;
    for (size_t i = 0; i < size; ++i) {
        if (matchResult.matchedProperties[i] != cacheItem->matchedProperties[i])
            return 0;
    }
    if (cacheItem->ranges != matchResult.ranges)
        return 0;
    return cacheItem;
}

void MatchedPropertiesCache::add(const RenderStyle* style, const RenderStyle* parentStyle, unsigned hash, const MatchResult& matchResult)
{
#if !ENABLE(OILPAN)
    static const unsigned maxAdditionsBetweenSweeps = 100;
    if (++m_additionsSinceLastSweep >= maxAdditionsBetweenSweeps
        && !m_sweepTimer.isActive()) {
        static const unsigned sweepTimeInSeconds = 60;
        m_sweepTimer.startOneShot(sweepTimeInSeconds, FROM_HERE);
    }
#endif

    ASSERT(hash);
    Cache::AddResult addResult = m_cache.add(hash, nullptr);
    if (addResult.isNewEntry)
        addResult.storedValue->value = adoptPtrWillBeNoop(new CachedMatchedProperties);

    CachedMatchedProperties* cacheItem = addResult.storedValue->value.get();
    if (!addResult.isNewEntry)
        cacheItem->clear();

    cacheItem->set(style, parentStyle, matchResult);
}

void MatchedPropertiesCache::clear()
{
    m_cache.clear();
}

void MatchedPropertiesCache::clearViewportDependent()
{
    Vector<unsigned, 16> toRemove;
    for (const auto& cacheEntry : m_cache) {
        CachedMatchedProperties* cacheItem = cacheEntry.value.get();
        if (cacheItem->renderStyle->hasViewportUnits())
            toRemove.append(cacheEntry.key);
    }
    m_cache.removeAll(toRemove);
}

#if !ENABLE(OILPAN)
void MatchedPropertiesCache::sweep(Timer<MatchedPropertiesCache>*)
{
    // Look for cache entries containing a style declaration with a single ref and remove them.
    // This may happen when an element attribute mutation causes it to generate a new inlineStyle()
    // or presentationAttributeStyle(), potentially leaving this cache with the last ref on the old one.
    Vector<unsigned, 16> toRemove;
    for (const auto& cacheEntry : m_cache) {
        CachedMatchedProperties* cacheItem = cacheEntry.value.get();
        Vector<MatchedProperties>& matchedProperties = cacheItem->matchedProperties;
        for (size_t i = 0; i < matchedProperties.size(); ++i) {
            if (matchedProperties[i].properties->hasOneRef()) {
                toRemove.append(cacheEntry.key);
                break;
            }
        }
    }
    m_cache.removeAll(toRemove);
    m_additionsSinceLastSweep = 0;
}
#endif

bool MatchedPropertiesCache::isCacheable(const Element* element, const RenderStyle* style, const RenderStyle* parentStyle)
{
    // FIXME: CSSPropertyWebkitWritingMode modifies state when applying to document element. We can't skip the applying by caching.
    if (element == element->document().documentElement() && element->document().writingModeSetOnDocumentElement())
        return false;
    if (style->unique() || (style->styleType() != NOPSEUDO && parentStyle->unique()))
        return false;
    if (style->hasAppearance())
        return false;
    if (style->zoom() != RenderStyle::initialZoom())
        return false;
    if (style->writingMode() != RenderStyle::initialWritingMode())
        return false;
    // The cache assumes static knowledge about which properties are inherited.
    if (parentStyle->hasExplicitlyInheritedProperties())
        return false;
    return true;
}

void MatchedPropertiesCache::trace(Visitor* visitor)
{
#if ENABLE(OILPAN)
    visitor->trace(m_cache);
#endif
}

}
<commit_msg>Steer clear of g++ scoping bug in range-based for loop.<commit_after>/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
 * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
 * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple Inc. All rights reserved.
 * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
 * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
 * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
 * Copyright (C) Research In Motion Limited 2011. All rights reserved.
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include "core/css/resolver/MatchedPropertiesCache.h"

#include "core/css/StylePropertySet.h"
#include "core/css/resolver/StyleResolverState.h"
#include "core/rendering/style/RenderStyle.h"

namespace blink {

#if ENABLE(OILPAN)
bool CachedMatchedPropertiesHashTraits::traceInCollection(Visitor* visitor, Member<CachedMatchedProperties>& cachedProperties, WTF::ShouldWeakPointersBeMarkedStrongly strongify)
{
    // Only honor the cache's weakness semantics if the collection is traced
    // with WeakPointersActWeak. Otherwise just trace the cachedProperties
    // strongly, ie. call trace on it.
    if (cachedProperties && strongify == WTF::WeakPointersActWeak) {
        // A given cache entry is only kept alive if none of the MatchedProperties
        // in the CachedMatchedProperties value contain a dead "properties" field.
        // If there is a dead field the entire cache entry is removed.
        for (const auto& matchedProperties : cachedProperties->matchedProperties) {
            if (!visitor->isAlive(matchedProperties.properties)) {
                // For now report the cache entry as dead. This might not
                // be the final result if in a subsequent call for this entry,
                // the "properties" field has been marked via another path.
                return true;
            }
        }
    }
    // At this point none of the entries in the matchedProperties vector
    // had a dead "properties" field so trace CachedMatchedProperties strongly.
    visitor->trace(cachedProperties);
    return false;
}
#endif

void CachedMatchedProperties::set(const RenderStyle* style, const RenderStyle* parentStyle, const MatchResult& matchResult)
{
    matchedProperties.appendVector(matchResult.matchedProperties);
    ranges = matchResult.ranges;

    // Note that we don't cache the original RenderStyle instance. It may be further modified.
    // The RenderStyle in the cache is really just a holder for the substructures and never used as-is.
    this->renderStyle = RenderStyle::clone(style);
    this->parentRenderStyle = RenderStyle::clone(parentStyle);
}

void CachedMatchedProperties::clear()
{
    matchedProperties.clear();
    renderStyle = nullptr;
    parentRenderStyle = nullptr;
}

MatchedPropertiesCache::MatchedPropertiesCache()
#if !ENABLE(OILPAN)
    : m_additionsSinceLastSweep(0)
    , m_sweepTimer(this, &MatchedPropertiesCache::sweep)
#endif
{
}

const CachedMatchedProperties* MatchedPropertiesCache::find(unsigned hash, const StyleResolverState& styleResolverState, const MatchResult& matchResult)
{
    ASSERT(hash);

    Cache::iterator it = m_cache.find(hash);
    if (it == m_cache.end())
        return 0;
    CachedMatchedProperties* cacheItem = it->value.get();
    ASSERT(cacheItem);

    size_t size = matchResult.matchedProperties.size();
    if (size != cacheItem->matchedProperties.size())
        return 0;
    if (cacheItem->renderStyle->insideLink() != styleResolverState.style()->insideLink())
        return 0;
    for (size_t i = 0; i < size; ++i) {
        if (matchResult.matchedProperties[i] != cacheItem->matchedProperties[i])
            return 0;
    }
    if (cacheItem->ranges != matchResult.ranges)
        return 0;
    return cacheItem;
}

void MatchedPropertiesCache::add(const RenderStyle* style, const RenderStyle* parentStyle, unsigned hash, const MatchResult& matchResult)
{
#if !ENABLE(OILPAN)
    static const unsigned maxAdditionsBetweenSweeps = 100;
    if (++m_additionsSinceLastSweep >= maxAdditionsBetweenSweeps
        && !m_sweepTimer.isActive()) {
        static const unsigned sweepTimeInSeconds = 60;
        m_sweepTimer.startOneShot(sweepTimeInSeconds, FROM_HERE);
    }
#endif

    ASSERT(hash);
    Cache::AddResult addResult = m_cache.add(hash, nullptr);
    if (addResult.isNewEntry)
        addResult.storedValue->value = adoptPtrWillBeNoop(new CachedMatchedProperties);

    CachedMatchedProperties* cacheItem = addResult.storedValue->value.get();
    if (!addResult.isNewEntry)
        cacheItem->clear();

    cacheItem->set(style, parentStyle, matchResult);
}

void MatchedPropertiesCache::clear()
{
    m_cache.clear();
}

void MatchedPropertiesCache::clearViewportDependent()
{
    Vector<unsigned, 16> toRemove;
    for (const auto& cacheEntry : m_cache) {
        CachedMatchedProperties* cacheItem = cacheEntry.value.get();
        if (cacheItem->renderStyle->hasViewportUnits())
            toRemove.append(cacheEntry.key);
    }
    m_cache.removeAll(toRemove);
}

#if !ENABLE(OILPAN)
void MatchedPropertiesCache::sweep(Timer<MatchedPropertiesCache>*)
{
    // Look for cache entries containing a style declaration with a single ref and remove them.
    // This may happen when an element attribute mutation causes it to generate a new inlineStyle()
    // or presentationAttributeStyle(), potentially leaving this cache with the last ref on the old one.
    Vector<unsigned, 16> toRemove;
    for (const auto& cacheEntry : m_cache) {
        CachedMatchedProperties* cacheItem = cacheEntry.value.get();
        Vector<MatchedProperties>& matchedProperties = cacheItem->matchedProperties;
        for (size_t i = 0; i < matchedProperties.size(); ++i) {
            if (matchedProperties[i].properties->hasOneRef()) {
                toRemove.append(cacheEntry.key);
                break;
            }
        }
    }
    m_cache.removeAll(toRemove);
    m_additionsSinceLastSweep = 0;
}
#endif

bool MatchedPropertiesCache::isCacheable(const Element* element, const RenderStyle* style, const RenderStyle* parentStyle)
{
    // FIXME: CSSPropertyWebkitWritingMode modifies state when applying to document element. We can't skip the applying by caching.
    if (element == element->document().documentElement() && element->document().writingModeSetOnDocumentElement())
        return false;
    if (style->unique() || (style->styleType() != NOPSEUDO && parentStyle->unique()))
        return false;
    if (style->hasAppearance())
        return false;
    if (style->zoom() != RenderStyle::initialZoom())
        return false;
    if (style->writingMode() != RenderStyle::initialWritingMode())
        return false;
    // The cache assumes static knowledge about which properties are inherited.
    if (parentStyle->hasExplicitlyInheritedProperties())
        return false;
    return true;
}

void MatchedPropertiesCache::trace(Visitor* visitor)
{
#if ENABLE(OILPAN)
    visitor->trace(m_cache);
#endif
}

}
<|endoftext|>


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

#include "QtZeitgeist/DataModel/DataSource"

#include <QMetaType>
#include <QDBusMetaType>

namespace QtZeitgeist
{

namespace DataModel
{

class DataSourcePrivate
{
public :
    QString uniqueId;
    QString name;
    QString description;
    QList<Event> eventTemplates;
    bool running;
    QDateTime lastSeen;
    bool enabled;
};

DataSource::DataSource(QObject *parent)
    : d(new DataSourcePrivate())
{
    Q_ASSERT(d);

    // Initialize the last seen time.
    d->lastSeen.setTime_t(0);
}

DataSource::DataSource(const DataSource & source, QObject *parent)
    : d(new DataSourcePrivate())
{
    Q_ASSERT(d);

    // Copy the source attribute's value.
    d->uniqueId = source.d->uniqueId;
    d->name = source.d->name;
    d->description = source.d->description;
    d->eventTemplates = source.d->eventTemplates;
    d->running = source.d->running;
    d->lastSeen = source.d->lastSeen;
    d->enabled = source.d->enabled;
}

DataSource::~DataSource()
{
    delete d;
}

QString DataSource::uniqueId() const
{
    return d->uniqueId;
}

QString DataSource::name() const
{
    return d->name;
}

QString DataSource::description() const
{
    return d->description;
}

QList<Event> DataSource::eventTemplates() const
{
    return d->eventTemplates;
}

bool DataSource::running() const
{
    return d->running;
}

QDateTime DataSource::lastSeen() const
{
    return d->lastSeen;
}

bool DataSource::enabled() const
{
    return d->enabled;
}

DataSource &DataSource::operator = (const DataSource & source)
{
    // Copy the source attribute's value.
    if (this != &source) {
        d->uniqueId = source.d->uniqueId;
        d->name = source.d->name;
        d->description = source.d->description;
        d->eventTemplates = source.d->eventTemplates;
        d->running = source.d->running;
        d->lastSeen = source.d->lastSeen;
        d->enabled = source.d->enabled;
    }

    return *this;
}

QDBusArgument & operator << (QDBusArgument &argument, const DataSource &datasource)
{
    argument.beginStructure();

    argument
        << datasource.d->uniqueId
        << datasource.d->name
        << datasource.d->description
        << datasource.d->eventTemplates
        << datasource.d->running
        // Convert the QDateTime into msecs since epoch.
        << QString::number(datasource.d->lastSeen.toTime_t() * 1000)
        << datasource.d->enabled;

    argument.endStructure();

    return argument;
}

const QDBusArgument & operator >> (const QDBusArgument &argument, DataSource &datasource)
{
    argument.beginStructure();
    QString lastSeenString;

    argument
        >> datasource.d->uniqueId
        >> datasource.d->name
        >> datasource.d->description
        >> datasource.d->eventTemplates
        >> datasource.d->running
        >> lastSeenString
        >> datasource.d->enabled;

    // Translate the last seen string
    datasource.d->lastSeen.setTime_t(0);
    datasource.d->lastSeen.addMSecs(lastSeenString.toLongLong());

    argument.endStructure();

    return argument;
}

};

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

#include "QtZeitgeist/DataModel/DataSource"

#include <QMetaType>
#include <QDBusMetaType>

namespace QtZeitgeist
{

namespace DataModel
{

class DataSourcePrivate
{
public :
    QString uniqueId;
    QString name;
    QString description;
    QList<Event> eventTemplates;
    bool running;
    QDateTime lastSeen;
    bool enabled;
};

DataSource::DataSource(QObject *parent)
    : d(new DataSourcePrivate())
{
    Q_ASSERT(d);

    // Initialize the last seen time.
    d->lastSeen.setTime_t(0);
}

DataSource::DataSource(const DataSource & source, QObject *parent)
    : d(new DataSourcePrivate())
{
    Q_ASSERT(d);

    // Copy the source attribute's value.
    d->uniqueId = source.d->uniqueId;
    d->name = source.d->name;
    d->description = source.d->description;
    d->eventTemplates = source.d->eventTemplates;
    d->running = source.d->running;
    d->lastSeen = source.d->lastSeen;
    d->enabled = source.d->enabled;
}

DataSource::~DataSource()
{
    delete d;
}

QString DataSource::uniqueId() const
{
    return d->uniqueId;
}

QString DataSource::name() const
{
    return d->name;
}

QString DataSource::description() const
{
    return d->description;
}

QList<Event> DataSource::eventTemplates() const
{
    return d->eventTemplates;
}

bool DataSource::running() const
{
    return d->running;
}

QDateTime DataSource::lastSeen() const
{
    return d->lastSeen;
}

bool DataSource::enabled() const
{
    return d->enabled;
}

DataSource &DataSource::operator = (const DataSource & source)
{
    // Copy the source attribute's value.
    if (this != &source) {
        d->uniqueId = source.d->uniqueId;
        d->name = source.d->name;
        d->description = source.d->description;
        d->eventTemplates = source.d->eventTemplates;
        d->running = source.d->running;
        d->lastSeen = source.d->lastSeen;
        d->enabled = source.d->enabled;
    }

    return *this;
}

QDBusArgument & operator << (QDBusArgument &argument, const DataSource &datasource)
{
    argument.beginStructure();
    // Convert the QDateTime into msecs since epoch.
    qint64 lastSeenMSecs = datasource.d->lastSeen.toTime_t() * 1000;

    argument
        << datasource.d->uniqueId
        << datasource.d->name
        << datasource.d->description
        << datasource.d->eventTemplates
        << datasource.d->running
        << lastSeenMSecs
        << datasource.d->enabled;

    argument.endStructure();

    return argument;
}

const QDBusArgument & operator >> (const QDBusArgument &argument,
    DataSource &datasource)
{
    argument.beginStructure();
    qint64 lastSeenMSecs;

    argument
        >> datasource.d->uniqueId
        >> datasource.d->name
        >> datasource.d->description
        >> datasource.d->eventTemplates
        >> datasource.d->running
        >> lastSeenMSecs
        >> datasource.d->enabled;

    // Translate the last seen string
    datasource.d->lastSeen.setTime_t(0);
    datasource.d->lastSeen.addMSecs(lastSeenMSecs);

    argument.endStructure();

    return argument;
}

};

};
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2003 Tommi Maekitalo
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * As a special exception, you may use this file as part of a free
 * software library without restriction. Specifically, if other files
 * instantiate templates or use macros or inline functions from this
 * file, or you compile this file and link it with other files to
 * produce an executable, this file does not by itself cause the
 * resulting executable to be covered by the GNU General Public
 * License. This exception does not however invalidate any other
 * reasons why the executable file might be covered by the GNU Library
 * General Public License.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <cxxtools/function.h>
#include <cxxtools/thread.h>
#include <cxxtools/mutex.h>
#include <cxxtools/condition.h>
#include <iostream>
#include <string>
#include <unistd.h>

cxxtools::Mutex coutMutex;
cxxtools::Mutex conditionMutex;
cxxtools::Condition running;

#define PRINTLN(expr) \
  do { \
    cxxtools::MutexLock lock(coutMutex); \
    std::cout << time(0) << ' ' << expr << std::endl; \
  } while (false)

class myDetachedThread : public cxxtools::DetachedThread
{
    ~myDetachedThread();

  protected:
    void run();
};

myDetachedThread::~myDetachedThread()
{
  PRINTLN("myDetachedThread::~myDetachedThread() called");
}

void myDetachedThread::run()
{
  PRINTLN("myDetachedThread is starting");

  cxxtools::MutexLock lock(conditionMutex);
  running.broadcast();
  lock.unlock();

  sleep(2);
  PRINTLN("myDetachedThread is ready");
}

void someFunction()
{
  PRINTLN("someFunction()");
  sleep(1);
  PRINTLN("someFunction() ends");
}

class AClass
{
    std::string id;

  public:
    AClass(const std::string& id_)
      : id(id_)
      { }
    ~AClass()
      { PRINTLN("AClass::~AClass of object \"" << id << '"'); }

    void run()
    {
      PRINTLN("aFunction() of object \"" << id << '"');
      sleep(1);
      PRINTLN("aFunction() of object \"" << id << "\" ends");
    }
};

int main()
{
  try
  {
    cxxtools::MutexLock lock(conditionMutex);

    // detached threads are created on the heap.
    // They are deleted automatically when the thread ends.
    cxxtools::Thread* d = new myDetachedThread;
    d->create();
    running.wait(lock);
    PRINTLN("myDetachedThread is running");

    // run a function as a attached thread
    cxxtools::AttachedThread th( cxxtools::callable(someFunction) );
    th.start();

    // run a method of a object as a thread
    AClass aInstance("a instance");
    AClass aInstance2("a instance 2");
    cxxtools::AttachedThread aclassThread( cxxtools::callable(aInstance, &AClass::run) );
    cxxtools::AttachedThread aclassThread2( cxxtools::callable(aInstance2, &AClass::run) );
    aclassThread.start();
    aclassThread2.start();
    sleep(2);
    aclassThread.join();
    aclassThread2.join();

    // The detached thread is killed, if it does not come to an end before main.
    // The attached thread blocks the main-program, until it is ready.
    PRINTLN("main stops");
  }
  catch (const std::exception& e)
  {
    std::cerr << "ERROR: " << e.what() << std::endl;
  }

  std::cout << "main stopped" << std::endl;
}
<commit_msg>use the right sleep-function in demo<commit_after>/*
 * Copyright (C) 2003 Tommi Maekitalo
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * As a special exception, you may use this file as part of a free
 * software library without restriction. Specifically, if other files
 * instantiate templates or use macros or inline functions from this
 * file, or you compile this file and link it with other files to
 * produce an executable, this file does not by itself cause the
 * resulting executable to be covered by the GNU General Public
 * License. This exception does not however invalidate any other
 * reasons why the executable file might be covered by the GNU Library
 * General Public License.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <cxxtools/function.h>
#include <cxxtools/thread.h>
#include <cxxtools/mutex.h>
#include <cxxtools/condition.h>
#include <iostream>
#include <string>
#include <unistd.h>

cxxtools::Mutex coutMutex;
cxxtools::Mutex conditionMutex;
cxxtools::Condition running;

#define PRINTLN(expr) \
  do { \
    cxxtools::MutexLock lock(coutMutex); \
    std::cout << time(0) << ' ' << expr << std::endl; \
  } while (false)

class myDetachedThread : public cxxtools::DetachedThread
{
    ~myDetachedThread();

  protected:
    void run();
};

myDetachedThread::~myDetachedThread()
{
  PRINTLN("myDetachedThread::~myDetachedThread() called");
}

void myDetachedThread::run()
{
  PRINTLN("myDetachedThread is starting");

  cxxtools::MutexLock lock(conditionMutex);
  running.broadcast();
  lock.unlock();

  ::sleep(1);
  PRINTLN("myDetachedThread waits");
  ::sleep(2);
  PRINTLN("myDetachedThread is ready");
}

void someFunction()
{
  PRINTLN("someFunction()");
  ::sleep(1);
  PRINTLN("someFunction() ends");
}

class AClass
{
    std::string id;

  public:
    AClass(const std::string& id_)
      : id(id_)
      { }
    ~AClass()
      { PRINTLN("AClass::~AClass of object \"" << id << '"'); }

    void run()
    {
      PRINTLN("aFunction() of object \"" << id << '"');
      ::sleep(1);
      PRINTLN("aFunction() of object \"" << id << "\" ends");
    }
};

int main()
{
  try
  {
    cxxtools::MutexLock lock(conditionMutex);

    // detached threads are created on the heap.
    // They are deleted automatically when the thread ends.
    cxxtools::Thread* d = new myDetachedThread;
    d->create();
    running.wait(lock);
    PRINTLN("myDetachedThread is running");

    // run a function as a attached thread
    cxxtools::AttachedThread th( cxxtools::callable(someFunction) );
    th.start();

    // run a method of a object as a thread
    AClass aInstance("a instance");
    AClass aInstance2("a instance 2");
    cxxtools::AttachedThread aclassThread( cxxtools::callable(aInstance, &AClass::run) );
    cxxtools::AttachedThread aclassThread2( cxxtools::callable(aInstance2, &AClass::run) );
    aclassThread.start();
    aclassThread2.start();
    ::sleep(2);
    aclassThread.join();
    aclassThread2.join();

    // The detached thread is killed, if it does not come to an end before main.
    // The attached thread blocks the main-program, until it is ready.
    PRINTLN("main stops");
  }
  catch (const std::exception& e)
  {
    std::cerr << "ERROR: " << e.what() << std::endl;
  }

  std::cout << "main stopped" << std::endl;
}
<|endoftext|>


<commit_before>#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/Instructions.h"
#include "llvm/InstVisitor.h"
using namespace llvm;

namespace {

    struct CustomInstVisitor : public InstVisitor<CustomInstVisitor> {
        CustomInstVisitor() : InstVisitor() {}

        void visitStoreInst(StoreInst &i) {
            errs() << "Store Inst Found: " << i.getName() << '\n';
        }

        void visitAllocaInst(AllocaInst &i) {
            errs() << "Allocate Inst Found: " << i.getName() << '\n';
        }

        void visitInstruction(Instruction &i) {
            errs() << "Analyzing Instruction: " << i.getName() << '\n';
        }
    };

    struct NaivePass : public FunctionPass {
        static char ID;
        NaivePass() : FunctionPass(ID) {}

        virtual bool runOnFunction(Function &F) {
            CustomInstVisitor visitor;
            visitor.visit(F);
            return false;
        }

    };

    char NaivePass::ID = 0;
    static RegisterPass<NaivePass> X("naive-reaching", "Naive Reaching Analysis", false, false);
}
<commit_msg>Gen and Kill Sets made<commit_after>#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/InstVisitor.h"
#include <set>
#include <list>
using namespace llvm;

namespace {

    class GenAndKillSets {
        public:
            std::set<StoreInst *> gen;
            std::set<StoreInst *> kill;
    };

    class BBGenAndKillSets {
        public:
            BasicBlock *bb;
            std::set<StoreInst *> gen;
            std::set<StoreInst *> kill;
            BBGenAndKillSets(BasicBlock *val) { bb = val; }
            std::string genString() {
                std::string ret = "Gen Set of BB:" + bb->getName().str() + '\n';
                for (std::set<StoreInst *>::iterator it = gen.begin(); it != gen.end(); it++) {
                    StoreInst *inst = *it;
                    ret += '\t' + inst->getPointerOperand()->getName().str() + '\n';
                }
                return ret;
            }
    };

    struct NaivePass : public FunctionPass {
        static char ID;
        NaivePass() : FunctionPass(ID) {}

        virtual bool runOnFunction(Function &F) {
            std::list<BBGenAndKillSets> listOfSets;
            for (Function::iterator f_it = F.begin(); f_it != F.end(); ++f_it) {
                BBGenAndKillSets bbSets = createBBGenAndKillSets(F, f_it);
                errs() << bbSets.genString();
            }
            return false;
        }

        BBGenAndKillSets createBBGenAndKillSets(Function &F, BasicBlock *f_it) {
            BBGenAndKillSets bbSets(f_it);
            for (BasicBlock::iterator bb_it = f_it->begin(); bb_it != f_it->end(); bb_it++) {
                if (StoreInst *inst = dyn_cast<StoreInst>(bb_it)) {
                    Value *var = inst->getPointerOperand();
                    GenAndKillSets sets;
                    sets.gen.insert(inst);
                    for (Function::iterator f2_it = F.begin(); f2_it != F.end(); ++f2_it) {
                        for (BasicBlock::iterator bb2_it = f2_it->begin();
                                bb2_it != f2_it->end(); bb2_it++) {
                            if (bb2_it == bb_it) {
                                continue;
                            }

                            if (StoreInst *inst2 = dyn_cast<StoreInst>(bb2_it)) {
                                if (inst2->getPointerOperand() == var) {
                                    sets.kill.insert(inst2);
                                }
                            }
                        }
                    }
                    for (std::set<StoreInst *>::iterator gen = sets.gen.begin(); gen != sets.gen.end(); gen++) {
                        bbSets.gen.insert(*gen);
                    }
                    for (std::set<StoreInst *>::iterator kill = sets.kill.begin(); kill != sets.kill.end(); kill++) {
                        bbSets.kill.insert(*kill);
                    }
                }
            }
            return bbSets;
        }

    };

    char NaivePass::ID = 0;
    static RegisterPass<NaivePass> X("naive-reaching", "Naive Reaching Analysis", false, false);
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2019 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "test/pc/e2e/analyzer/video/video_quality_analyzer_injection_helper.h"

#include <utility>

#include "absl/memory/memory.h"
#include "test/pc/e2e/analyzer/video/quality_analyzing_video_decoder.h"
#include "test/pc/e2e/analyzer/video/quality_analyzing_video_encoder.h"
#include "test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper.h"

namespace webrtc {
namespace webrtc_pc_e2e {

namespace {

// Intercepts generated frames and passes them also to video quality analyzer
// and into video frame writer, if the last one is provided.
class InterceptingFrameGenerator : public test::FrameGenerator {
 public:
  InterceptingFrameGenerator(std::string stream_label,
                             std::unique_ptr<test::FrameGenerator> delegate,
                             VideoQualityAnalyzerInterface* analyzer,
                             test::VideoFrameWriter* video_writer)
      : stream_label_(std::move(stream_label)),
        delegate_(std::move(delegate)),
        analyzer_(analyzer),
        video_writer_(video_writer) {
    RTC_DCHECK(analyzer_);
  }
  ~InterceptingFrameGenerator() override = default;

  VideoFrame* NextFrame() override {
    VideoFrame* frame = delegate_->NextFrame();
    uint16_t frame_id = analyzer_->OnFrameCaptured(stream_label_, *frame);
    frame->set_id(frame_id);
    if (video_writer_) {
      bool result = video_writer_->WriteFrame(*frame);
      RTC_CHECK(result) << "Failed to write frame";
    }
    return frame;
  }

  void ChangeResolution(size_t width, size_t height) override {
    delegate_->ChangeResolution(width, height);
  }

 private:
  std::string stream_label_;
  std::unique_ptr<test::FrameGenerator> delegate_;
  VideoQualityAnalyzerInterface* analyzer_;
  test::VideoFrameWriter* video_writer_;
};

// Implements the video sink, that forwards rendered frames to the video quality
// analyzer and to the video frame writer, if the last one is provided.
class AnalyzingVideoSink : public rtc::VideoSinkInterface<VideoFrame> {
 public:
  AnalyzingVideoSink(VideoQualityAnalyzerInterface* analyzer,
                     test::VideoFrameWriter* video_writer)
      : analyzer_(analyzer), video_writer_(video_writer) {
    RTC_DCHECK(analyzer_);
  }
  ~AnalyzingVideoSink() override = default;

  void OnFrame(const VideoFrame& frame) override {
    if (IsDummyFrameBuffer(frame.video_frame_buffer()->ToI420())) {
      // This is dummy frame, so we  don't need to process it further.
      return;
    }
    analyzer_->OnFrameRendered(frame);
    if (video_writer_) {
      bool result = video_writer_->WriteFrame(frame);
      RTC_CHECK(result) << "Failed to write frame";
    }
  }
  void OnDiscardedFrame() override {}

 private:
  VideoQualityAnalyzerInterface* analyzer_;
  test::VideoFrameWriter* video_writer_;
};

}  // namespace

VideoQualityAnalyzerInjectionHelper::VideoQualityAnalyzerInjectionHelper(
    std::unique_ptr<VideoQualityAnalyzerInterface> analyzer,
    EncodedImageDataInjector* injector,
    EncodedImageDataExtractor* extractor)
    : analyzer_(std::move(analyzer)),
      injector_(injector),
      extractor_(extractor),
      encoding_entities_id_generator_(absl::make_unique<IntIdGenerator>(1)) {
  RTC_DCHECK(injector_);
  RTC_DCHECK(extractor_);
}
VideoQualityAnalyzerInjectionHelper::~VideoQualityAnalyzerInjectionHelper() =
    default;

std::unique_ptr<VideoEncoderFactory>
VideoQualityAnalyzerInjectionHelper::WrapVideoEncoderFactory(
    std::unique_ptr<VideoEncoderFactory> delegate,
    double bitrate_multiplier,
    std::map<std::string, absl::optional<int>> stream_required_spatial_index)
    const {
  return absl::make_unique<QualityAnalyzingVideoEncoderFactory>(
      std::move(delegate), bitrate_multiplier,
      std::move(stream_required_spatial_index),
      encoding_entities_id_generator_.get(), injector_, analyzer_.get());
}

std::unique_ptr<VideoDecoderFactory>
VideoQualityAnalyzerInjectionHelper::WrapVideoDecoderFactory(
    std::unique_ptr<VideoDecoderFactory> delegate) const {
  return absl::make_unique<QualityAnalyzingVideoDecoderFactory>(
      std::move(delegate), encoding_entities_id_generator_.get(), extractor_,
      analyzer_.get());
}

std::unique_ptr<test::FrameGenerator>
VideoQualityAnalyzerInjectionHelper::WrapFrameGenerator(
    std::string stream_label,
    std::unique_ptr<test::FrameGenerator> delegate,
    test::VideoFrameWriter* writer) const {
  return absl::make_unique<InterceptingFrameGenerator>(
      std::move(stream_label), std::move(delegate), analyzer_.get(), writer);
}

std::unique_ptr<rtc::VideoSinkInterface<VideoFrame>>
VideoQualityAnalyzerInjectionHelper::CreateVideoSink(
    test::VideoFrameWriter* writer) const {
  return absl::make_unique<AnalyzingVideoSink>(analyzer_.get(), writer);
}

void VideoQualityAnalyzerInjectionHelper::Start(std::string test_case_name,
                                                int max_threads_count) {
  analyzer_->Start(std::move(test_case_name), max_threads_count);
}

void VideoQualityAnalyzerInjectionHelper::OnStatsReports(
    const std::string& pc_label,
    const StatsReports& stats_reports) {
  analyzer_->OnStatsReports(pc_label, stats_reports);
}

void VideoQualityAnalyzerInjectionHelper::Stop() {
  analyzer_->Stop();
}

}  // namespace webrtc_pc_e2e
}  // namespace webrtc
<commit_msg>Refactor video analyzer injection helper<commit_after>/*
 *  Copyright (c) 2019 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "test/pc/e2e/analyzer/video/video_quality_analyzer_injection_helper.h"

#include <utility>

#include "absl/memory/memory.h"
#include "test/pc/e2e/analyzer/video/quality_analyzing_video_decoder.h"
#include "test/pc/e2e/analyzer/video/quality_analyzing_video_encoder.h"
#include "test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper.h"

namespace webrtc {
namespace webrtc_pc_e2e {

namespace {

class VideoFrameInterceptor {
 public:
  virtual ~VideoFrameInterceptor() = default;

  // Performs desired actions with video frame. It may change video frame.
  virtual void OnVideoFrame(VideoFrame* frame) = 0;
};

class VideoAnalyzerCapturingInterceptor : public VideoFrameInterceptor {
 public:
  VideoAnalyzerCapturingInterceptor(std::string stream_label,
                                    VideoQualityAnalyzerInterface* analyzer)
      : stream_label_(std::move(stream_label)), analyzer_(analyzer) {
    RTC_DCHECK(analyzer_);
  }
  ~VideoAnalyzerCapturingInterceptor() override = default;

  void OnVideoFrame(VideoFrame* frame) override {
    uint16_t frame_id = analyzer_->OnFrameCaptured(stream_label_, *frame);
    frame->set_id(frame_id);
  }

 private:
  const std::string stream_label_;
  VideoQualityAnalyzerInterface* analyzer_;
};

class VideoWriterInterceptor : public VideoFrameInterceptor {
 public:
  VideoWriterInterceptor(test::VideoFrameWriter* video_writer)
      : video_writer_(video_writer) {}
  ~VideoWriterInterceptor() override = default;

  void OnVideoFrame(VideoFrame* frame) override {
    bool result = video_writer_->WriteFrame(*frame);
    RTC_CHECK(result) << "Failed to write frame";
  }

 private:
  test::VideoFrameWriter* video_writer_;
};

// Intercepts generated frames and passes them also to video quality analyzer
// and into video frame writer, if the last one is provided.
class InterceptingFrameGenerator : public test::FrameGenerator {
 public:
  InterceptingFrameGenerator(
      std::unique_ptr<test::FrameGenerator> delegate,
      std::vector<std::unique_ptr<VideoFrameInterceptor>> interceptors)
      : delegate_(std::move(delegate)),
        interceptors_(std::move(interceptors)) {}
  ~InterceptingFrameGenerator() override = default;

  VideoFrame* NextFrame() override {
    VideoFrame* frame = delegate_->NextFrame();
    for (auto& interceptor : interceptors_) {
      interceptor->OnVideoFrame(frame);
    }
    return frame;
  }

  void ChangeResolution(size_t width, size_t height) override {
    delegate_->ChangeResolution(width, height);
  }

 private:
  std::unique_ptr<test::FrameGenerator> delegate_;
  std::vector<std::unique_ptr<VideoFrameInterceptor>> interceptors_;
};

// Implements the video sink, that forwards rendered frames to the video quality
// analyzer and to the video frame writer, if the last one is provided.
class AnalyzingVideoSink : public rtc::VideoSinkInterface<VideoFrame> {
 public:
  AnalyzingVideoSink(VideoQualityAnalyzerInterface* analyzer,
                     test::VideoFrameWriter* video_writer)
      : analyzer_(analyzer), video_writer_(video_writer) {
    RTC_DCHECK(analyzer_);
  }
  ~AnalyzingVideoSink() override = default;

  void OnFrame(const VideoFrame& frame) override {
    if (IsDummyFrameBuffer(frame.video_frame_buffer()->ToI420())) {
      // This is dummy frame, so we  don't need to process it further.
      return;
    }
    analyzer_->OnFrameRendered(frame);
    if (video_writer_) {
      bool result = video_writer_->WriteFrame(frame);
      RTC_CHECK(result) << "Failed to write frame";
    }
  }
  void OnDiscardedFrame() override {}

 private:
  VideoQualityAnalyzerInterface* analyzer_;
  test::VideoFrameWriter* video_writer_;
};

}  // namespace

VideoQualityAnalyzerInjectionHelper::VideoQualityAnalyzerInjectionHelper(
    std::unique_ptr<VideoQualityAnalyzerInterface> analyzer,
    EncodedImageDataInjector* injector,
    EncodedImageDataExtractor* extractor)
    : analyzer_(std::move(analyzer)),
      injector_(injector),
      extractor_(extractor),
      encoding_entities_id_generator_(absl::make_unique<IntIdGenerator>(1)) {
  RTC_DCHECK(injector_);
  RTC_DCHECK(extractor_);
}
VideoQualityAnalyzerInjectionHelper::~VideoQualityAnalyzerInjectionHelper() =
    default;

std::unique_ptr<VideoEncoderFactory>
VideoQualityAnalyzerInjectionHelper::WrapVideoEncoderFactory(
    std::unique_ptr<VideoEncoderFactory> delegate,
    double bitrate_multiplier,
    std::map<std::string, absl::optional<int>> stream_required_spatial_index)
    const {
  return absl::make_unique<QualityAnalyzingVideoEncoderFactory>(
      std::move(delegate), bitrate_multiplier,
      std::move(stream_required_spatial_index),
      encoding_entities_id_generator_.get(), injector_, analyzer_.get());
}

std::unique_ptr<VideoDecoderFactory>
VideoQualityAnalyzerInjectionHelper::WrapVideoDecoderFactory(
    std::unique_ptr<VideoDecoderFactory> delegate) const {
  return absl::make_unique<QualityAnalyzingVideoDecoderFactory>(
      std::move(delegate), encoding_entities_id_generator_.get(), extractor_,
      analyzer_.get());
}

std::unique_ptr<test::FrameGenerator>
VideoQualityAnalyzerInjectionHelper::WrapFrameGenerator(
    std::string stream_label,
    std::unique_ptr<test::FrameGenerator> delegate,
    test::VideoFrameWriter* writer) const {
  std::vector<std::unique_ptr<VideoFrameInterceptor>> interceptors;
  interceptors.push_back(absl::make_unique<VideoAnalyzerCapturingInterceptor>(
      std::move(stream_label), analyzer_.get()));
  if (writer) {
    interceptors.push_back(absl::make_unique<VideoWriterInterceptor>(writer));
  }
  return absl::make_unique<InterceptingFrameGenerator>(std::move(delegate),
                                                       std::move(interceptors));
}

std::unique_ptr<rtc::VideoSinkInterface<VideoFrame>>
VideoQualityAnalyzerInjectionHelper::CreateVideoSink(
    test::VideoFrameWriter* writer) const {
  return absl::make_unique<AnalyzingVideoSink>(analyzer_.get(), writer);
}

void VideoQualityAnalyzerInjectionHelper::Start(std::string test_case_name,
                                                int max_threads_count) {
  analyzer_->Start(std::move(test_case_name), max_threads_count);
}

void VideoQualityAnalyzerInjectionHelper::OnStatsReports(
    const std::string& pc_label,
    const StatsReports& stats_reports) {
  analyzer_->OnStatsReports(pc_label, stats_reports);
}

void VideoQualityAnalyzerInjectionHelper::Stop() {
  analyzer_->Stop();
}

}  // namespace webrtc_pc_e2e
}  // namespace webrtc
<|endoftext|>